来自 入库分拣工作站_源代码_v1.0.75:点商品名抖动的中间帧修复、ui/osk/tablet 调整、严格入库校验、分拣场景样本(review_queue station=picking);版本/安装包/说明同步 1.0.75。注意:本版 confirm_before_submit 恒 True、submit_on_remove 恒 False,1.0.71 的 inbound_auto_submit 账号开关被移除;models/cls 与 data/ 未入库。EXE 由用户侧打包分发,本次只推源码。
256 lines
11 KiB
Python
256 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""v1.1.0 回归:建议模式(本地给建议 + 98% 采样 + 人工确认留痕)
|
||
|
||
三条设计铁律用断言钉住,改坏了这里就先红:
|
||
|
||
A. **默认关**:config 里没有 vision.assist ⇒ 行为与加入之前逐字节一致。
|
||
B. **98% 只是开关**:本地 ≥98% 就不调云端,但**仍然要人点确认**;
|
||
本地 <98% 或本地没意见 ⇒ 照旧问云端,两边建议一起摊给操作员。
|
||
C. **人是唯一基准**:force_confirm 一开,flow.confirm_before_submit=false
|
||
也强制走确认;云端挂了/答名单外的名字,本地建议顶上,流程不停。
|
||
D. **记录 schema**:图 sha、名单快照、两边建议、最终人工选择、是否改判;
|
||
图对不上就整条丢弃 —— 错标签不报错,只会安静地把训练集喂歪。
|
||
"""
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
|
||
import numpy as np
|
||
import cv2
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from core.flow import FlowEngine
|
||
from core.recognition.assist import Assist, iter_journal
|
||
from core.recognition.local_cls import LocalClassifier, letterbox
|
||
from core.recognition.cloud import RecognitionError
|
||
|
||
ok = fail = 0
|
||
|
||
|
||
def check(name, cond, extra=''):
|
||
global ok, fail
|
||
if cond:
|
||
ok += 1
|
||
print(' ✓', name)
|
||
else:
|
||
fail += 1
|
||
print(' ✗', name, extra)
|
||
|
||
|
||
TMP = tempfile.mkdtemp(prefix='assist_')
|
||
|
||
|
||
def snapshot(tag='a'):
|
||
"""造一张真图:记录里要算 sha/mtime,路径必须在磁盘上真的存在。"""
|
||
p = os.path.join(TMP, 'snap_%s.jpg' % tag)
|
||
cv2.imwrite(p, np.full((72, 160, 3), 90, np.uint8))
|
||
return p
|
||
|
||
|
||
def yolo_of(name, prob, top=None):
|
||
return {'name': name, 'prob': prob,
|
||
'top': top or [[name, prob]],
|
||
'all_top': [[name, prob]],
|
||
'covered': 3, 'ms': 12, 'imgsz': 320}
|
||
|
||
|
||
class FakeRecog:
|
||
def __init__(self, info=None, err=None):
|
||
self.info = dict(info if info is not None else
|
||
{'name': '苹果', 'conf': 88, 'alt': '',
|
||
'alt_conf': None, 'prompt_tag': 'cloud'})
|
||
self.err = err
|
||
self.calls = 0
|
||
|
||
def identify_ex(self, path, names, timeout=None):
|
||
self.calls += 1
|
||
if self.err:
|
||
raise self.err
|
||
return dict(self.info)
|
||
|
||
|
||
def cfg_of(assist=None):
|
||
a = {'enabled': True, 'journal_dir': os.path.join(TMP, 'journal')}
|
||
a.update(assist or {})
|
||
return {'flow': {'recognize_timeout': 8, 'confirm_before_submit': False},
|
||
'vision': {'assist': a},
|
||
'camera': {'simulate': False}}
|
||
|
||
|
||
def engine(cfg, recog=None, yolo=None, img=None):
|
||
e = object.__new__(FlowEngine)
|
||
e.cfg = cfg
|
||
e.assist = Assist(cfg)
|
||
e.recog = recog or FakeRecog()
|
||
e.station = 'loading'
|
||
e._frozen_kg = 2.8
|
||
e._cycle_recog_path = img
|
||
e._focus = None
|
||
e._assist_pending = None
|
||
e._aborted = False
|
||
e._running = True
|
||
e.inbound_auto_submit = True
|
||
e.logs = []
|
||
e.emit = lambda ev, p=None: e.logs.append((ev, p))
|
||
if yolo is not None:
|
||
e.assist.local_suggest = lambda *a, **k: dict(yolo)
|
||
return e
|
||
|
||
|
||
print('A 默认关:不配 vision.assist ⇒ 只问云端,一个字都不多写')
|
||
a0 = Assist({'vision': {}})
|
||
check('默认 enabled=False', a0.enabled is False)
|
||
check('默认 ask_cloud_below=0.98', abs(a0.ask_cloud_below - 0.98) < 1e-9)
|
||
check('连 None 配置都不炸', Assist(None).enabled is False)
|
||
e = object.__new__(FlowEngine)
|
||
e.cfg = {'flow': {'recognize_timeout': 8}, 'vision': {}}
|
||
e.assist = Assist(e.cfg)
|
||
e.recog = FakeRecog()
|
||
e.station = 'loading'
|
||
e._frozen_kg = 1.0
|
||
e._assist_pending = 'stale'
|
||
e.emit = lambda *a, **k: None
|
||
info = e._recognize_cycle(snapshot('a'), ['苹果'])
|
||
check('关着时直接走云端', e.recog.calls == 1 and info.get('name') == '苹果')
|
||
check('关着时不留下建议记录', e._assist_pending is None)
|
||
|
||
print('B 本地 ≥98%:不调云端,但建议照样只是建议')
|
||
img = snapshot('b')
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.991))
|
||
info = e._recognize_cycle(img, ['苹果', '香蕉'])
|
||
rec = e._assist_pending
|
||
check('没调云端', e.recog.calls == 0)
|
||
check('用的是本地名字', info.get('name') == '苹果', repr(info))
|
||
check('conf 换成百分比整数', info.get('conf') == 99, repr(info.get('conf')))
|
||
check('prompt_tag 标成 local', info.get('prompt_tag') == 'local')
|
||
check('记录里云端那格 asked=false',
|
||
rec['cloud']['asked'] is False and rec['cloud']['reason'].startswith('yolo>='),
|
||
repr(rec['cloud']))
|
||
check('记录里 yolo 分数原样保留',
|
||
abs(rec['yolo']['prob'] - 0.991) < 1e-9)
|
||
check('记录里带了名单快照', rec['whitelist'] == ['苹果', '香蕉'], repr(rec['whitelist']))
|
||
check('记录里带了图 sha', len(rec['image_sha']) == 12, rec['image_sha'])
|
||
check('两个引擎都同意也不自动记账(force_confirm)',
|
||
e.assist.enabled and e.confirm_before_submit() is True)
|
||
|
||
print('C 本地 <98% / 本地没意见 ⇒ 照旧问云端')
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.40))
|
||
info = e._recognize_cycle(img, ['苹果'])
|
||
check('低分时调了云端', e.recog.calls == 1)
|
||
check('两边的建议都留在记录里',
|
||
e._assist_pending['yolo']['name'] == '苹果'
|
||
and e._assist_pending['cloud']['name'] == '苹果'
|
||
and e._assist_pending['cloud']['asked'] is True)
|
||
check('阈值可以调:0.30 时同样不调云端',
|
||
engine(cfg_of({'ask_cloud_below': 0.30}),
|
||
yolo=yolo_of('苹果', 0.40))._recognize_cycle(img, ['苹果'])
|
||
is not None)
|
||
e = engine(cfg_of({'ask_cloud_below': 0.30}), yolo=yolo_of('苹果', 0.40))
|
||
e._recognize_cycle(img, ['苹果'])
|
||
check('真的没调云端', e.recog.calls == 0)
|
||
|
||
print('D 云端挂掉 / 答名单外的名字:本地顶上,流程不停')
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.55),
|
||
recog=FakeRecog(err=RecognitionError('超时')))
|
||
info = e._recognize_cycle(img, ['苹果'])
|
||
check('不抛异常', isinstance(info, dict))
|
||
check('返回本地建议(不是空)', info.get('name') == '苹果', repr(info))
|
||
check('云端那格记了 error', 'error' in (e._assist_pending['cloud'] or {}),
|
||
repr(e._assist_pending['cloud']))
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.55),
|
||
recog=FakeRecog(info={'name': '', 'conf': None, 'alt': '',
|
||
'alt_conf': None, 'prompt_tag': 'none'}))
|
||
info = e._recognize_cycle(img, ['苹果'])
|
||
check('云端 NOT_IN_LIST 时用本地预选', info.get('name') == '苹果', repr(info))
|
||
check('云端那格保持空(不拿本地分数冒充)',
|
||
e._assist_pending['cloud']['name'] == ''
|
||
and e._assist_pending['cloud']['conf'] is None)
|
||
|
||
|
||
print('E 人确认后落一条:schema 齐全,改判要能看出来')
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.991))
|
||
e._recognize_cycle(img, ['苹果', '香蕉'])
|
||
e._focus = {'snapshot': img, 'business': 5.0, 'detected': '苹果'}
|
||
e._flush_assist({'id': 1024, 'item_name': '苹果', 'unit': '斤'}, '确认记账')
|
||
rows = list(iter_journal(os.path.join(TMP, 'journal')))
|
||
check('一天一个文件、写了一行', len(rows) == 1, str(len(rows)))
|
||
r = rows[0] if rows else {}
|
||
need = ['v', 'ts', 'cycle', 'station', 'weight_kg', 'image', 'image_sha',
|
||
'image_mtime', 'n_rows', 'whitelist', 'yolo', 'cloud', 'human',
|
||
'final']
|
||
check('顶层字段齐全', all(k in r for k in need), repr(sorted(r)))
|
||
check('称重读数记下来了', abs(float(r.get('weight_kg') or 0) - 2.8) < 1e-6)
|
||
check('人工选的那一行在里面',
|
||
(r.get('human') or {}).get('item_name') == '苹果'
|
||
and str((r.get('human') or {}).get('row_id')) == '1024',
|
||
repr(r.get('human')))
|
||
check('没改判时 changed=false', (r.get('human') or {}).get('changed') is False)
|
||
check('final 带上记账量',
|
||
abs(float((r.get('final') or {}).get('business')) - 5.0) < 1e-6)
|
||
check('_part 这类内部字段没落盘', not any(k.startswith('_') for k in r))
|
||
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.991))
|
||
e._recognize_cycle(img, ['苹果', '香蕉'])
|
||
e._focus = {'snapshot': img, 'business': 3.0}
|
||
e._flush_assist({'id': 7, 'item_name': '红富士苹果'}, '确认记账')
|
||
rows = list(iter_journal(os.path.join(TMP, 'journal')))
|
||
r2 = rows[-1] if rows else {}
|
||
check('人工改判 ⇒ changed=true', (r2.get('human') or {}).get('changed') is True,
|
||
repr(r2.get('human')))
|
||
check('改判后的名字就是训练标签',
|
||
(r2.get('human') or {}).get('item_name') == '红富士苹果')
|
||
|
||
print('F 图对不上 ⇒ 整条丢掉(错标签比没标签坏)')
|
||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.991))
|
||
e._recognize_cycle(img, ['苹果'])
|
||
other = snapshot('other')
|
||
e._focus = {'snapshot': other, 'business': 1.0}
|
||
before = len(list(iter_journal(os.path.join(TMP, 'journal'))))
|
||
e._flush_assist({'id': 9, 'item_name': '苹果'}, '确认记账')
|
||
after = len(list(iter_journal(os.path.join(TMP, 'journal'))))
|
||
check('没有多写一行', after == before, '%d -> %d' % (before, after))
|
||
check('待用记录已清空', e._assist_pending is None)
|
||
check('日志里说了为什么丢', any('对不上' in str(p) for _, p in e.logs),
|
||
str(e.logs[-3:]))
|
||
|
||
print('G 本地分类器:没模型 = 没意见,绝不抛异常')
|
||
lc = LocalClassifier({'assist': {'model': 'no/such.onnx',
|
||
'classes': 'no/such.json'}})
|
||
check('available() 为假', lc.available() is False)
|
||
check('reason() 说得出原因', bool(lc.reason()))
|
||
check('predict 返回空 dict', lc.predict(img, ['苹果']) == {})
|
||
check('空路径直接返回空', lc.predict('', ['苹果']) == {})
|
||
a = Assist(cfg_of({'model': 'no/such.onnx', 'classes': 'no/such.json'}))
|
||
check('建议模式里 local_suggest 同样返回 None',
|
||
a.local_suggest(img, ['苹果']) is None)
|
||
|
||
# 装到中文目录(D:\嵌入式识别\... / 入库分拣工作台\...)时,cv2.dnn 用「路径」
|
||
# 读 onnx 会直接报 Can't read ONNX file;必须是读字节再喂。这条断言防回退。
|
||
_lc_src = open(os.path.join('core', 'recognition', 'local_cls.py'),
|
||
encoding='utf-8').read()
|
||
check('onnx 走字节缓冲读取(中文路径也能加载)',
|
||
'readNetFromONNX(buf)' in _lc_src)
|
||
|
||
# ultralytics 训分类的预处理是 Resize→CenterCrop→ToTensor→Normalize(0,1),
|
||
# Normalize 那步等于空操作,也就是**只有 /255**。端上如果再多减一组 ImageNet
|
||
# 的 mean/std,输入分布就和训练时差一截:实测 123 张测试图,减 mean/std 时
|
||
# cv2.dnn 只对 13 张(10.6%),只做 /255 时和 torch 123/123 一致。
|
||
# 这类错不报错、只静默掉准确率,必须用断言锁住。
|
||
check('前处理只做 /255,没有多余的 ImageNet 归一化',
|
||
'0.485' not in _lc_src and '0.229' not in _lc_src)
|
||
check('前处理确实是 BGR→RGB + /255', '/ 255.0' in _lc_src)
|
||
|
||
print('H letterbox:只加边不丢内容(训练/推理共用同一口径)')
|
||
src = np.full((72, 160, 3), 200, np.uint8)
|
||
out = letterbox(src, 320)
|
||
check('输出是 320×320×3', out.shape == (320, 320, 3), str(out.shape))
|
||
check('左上角是补的灰 114', int(out[0, 0, 0]) == 114)
|
||
check('中间还是原图(200)', int(out[160, 160, 0]) == 200)
|
||
check('等比:宽占满、高补边', int(out[160, 2, 0]) == 200)
|
||
|
||
print()
|
||
print('通过 %d,失败 %d' % (ok, fail))
|
||
sys.exit(1 if fail else 0)
|