Files

284 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""v1.0.55 回归:识别前处理(裁剪降噪)+ 提示词【看图范围/业务规则校验】
现场 2026-11-05 21:38 那袋土豆,抓拍帧里左手占了左上三分之一、袋子上还
印着红字,模型先看到的是手和字。原来只靠提示词一句「不要被带偏」兜,
兜不住——所以分两层改:
· 图这一层:喂给模型前裁掉四周、按需提亮锐化(core/recognition/prep.py)。
留档照片、上传服务端的凭证图仍是相机原帧,一个像素都不动。
· 词这一层:加【看图范围】(只判中心秤盘那件)+【业务规则校验】
(名称口径/同物异名/形态/颜色/两件货/空盘)。
不联网、不建界面、不真打打印机。
"""
import io
import os
import sys
import json
import hashlib
import tempfile
import cv2
import numpy as np
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from core.recognition import prep # noqa: E402
from core.recognition.prompts import BUILTIN, render, missing_vars # noqa: E402
from core.recognition.cloud import CloudRecognizer # noqa: E402
from core.flow import _prep_note # noqa: E402
TMP = os.path.join(ROOT, 'data', '_diag', '_v1055')
os.makedirs(TMP, exist_ok=True)
ok = fail = 0
def check(name, cond, extra=''):
global ok, fail
if cond:
ok += 1
print(' ✔ %s' % name)
else:
fail += 1
print(' ✘ %s %s' % (name, extra))
def mkimg(w, h, mean=128, color=None):
if color is None:
return np.full((h, w, 3), int(mean), dtype=np.uint8)
img = np.zeros((h, w, 3), dtype=np.uint8)
img[:, :] = color
return img
def save(img, name):
"""写图用 encode + open:cv2.imwrite 在中文路径下静默失败(本模块注释
里记的就是这个坑,测试自己不能踩)。"""
p = os.path.join(TMP, name)
with open(p, 'wb') as f:
f.write(prep.encode_jpeg(img, 92))
return p
def recognizer(**vision):
v = {'api_key': 'test-key', 'provider': 'custom',
'vision_model': 'm', 'text_model': 'm'}
v.update(vision)
return CloudRecognizer({'vision': v, 'account': {'role': 'picker'}})
print('=== 1. 裁剪:默认保留中心 86% ===')
img = mkimg(1280, 720)
out, meta = prep.for_ai(img, {'recog_crop': 0.86, 'recog_enhance': False})
check('1280×720 裁 86% → 1101×619',
out.shape[1] == 1101 and out.shape[0] == 619, out.shape)
check('meta 记下裁剪比例 0.86', abs(meta['crop'] - 0.86) < 1e-6, meta)
check('meta 记下前后尺寸', meta['from'] == '1280x720'
and meta['to'] == '1101x619', meta)
print()
print('=== 2. 裁的是正中间,不是左上角 ===')
big = np.zeros((100, 100, 3), dtype=np.uint8)
big[40:60, 40:60] = 255 # 中心 20×20 白块
mid, _ = prep.for_ai(big, {'recog_crop': 0.5, 'recog_enhance': False})
h, w = mid.shape[:2]
c = mid[h // 2 - 3:h // 2 + 3, w // 2 - 3:w // 2 + 3]
check('裁完中心仍是白块(没有偏到一角)', float(c.mean()) > 240, c.mean())
check('裁完四角是黑的(四周被切掉)',
float(mid[0:3, 0:3].mean()) < 10 and float(mid[-3:, -3:].mean()) < 10)
print()
print('=== 3. 开关与边界 ===')
same, m1 = prep.for_ai(img, {'recog_crop': 1.0, 'recog_enhance': False})
check('recog_crop=1.0 不裁', same.shape[:2] == (720, 1280), same.shape)
check('meta.crop=1.0', m1['crop'] == 1.0, m1)
weird, m2 = prep.for_ai(img, {'recog_crop': 0.05, 'recog_enhance': False})
check('recog_crop 越界(0.05)不裁,避免把货裁没',
weird.shape[:2] == (720, 1280), weird.shape)
print()
print('=== 4. 缩放:只缩不放 ===')
huge = mkimg(2400, 1200)
small, mh = prep.for_ai(huge, {'recog_crop': 1.0, 'recog_enhance': False,
'recognition_image_max_px': 1280})
check('2400 长边缩到 1280', max(small.shape[:2]) == 1280, small.shape)
tiny = mkimg(400, 300)
up, _ = prep.for_ai(tiny, {'recog_crop': 1.0, 'recog_enhance': False,
'recognition_image_max_px': 1280})
check('400×300 不放大(放大不会多出信息)', up.shape[:2] == (300, 400),
up.shape)
print()
print('=== 5. 提亮:暗图拉起来,亮图不动 ===')
dark = mkimg(600, 400, mean=60)
lit, md = prep.for_ai(dark, {'recog_crop': 1.0, 'recog_enhance': True})
g = cv2.cvtColor(lit, cv2.COLOR_BGR2GRAY).mean()
check('均值 60 的暗帧被提亮(>75)', g > 75, g)
check('提亮倍数记进 meta 且 >1', float(md['gamma']) > 1.05, md)
bright = mkimg(600, 400, mean=130)
bl, mb = prep.for_ai(bright, {'recog_crop': 1.0, 'recog_enhance': True})
check('均值 130 算正常光,不提亮', float(mb['gamma']) == 1.0, mb)
nolit, mn = prep.for_ai(dark, {'recog_crop': 1.0, 'recog_enhance': False})
check('recog_enhance=false 不提亮也不锐化',
float(mn['gamma']) == 1.0 and not mn['sharp'], mn)
print()
print('=== 6. 提亮不偏色(火龙果的红、青椒的绿要保住)===')
red = mkimg(200, 200, color=(30, 30, 200)) # BGR 红
rout, _ = prep.for_ai(red, {'recog_crop': 1.0, 'recog_enhance': True})
b, gch, r = [float(rout[:, :, i].mean()) for i in range(3)]
check('提亮后红仍远大于蓝绿', r > 180 and b < 100 and gch < 100, (b, gch, r))
print()
print('=== 7. 中文路径能读(cv2.imread 会静默返回 None)===')
cn_dir = os.path.join(TMP, '入库分拣抓拍')
os.makedirs(cn_dir, exist_ok=True)
cn_path = os.path.join(cn_dir, '测试帧.jpg')
with open(cn_path, 'wb') as f:
f.write(prep.encode_jpeg(mkimg(320, 240, mean=100), 92))
got = prep.read_image(cn_path)
check('中文目录下的 jpg 读得出来', got is not None and got.shape[:2] == (240, 320),
None if got is None else got.shape)
bad = os.path.join(TMP, '坏图.jpg')
with open(bad, 'wb') as f:
f.write(b'not a jpeg')
check('坏文件返回 None,不抛异常', prep.read_image(bad) is None)
check('不存在的路径返回 None', prep.read_image(os.path.join(TMP, '没有这个.jpg'))
is None)
check('for_ai(None) 不崩', prep.for_ai(None, {})[0] is None)
print()
print('=== 8. 原图一个像素都不改(留档/凭证必须还是相机原帧)===')
src = save(mkimg(1280, 720, mean=70), '原帧.jpg')
sha_before = hashlib.sha256(open(src, 'rb').read()).hexdigest()
r = recognizer()
b64, meta = r._image_b64(src)
sha_after = hashlib.sha256(open(src, 'rb').read()).hexdigest()
check('前处理没有回写原文件', sha_before == sha_after)
check('返回的 base64 非空', len(b64) > 1000, len(b64))
check('meta 里裁 86%', abs(meta['crop'] - 0.86) < 1e-6, meta)
check('暗帧走了提亮', float(meta['gamma']) > 1.0, meta)
print()
print('=== 9. recog_prep=false 完全回到老样子(整帧直发)===')
r2 = recognizer(recog_prep=False)
b64_off, meta_off = r2._image_b64(src)
raw = open(src, 'rb').read()
import base64 as _b64
check('关闭后发的就是原文件字节', _b64.b64decode(b64_off) == raw)
check('meta 标记 off', meta_off.get('off') is True, meta_off)
print()
print('=== 10. 免称重要传更保守的裁剪(别把整袋货切了)===')
r3 = recognizer()
b64_c, meta_c = r3._image_b64(src, crop=0.96)
check('crop 参数覆盖默认值', abs(meta_c['crop'] - 0.96) < 1e-6, meta_c)
check('覆盖只作用于本次,不污染识别器默认',
abs(recognizer().cfg.get('recog_crop', -1) - (-1)) < 1e-9)
flow_src = open(os.path.join(ROOT, 'core', 'flow.py'), encoding='utf-8').read()
check('免称重识别调用带 recog_crop_noweigh',
'recog_crop_noweigh' in flow_src)
check('称重台识别没有跟着改(走默认 86%)',
flow_src.count('recog_crop_noweigh') == 1)
print()
print('=== 11. identify_ex 把前处理结果带回去(供日志复盘)===')
r4 = recognizer()
sent = {}
def fake_chat(messages, model, timeout, max_tokens=None):
sent['text'] = messages[0]['content'][0]['text']
sent['img'] = messages[0]['content'][1]['image_url']['url']
return '{"name":"土豆","conf":82,"alt":"","alt_conf":0}'
r4._chat = fake_chat
info = r4.identify_ex(src, ['土豆', '大葱'])
check('名字解析正常', info['name'] == '土豆', info)
check('带回 prep 元信息', isinstance(info.get('prep'), dict)
and info['prep'].get('to'), info.get('prep'))
check('带回提示词标记', info.get('prompt_tag') not in (None, ''), info)
check('发出去的图是 jpeg base64', sent['img'].startswith('data:image/jpeg;base64,'))
print()
print('=== 12. 提示词补了【看图范围】和【业务规则校验】===')
tpl = BUILTIN['weigh.recognize.pick_list']
check('有【看图范围】', '【看图范围】' in tpl)
check('有【业务规则校验】', '【业务规则校验】' in tpl)
check('写明只判画面中央秤盘那件', '只判画面中央' in tpl)
check('写名人手/塑料袋是遮挡物不是商品', '遮挡物' in tpl)
check('写明被挡住要压 conf', '遮得越多 conf 越低' in tpl)
check('有名称口径(不加产地规格品牌)', '不加产地、规格、等级、品牌' in tpl)
check('有同物异名条', '土豆=马铃薯' in tpl)
check('有形态不改品种条', '形态不改品种' in tpl)
check('有只凭颜色压分条(≤75)', '只凭颜色下结论时 conf 不超过 75' in tpl)
check('有中央两件货只判一件', '更靠中心的那件' in tpl)
check('有空盘 NOT_IN_LIST 条', '空盘、只有空袋' in tpl)
check('alt_conf 给了量化口径(50 以上才叫分不清)', '才给 50 以上' in tpl)
check('必需占位符一个不少', missing_vars(tpl, 'weigh.recognize.pick_list') == [])
check('{{scene}}/{{item_list}} 都在', '{{scene}}' in tpl and '{{item_list}}' in tpl)
print()
print('=== 13. 端上内置与服务端 defaults.ts 必须逐字一致 ===')
ts_path = os.path.join(ROOT, '配送系统', 'server', 'src', 'prompts', 'defaults.ts')
if os.path.exists(ts_path):
import re
src_ts = open(ts_path, encoding='utf-8').read()
i = src_ts.index("featureKey: 'weigh.recognize.pick_list'")
m = re.search(r'systemTemplate: `(.*?)`,\n', src_ts[i:], re.S)
ts_tpl = m.group(1) if m else ''
check('与 defaults.ts 同文(否则服务端 v1 会把老文本盖回来)',
ts_tpl == tpl, 'ts=%d py=%d' % (len(ts_tpl), len(tpl)))
else:
check('跳过:服务端仓库不在本机', True)
print()
print('=== 14. 渲染后不残留占位符 ===')
rendered = render(tpl, {'scene': '待拣分拣',
'item_list': '- 土豆\n- 大葱\n- 火龙果',
'confusable': ''})
check('没有 {{ 残留', '{{' not in rendered, rendered[-80:])
check('名单塞进去了', '- 土豆' in rendered and '- 火龙果' in rendered)
check('场景词塞进去了', '当前场景:待拣分拣。' in rendered)
check('长度可控(<1200 字,别把指令稀释了)', len(rendered) < 1200,
len(rendered))
print()
print('=== 15. 日志里的前处理摘要 ===')
check('没动过图就不占日志', _prep_note({'prep': {'crop': 1.0, 'gamma': 1.0}}) == '')
check('关闭前处理不写', _prep_note({'prep': {'off': True}}) == '')
check('裁过就写「裁 86%」',
'裁 86%' in _prep_note({'prep': {'crop': 0.86, 'gamma': 1.0,
'from': '1280x720', 'to': '1101x619'}}))
check('提亮过就写倍数',
'提亮×1.58' in _prep_note({'prep': {'crop': 0.86, 'gamma': 1.58,
'from': 'a', 'to': 'b'}}))
check('没有 prep 字段也不崩', _prep_note({}) == '')
print()
print('=== 16. 现场真实帧:前处理确实把边缘干扰削掉 ===')
real = os.path.join(ROOT, 'data', '_diag', 'shots', 'a.jpg')
if os.path.exists(real):
img = prep.read_image(real)
out, meta = prep.for_ai(img, {'recog_crop': 0.86, 'recog_enhance': True,
'recognition_image_max_px': 1280})
check('真实帧裁完更小更亮',
out.shape[1] < img.shape[1] and meta['gamma'] > 1.0, meta)
check('补白亮度上升',
cv2.cvtColor(out, cv2.COLOR_BGR2GRAY).mean()
> cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).mean() + 10,
(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).mean(),
cv2.cvtColor(out, cv2.COLOR_BGR2GRAY).mean()))
else:
check('跳过:没有现场样本帧', True)
print()
print('通过 %d 项,失败 %d 项' % (ok, fail))
sys.exit(0 if fail == 0 else 1)