Files
windows-fenjian/tools/_test_v1080_assist.py
T
Ubuntu 5d4f2d1ba3 feat(1.0.76): 识别记录留档(本地 YOLO + 云端)
来自 秤端源码-v1.0.76:flow 生成 recognition_audit(本地候选/耗时 + 云端结果)并随 review_queue 送审;assist/local_cls 记录本地推理;审核后台可查;版本/安装包 1.0.76。保留 1.0.71-1.0.75 既有修复与文档;config.json/data/models 未入库。
2026-12-03 17:05:19 +08:00

171 lines
6.5 KiB
Python
Raw 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 -*-
"""本地后台留档、云端独立返回和本地模型兼容性回归。"""
import os
import sys
import tempfile
import threading
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
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.predict = lambda *a, **k: dict(yolo)
return e
img = snapshot('parallel')
started = threading.Event()
release = threading.Event()
def blocked_local(*args, **kwargs):
started.set()
if not release.wait(3):
raise RuntimeError('等待测试释放')
return yolo_of('香蕉', 0.999)
e = engine(cfg_of())
e.assist.local.predict = blocked_local
original_cloud = e.recog.identify_ex
def cloud_while_local_runs(*args, **kwargs):
check('云端调用时本地已经开始', started.wait(2))
return original_cloud(*args, **kwargs)
e.recog.identify_ex = cloud_while_local_runs
answer = e._recognize_cycle(img, ['苹果', '香蕉'])
first = e._assist_pending
try:
check('本地未完成,云端仍已返回', not first['local'].done() and answer['name'] == '苹果')
check('下一件不会积压本地推理', e._recognize_cycle(img, ['苹果'])['name'] == '苹果'
and e._assist_pending['local'].result(2)['status'] == 'busy')
finally:
release.set()
check('后台留档保留不同的本地结果', first['local'].result(2)['name'] == '香蕉')
check('云端正常记录', first['cloud']['status'] == 'recognized')
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(err=RecognitionError('failed')))
try:
e._recognize_cycle(img, ['苹果'])
except RecognitionError:
check('云端失败保留原有人工处理路径', e._assist_pending['cloud']['status'] == 'unavailable')
else:
check('云端失败不以本地结果代替', False)
check('本地高分也没有跳过云端', e.recog.calls == 1)
check('人工确认仍为必需', e.confirm_before_submit())
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(info={'name': ''}))
check('云端未命中时不回退到本地', not e._recognize_cycle(img, ['苹果']).get('name'))
check('云端未命中有独立状态', e._assist_pending['cloud']['status'] == 'no_match')
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)