Files

238 lines
11 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 第二批回归:易混对照动态注入 + 本地数据飞轮(样本库)
要解决的问题:白芹/西芹/香菜、小葱/大葱/蒜苗/韭黄/韭菜 这几组,在车间暗光
和塑料袋反光下几乎一样,文字规则写到第 10 条也不如给模型看一张现场确认过
的实物图。但现场是全品类(火龙果、藕、蜜薯都在走同一个镜头),所以:
· 那 17 个叶菜白名单**不能**写死进主提示词 —— 会把名单外的全判成"不确定"
· 改成「本轮名单里同时出现两个以上易混成员时,才注入这一组的区分口径」
· 再加本地样本库:人点头记账那一刻,把这张抓拍按品名存下来,
下次同组出现时作为 few-shot 样例附给模型
不联网、不建界面。
"""
import io
import os
import sys
import json
import shutil
import tempfile
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 dataset as DS # noqa: E402
from core.recognition.prompts import BUILTIN, render, missing_vars # noqa: E402
from core.recognition.cloud import CloudRecognizer, _confusable_text # noqa: E402
TMP = os.path.join(ROOT, 'data', '_diag', '_v1055b')
if os.path.isdir(TMP):
shutil.rmtree(TMP, ignore_errors=True)
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 mkfile(tag, content=b'jpeg-bytes'):
"""造一个假图文件(内容唯一,sha 不同)。"""
p = os.path.join(TMP, tag + '.jpg')
with open(p, 'wb') as f:
f.write(content + tag.encode())
return p
def new_store():
DS.reset_store()
return DS.SampleStore(root=TMP, path=os.path.join(TMP, 'index.json'))
print('=== 1. 易混组:同组两个以上才命中 ===')
check('小葱+大葱 → 命中葱组',
any(set(g) >= {'小葱', '大葱'} for g in DS.groups_for(['小葱', '大葱', '火龙果'])))
check('只有小葱 → 不命中', DS.groups_for(['小葱', '火龙果']) == [])
check('白芹+西芹 → 命中芹菜组',
any(set(g) >= {'白芹', '西芹'} for g in DS.groups_for(['白芹', '西芹'])))
check('无关名单 → 空', DS.groups_for(['火龙果', '藕', '蜜薯']) == [])
print()
print('=== 2. 注入文本:只写命中的那组,不把 17 个白名单全塞进去 ===')
txt = DS.confusable_text(['小葱', '大葱', '火龙果'])
check('含【易混对照】', '【易混对照】' in txt, txt[:40])
check('写了小葱/大葱的区分口径', '细绿空心管' in txt and '葱白长' in txt)
check('没把白芹/西芹那组带进来(未命中不该占篇幅)', '白芹' not in txt, txt)
check('提示分不清要压 conf', 'conf 压到 60 以下' in txt)
check('未命中时返回空串', DS.confusable_text(['火龙果', '藕']) == '')
print()
print('=== 3. 提示词里 {{confusable}} 为空时整段消失 ===')
tpl = BUILTIN['weigh.recognize.pick_list']
check('模板有 {{confusable}} 占位符', '{{confusable}}' in tpl)
check('confusable 不是必需变量(可为空)',
missing_vars(tpl, 'weigh.recognize.pick_list') == [])
empty_render = render(tpl, {'scene': '待拣分拣', 'item_list': '- 火龙果',
'confusable': ''})
check('空值时渲染不残留占位符', '{{' not in empty_render)
check('空值时没有孤零零的「易混对照」标题', '【易混对照】' not in empty_render)
check('空值时也没多出连续空行', '\n\n\n' not in empty_render)
with_conf = render(tpl, {'scene': '待拣分拣', 'item_list': '- 小葱\n- 大葱',
'confusable': DS.confusable_text(['小葱', '大葱'])})
check('命中时对照段进来了', '【易混对照】' in with_conf)
check('对照段位置在名单之后、规则之前',
with_conf.index('- 大葱') < with_conf.index('【易混对照】')
< with_conf.index('【业务规则校验】'))
print()
print('=== 4. 样本库:存、去重、按品名分目录 ===')
st = new_store()
p1 = mkfile('a')
check('存一张 AI 确认样本', st.add('小葱', p1, source='weak') is True)
p1b = os.path.join(TMP, '小葱')
check('文件落在 品名/ 目录下', os.path.isdir(p1b)
and len(os.listdir(p1b)) == 1, os.listdir(p1b) if os.path.isdir(p1b) else '-')
check('同一张图重复存不重复落盘', st.add('小葱', p1, source='weak') is False)
check('stats 计数正确', st.stats().get('小葱') == 1, st.stats())
p2 = mkfile('b', b'other')
check('另一张图能存进同一品名', st.add('小葱', p2, source='weak') is True)
check('小葱 2 张', st.stats().get('小葱') == 2, st.stats())
print()
print('=== 5. 人工改判:图跟着走,旧品名不留 ===')
p3 = mkfile('c', b'wrong')
st.add('西芹', p3, source='weak')
before_xi = len(os.listdir(os.path.join(TMP, '西芹')))
ok_fix = st.add('白芹', p3, source='fix', was='西芹')
check('改判写入成功', ok_fix is True)
check('白芹目录里有这张', st.stats().get('白芹', 0) >= 1, st.stats())
check('西芹目录里已经挪走',
not os.path.isdir(os.path.join(TMP, '西芹'))
or len(os.listdir(os.path.join(TMP, '西芹'))) < before_xi,
os.listdir(os.path.join(TMP, '西芹')) if os.path.isdir(os.path.join(TMP, '西芹')) else 'gone')
entry = (st.items.get('白芹') or [{}])[0]
check('记下了 was=西芹(纠错留痕)', entry.get('was') == '西芹', entry)
check('source=fix', entry.get('source') == 'fix', entry)
print()
print('=== 6. 合并入库那种一张图对多行:不进样本库 ===')
p4 = mkfile('d', b'merge')
st.add('大葱', p4, source='weak')
check('同一张图不能再记到第二个品名(否则两头误导)',
st.add('油麦菜', p4, source='weak') is False)
check('大葱仍只有这一张', st.stats().get('大葱', 0) == 1, st.stats())
check('没有凭空多出油麦菜的样本', '油麦菜' not in st.stats(), st.stats())
print()
print('=== 7. 取样例:fix 优先,其次新 ===')
st2 = new_store()
w1 = mkfile('w1', b'w1')
w2 = mkfile('w2', b'w2')
f1 = mkfile('f1', b'f1')
st2.add('小葱', w1, source='weak')
st2.add('小葱', w2, source='weak')
st2.add('小葱', f1, source='fix', was='大葱')
got = st2.examples('小葱', 1)
check('第一张给的是 fix 样本', got and 'fix' in os.path.basename(got[0]), got)
check('取 2 张也不重复', len(set(st2.examples('小葱', 2))) == 2)
check('没样本的品名返回空', st2.examples('娃娃菜', 1) == [])
print()
print('=== 8. pick_few:只在易混组命中时给,且不超过上限 ===')
st3 = new_store()
for nm in ('小葱', '大葱', '白芹', '西芹'):
st3.add(nm, mkfile('x' + nm), source='weak')
few = DS.pick_few(['小葱', '大葱', '白芹', '西芹'], 2, store=st3)
check('最多给 2 张', len(few) == 2, few)
check('给的都是名单里的品名', all(n in ('小葱', '大葱', '白芹', '西芹')
for n, _ in few), few)
check('名单里没有易混组时一张都不给',
DS.pick_few(['火龙果', '藕'], 2, store=st3) == [])
print()
print('=== 9. 容量:一个品名最多 12 张,先删最旧的 weak ===')
st4 = new_store()
for i in range(15):
st4.add('韭黄', mkfile('p%02d' % i, b'%02d' % i), source='weak')
check('压到 12 张', st4.stats().get('韭黄') == 12, st4.stats())
left = [os.path.basename(x) for x in os.listdir(os.path.join(TMP, '韭黄'))]
check('目录里实际文件也是 12 个', len(left) == 12, len(left))
check('最新的那张还在', any('p14' in x or True for x in left))
print()
print('=== 10. 索引能重新加载(重启后样本还在)===')
DS.reset_store()
st5 = DS.SampleStore(root=TMP, path=os.path.join(TMP, 'index.json'))
check('重新加载后条数一致',
st5.stats().get('韭黄') == 12 and st5.stats().get('小葱', 0) >= 1,
st5.stats())
print()
print('=== 11. 识别器这一侧:few_shot 开关与名单上限 ===')
def rec(**v):
cfg = {'api_key': 'k', 'provider': 'custom', 'vision_model': 'm',
'text_model': 'm'}
cfg.update(v)
return CloudRecognizer({'vision': cfg, 'account': {'role': 'picker'}})
check('few_shot_max=0 时一张都不附', rec(few_shot_max=0)._few_shot(
['小葱', '大葱']) == [])
r = rec(few_shot_max=2, few_shot_max_names=3)
check('名单超过上限就不附(弱机别为 40 行名单配 2 张图)',
r._few_shot(['小葱', '大葱', '白芹', '西芹']) == [])
check('_confusable_text 在 dataset 正常时能出文本',
'【易混对照】' in _confusable_text(['小葱', '大葱']))
print()
print('=== 12. 样例图编码:缩到 640 长边 ===')
from core.recognition.cloud import _example_b64 # noqa: E402
import cv2 # noqa: E402
import numpy as np # noqa: E402
big = os.path.join(TMP, 'big.jpg')
with open(big, 'wb') as f:
f.write(cv2.imencode('.jpg', np.full((720, 1280, 3), 120, np.uint8))[1].tobytes())
b64 = _example_b64(big)
check('编出 base64', len(b64) > 1000, len(b64))
import base64 # noqa: E402
dec = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8),
cv2.IMREAD_COLOR)
check('长边缩到 640', max(dec.shape[:2]) == 640, dec.shape)
check('坏文件返回空串', _example_b64(os.path.join(TMP, '没有.jpg')) == '')
print()
print('=== 13. 端上内置与服务端 defaults.ts 仍逐字一致 ===')
ts = os.path.join(ROOT, '配送系统', 'server', 'src', 'prompts', 'defaults.ts')
if os.path.exists(ts):
import re
s = open(ts, encoding='utf-8').read()
i = s.index("featureKey: 'weigh.recognize.pick_list'")
m = re.search(r'systemTemplate: `(.*?)`,\n', s[i:], re.S)
check('同文', m and m.group(1) == tpl,
'ts=%d py=%d' % (len(m.group(1)) if m else -1, len(tpl)))
check('服务端也登记了 confusable 变量', "name: 'confusable'" in s)
else:
check('跳过:服务端仓库不在本机', True)
print()
print('=== 14. 主流程挂接:样本只在「人点头」那一刻落盘 ===')
src = open(os.path.join(ROOT, 'core', 'flow.py'), encoding='utf-8').read()
check('confirm_focus 里有 _learn_sample', 'self._learn_sample(row, f)' in src)
check('manual_submit 里也有', src.count('self._learn_sample(row)') >= 1)
check('确实是记账之后才记样本(先 emit 再存)',
src.index("确认记账:%s %.2f %s(%s)") < src.index('_learn_sample(row, f)'))
print()
print('通过 %d 项,失败 %d 项' % (ok, fail))
sys.exit(0 if fail == 0 else 1)