Files
windows-fenjian/core/recognition/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

332 lines
14 KiB
Python

# -*- coding: utf-8 -*-
"""建议模式(assist):本地分类器给建议 + 云端按 98% 决定要不要问 + 每一笔
人工确认留痕。**这里不产生任何自动记账**。
三条规则(设计上不容商量,代码也照着写):
1. **98% 只是一个开关**,决定这次要不要额外调一次云端;它不代表「够准」。
现在效率不重要,攒数据才重要。所以 `ask_cloud_below` 设高一点(几乎每单
都问)也是在攒**配对**数据:同一次称重,本地说什么、云端说什么、人怎么
选 —— 这三样凑齐,才谈得上日后标定这个 98%。
2. **人是唯一基准**。两个引擎都说是苹果,也仍然要人点确认;`force_confirm`
默认 true 就是干这个的:建议模式一开,就不存在「认出即提交」。
3. **本地引擎不做任何判断**。它没有「我自己能不能搞定」这种话,只输出一个
建议。所以这里也没有加权、没有不一致处理、没有比分阶梯 —— 引擎答错是
零成本的,因为没人会点它。
落盘格式(每笔确认一行,UTF-8 JSONL,按天分文件):
data/assist/cycles/2026-11-30.jsonl
{"v":1,"ts":"...","cycle":"113045-a1b2","station":"loading",
"weight_kg":2.81,"image":"data/snapshots/20261130_113045.jpg",
"image_sha":"9f2c...","image_mtime":1764492645.1,"n_rows":7,
"whitelist":["苹果","香蕉", ...],
"yolo":{"name":"苹果","prob":0.991,"top":[["苹果",0.991]],
"all_top":[["苹果",0.991],["红富士苹果",0.004]],"covered":6,"ms":41},
"cloud":{"asked":false,"reason":"yolo>=0.98","name":"","conf":null,
"alt":"","alt_conf":null,"ms":null},
"human":{"row_id":"1024","item_name":"苹果","changed":false,
"source":"确认记账","part":1},
"final":{"row_id":"1024","item_name":"苹果","business":5.0}}
为什么 `image_sha` 必须记:「取时间最近的那张图」在卡顿或重新拍照时会悄悄
错位,而错位的标签会污染训练集且不报任何错。sha + mtime 是和图片本身绑死
的证据,日后对不上就整行丢掉。
飞轮怎么用这三样:
· 图 + human.item_name = 一条带标签的训练样本
· yolo.prob + human.changed = 日后标定 ask_cloud_below 的依据
· 两边一致但 human.changed 的比例 = 未来免确认的错误率底线
"""
from concurrent.futures import Future
import threading
import os
import json
import time
import hashlib
from core.recognition.local_cls import LocalClassifier
DEFAULTS = {
'enabled': False, # 总开关,默认关
'ask_cloud_below': 0.98, # 低于这个概率才额外调云端
'force_confirm': True, # 建议模式下一律人工确认
'model': 'models/cls/product_cls.onnx',
'classes': 'models/cls/classes.json',
'imgsz': 320,
'topk': 3,
'journal_dir': 'data/assist',
'whitelist_max': 200, # 名单快照最多记多少条
}
def _sha12(path):
"""文件内容 sha1 前 12 位;读不出来返回空串(不阻断记录)。"""
try:
h = hashlib.sha1()
with open(path, 'rb') as f:
while True:
b = f.read(1 << 18)
if not b:
break
h.update(b)
return h.hexdigest()[:12]
except (OSError, ValueError):
return ''
def _norm(p):
try:
return os.path.normcase(os.path.abspath(str(p)))
except (TypeError, ValueError):
return ''
class Assist:
"""建议模式的全部旁路逻辑:不碰记账,只读状态 + 写日志。"""
def __init__(self, cfg=None):
v = (cfg or {}).get('vision') if isinstance(cfg, dict) else {}
if not isinstance(v, dict):
v = {}
raw = v.get('assist')
self.cfg = dict(DEFAULTS)
if isinstance(raw, dict):
self.cfg.update(raw)
self._recording_slot = threading.Lock()
self.enabled = bool(self.cfg.get('enabled'))
try:
self.ask_cloud_below = float(self.cfg.get('ask_cloud_below', 0.98))
except (TypeError, ValueError):
self.ask_cloud_below = 0.98
self.force_confirm = bool(self.cfg.get('force_confirm', True))
self.journal_dir = str(self.cfg.get('journal_dir') or 'data/assist')
try:
self.whitelist_max = max(1, int(self.cfg.get('whitelist_max', 200)))
except (TypeError, ValueError):
self.whitelist_max = 200
self.local = LocalClassifier({'assist': self.cfg})
self._said = '' # 启动后第一单才解释一次「本地能不能用」
def reload_local(self):
"""模型文件换版后调用:重建分类器。
旧实例里的 `_net` 是上一版权重、`names` 是上一版类别表 —— 复用就等于
「换了模型但没换模型」。这里整体换对象而不是原地改字段:`local_suggest`
每单只取一次 `self.local`,赋值本身是原子的,不会出现半新半旧。
"""
self.local = LocalClassifier({'assist': self.cfg})
self._said = ''
return self.local
# ------------------------------------------------------------ 建议
def local_suggest(self, path, names, crop=None):
"""本地建议;关着/没模型/出错一律 None(外面当「本地没意见」)。"""
if not self.enabled:
return None
y = self.local.predict(path, names, crop=crop)
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):
"""要不要额外调一次云端。**只是采样开关**,不是可信度判断。
没有本地建议时照样要问 —— 那就回到了加入建议模式之前的行为。
"""
if not y:
return True
try:
p = float(y.get('prob') or 0.0)
except (TypeError, ValueError):
return True
return p < self.ask_cloud_below
def local_info(self, y):
"""把本地建议翻成和 identify_ex 同形状的 dict,流程两条路共用一份。"""
top = y.get('top') or []
alt = top[1][0] if len(top) > 1 else ''
alt_p = top[1][1] if len(top) > 1 else None
try:
conf = int(round(float(y.get('prob') or 0.0) * 100))
except (TypeError, ValueError):
conf = 0
return {
'name': y.get('name') or '',
'conf': conf,
'alt': alt,
'alt_conf': (None if alt_p is None
else int(round(float(alt_p) * 100))),
'prompt_tag': 'local',
}
# ------------------------------------------------------------ 留痕
def begin(self, station='', weight_kg=None, image='', names=None):
"""开一条「这一件」的记录(先挂内存,人确认时才落盘)。"""
now = time.time()
names = [str(n) for n in (names or []) if str(n or '').strip()]
rec = {
'v': 1,
'ts': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
'cycle': time.strftime('%H%M%S', time.localtime(now)) + '-'
+ ('%04x' % int((now % 1) * 65535)),
'station': station or '',
'weight_kg': (None if weight_kg is None
else round(float(weight_kg), 3)),
'image': str(image or ''),
'image_sha': _sha12(image) if image else '',
'image_mtime': (round(os.path.getmtime(image), 1)
if image and os.path.isfile(image) else None),
'n_rows': len(names),
'whitelist': names[:self.whitelist_max],
'yolo': None,
'cloud': None,
'human': None,
'final': None,
}
return rec
def cloud_slot(self, info=None, error=''):
"""云端那一格。没调用 = asked:false + 原因,其余留空(不写假分数)。"""
info = info or {}
if error:
return {'asked': True, 'error': error, 'name': '', 'conf': None,
'alt': '', 'alt_conf': None, 'ms': None}
return {'asked': True,
'reason': '',
'name': str(info.get('name') or ''),
'conf': info.get('conf'),
'alt': str(info.get('alt') or ''),
'alt_conf': info.get('alt_conf'),
'ms': info.get('ms')}
def skip_cloud(self, reason):
"""没调云端时的那一格:明确写下 asked:false 和原因。"""
return {'asked': False, 'reason': reason, 'name': '', 'conf': None,
'alt': '', 'alt_conf': None, 'ms': None}
def same_image(self, rec, image_path):
"""这条记录是不是这一件(图对不上就当不是,宁可丢一行也别记错)。"""
if not rec:
return False
a = _norm(rec.get('image') or '')
b = _norm(image_path or '')
if not a or not b:
return False
return a == b
def finish(self, rec, row, focus=None, source=''):
"""人确认了:把最终选的行补进去并落盘。返回落盘路径或空串。"""
if not rec:
return ''
f = focus if isinstance(focus, dict) else {}
name = str((row or {}).get('item_name') or '').strip()
rid = str((row or {}).get('id') or '')
y = rec.get('yolo') or {}
c = rec.get('cloud') or {}
yname = str(y.get('name') or '')
cname = str(c.get('name') or '')
# 「人有没有覆盖建议」:两个引擎都只算建议,任一与最终行不同就是覆盖。
# 两个都空(本地没意见 + 云端没认出)不算覆盖 —— 那是「没建议」,
# 不是「建议错了」,混在一起会把错误率算高。
changed = bool((yname and yname != name)
or (cname and cname != name))
rec['human'] = {
'row_id': rid,
'item_name': name,
'changed': changed,
'source': str(source or ''),
'part': int(rec.get('_part') or 0) + 1,
}
rec['final'] = {
'row_id': rid,
'item_name': name,
'business': f.get('business'),
}
rec['_part'] = int(rec.get('_part') or 0) + 1
return self.write(rec)
def write(self, rec):
"""追加一行到当天的 jsonl。失败返回空串(记录不能反过来拖停流程)。"""
try:
d = os.path.join(self.journal_dir, 'cycles')
os.makedirs(d, exist_ok=True)
path = os.path.join(d, time.strftime('%Y-%m-%d') + '.jsonl')
out = {k: v for k, v in rec.items() if not k.startswith('_')}
line = json.dumps(out, ensure_ascii=False, separators=(',', ':'))
with open(path, 'a', encoding='utf-8') as f:
f.write(line + '\n')
return path
except (OSError, TypeError, ValueError):
return ''
def explain_once(self):
"""第一单跑通后解释一次本地引擎状态(只解释一次,不刷屏)。"""
if self._said or not self.enabled:
return ''
if self.local.available():
self._said = ('建议模式:本地分类器可用(%d 类,%d px);'
'低于 %.0f%% 才额外调云端,一律人工确认'
% (len(self.local.names), self.local.imgsz,
self.ask_cloud_below * 100))
else:
self._said = ('建议模式:本地分类器不可用(%s);'
'仍按云端 + 人工确认走,记录照留'
% self.local.reason())
return self._said
def iter_journal(journal_dir='data/assist'):
"""按天读回记录(标定 98% 的脚本、复盘用)。坏行跳过,不抛。"""
d = os.path.join(journal_dir, 'cycles')
if not os.path.isdir(d):
return
for fn in sorted(os.listdir(d)):
if not fn.endswith('.jsonl'):
continue
try:
with open(os.path.join(d, fn), 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except ValueError:
continue
except OSError:
continue