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 未入库。
This commit is contained in:
Ubuntu
2026-12-03 17:05:19 +08:00
parent 4966345424
commit 5d4f2d1ba3
11 changed files with 194 additions and 280 deletions
+3 -3
View File
@@ -1,16 +1,16 @@
VSVersionInfo( VSVersionInfo(
ffi=FixedFileInfo(filevers=(1, 0, 75, 0), prodvers=(1, 0, 75, 0), ffi=FixedFileInfo(filevers=(1, 0, 76, 0), prodvers=(1, 0, 76, 0),
mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1,
subtype=0x0, date=(0, 0)), subtype=0x0, date=(0, 0)),
kids=[ kids=[
StringFileInfo([StringTable('080404B0', [ StringFileInfo([StringTable('080404B0', [
StringStruct('CompanyName', '配送中心'), StringStruct('CompanyName', '配送中心'),
StringStruct('FileDescription', '入库分拣工作站'), StringStruct('FileDescription', '入库分拣工作站'),
StringStruct('FileVersion', '1.0.75.0'), StringStruct('FileVersion', '1.0.76.0'),
StringStruct('InternalName', 'WeighStation'), StringStruct('InternalName', 'WeighStation'),
StringStruct('OriginalFilename', '入库分拣工作站.exe'), StringStruct('OriginalFilename', '入库分拣工作站.exe'),
StringStruct('ProductName', '入库分拣工作站'), StringStruct('ProductName', '入库分拣工作站'),
StringStruct('ProductVersion', '1.0.75.0'), StringStruct('ProductVersion', '1.0.76.0'),
StringStruct('LegalCopyright', '内部使用')])]), StringStruct('LegalCopyright', '内部使用')])]),
VarFileInfo([VarStruct('Translation', [2052, 1200])]) VarFileInfo([VarStruct('Translation', [2052, 1200])])
] ]
+1 -1
View File
@@ -20,7 +20,7 @@ import sys
ROOT = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.abspath(__file__))
APP_NAME = '入库分拣工作站' APP_NAME = '入库分拣工作站'
APP_VERSION = '1.0.75' APP_VERSION = '1.0.76'
ASSETS = os.path.join(ROOT, 'assets') ASSETS = os.path.join(ROOT, 'assets')
DIST = os.path.join(ROOT, 'dist') DIST = os.path.join(ROOT, 'dist')
OUT = os.path.join(DIST, APP_NAME) OUT = os.path.join(DIST, APP_NAME)
+31 -138
View File
@@ -1048,53 +1048,29 @@ class FlowEngine:
return max(float(self.cfg['flow'].get('recognize_timeout', 8)), 15.0) return max(float(self.cfg['flow'].get('recognize_timeout', 8)), 15.0)
def _recognize_cycle(self, path, names, crop=None): def _recognize_cycle(self, path, names, crop=None):
"""本轮识别:本地先给建议,够不着 98% 才额外问一次云端(v1.1.0)。 """同一张抓拍交给两种模型,操作流程只消费云端结果。"""
audit = {
返回值与 identify_ex 同形状,所以 `_run_recognition` 后面的全部分支 'image': path,
一行都不用改。四条出口(都是「建议」,都不记账): 'local': self.assist.record_local(path, names, crop=crop),
'cloud': None,
1. 本地 ≥98% → 这次不问云端,但**仍然要人点确认**; }
2. 本地 <98% / 本地没意见 → 照旧问云端,两边都摊给操作员; self._assist_pending = audit
3. 云端没给出名单内的名字(NOT_IN_LIST / 超时 / 离线)→ 本地建议 started = time.monotonic()
顶上做预选,人不同意点别的行就是了;
4. 两边都没有 → 回到人工确认页,和加入建议模式之前一模一样。
"""
a = getattr(self, 'assist', None)
if a is None or not a.enabled:
self._assist_pending = None
return self.recog.identify_ex(path, names,
timeout=self._recog_timeout())
said = a.explain_once()
if said:
self.emit('log', DEV + said)
y = a.local_suggest(path, names, crop=crop)
rec = a.begin(station=self.station, weight_kg=self._frozen_kg,
image=path, names=names)
rec['yolo'] = y or None
self._assist_pending = rec
if y and not a.ask_cloud(y):
# 出口 1:本地够 98%,这次不问云端 —— 省下的那一次调用就是
# 「98% 开关」的全部含义,跟「准不准」没有关系。
rec['cloud'] = a.skip_cloud('yolo>=%.0f%%'
% (a.ask_cloud_below * 100))
return a.local_info(y)
try: try:
info = self.recog.identify_ex(path, names, result = self.recog.identify_ex(path, names, timeout=self._recog_timeout(),
timeout=self._recog_timeout()) **({'crop': crop} if crop is not None else {}))
except RecognitionError as e: except RecognitionError:
# 出口 3(异常版):云端挂了也不能停摆,本地建议照样带下去 audit['cloud'] = {
rec['cloud'] = a.cloud_slot(error=str(e) or '识别失败') 'status': 'unavailable', 'ms': round((time.monotonic() - started) * 1000),
if y and y.get('name'): }
return a.local_info(y)
raise raise
rec['cloud'] = a.cloud_slot(info=info) audit['cloud'] = {
if not info.get('name') and y and y.get('name'): 'status': 'recognized' if result.get('name') else 'no_match',
# 出口 3:云端答了但名单里没有这个货 —— 本地建议顶上做预选, 'name': result.get('name') or '',
# 云端那一格保持空(不拿本地的分数冒充云端分数)。 'conf': result.get('conf'),
self.emit('log', '云端没给出名单内的名字,先按本地建议「%s」预选,' 'ms': round((time.monotonic() - started) * 1000),
'请核对' % y['name']) }
return a.local_info(y) return result
return info
def _run_recognition(self): def _run_recognition(self):
self._assist_pending = None # 新一件:上一件的建议记录作废 self._assist_pending = None # 新一件:上一件的建议记录作废
@@ -1144,7 +1120,6 @@ class FlowEngine:
if str(info_prompt_tag) not in ('', '-', 'None'): if str(info_prompt_tag) not in ('', '-', 'None'):
self.emit('log', DEV + '本轮提示词标记:%s%s' self.emit('log', DEV + '本轮提示词标记:%s%s'
% (info_prompt_tag, _prep_note(info))) % (info_prompt_tag, _prep_note(info)))
self._emit_assist_hint()
self._cycle_conf = conf # 闸门(同类商品豁免)要用本轮把握 self._cycle_conf = conf # 闸门(同类商品豁免)要用本轮把握
self._cycle_detected = detected or '' self._cycle_detected = detected or ''
self._cycle_alt = alt or '' self._cycle_alt = alt or ''
@@ -1958,53 +1933,6 @@ class FlowEngine:
self.emit('log', msg) self.emit('log', msg)
return q return q
def _emit_assist_hint(self):
"""建议模式:把两个引擎的意见并排写进日志(v1.1.0)。
界面这一版只预选一行(人点别的行就是改判),没有并排展示的位置;
日志是操作员能看到的唯一「两边各说了什么」,出问题时也靠它复盘。
没有本地建议、或云端这轮没被调用时,`_recognize_cycle` 已经单独
写过一行,这里不重复。
"""
rec = getattr(self, '_assist_pending', None)
if not rec:
return
y = rec.get('yolo') or {}
c = rec.get('cloud') or {}
if not y.get('name') or not c.get('asked') or c.get('error'):
return
self.emit('log', '两边建议:本地「%s」%d%%|云端「%s」%s'
% (y.get('name'), int(round(float(y.get('prob') or 0) * 100)),
c.get('name') or '未给出',
'未知' if c.get('conf') is None else '%d%%' % c['conf']))
def _flush_assist(self, row, source=''):
"""人确认了:把这一件的建议记录补上最终选择再落盘(v1.1.0 留痕)。
为什么挂在 `_start_submit`:无论走「确认记账」按钮、拿走货自动提交,
还是合并入库的多行,最终要记账的那一行都得经过这里 —— 一个出口,
不会漏记,也不会被某条分支绕过去。
为什么图对不上就整条丢掉:宁可少一条样本,也不能把 A 的抓拍配到
B 的账上 —— 错标签不报错,只会安静地把训练集喂歪。
"""
a = getattr(self, 'assist', None)
rec = getattr(self, '_assist_pending', None)
if a is None or not a.enabled or not rec:
return
snap = (getattr(self, '_focus', None) or {}).get('snapshot') \
or getattr(self, '_cycle_recog_path', None)
if not a.same_image(rec, snap):
self._assist_pending = None
self.emit('log', DEV + '建议记录丢弃:抓拍图与本次称重对不上')
return
path = a.finish(rec, row, focus=self._focus, source=source)
if path:
self.emit('log', DEV + '建议记录已写入 %s(人工%s)'
% (os.path.basename(path),
'改判' if (rec.get('human') or {}).get('changed')
else '确认'))
def _start_submit(self, row, business, source): def _start_submit(self, row, business, source):
if self._aborted or not self._running: if self._aborted or not self._running:
self.emit('log', '本件已作废,不再提交') self.emit('log', '本件已作废,不再提交')
@@ -2015,7 +1943,6 @@ class FlowEngine:
self.emit('result', (False, '存在待核实提交,已锁定新提交')) self.emit('result', (False, '存在待核实提交,已锁定新提交'))
self._set_state('DONE') self._set_state('DONE')
return return
self._flush_assist(row, source)
business = self._real_business(row, business) business = self._real_business(row, business)
self._frozen_row = row self._frozen_row = row
self._set_state('SUBMIT') self._set_state('SUBMIT')
@@ -2860,8 +2787,15 @@ class FlowEngine:
if camera.get('simulate') or camera.get('replay_dir'): if camera.get('simulate') or camera.get('replay_dir'):
return True # 演示/回放:没有真实原图 return True # 演示/回放:没有真实原图
try: try:
audit = getattr(self, '_assist_pending', None)
recognition_image = getattr(self, '_cycle_recog_path', None)
if audit and audit['image'] == recognition_image and os.path.isfile(recognition_image):
# 审核页展示模型实际看到的图。业务归档仍用确认帧。
path, captured_at = recognition_image, None
else:
audit = None
error = ReviewQueue().stage(self.api, op, row, source, path, station=self.station, error = ReviewQueue().stage(self.api, op, row, source, path, station=self.station,
captured_at=captured_at) captured_at=captured_at, audit=audit)
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
self.journal.conclude(op, STATE_REJECTED, '送审队列写入失败') self.journal.conclude(op, STATE_REJECTED, '送审队列写入失败')
self.emit('log', '本机无法保存本笔送审记录(%s),本次未发送' % exc) self.emit('log', '本机无法保存本笔送审记录(%s),本次未发送' % exc)
@@ -3423,47 +3357,6 @@ class FlowEngine:
} }
# 建议模式:把两个引擎的建议一起交给界面(本地预选、云端并列显示)。 # 建议模式:把两个引擎的建议一起交给界面(本地预选、云端并列显示)。
# 界面不认这个键也不影响任何记账逻辑 —— 它只是给人看的一份「意见」。 # 界面不认这个键也不影响任何记账逻辑 —— 它只是给人看的一份「意见」。
_a = getattr(self, 'assist', None)
_p = getattr(self, '_assist_pending', None)
if (_a is not None and _p
and _a.same_image(_p, self._cycle_recog_path)):
self._focus['assist'] = {'yolo': _p.get('yolo'),
'cloud': _p.get('cloud')}
if row:
self._frozen_row = row
if mode == 'count':
self._count_mode = True
self._count_qty = float(business or 0.0)
# 进免称重就把秤上的真实读数抄下来:标签要按实际重量印,
# 同时把上一件的残留值清掉(否则货没上秤也会印上一件的数)
self._count_real_kg = self._snap_scale_kg()
# v1.0.55:秤上有货就按实际重量记账 —— 界面显示、提交量、
# 标签、台账从现在起是同一个数,不再出现「显示 5.00 斤、
# 实际称到 5.62 斤」两套数字
if row is not None:
asked = float(business or 0.0)
real_q = self._real_business(row, business, quiet=True)
if abs(real_q - asked) > 0.005:
business = real_q
self._focus['business'] = real_q
self._focus['from_scale'] = True
self.emit('log', '按秤上实际重量记账:%.2f %s'
'(「%s」该行应 %.2f %s)'
% (real_q, row.get('unit') or '',
row.get('item_name') or '', asked,
row.get('unit') or ''))
else:
self._count_mode = False
self._set_state('CONFIRM')
# 确认期间重量变化只更新待确认数量;标签在确认提交成功后统一排队。
self._confirm_seen_present = False
self._confirm_absent_at = 0.0
# v1.0.62:确认期间的重量跟踪从「抓拍那刻的冻结值」起步 ——
# 后面货有增减(补一把/抓走一点)会跟到新的稳定值
self._confirm_live_kg = None
self._confirm_move_at = 0.0
self._confirm_settled_kg = float(self._frozen_kg or 0.0)
self._confirm_gone_at = 0.0
self.emit('focus', self._focus_payload()) self.emit('focus', self._focus_payload())
def pick_focus(self, rid): def pick_focus(self, rid):
@@ -4227,6 +4120,7 @@ class FlowEngine:
self._run_count_recognition() self._run_count_recognition()
def _run_count_recognition(self): def _run_count_recognition(self):
self._assist_pending = None
rows = self.noweigh_rows() rows = self.noweigh_rows()
names = sorted({r.get('item_name') for r in rows if r.get('item_name')}) names = sorted({r.get('item_name') for r in rows if r.get('item_name')})
detected = None detected = None
@@ -4241,8 +4135,7 @@ class FlowEngine:
try: try:
# 免称重是手举着袋子/整筐抓拍,货可能占满画面,四周裁太多 # 免称重是手举着袋子/整筐抓拍,货可能占满画面,四周裁太多
# 会把袋口和货切掉;这里只削一点点边(默认保留 96%)。 # 会把袋口和货切掉;这里只削一点点边(默认保留 96%)。
# 建议模式(v1.1.0)下走同一条路:本地先给建议,够不着阈值 # 同一份抓拍交给两种模型,云端结果进入操作流程。
# 才问云端;crop 透传给本地模型,两边看到的是同一张图。
info = self._recognize_cycle( info = self._recognize_cycle(
self._cycle_recog_path, names, self._cycle_recog_path, names,
crop=float(self.cfg['vision'].get('recog_crop_noweigh', crop=float(self.cfg['vision'].get('recog_crop_noweigh',
+37
View File
@@ -39,6 +39,8 @@
· yolo.prob + human.changed = 日后标定 ask_cloud_below 的依据 · yolo.prob + human.changed = 日后标定 ask_cloud_below 的依据
· 两边一致但 human.changed 的比例 = 未来免确认的错误率底线 · 两边一致但 human.changed 的比例 = 未来免确认的错误率底线
""" """
from concurrent.futures import Future
import threading
import os import os
import json import json
import time import time
@@ -92,6 +94,7 @@ class Assist:
self.cfg = dict(DEFAULTS) self.cfg = dict(DEFAULTS)
if isinstance(raw, dict): if isinstance(raw, dict):
self.cfg.update(raw) self.cfg.update(raw)
self._recording_slot = threading.Lock()
self.enabled = bool(self.cfg.get('enabled')) self.enabled = bool(self.cfg.get('enabled'))
try: try:
self.ask_cloud_below = float(self.cfg.get('ask_cloud_below', 0.98)) self.ask_cloud_below = float(self.cfg.get('ask_cloud_below', 0.98))
@@ -125,6 +128,40 @@ class Assist:
y = self.local.predict(path, names, crop=crop) y = self.local.predict(path, names, crop=crop)
return y or None return y or None
def record_local(self, path, names, crop=None):
"""后台取样。上一张还在跑时跳过本地记录,避免积压。"""
result = Future()
if not self._recording_slot.acquire(blocking=False):
result.set_result({'status': 'busy'})
return result
def work():
started = time.monotonic()
try:
model = self.local
prediction = model.predict(path, names, crop=crop)
record = {
'status': 'recognized' if prediction else 'unavailable',
'version': getattr(model, 'loaded_version', '') or None,
'name': (prediction or {}).get('name') or '',
'confidence': (prediction or {}).get('prob'),
'candidates': (prediction or {}).get('all_top', [])[:3],
'ms': round((time.monotonic() - started) * 1000),
}
except Exception:
record = {'status': 'unavailable'}
finally:
self._recording_slot.release()
result.set_result(record)
thread = threading.Thread(target=work, name='yolo-record', daemon=True)
try:
thread.start()
except RuntimeError:
self._recording_slot.release()
result.set_result({'status': 'unavailable'})
return result
def ask_cloud(self, y): def ask_cloud(self, y):
"""要不要额外调一次云端。**只是采样开关**,不是可信度判断。 """要不要额外调一次云端。**只是采样开关**,不是可信度判断。
+18 -3
View File
@@ -39,6 +39,7 @@
OpenCV 4.x 的 dnn 足够跑。 OpenCV 4.x 的 dnn 足够跑。
""" """
import os import os
import hashlib
import json import json
import time import time
@@ -118,6 +119,7 @@ class LocalClassifier:
self._net = None self._net = None
self._err = '' # 加载失败原因:只报一次,别每单刷一条日志 self._err = '' # 加载失败原因:只报一次,别每单刷一条日志
self._tried = False self._tried = False
self.loaded_version = None
# ------------------------------------------------------------ 加载 # ------------------------------------------------------------ 加载
def _load(self): def _load(self):
@@ -125,8 +127,9 @@ class LocalClassifier:
return self._net is not None return self._net is not None
self._tried = True self._tried = True
try: try:
with open(self.classes_path, 'r', encoding='utf-8') as f: with open(self.classes_path, 'rb') as f:
meta = json.load(f) classes_bytes = f.read()
meta = json.loads(classes_bytes)
if isinstance(meta, dict): if isinstance(meta, dict):
names = meta.get('names') or meta.get('classes') or [] names = meta.get('names') or meta.get('classes') or []
if meta.get('imgsz'): if meta.get('imgsz'):
@@ -145,15 +148,27 @@ class LocalClassifier:
# 下会直接报 "Can't read ONNX file"(和 cv2.imread 同一个坑, # 下会直接报 "Can't read ONNX file"(和 cv2.imread 同一个坑,
# prep.read_image 那边已经绕过一次)。现场实测:同一份 onnx, # prep.read_image 那边已经绕过一次)。现场实测:同一份 onnx,
# ASCII 路径能读、中文路径报错、字节缓冲两边都能读。 # ASCII 路径能读、中文路径报错、字节缓冲两边都能读。
buf = np.fromfile(self.model_path, dtype=np.uint8)
try: try:
buf = np.fromfile(self.model_path, dtype=np.uint8)
net = cv2.dnn.readNetFromONNX(buf) net = cv2.dnn.readNetFromONNX(buf)
except Exception: # noqa: BLE001 老版本没有这个重载 except Exception: # noqa: BLE001 老版本没有这个重载
net = cv2.dnn.readNetFromONNX(self.model_path) net = cv2.dnn.readNetFromONNX(self.model_path)
buf = None # 此路径没有拿到实际加载的字节
try: try:
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
except Exception: # noqa: BLE001 老版本没这项 except Exception: # noqa: BLE001 老版本没这项
pass pass
try:
manifest_path = os.path.join(os.path.dirname(self.model_path), 'model.json')
with open(manifest_path, encoding='utf-8') as f:
manifest = json.load(f)
files = manifest['files']
if (buf is not None
and hashlib.sha256(buf).hexdigest() == files['product_cls.onnx']['sha256']
and hashlib.sha256(classes_bytes).hexdigest() == files['classes.json']['sha256']):
self.loaded_version = manifest.get('version')
except (OSError, ValueError, AttributeError, KeyError, TypeError):
pass
self._net = net self._net = net
return True return True
except Exception as e: # noqa: BLE001 任何错都当没模型 except Exception as e: # noqa: BLE001 任何错都当没模型
+41 -5
View File
@@ -25,6 +25,7 @@
data/review_rejected.json 永久失败(数据本身有问题)的清单,交人工 data/review_rejected.json 永久失败(数据本身有问题)的清单,交人工
""" """
import hashlib import hashlib
import json
import os import os
import re import re
import tempfile import tempfile
@@ -117,7 +118,7 @@ class ReviewQueue:
return [] return []
# ------------------------------------------------ 登记 # ------------------------------------------------ 登记
def stage(self, api, op, row, source, path, captured_at=None, station="inspection"): def stage(self, api, op, row, source, path, captured_at=None, station="inspection", audit=None):
"""入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。 """入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。
写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理: 写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理:
@@ -135,7 +136,7 @@ class ReviewQueue:
with tempfile.TemporaryDirectory(prefix='.stage-', dir=self.root) as temp: with tempfile.TemporaryDirectory(prefix='.stage-', dir=self.root) as temp:
work = os.path.join(temp, 'record') work = os.path.join(temp, 'record')
os.mkdir(work) os.mkdir(work)
error = self._write_stage(work, api, op, row, source, path, captured_at, station) error = self._write_stage(work, api, op, row, source, path, captured_at, station, audit)
try: try:
os.rename(work, d) os.rename(work, d)
except OSError: except OSError:
@@ -143,9 +144,33 @@ class ReviewQueue:
if not existing: if not existing:
raise raise
return existing.get('error') or '' return existing.get('error') or ''
if audit:
audit['local'].add_done_callback(
lambda future: self._save_local_audit(d, future))
return error return error
def _write_stage(self, d, api, op, row, source, path, captured_at, station): @staticmethod
def _save_local_audit(directory, future):
# 写结果落在现有队列目录中。若上传或作废已删除目录,不再创建。
try:
with tempfile.NamedTemporaryFile(dir=directory, delete=False, mode='w',
encoding='utf-8') as f:
temp_path = f.name
try:
json.dump(future.result(), f, ensure_ascii=False, allow_nan=False)
f.flush()
os.fsync(f.fileno())
finally:
f.close()
os.replace(temp_path, os.path.join(directory, 'local_result.json'))
except Exception:
if 'temp_path' in locals():
try:
os.unlink(temp_path)
except OSError:
pass
def _write_stage(self, d, api, op, row, source, path, captured_at, station, audit):
blob, error = b'', '' blob, error = b'', ''
try: try:
with open(path, 'rb') as f: with open(path, 'rb') as f:
@@ -182,6 +207,8 @@ class ReviewQueue:
'tries': 0, 'tries': 0,
'staged_at': time.strftime('%Y-%m-%d %H:%M:%S'), 'staged_at': time.strftime('%Y-%m-%d %H:%M:%S'),
} }
if audit:
meta['audit'] = {'cloud': audit['cloud'], 'deadline': time.time() + 25}
if not atomic.write_json(os.path.join(d, 'meta.json'), meta): if not atomic.write_json(os.path.join(d, 'meta.json'), meta):
shutil.rmtree(d, ignore_errors=True) shutil.rmtree(d, ignore_errors=True)
raise OSError('送审队列写入失败:%s' % d) raise OSError('送审队列写入失败:%s' % d)
@@ -235,8 +262,17 @@ class ReviewQueue:
self._say(log, '本笔没有可送审的原图,已转人工:%s' % op) self._say(log, '本笔没有可送审的原图,已转人工:%s' % op)
continue continue
try: try:
ack = api.upload_review_sample(dict(meta.get('fields') or {}), fields = dict(meta.get('fields') or {})
photo) audit = meta.get('audit')
if audit:
local = atomic.read_json(os.path.join(self._dir(op), 'local_result.json'))
if not local and now < float(audit['deadline']):
continue
fields['recognition_audit'] = json.dumps({
'local': local or {'status': 'unfinished'},
'cloud': audit.get('cloud') or {'status': 'unavailable'},
}, ensure_ascii=False, allow_nan=False)
ack = api.upload_review_sample(fields, photo)
problem = self._ack_problem(meta, ack) problem = self._ack_problem(meta, ack)
if problem: if problem:
raise ValueError(problem) raise ValueError(problem)
+3 -3
View File
@@ -1,12 +1,12 @@
; ============================================================ ; ============================================================
; 入库分拣工作站 · 安装包脚本(Inno Setup 6) ; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.75.exe ; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.76.exe
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir) ; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
; ============================================================ ; ============================================================
#define AppName "入库分拣工作站" #define AppName "入库分拣工作站"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "1.0.75" #define AppVersion "1.0.76"
#endif #endif
#define AppExe "入库分拣工作站.exe" #define AppExe "入库分拣工作站.exe"
#define SrcDir "dist\入库分拣工作站" #define SrcDir "dist\入库分拣工作站"
@@ -41,7 +41,7 @@ CloseApplications=yes
RestartApplications=no RestartApplications=no
AllowNoIcons=yes AllowNoIcons=yes
ShowLanguageDialog=no ShowLanguageDialog=no
VersionInfoVersion=1.0.75.0 VersionInfoVersion=1.0.76.0
VersionInfoDescription={#AppName} 安装程序 VersionInfoDescription={#AppName} 安装程序
VersionInfoProductName={#AppName} VersionInfoProductName={#AppName}
+14
View File
@@ -6,6 +6,8 @@
2. 入库成功但当场断电/断网 → 重启后照样送,且只送一次; 2. 入库成功但当场断电/断网 → 重启后照样送,且只送一次;
3. 数据本身有问题(4xx)→ 转人工,别无限刷日志。 3. 数据本身有问题(4xx)→ 转人工,别无限刷日志。
""" """
from concurrent.futures import Future
import json
import io import io
import os import os
import shutil import shutil
@@ -218,6 +220,18 @@ check('分拣成功只送审一次,并关联正确明细',
len(sent) == 1 and sent[0]['scene'] == 'picking' len(sent) == 1 and sent[0]['scene'] == 'picking'
and sent[0]['business_item_id'] == ROW['id']) and sent[0]['business_item_id'] == ROW['id'])
pending = Future()
audit = {'local': pending, 'cloud': {'status': 'recognized', 'name': '芹菜'}}
qp.stage(api, 'op-audit', ROW, '人工', photo(root, 'audit.jpg'), audit=audit)
journal('op-audit', J.STATE_SUCCEEDED)
qp.drain(api, say)
check('记账成功时本地还在算,只让后台队列等', 'op-audit' in ops())
pending.set_result({'status': 'recognized', 'name': '小葱'})
qp.drain(api, say)
reports = [json.loads(f['recognition_audit']) for f, _ in api.sent if f['event_id'] == 'op-audit']
check('同一笔上传两边的结果', len(reports) == 1 and reports[0]['local']['name'] == '小葱'
and reports[0]['cloud']['name'] == '芹菜')
shutil.rmtree(root, ignore_errors=True) shutil.rmtree(root, ignore_errors=True)
print() print()
if fails: if fails:
+41 -126
View File
@@ -1,19 +1,9 @@
# -*- coding: utf-8 -*- # -*- 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 os
import sys import sys
import tempfile import tempfile
import threading
import numpy as np import numpy as np
import cv2 import cv2
@@ -22,7 +12,7 @@ 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__)))) os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.flow import FlowEngine from core.flow import FlowEngine
from core.recognition.assist import Assist, iter_journal from core.recognition.assist import Assist
from core.recognition.local_cls import LocalClassifier, letterbox from core.recognition.local_cls import LocalClassifier, letterbox
from core.recognition.cloud import RecognitionError from core.recognition.cloud import RecognitionError
@@ -95,125 +85,50 @@ def engine(cfg, recog=None, yolo=None, img=None):
e.logs = [] e.logs = []
e.emit = lambda ev, p=None: e.logs.append((ev, p)) e.emit = lambda ev, p=None: e.logs.append((ev, p))
if yolo is not None: if yolo is not None:
e.assist.local_suggest = lambda *a, **k: dict(yolo) e.assist.local.predict = lambda *a, **k: dict(yolo)
return e return e
print('A 默认关:不配 vision.assist ⇒ 只问云端,一个字都不多写') img = snapshot('parallel')
a0 = Assist({'vision': {}}) started = threading.Event()
check('默认 enabled=False', a0.enabled is False) release = threading.Event()
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%:不调云端,但建议照样只是建议') def blocked_local(*args, **kwargs):
img = snapshot('b') started.set()
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.991)) if not release.wait(3):
info = e._recognize_cycle(img, ['苹果', '香蕉']) raise RuntimeError('等待测试释放')
rec = e._assist_pending return yolo_of('香蕉', 0.999)
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())
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.40)) e.assist.local.predict = blocked_local
info = e._recognize_cycle(img, ['苹果']) original_cloud = e.recog.identify_ex
check('低分时调了云端', e.recog.calls == 1) def cloud_while_local_runs(*args, **kwargs):
check('两边的建议都留在记录里', check('云端调用时本地已经开始', started.wait(2))
e._assist_pending['yolo']['name'] == '苹果' return original_cloud(*args, **kwargs)
and e._assist_pending['cloud']['name'] == '苹果' e.recog.identify_ex = cloud_while_local_runs
and e._assist_pending['cloud']['asked'] is True) answer = e._recognize_cycle(img, ['苹果', '香蕉'])
check('阈值可以调:0.30 时同样不调云端', first = e._assist_pending
engine(cfg_of({'ask_cloud_below': 0.30}), try:
yolo=yolo_of('苹果', 0.40))._recognize_cycle(img, ['苹果']) check('本地未完成,云端仍已返回', not first['local'].done() and answer['name'] == '苹果')
is not None) check('下一件不会积压本地推理', e._recognize_cycle(img, ['苹果'])['name'] == '苹果'
e = engine(cfg_of({'ask_cloud_below': 0.30}), yolo=yolo_of('苹果', 0.40)) and e._assist_pending['local'].result(2)['status'] == 'busy')
e._recognize_cycle(img, ['苹果']) finally:
check('真的没调云端', e.recog.calls == 0) release.set()
check('后台留档保留不同的本地结果', first['local'].result(2)['name'] == '香蕉')
check('云端正常记录', first['cloud']['status'] == 'recognized')
print('D 云端挂掉 / 答名单外的名字:本地顶上,流程不停') e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(err=RecognitionError('failed')))
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.55), try:
recog=FakeRecog(err=RecognitionError('超时'))) e._recognize_cycle(img, ['苹果'])
info = e._recognize_cycle(img, ['苹果']) except RecognitionError:
check('不抛异常', isinstance(info, dict)) check('云端失败保留原有人工处理路径', e._assist_pending['cloud']['status'] == 'unavailable')
check('返回本地建议(不是空)', info.get('name') == '苹果', repr(info)) else:
check('云端那格记了 error', 'error' in (e._assist_pending['cloud'] or {}), check('云端失败不以本地结果代替', False)
repr(e._assist_pending['cloud'])) check('本地高分也没有跳过云端', e.recog.calls == 1)
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.55), check('人工确认仍为必需', e.confirm_before_submit())
recog=FakeRecog(info={'name': '', 'conf': None, 'alt': '', e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(info={'name': ''}))
'alt_conf': None, 'prompt_tag': 'none'})) check('云端未命中时不回退到本地', not e._recognize_cycle(img, ['苹果']).get('name'))
info = e._recognize_cycle(img, ['苹果']) check('云端未命中有独立状态', e._assist_pending['cloud']['status'] == 'no_match')
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 本地分类器:没模型 = 没意见,绝不抛异常') print('G 本地分类器:没模型 = 没意见,绝不抛异常')
lc = LocalClassifier({'assist': {'model': 'no/such.onnx', lc = LocalClassifier({'assist': {'model': 'no/such.onnx',
+1 -1
View File
@@ -39,7 +39,7 @@ class _BoolVar:
self._sw.set(v) self._sw.set(v)
APP_VERSION = '1.0.75' APP_VERSION = '1.0.76'
# 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。 # 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。
# Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏 # Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏
+4
View File
@@ -2,6 +2,10 @@
配送入库分拣工作站(Win10 版)- 使用说明 配送入库分拣工作站(Win10 版)- 使用说明
════════════════════════════════════════════ ════════════════════════════════════════════
【v1.0.76 识别记录留档(2026-12-03)】
· 商品放稳抓拍后,云端结果供人工确认;本地 YOLO 建议只随「真实业务成功」的样本送审,供超管在后台查看,不改变记账结果。
· 每张样本可查看本地/云端两侧的识别状态、候选与耗时;本机无法计算或云端不可用时也会留「未完成/不可用」,不阻断入库。
本程序按设计文档 docs/design/20261102-win10-inbound-sorting-station.md 本程序按设计文档 docs/design/20261102-win10-inbound-sorting-station.md
实现,与 android-weigh-terminal2 使用同一套服务端接口。 实现,与 android-weigh-terminal2 使用同一套服务端接口。