feat(1.0.72): 本地模型自动更新 + 入库照片送审(数据飞轮)
基于 1.0.71 合入:model_sync/local_cls/assist 本地模型自动更新(版本比对/下载/sha+加载校验/替换失败回滚);review_queue 入库照先落队列、成功才送审、回执 image_sha256 核对;build_exe/installer 有 models/cls 就打包;版本 1.0.72;补工具脚本、文档与 config.sanitized.json。
This commit is contained in:
@@ -28,3 +28,6 @@ Thumbs.db
|
||||
*.log
|
||||
*.tmp
|
||||
_nul
|
||||
|
||||
# 本地识别模型(YOLO-cls):由服务端分发/本地发布脚本写入 models/cls,约 10MB,不入库
|
||||
models/cls/
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 71, 0), prodvers=(1, 0, 71, 0),
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 72, 0), prodvers=(1, 0, 72, 0),
|
||||
mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1,
|
||||
subtype=0x0, date=(0, 0)),
|
||||
kids=[
|
||||
StringFileInfo([StringTable('080404B0', [
|
||||
StringStruct('CompanyName', '配送中心'),
|
||||
StringStruct('FileDescription', '入库分拣工作站'),
|
||||
StringStruct('FileVersion', '1.0.71.0'),
|
||||
StringStruct('FileVersion', '1.0.72.0'),
|
||||
StringStruct('InternalName', 'WeighStation'),
|
||||
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
|
||||
StringStruct('ProductName', '入库分拣工作站'),
|
||||
StringStruct('ProductVersion', '1.0.71.0'),
|
||||
StringStruct('ProductVersion', '1.0.72.0'),
|
||||
StringStruct('LegalCopyright', '内部使用')])]),
|
||||
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
||||
]
|
||||
|
||||
+21
-1
@@ -20,7 +20,7 @@ import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
APP_NAME = '入库分拣工作站'
|
||||
APP_VERSION = '1.0.71'
|
||||
APP_VERSION = '1.0.72'
|
||||
ASSETS = os.path.join(ROOT, 'assets')
|
||||
DIST = os.path.join(ROOT, 'dist')
|
||||
OUT = os.path.join(DIST, APP_NAME)
|
||||
@@ -126,6 +126,26 @@ def copy_resources():
|
||||
os.path.join(dst_dir, fn))
|
||||
n += 1
|
||||
print(' + data/photos/ (%d 张)' % n)
|
||||
# models/cls:本地识别模型(有就带上,installer.iss 的
|
||||
# 「Source: {#SrcDir}\models\cls\*」只认 dist 目录,源码树里的模型
|
||||
# 不搬过来那行永远命中不到,装出来就没有本地模型。
|
||||
# 没有也不阻塞打包:秤端登录后会自动从后台下载(见 tools/sync_cls_model.py)。
|
||||
src_cls = os.path.join(ROOT, 'models', 'cls')
|
||||
dst_cls = os.path.join(OUT, 'models', 'cls')
|
||||
if os.path.isdir(src_cls):
|
||||
os.makedirs(dst_cls, exist_ok=True)
|
||||
n = 0
|
||||
for fn in ('product_cls.onnx', 'classes.json', 'model.json'):
|
||||
sp = os.path.join(src_cls, fn)
|
||||
if os.path.isfile(sp):
|
||||
shutil.copy2(sp, os.path.join(dst_cls, fn))
|
||||
n += 1
|
||||
if n:
|
||||
print(' + models/cls/ (%d 个文件)' % n)
|
||||
else:
|
||||
print(' [提示] models/cls 里没有模型三件套,本次不打包模型')
|
||||
else:
|
||||
print(' [提示] 无 models/cls,安装包不含本地模型(登录后自动下载)')
|
||||
for sub in ('data/journal', 'data/snapshots', 'data/thumb_cache'):
|
||||
os.makedirs(os.path.join(OUT, sub), exist_ok=True)
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"server": {
|
||||
"base_url": "https://www.xdjchuanhui.com/api",
|
||||
"mock": false
|
||||
},
|
||||
"account": {
|
||||
"username": "13000000008",
|
||||
"password": "",
|
||||
"role": "picker"
|
||||
},
|
||||
"scale": {
|
||||
"simulate": true,
|
||||
"port": "COM3",
|
||||
"baudrate": 1200,
|
||||
"bytesize": 8,
|
||||
"parity": "N",
|
||||
"stopbits": 1.0,
|
||||
"unit": "auto",
|
||||
"pattern": "",
|
||||
"poll_cmd": "",
|
||||
"poll_ms": 500,
|
||||
"protocol": "generic",
|
||||
"min_weight_kg": 0.01,
|
||||
"stable_count": 5,
|
||||
"stable_tolerance_kg": 0.02,
|
||||
"tare_cmd": "",
|
||||
"zero_cmd": "",
|
||||
"sim_loop_kg": 3.0,
|
||||
"sim_loop_hold_s": 2.5,
|
||||
"sim_loop_keep_s": 10.0,
|
||||
"sim_loop_idle_s": 3.0,
|
||||
"sim_loop_jitter_kg": 0.6
|
||||
},
|
||||
"camera": {
|
||||
"simulate": true,
|
||||
"index": 1,
|
||||
"backend": "dshow",
|
||||
"auto_pick": true,
|
||||
"width": 1280,
|
||||
"height": 720,
|
||||
"usb_only": true,
|
||||
"name": "BisonCam,NB Pro"
|
||||
},
|
||||
"vision": {
|
||||
"provider": "doubao",
|
||||
"api_key": "",
|
||||
"base_url": "https://ark.cn-beijing.volces.com/api/v3",
|
||||
"vision_model": "doubao-seed-2-1-pro-260915",
|
||||
"text_model": "doubao-seed-2-1-pro-260915",
|
||||
"disable_thinking": true,
|
||||
"max_tokens": 32,
|
||||
"timeout": 15,
|
||||
"recognition_image_max_px": 1280,
|
||||
"assist": {
|
||||
"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",
|
||||
"auto_update": true,
|
||||
"update_interval_sec": 21600,
|
||||
"update_timeout": 180
|
||||
}
|
||||
},
|
||||
"printer": {
|
||||
"enabled": false,
|
||||
"type": "tspl",
|
||||
"printer_name": "HUAWEI CV81-WDMSE-0470",
|
||||
"width_mm": 50,
|
||||
"height_mm": 50,
|
||||
"release_usb": false
|
||||
},
|
||||
"flow": {
|
||||
"auto_submit": true,
|
||||
"min_scale_kg": 0.01,
|
||||
"stable_ms": 400,
|
||||
"stable_delta_kg": 0.03,
|
||||
"rescan_delta_kg": 0.04,
|
||||
"unstable_fallback_ms": 2500,
|
||||
"done_lift_off_kg": 0.2,
|
||||
"recognize_timeout": 8,
|
||||
"commit_timeout": 10,
|
||||
"recognize_cooldown": 30,
|
||||
"dedup_delta_kg": 0.005,
|
||||
"frame_stale_ms": 5000,
|
||||
"tolerance_policy": "block_auto",
|
||||
"use_scale_stable": true,
|
||||
"demo_recog": true
|
||||
},
|
||||
"capture_dir": "data/snapshots",
|
||||
"record_file": "data/records_demo.csv",
|
||||
"snapshot_keep_days": 30,
|
||||
"ui": {
|
||||
"mode": "window",
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"borderless": false,
|
||||
"todo_thumb": false,
|
||||
"todo_group": "customer",
|
||||
"fit_screen": false
|
||||
},
|
||||
"devices": {
|
||||
"auto_detect": true
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
mock=True 时用内置数据离线跑通全流程(P1/P2 验收用),接口签名与真实模式一致。
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
@@ -164,6 +165,9 @@ class ApiClient:
|
||||
self.token = ''
|
||||
self.user_id = 'user-' + self.account.get('username', 'demo')
|
||||
self.account_name = '' # 登录后从 profile 拿(顶栏显示用)
|
||||
# 登录后从 profile.branch_code 拿:送审回执要核对自己落在哪个分公司,
|
||||
# 换分公司却没换号会把不同公司的照片混进同一个训练库
|
||||
self.review_branch = ''
|
||||
# 账号开关 profiles.inbound_auto_submit:默认关(入库必须手动点确认);
|
||||
# 仅 mock/演示时回退到本地 config(flow.inbound_auto_submit,默认 True)
|
||||
self.inbound_auto_submit = bool(self._flow_cfg.get('inbound_auto_submit', True))
|
||||
@@ -211,6 +215,7 @@ class ApiClient:
|
||||
# 缺省/旧服务端/未下发 ⇒ False ⇒ 入库必须手动点「确认记账」
|
||||
self.inbound_auto_submit = bool(prof.get('inbound_auto_submit'))
|
||||
self.user_id = prof.get('id') or self.user_id
|
||||
self.review_branch = str(prof.get('branch_code') or '').strip()
|
||||
return r
|
||||
|
||||
def pending(self, station, timeout=None):
|
||||
@@ -721,6 +726,140 @@ class ApiClient:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '照片上传响应解析失败')
|
||||
return _check_photo_ack(body, target_id, operation_id, client_photo_id)
|
||||
|
||||
def upload_review_sample(self, fields, image):
|
||||
"""把入库照片送后台「识别样本」待审核(数据飞轮第二步)。
|
||||
|
||||
契约:POST /mobile/recognition/samples(multipart),字段 image + 业务字段。
|
||||
幂等靠 sample_id / event_id(都填操作号):同号同图服务端回 duplicate。
|
||||
失败分类沿用 _request 的规矩,只是这里自己发 multipart:
|
||||
-1 连接未建立 → 可安全重试;-2 已发出无响应 → 也重试(同号同图不产生第二条);
|
||||
4xx → 明确拒绝(数据本身有问题),交人工。
|
||||
"""
|
||||
if self.mock:
|
||||
return {'sample_id': fields.get('sample_id'),
|
||||
'image_sha256': fields.get('image_sha256', ''),
|
||||
'event_id': fields.get('event_id'),
|
||||
'duplicate': False}
|
||||
url = self.base_url.rstrip('/') + '/mobile/recognition/samples'
|
||||
files = {'image': ('scale.jpg', image, 'image/jpeg')}
|
||||
try:
|
||||
r = self._session.post(url, files=files, data=fields,
|
||||
headers=self._auth(), timeout=(3, 45),
|
||||
allow_redirects=False)
|
||||
except (requests.exceptions.ConnectionError,
|
||||
requests.exceptions.ConnectTimeout):
|
||||
raise ApiError(CODE_NETWORK_FAILURE, '识别样本连接失败')
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '识别样本上传中断: %s' % e)
|
||||
if r.status_code in (401, 403):
|
||||
raise ApiError(r.status_code, '识别样本被拒绝(登录/权限,%d)'
|
||||
% r.status_code)
|
||||
if r.status_code >= 500 or r.status_code == 408:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '识别样本服务端 %d' % r.status_code)
|
||||
if r.status_code >= 400:
|
||||
raise ApiError(r.status_code, '识别样本被拒绝 %d: %s'
|
||||
% (r.status_code, r.text[:160]))
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '识别样本回执解析失败')
|
||||
data = body.get('data') if isinstance(body, dict) else None
|
||||
if not isinstance(data, dict) or not data.get('sample_id'):
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '识别样本回执缺样本号')
|
||||
return data
|
||||
|
||||
def cls_model_manifest(self):
|
||||
"""问服务端要本地识别模型(YOLO-cls)的当前版本清单。
|
||||
|
||||
契约:GET /mobile/weigh/cls-model/manifest
|
||||
200 → data{version, created_at, imgsz, class_count, notes,
|
||||
files:[{name, sha256, size, url}]}
|
||||
404 → 服务器还没发布模型(返回 None,不算错误)
|
||||
除 404 外的非 200、或回执字段不可用,一律抛 ApiError:交给 ModelSync
|
||||
记一行日志、保持现有版本 —— 拿不准的时候绝不动本地模型文件。
|
||||
"""
|
||||
if self.mock:
|
||||
return None
|
||||
url = self.base_url.rstrip('/') + '/mobile/weigh/cls-model/manifest'
|
||||
try:
|
||||
r = self._session.get(url, headers=self._auth(), timeout=(3, 10),
|
||||
allow_redirects=False)
|
||||
except (requests.exceptions.ConnectionError,
|
||||
requests.exceptions.ConnectTimeout):
|
||||
raise ApiError(CODE_NETWORK_FAILURE, '模型清单连接失败')
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型清单请求中断: %s' % e)
|
||||
if r.status_code == 404:
|
||||
return None
|
||||
if r.status_code in (401, 403):
|
||||
raise ApiError(r.status_code, '模型清单被拒绝(登录/权限,%d)'
|
||||
% r.status_code)
|
||||
if r.status_code >= 400:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型清单不可用(%d)'
|
||||
% r.status_code)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型清单解析失败')
|
||||
data = body.get('data') if isinstance(body, dict) else None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
def download_cls_model_file(self, name, dest_path, sha256='', size=0,
|
||||
timeout=None):
|
||||
"""把一个模型文件流式写到 dest_path,并按 sha256/大小校验。
|
||||
|
||||
先写 `.part`、验过才 `os.replace`:半个 onnx 比没有 onnx 更坏 ——
|
||||
cv2 读得进来、推理结果却全是错的,而且不会报任何错。
|
||||
"""
|
||||
if self.mock:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, 'mock 模式不下载模型')
|
||||
url = (self.base_url.rstrip('/')
|
||||
+ '/mobile/weigh/cls-model/file/' + str(name))
|
||||
tmp = dest_path + '.part'
|
||||
digest = hashlib.sha256()
|
||||
got = 0
|
||||
try:
|
||||
try:
|
||||
r = self._session.get(url, headers=self._auth(),
|
||||
timeout=timeout or (5, 180),
|
||||
stream=True, allow_redirects=False)
|
||||
except (requests.exceptions.ConnectionError,
|
||||
requests.exceptions.ConnectTimeout):
|
||||
raise ApiError(CODE_NETWORK_FAILURE, '模型下载连接失败')
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型下载中断: %s' % e)
|
||||
if r.status_code != 200:
|
||||
raise ApiError(r.status_code if r.status_code >= 400
|
||||
else CODE_RESULT_UNKNOWN,
|
||||
'模型下载被拒绝 %d' % r.status_code)
|
||||
with open(tmp, 'wb') as f:
|
||||
try:
|
||||
for chunk in r.iter_content(1 << 16):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
digest.update(chunk)
|
||||
got += len(chunk)
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型下载中断: %s' % e)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
if size and got != int(size):
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型大小不符(%d/%d)'
|
||||
% (got, int(size)))
|
||||
hex_digest = digest.hexdigest()
|
||||
if sha256 and hex_digest.lower() != str(sha256).strip().lower():
|
||||
raise ApiError(CODE_RESULT_UNKNOWN, '模型 sha256 不符(%s…)'
|
||||
% hex_digest[:12])
|
||||
os.replace(tmp, dest_path)
|
||||
return {'bytes': got, 'sha256': hex_digest}
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------ 内部
|
||||
def _auth(self):
|
||||
h = {}
|
||||
|
||||
+257
-14
@@ -32,10 +32,13 @@ from core.scale.reader import ScaleReader, FRAME_STALE_MS
|
||||
from core.evidence.frames import FrameSource
|
||||
from core.matching import engine as M
|
||||
from core.recognition.cloud import CloudRecognizer, RecognitionError
|
||||
from core.recognition.assist import Assist
|
||||
from core.recognition.model_sync import ModelSync
|
||||
from core.api.client import ApiClient, ApiError, new_operation_id, \
|
||||
CODE_NETWORK_FAILURE, CODE_RESULT_UNKNOWN
|
||||
from core.submission.journal import StrictSubmitJournal, \
|
||||
STATE_SUCCEEDED, STATE_REJECTED, STATE_UNKNOWN
|
||||
from core.submission.review_queue import ReviewQueue, RETRY_SECONDS
|
||||
from core.printing.label import LabelPrinter
|
||||
from core.storage import atomic
|
||||
from core.evidence import retention
|
||||
@@ -162,6 +165,17 @@ class FlowEngine:
|
||||
self.frames = FrameSource(cfg)
|
||||
self.api = ApiClient(cfg)
|
||||
self.recog = CloudRecognizer(cfg)
|
||||
# v1.1.0 建议模式(vision.assist.enabled,默认关):
|
||||
# 本地分类器只输出「建议」,98% 只决定这次要不要额外问一次云端,
|
||||
# 记账永远等人点确认。默认关 ⇒ 行为与加入之前逐字节一致。
|
||||
# 详见 core/recognition/assist.py 顶部三条规则。
|
||||
self.assist = Assist(cfg)
|
||||
self._assist_pending = None # 这一件的建议记录(人确认时才落盘)
|
||||
# v1.2.0 模型自动更新:登录后向后台要一版本地模型(版本 + sha256 比对,
|
||||
# 验过才替换;失败一律保持旧版)。发布侧见 yolo-training/scripts/
|
||||
# publish_cls_model.py,端上逻辑见 core/recognition/model_sync.py。
|
||||
self.model_sync = ModelSync(cfg)
|
||||
self._model_busy = False
|
||||
self.printer = LabelPrinter(cfg)
|
||||
self.journal = StrictSubmitJournal()
|
||||
|
||||
@@ -314,6 +328,14 @@ class FlowEngine:
|
||||
daemon=True)
|
||||
self._print_thread.start()
|
||||
threading.Thread(target=self._photo_retry_loop, daemon=True).start()
|
||||
# 入库照片送审:只登记/补传,真正的发送要等 submission journal 说成功
|
||||
# (见 _review_stage / _review_retry_loop)。分拣工位不送审。
|
||||
if self.station == 'inspection' and not getattr(self.api, 'mock', False):
|
||||
threading.Thread(target=self._review_retry_loop,
|
||||
daemon=True).start()
|
||||
# 模型自动更新:登录后会立刻查一次,这里负责「开着一整天」的定时复查
|
||||
# (默认 6 小时一次;auto_update=false 时循环空转,不会发请求)。
|
||||
threading.Thread(target=self._model_sync_loop, daemon=True).start()
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
@@ -367,6 +389,8 @@ class FlowEngine:
|
||||
% (acc.get('username'), self.station, acc.get('role')))
|
||||
# 提示词先拉再拉待办:登录这一刻网络刚通,是唯一能确定「连得上」的时机
|
||||
self._sync_prompts(force=True)
|
||||
# 模型跟着一起查(后台线程,不挡住登录完成;失败只记一行日志)
|
||||
self.sync_model(force=True)
|
||||
self.refresh_pending(initial=True)
|
||||
self.emit('login_ok', {'account': acc.get('username') or '',
|
||||
'role': acc.get('role') or '',
|
||||
@@ -1026,7 +1050,60 @@ class FlowEngine:
|
||||
self._demo_i = i + 1
|
||||
return str(rows[i % len(rows)].get('item_name'))
|
||||
|
||||
def _recog_timeout(self):
|
||||
return max(float(self.cfg['flow'].get('recognize_timeout', 8)), 15.0)
|
||||
|
||||
def _recognize_cycle(self, path, names, crop=None):
|
||||
"""本轮识别:本地先给建议,够不着 98% 才额外问一次云端(v1.1.0)。
|
||||
|
||||
返回值与 identify_ex 同形状,所以 `_run_recognition` 后面的全部分支
|
||||
一行都不用改。四条出口(都是「建议」,都不记账):
|
||||
|
||||
1. 本地 ≥98% → 这次不问云端,但**仍然要人点确认**;
|
||||
2. 本地 <98% / 本地没意见 → 照旧问云端,两边都摊给操作员;
|
||||
3. 云端没给出名单内的名字(NOT_IN_LIST / 超时 / 离线)→ 本地建议
|
||||
顶上做预选,人不同意点别的行就是了;
|
||||
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:
|
||||
info = self.recog.identify_ex(path, names,
|
||||
timeout=self._recog_timeout())
|
||||
except RecognitionError as e:
|
||||
# 出口 3(异常版):云端挂了也不能停摆,本地建议照样带下去
|
||||
rec['cloud'] = a.cloud_slot(error=str(e) or '识别失败')
|
||||
if y and y.get('name'):
|
||||
return a.local_info(y)
|
||||
raise
|
||||
rec['cloud'] = a.cloud_slot(info=info)
|
||||
if not info.get('name') and y and y.get('name'):
|
||||
# 出口 3:云端答了但名单里没有这个货 —— 本地建议顶上做预选,
|
||||
# 云端那一格保持空(不拿本地的分数冒充云端分数)。
|
||||
self.emit('log', '云端没给出名单内的名字,先按本地建议「%s」预选,'
|
||||
'请核对' % y['name'])
|
||||
return a.local_info(y)
|
||||
return info
|
||||
|
||||
def _run_recognition(self):
|
||||
self._assist_pending = None # 新一件:上一件的建议记录作废
|
||||
# v1.0.57:只拿「锁定客户」的品名去问模型 —— 名单缩了,识别更准,
|
||||
# 也不会把这一家的货匹配到别家同名行上
|
||||
names = sorted({r.get('item_name') for r in self.scoped_rows()
|
||||
@@ -1044,10 +1121,7 @@ class FlowEngine:
|
||||
else:
|
||||
info = {}
|
||||
try:
|
||||
info = self.recog.identify_ex(
|
||||
self._cycle_recog_path, names,
|
||||
timeout=max(float(self.cfg['flow'].get('recognize_timeout',
|
||||
8)), 15.0))
|
||||
info = self._recognize_cycle(self._cycle_recog_path, names)
|
||||
except RecognitionError as e:
|
||||
self.emit('log', DEV + str(e))
|
||||
detected = info.get('name')
|
||||
@@ -1076,6 +1150,7 @@ class FlowEngine:
|
||||
if str(info_prompt_tag) not in ('', '-', 'None'):
|
||||
self.emit('log', DEV + '本轮提示词标记:%s%s'
|
||||
% (info_prompt_tag, _prep_note(info)))
|
||||
self._emit_assist_hint()
|
||||
self._cycle_conf = conf # 闸门(同类商品豁免)要用本轮把握
|
||||
self._cycle_detected = detected or ''
|
||||
self._cycle_alt = alt or ''
|
||||
@@ -1644,6 +1719,9 @@ class FlowEngine:
|
||||
self.emit('result', (False, '日志落盘失败,本次未发送请求'))
|
||||
self._set_state('DONE')
|
||||
return
|
||||
# 发请求前先登记送审(原图/货单/操作号),入库成功后才真的发出去
|
||||
if not self._review_stage(op, row, source, self._cycle_recog_path):
|
||||
return
|
||||
cost = 0.0
|
||||
for k in ('unit_cost', 'purchase_price', 'cost', 'price'):
|
||||
try:
|
||||
@@ -1914,6 +1992,53 @@ class FlowEngine:
|
||||
self.emit('log', msg)
|
||||
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):
|
||||
if self._aborted or not self._running:
|
||||
self.emit('log', '本件已作废,不再提交')
|
||||
@@ -1924,6 +2049,7 @@ class FlowEngine:
|
||||
self.emit('result', (False, '存在待核实提交,已锁定新提交'))
|
||||
self._set_state('DONE')
|
||||
return
|
||||
self._flush_assist(row, source)
|
||||
business = self._real_business(row, business)
|
||||
self._frozen_row = row
|
||||
self._set_state('SUBMIT')
|
||||
@@ -1999,6 +2125,12 @@ class FlowEngine:
|
||||
self._set_state('WEIGHING')
|
||||
return
|
||||
|
||||
# 同一次识别的分摊记录共用在秤照片;没有识别帧时用本次合格留档帧。
|
||||
# 先登记送审(还不发):入库成功、哪怕当场断电,这张图也还能补上去。
|
||||
review_photo = shot['path'] if shot['qualified'] else self._cycle_recog_path
|
||||
if not self._review_stage(op, row, source, review_photo,
|
||||
captured_at=shot.get('captured_at')):
|
||||
return
|
||||
photo_expected = shot['qualified']
|
||||
shot['uploaded'] = False
|
||||
if self.station != 'picking' and shot['qualified']:
|
||||
@@ -2752,6 +2884,105 @@ class FlowEngine:
|
||||
except Exception as e:
|
||||
self.emit('log', DEV + '照片补传队列写入失败: %s' % e)
|
||||
|
||||
# ------------------------------------------------------------ 入库照片送审(飞轮)
|
||||
def _review_stage(self, op, row, source, path, captured_at=None):
|
||||
"""入库请求发出去之前:把「哪次操作、哪张原图、哪条货单」记进本机队列。
|
||||
|
||||
这里只登记,不发送 —— 发送由 _review_retry_loop 在提交日志给出
|
||||
succeeded 之后做。理由见 core/submission/review_queue.py 顶部:
|
||||
入库没成功的货不该有训练图;入库成功的货,哪怕当场断电也得补得上。
|
||||
|
||||
返回 False = 本机连「记一笔」都做不到,这一笔不发(与「日志落盘失败,
|
||||
本次未发送请求」同一口径:能追溯才允许动账)。
|
||||
"""
|
||||
if self.station != 'inspection' or getattr(self.api, 'mock', False):
|
||||
return True
|
||||
camera = self.cfg.get('camera', {}) or {}
|
||||
if camera.get('simulate') or camera.get('replay_dir'):
|
||||
return True # 演示/回放:没有真实原图
|
||||
try:
|
||||
error = ReviewQueue().stage(self.api, op, row, source, path,
|
||||
captured_at=captured_at)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.journal.conclude(op, STATE_REJECTED, '送审队列写入失败')
|
||||
self.emit('log', '本机无法保存本笔送审记录(%s),本次未发送' % exc)
|
||||
self.emit('result', (False,
|
||||
'本机无法保存本笔记录,本次未发送:%s' % exc))
|
||||
self._to_done()
|
||||
return False
|
||||
if error:
|
||||
# 缺图不拦入库:货是真的,账照记;只是这张图进不了训练库
|
||||
self.emit('log', '本笔没有可送审的原图(%s),入库照常' % error)
|
||||
else:
|
||||
self.emit('log', DEV + '照片已登记待送审(%s)' % op)
|
||||
return True
|
||||
|
||||
def _review_retry_loop(self):
|
||||
"""每 20 秒看一次:入库结了吗?结了就把登记过的照片送审(断电/断网后照传)。"""
|
||||
while self._running:
|
||||
time.sleep(RETRY_SECONDS)
|
||||
try:
|
||||
if not self.logged_in or not self.api.token:
|
||||
continue
|
||||
ReviewQueue().drain(self.api, lambda m: self.emit('log', m))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.emit('log', '入库照片送审检查暂停:%s' % exc)
|
||||
|
||||
# ------------------------------------------------------------ 本地模型自动更新
|
||||
def sync_model(self, force=False):
|
||||
"""向后台要一版本地模型(后台线程;任何失败都只记一行日志)。
|
||||
|
||||
为什么不在登录线程里同步做:10 MB 下载在 4G 现场可能要几十秒,
|
||||
而登录线程卡住时界面还在等 login_ok。模型是「今天用不上也不影响记账」
|
||||
的东西,永远排在业务后面。
|
||||
"""
|
||||
if self._model_busy:
|
||||
return
|
||||
if getattr(self.api, 'mock', False):
|
||||
return
|
||||
self._model_busy = True
|
||||
|
||||
def work():
|
||||
try:
|
||||
res = self.model_sync.run(self.api, force=force)
|
||||
status = res.get('status')
|
||||
if status == 'updated':
|
||||
# 换掉分类器:旧实例里的 net/names 还是上一版
|
||||
self.assist.reload_local()
|
||||
self.emit('log', '本地模型已更新:%s(%d 类%s)'
|
||||
% (res.get('version'),
|
||||
int(res.get('class_count') or 0),
|
||||
',' + res['notes'] if res.get('notes') else ''))
|
||||
elif status == 'failed':
|
||||
self.emit('log', '本地模型未更新:%s(继续用现有版本)'
|
||||
% res.get('reason'))
|
||||
elif status == 'current':
|
||||
self.emit('log', DEV + '本地模型已是最新(%s)'
|
||||
% res.get('version'))
|
||||
else:
|
||||
self.emit('log', DEV + '本地模型跳过:%s'
|
||||
% res.get('reason'))
|
||||
except Exception as exc: # noqa: BLE001 换模型绝不能拖垮主流程
|
||||
self.emit('log', '本地模型检查异常:%s' % exc)
|
||||
finally:
|
||||
self._model_busy = False
|
||||
|
||||
threading.Thread(target=work, daemon=True).start()
|
||||
|
||||
def _model_sync_loop(self):
|
||||
"""定时复查(默认 6 小时);auto_update=false 时 ModelSync 自己会 skip。"""
|
||||
while self._running:
|
||||
time.sleep(60)
|
||||
try:
|
||||
if not self.logged_in or not self.api.token:
|
||||
continue
|
||||
if not self.model_sync.due():
|
||||
continue
|
||||
self.sync_model()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.emit('log', DEV + '本地模型定时检查暂停:%s' % exc)
|
||||
|
||||
|
||||
def _photo_retry_loop(self):
|
||||
while self._running:
|
||||
time.sleep(60)
|
||||
@@ -3127,6 +3358,11 @@ class FlowEngine:
|
||||
|
||||
关掉(flow.confirm_before_submit=false)回到旧行为:认出即提交。
|
||||
"""
|
||||
# v1.1.0 建议模式:本地和云端都只是「建议」,人必须点一下。
|
||||
# 两个引擎都说苹果也不自动记账 —— 人是唯一基准(assist.force_confirm)。
|
||||
_a = getattr(self, 'assist', None)
|
||||
if _a is not None and _a.enabled and _a.force_confirm:
|
||||
return True
|
||||
# 2026-11-29:入库账号未开启「自动提交」⇒ 强制走确认页(必须点确认)
|
||||
if self._manual_confirm_required():
|
||||
return True
|
||||
@@ -3273,6 +3509,14 @@ class FlowEngine:
|
||||
'auto': bool(auto),
|
||||
'from_scale': False, # 记账量是否取自秤上实际读数(v1.0.55)
|
||||
}
|
||||
# 建议模式:把两个引擎的建议一起交给界面(本地预选、云端并列显示)。
|
||||
# 界面不认这个键也不影响任何记账逻辑 —— 它只是给人看的一份「意见」。
|
||||
_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':
|
||||
@@ -3804,14 +4048,13 @@ class FlowEngine:
|
||||
|
||||
# ------------------------------------------------ AI 自动免称重(v1.0.29)
|
||||
def auto_noweigh_on(self):
|
||||
"""不称重商品是否由 AI **自动识别**(放上去就认,不用点屏幕)
|
||||
"""不称重商品是否由 AI 自动识别、自动入库/分拣(不用点屏幕)
|
||||
|
||||
默认开。关掉就退回 v1.0.28 的行为:点按钮 → 抓拍 → 核对页 → 提交。
|
||||
|
||||
2026-11-29 的账号「手动确认」开关**不影响这里**:识别照旧自动跑,
|
||||
只是认出后由 `confirm_before_submit()` 强制进确认页,点了才算记账。
|
||||
以前这里跟着一起关,袋/包/桶连自动识别都没了,每件都要手点一下。
|
||||
"""
|
||||
# 2026-11-29:入库账号未开启「自动提交」⇒ 免称重也不自动记账,必须人工点确认
|
||||
if self._manual_confirm_required():
|
||||
return False
|
||||
cfg = self.cfg.get('noweigh', {}) or {}
|
||||
return bool(cfg.get('auto', True))
|
||||
|
||||
@@ -4085,12 +4328,12 @@ class FlowEngine:
|
||||
else:
|
||||
info = {}
|
||||
try:
|
||||
info = self.recog.identify_ex(
|
||||
# 免称重是手举着袋子/整筐抓拍,货可能占满画面,四周裁太多
|
||||
# 会把袋口和货切掉;这里只削一点点边(默认保留 96%)。
|
||||
# 建议模式(v1.1.0)下走同一条路:本地先给建议,够不着阈值
|
||||
# 才问云端;crop 透传给本地模型,两边看到的是同一张图。
|
||||
info = self._recognize_cycle(
|
||||
self._cycle_recog_path, names,
|
||||
timeout=max(float(self.cfg['flow'].get('recognize_timeout',
|
||||
8)), 15.0),
|
||||
# 免称重是手举着袋子/整筐抓拍,货可能占满画面,四周裁太多
|
||||
# 会把袋口和货切掉;这里只削一点点边(默认保留 96%)。
|
||||
crop=float(self.cfg['vision'].get('recog_crop_noweigh',
|
||||
0.96)))
|
||||
except RecognitionError as e:
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
# -*- 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 的比例 = 未来免确认的错误率底线
|
||||
"""
|
||||
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.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 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
|
||||
@@ -0,0 +1,263 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""本地品类分类器(YOLO-cls → ONNX):只给建议,不做决定。
|
||||
|
||||
它存在的原因不是「取代云端」,而是**因为每一笔人工确认过的交易都该变成训练
|
||||
样本**。云端识别一次要几秒、要网络、要 token;本地模型不联网、几十毫秒,
|
||||
但它现在一定不如云端准 —— 所以这个模块被刻意写成「哑巴」:
|
||||
|
||||
· **永远给答案**(名单里最像的几个 + 分数),从不返回「我不确定」;
|
||||
· **不做任何判断**:没有阈值、没有「够不够准」、没有「要不要问人」;
|
||||
· 98% 那个开关在 `core/recognition/assist.py` 里,只决定「这次还要不要
|
||||
额外调一次云端」,不是可信度声明;
|
||||
· 出了任何问题(没模型、没 onnx、图读不出来、cv2.dnn 不认这个算子)
|
||||
一律返回 {},外面当「本地这次没意见」处理,流程一步都不停。
|
||||
|
||||
前处理口径必须和训练时一模一样,否则模型等于瞎猜。口径定死在这里:
|
||||
|
||||
读图 → 可选中心裁剪(复用 prep.crop_center)→ letterbox 到 size×size
|
||||
(保持长宽比,四周补 114 灰)→ BGR→RGB → /255
|
||||
(**仅 /255**:ultralytics 训分类就是这个口径,别再减 ImageNet 均值,
|
||||
见 _probs() 里的实测说明)
|
||||
|
||||
为什么是 letterbox 而不是「中心裁成方形」:现场帧是 1600×719 这种宽幅,
|
||||
按短边裁方会砍掉一半宽度,货稍微偏一点就被裁出画外。letterbox 只加边不
|
||||
丢内容。为什么不用 ultralytics 默认的 CenterCrop:它是「裁」,我们训练时
|
||||
已经把图**预处理成 size×size 的方图**了,CenterCrop(size) 正好是空操作,
|
||||
两边自然一致(见 yolo-training/scripts/build_cls_dataset.py 的同名实现,
|
||||
两处必须同时改)。
|
||||
|
||||
配置在 config.json 的 `vision.assist`(不配 = 整个功能关掉):
|
||||
|
||||
enabled 总开关,默认 false
|
||||
model ONNX 路径,默认 models/cls/product_cls.onnx
|
||||
classes 类别表,默认 models/cls/classes.json(训练侧同目录产出)
|
||||
imgsz 默认 320;classes.json 里有 imgsz 时以它为准
|
||||
topk 返回几个候选,默认 3
|
||||
|
||||
依赖:只用 cv2.dnn,**不引入 onnxruntime**。端上是打包好的 exe,多带一个
|
||||
运行时就是多一份体积、多一条装不上的路;分类网的算子就 conv/pool/gemm,
|
||||
OpenCV 4.x 的 dnn 足够跑。
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
|
||||
|
||||
def _softmax(v):
|
||||
v = np.asarray(v, dtype=np.float32).ravel()
|
||||
if v.size == 0:
|
||||
return v
|
||||
m = float(v.max())
|
||||
e = np.exp(v - m)
|
||||
s = float(e.sum())
|
||||
return (e / s) if s > 0 else e
|
||||
|
||||
|
||||
def _looks_like_prob(v):
|
||||
"""判断网络输出已经是概率还是 logits。
|
||||
|
||||
不同 ultralytics 版本导出的 cls 头,有的在 forward 里就做了 softmax,
|
||||
有的只给 logits。硬编码任何一种,另一批权重就会把「0.02」当 2% 报出去,
|
||||
或者把 logits 当概率直接比大小。这里看一眼值域和总和,比查版本可靠。
|
||||
"""
|
||||
v = np.asarray(v, dtype=np.float32).ravel()
|
||||
if v.size == 0:
|
||||
return False
|
||||
if float(v.min()) < -1e-6:
|
||||
return False
|
||||
return abs(float(v.sum()) - 1.0) < 1e-2
|
||||
|
||||
|
||||
def letterbox(img, size, pad=114):
|
||||
"""等比缩放进 size×size 方图,四周补 pad 灰。
|
||||
|
||||
与 yolo-training/scripts/build_cls_dataset.py 的 letterbox() 必须一致:
|
||||
训练集是用这个函数生成的,推理换一种缩放方式 = 分布漂移。
|
||||
"""
|
||||
h, w = img.shape[:2]
|
||||
if h <= 0 or w <= 0:
|
||||
return None
|
||||
r = min(float(size) / float(w), float(size) / float(h))
|
||||
nw = max(1, int(round(w * r)))
|
||||
nh = max(1, int(round(h * r)))
|
||||
if (nw, nh) == (w, h):
|
||||
resized = img
|
||||
else:
|
||||
interp = cv2.INTER_AREA if r < 1.0 else cv2.INTER_LINEAR
|
||||
resized = cv2.resize(img, (nw, nh), interpolation=interp)
|
||||
out = np.full((int(size), int(size), 3), int(pad), dtype=np.uint8)
|
||||
dx = (int(size) - nw) // 2
|
||||
dy = (int(size) - nh) // 2
|
||||
out[dy:dy + nh, dx:dx + nw] = resized
|
||||
return out
|
||||
|
||||
|
||||
class LocalClassifier:
|
||||
"""本地分类器。构造不碰磁盘,第一次 predict 才加载(流程启动不受影响)。"""
|
||||
|
||||
def __init__(self, vision_cfg=None):
|
||||
v = vision_cfg if isinstance(vision_cfg, dict) else {}
|
||||
a = v.get('assist') if isinstance(v.get('assist'), dict) else {}
|
||||
self.cfg = a
|
||||
self.model_path = str(a.get('model') or 'models/cls/product_cls.onnx')
|
||||
self.classes_path = str(a.get('classes')
|
||||
or 'models/cls/classes.json')
|
||||
try:
|
||||
self.topk = max(1, int(a.get('topk', 3)))
|
||||
except (TypeError, ValueError):
|
||||
self.topk = 3
|
||||
try:
|
||||
self.imgsz = int(a.get('imgsz', 320) or 320)
|
||||
except (TypeError, ValueError):
|
||||
self.imgsz = 320
|
||||
self.pad = 114
|
||||
self.names = [] # 类别表,下标即网络输出下标
|
||||
self._net = None
|
||||
self._err = '' # 加载失败原因:只报一次,别每单刷一条日志
|
||||
self._tried = False
|
||||
|
||||
# ------------------------------------------------------------ 加载
|
||||
def _load(self):
|
||||
if self._net is not None or self._tried:
|
||||
return self._net is not None
|
||||
self._tried = True
|
||||
try:
|
||||
with open(self.classes_path, 'r', encoding='utf-8') as f:
|
||||
meta = json.load(f)
|
||||
if isinstance(meta, dict):
|
||||
names = meta.get('names') or meta.get('classes') or []
|
||||
if meta.get('imgsz'):
|
||||
self.imgsz = int(meta['imgsz'])
|
||||
else:
|
||||
names = meta
|
||||
self.names = [str(x) for x in (names or [])]
|
||||
if not self.names:
|
||||
self._err = '类别表为空:%s' % self.classes_path
|
||||
return False
|
||||
if not os.path.isfile(self.model_path):
|
||||
self._err = '模型不存在:%s' % self.model_path
|
||||
return False
|
||||
# 必须自己读字节再喂:cv2.dnn.readNetFromONNX(路径) 走的是窄字符
|
||||
# fopen,装到「D:\嵌入式识别\...」「入库分拣工作台\...」这类中文路径
|
||||
# 下会直接报 "Can't read ONNX file"(和 cv2.imread 同一个坑,
|
||||
# prep.read_image 那边已经绕过一次)。现场实测:同一份 onnx,
|
||||
# ASCII 路径能读、中文路径报错、字节缓冲两边都能读。
|
||||
try:
|
||||
buf = np.fromfile(self.model_path, dtype=np.uint8)
|
||||
net = cv2.dnn.readNetFromONNX(buf)
|
||||
except Exception: # noqa: BLE001 老版本没有这个重载
|
||||
net = cv2.dnn.readNetFromONNX(self.model_path)
|
||||
try:
|
||||
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
|
||||
except Exception: # noqa: BLE001 老版本没这项
|
||||
pass
|
||||
self._net = net
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 任何错都当没模型
|
||||
self._err = '加载失败:%s' % e
|
||||
self.names = []
|
||||
return False
|
||||
|
||||
def available(self):
|
||||
return self._load()
|
||||
|
||||
def reason(self):
|
||||
"""为什么不可用(给日志用;可用时返回空串)。"""
|
||||
return '' if self.available() else (self._err or '未加载')
|
||||
|
||||
# ------------------------------------------------------------ 推理
|
||||
def _probs(self, img, crop=None):
|
||||
"""图 -> 全类概率向量(与 self.names 对齐)。失败返回 None。"""
|
||||
try:
|
||||
if crop is not None:
|
||||
from core.recognition import prep
|
||||
img = prep.crop_center(img, crop)
|
||||
except Exception: # noqa: BLE001 裁剪失败就整帧
|
||||
pass
|
||||
sq = letterbox(img, self.imgsz, self.pad)
|
||||
if sq is None:
|
||||
return None
|
||||
# 只做 /255,**不要**再减 ImageNet 的 mean/std。ultralytics 训练分类
|
||||
# 时的预处理是 Resize→CenterCrop→ToTensor→Normalize(
|
||||
# DEFAULT_MEAN=(0,0,0), DEFAULT_STD=(1,1,1)),也就是 ToTensor 的 /255
|
||||
# 之后归一化等于空操作。这里多减一组 ImageNet 均值,输入分布就和训练
|
||||
# 时差一截:实测同一批 123 张测试图,减去 mean/std 时 cv2.dnn 只对
|
||||
# 13 张(10.6%),只做 /255 时和 torch 完全一致。这个坑不报错、只掉
|
||||
# 准确率,最难发现,改之前先跑 scripts/eval_cls.py --onnx。
|
||||
x = sq.astype(np.float32)[:, :, ::-1] / 255.0 # BGR -> RGB
|
||||
x = np.ascontiguousarray(x.transpose(2, 0, 1)[None, ...])
|
||||
self._net.setInput(x)
|
||||
out = np.asarray(self._net.forward()).ravel()
|
||||
if out.size != len(self.names):
|
||||
# 类别表和数据不同步 —— 宁可当「没意见」,也不能把名字错位配上去
|
||||
self._err = ('输出维度 %d 与类别表 %d 不一致(classes.json 与 '
|
||||
'onnx 不是同一次训练产出的?)'
|
||||
% (out.size, len(self.names)))
|
||||
self._net = None
|
||||
return None
|
||||
return out if _looks_like_prob(out) else _softmax(out)
|
||||
|
||||
def predict(self, image_path, pending_names=None, crop=None):
|
||||
"""image_path -> 建议 dict;任何问题返回 {}(调用方当「本地没意见」)。
|
||||
|
||||
返回:
|
||||
name 名单内最像的品名(名单为空/全不相交时为空串)
|
||||
prob 它的概率 0~1(**不是**百分比)
|
||||
top [[名字, 概率], ...] 只含本轮名单里的,按概率降序,≤topk
|
||||
all_top [[名字, 概率], ...] 全类前 3 —— 用来看「本地其实认为是
|
||||
别的货」:飞轮里这条比名单内答案更能说明名单覆盖不足
|
||||
covered 本轮名单里模型认识的品名个数
|
||||
ms 耗时毫秒
|
||||
注意:这里**不做**任何阈值判断,也不返回「要不要问云端」。
|
||||
"""
|
||||
t0 = time.time()
|
||||
if not image_path or not self._load():
|
||||
return {}
|
||||
try:
|
||||
from core.recognition import prep
|
||||
img = prep.read_image(image_path)
|
||||
if img is None:
|
||||
return {}
|
||||
probs = self._probs(img, crop)
|
||||
if probs is None:
|
||||
return {}
|
||||
except Exception as e: # noqa: BLE001 推理失败绝不外抛
|
||||
self._err = '推理失败:%s' % e
|
||||
return {}
|
||||
ms = int(round((time.time() - t0) * 1000))
|
||||
order = np.argsort(-probs)
|
||||
all_top = [[self.names[i], round(float(probs[i]), 4)]
|
||||
for i in order[:3] if i < len(self.names)]
|
||||
want = set()
|
||||
for n in (pending_names or []):
|
||||
s = str(n or '').strip()
|
||||
if s:
|
||||
want.add(s)
|
||||
top = []
|
||||
if want:
|
||||
for i in order:
|
||||
if i >= len(self.names):
|
||||
break
|
||||
nm = self.names[i]
|
||||
if nm in want:
|
||||
top.append([nm, round(float(probs[i]), 4)])
|
||||
if len(top) >= self.topk:
|
||||
break
|
||||
else:
|
||||
# 没有名单 = 不限制(自检/离线看效果用),但仍然只是建议
|
||||
for i in order[:self.topk]:
|
||||
if i < len(self.names):
|
||||
top.append([self.names[i], round(float(probs[i]), 4)])
|
||||
covered = len(want & set(self.names))
|
||||
return {
|
||||
'name': top[0][0] if top else '',
|
||||
'prob': float(top[0][1]) if top else 0.0,
|
||||
'top': top,
|
||||
'all_top': all_top,
|
||||
'covered': covered,
|
||||
'ms': ms,
|
||||
'imgsz': self.imgsz,
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""本地模型自动更新:服务器上有新版本就换,换不动就不换。
|
||||
|
||||
为什么需要它:模型不是「装一次就完」的东西 —— 每攒一批审核图就重训一版,
|
||||
而现场十来台秤分散在几个库房。人工拷 U 盘的结果是「三台新、两台旧,
|
||||
谁也说不出哪台是哪版」。这里把「哪一版」变成一个可比对的版本号。
|
||||
|
||||
三条底线(代码照这个写):
|
||||
|
||||
1. **先验后用**:下载完先算 sha256、再用端上那份 `local_cls.py` 真加载一遍;
|
||||
过不了就整批丢弃 —— 宁可继续用旧版,也不能让某台秤明天开局「本地没意见」。
|
||||
2. **原子替换 + 失败回滚**:两个文件先落 `models/cls/.incoming/`,验过才
|
||||
`os.replace` 到正式路径,`model.json` 最后写;换到一半失败(第二个文件换不动、
|
||||
清单没写成)就按 `.incoming/.backup` 把已换的文件还原,磁盘回到旧版完整状态。
|
||||
中途断电最坏是版本号对不上、下次重装一遍。
|
||||
3. **绝不挡流程**:任何异常都吞掉、只返回一句话。登录、称重、提交一步都不等它。
|
||||
|
||||
配置(config.json → vision.assist,都有默认值):
|
||||
|
||||
auto_update 默认 true;关掉就只用手工放进 models/cls 的文件
|
||||
update_interval_sec 默认 21600(6 小时);登录时先查一次
|
||||
update_timeout 下载超时秒,默认 180
|
||||
|
||||
返回的 status:
|
||||
|
||||
current 服务器版本与本地一致,什么都没做
|
||||
updated 换了新版本(附新 manifest,调用方要重建 LocalClassifier)
|
||||
skipped 没开自动更新 / mock 模式 / 服务器还没发布模型
|
||||
failed 取版本、下载、校验任一步失败 —— 本地文件保持原样
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
|
||||
from core.recognition.local_cls import LocalClassifier
|
||||
|
||||
DEFAULTS = {
|
||||
'auto_update': True,
|
||||
'update_interval_sec': 21600,
|
||||
'update_timeout': 180,
|
||||
}
|
||||
|
||||
# 与后台 `server/src/services/clsModelService.ts` 的白名单一致;新增文件三处一起改
|
||||
MODEL_FILES = ('product_cls.onnx', 'classes.json')
|
||||
|
||||
|
||||
def _sha256(path):
|
||||
h = hashlib.sha256()
|
||||
with open(path, 'rb') as f:
|
||||
while True:
|
||||
b = f.read(1 << 20)
|
||||
if not b:
|
||||
break
|
||||
h.update(b)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _read_json(path):
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _iso_now():
|
||||
t = time.localtime()
|
||||
off = -(time.altzone if t.tm_isdst > 0 else time.timezone)
|
||||
sign = '+' if off >= 0 else '-'
|
||||
off = abs(int(off))
|
||||
return '%s%s%02d:%02d' % (time.strftime('%Y-%m-%dT%H:%M:%S', t), sign,
|
||||
off // 3600, (off % 3600) // 60)
|
||||
|
||||
|
||||
|
||||
class ModelSync:
|
||||
"""模型拉取/校验/替换。构造不碰网络,也不碰磁盘。"""
|
||||
|
||||
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.enabled = bool(self.cfg.get('auto_update', True))
|
||||
try:
|
||||
self.interval = max(60, int(self.cfg.get('update_interval_sec')
|
||||
or 21600))
|
||||
except (TypeError, ValueError):
|
||||
self.interval = 21600
|
||||
try:
|
||||
self.timeout = max(10, int(self.cfg.get('update_timeout') or 180))
|
||||
except (TypeError, ValueError):
|
||||
self.timeout = 180
|
||||
self.model_path = str(self.cfg.get('model')
|
||||
or 'models/cls/product_cls.onnx')
|
||||
self.classes_path = str(self.cfg.get('classes')
|
||||
or 'models/cls/classes.json')
|
||||
self.dir = os.path.dirname(self.model_path) or 'models/cls'
|
||||
self.manifest_path = os.path.join(self.dir, 'model.json')
|
||||
self._next_at = 0.0 # 下次允许检查的时刻
|
||||
|
||||
# ------------------------------------------------------------ 状态
|
||||
def due(self):
|
||||
return time.time() >= self._next_at
|
||||
|
||||
def local_manifest(self):
|
||||
"""本机 model.json(发布/自动更新写的那份);没有就返回 {}。"""
|
||||
return _read_json(self.manifest_path)
|
||||
|
||||
def local_version(self):
|
||||
return str(self.local_manifest().get('version') or '')
|
||||
|
||||
def _files_present(self):
|
||||
for name in MODEL_FILES:
|
||||
if not os.path.isfile(os.path.join(self.dir, name)):
|
||||
return False
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------ 主流程
|
||||
def run(self, api, force=False):
|
||||
"""比对 + 下载 + 替换。**不抛异常**,返回 {'status': ..., ...}。"""
|
||||
if not self.enabled:
|
||||
self._next_at = time.time() + self.interval
|
||||
return {'status': 'skipped', 'reason': 'auto_update 已关闭'}
|
||||
if getattr(api, 'mock', False):
|
||||
self._next_at = time.time() + self.interval
|
||||
return {'status': 'skipped', 'reason': 'mock 模式不拉模型'}
|
||||
if not force and not self.due():
|
||||
return {'status': 'skipped', 'reason': '还没到检查时间'}
|
||||
self._next_at = time.time() + self.interval
|
||||
|
||||
try:
|
||||
remote = api.cls_model_manifest()
|
||||
except Exception as e: # noqa: BLE001
|
||||
return {'status': 'failed', 'reason': '取版本失败:%s' % e}
|
||||
if not remote:
|
||||
return {'status': 'skipped', 'reason': '服务器未发布模型'}
|
||||
|
||||
version = str(remote.get('version') or '').strip()
|
||||
want = self._remote_files(remote)
|
||||
if not version or not want:
|
||||
return {'status': 'failed', 'reason': '服务器版本清单不完整'}
|
||||
|
||||
if str(self.local_manifest().get('version') or '') == version:
|
||||
if self._files_present():
|
||||
return {'status': 'current', 'version': version}
|
||||
# 清单写着这版、文件却没了(被人删了 / 上次拷了一半)→ 当成没装,重下一遍
|
||||
return self._install(api, remote, version, want)
|
||||
|
||||
def _install(self, api, remote, version, want):
|
||||
"""下载 → 校验 → 试加载 → 换文件 → 写清单;任一步失败都回到旧版。
|
||||
|
||||
「换文件」不是一个原子动作:product_cls.onnx 和 classes.json 是两个
|
||||
`os.replace`。只把第一个换成功、第二个失败(被杀毒软件占住、磁盘满、
|
||||
断电)就会留下「新 onnx + 旧 classes + 旧 manifest」——端上加载得了,
|
||||
却用两份对不上的资产推理,还不报错。所以替换前先备份旧文件,替换/写
|
||||
清单任一步抛异常就回滚已替换的那几个(见 `_rollback`)。
|
||||
"""
|
||||
incoming = os.path.join(self.dir, '.incoming')
|
||||
backup_dir = os.path.join(incoming, '.backup')
|
||||
replaced = [] # 已换到正式路径的文件名(回滚按逆序还原)
|
||||
backups = {} # name -> 备份路径;None = 替换前本来没有
|
||||
try:
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
os.makedirs(incoming, exist_ok=True)
|
||||
for name in MODEL_FILES:
|
||||
api.download_cls_model_file(
|
||||
name, os.path.join(incoming, name),
|
||||
sha256=want[name]['sha256'], size=want[name]['size'],
|
||||
timeout=self.timeout)
|
||||
# 落盘后再自己算一遍:客户端那边验过,这是「换上去之前」的总闸
|
||||
for name in MODEL_FILES:
|
||||
got = _sha256(os.path.join(incoming, name))
|
||||
if got != want[name]['sha256']:
|
||||
raise RuntimeError('%s 校验不一致(%s…)' % (name, got[:12]))
|
||||
# 试加载:端上读不了就不换 —— 换模型是为了更好用,不是换一个加载不了的
|
||||
probe_cfg = dict(self.cfg)
|
||||
probe_cfg['model'] = os.path.join(incoming, 'product_cls.onnx')
|
||||
probe_cfg['classes'] = os.path.join(incoming, 'classes.json')
|
||||
probe = LocalClassifier({'assist': probe_cfg})
|
||||
if not probe.available():
|
||||
raise RuntimeError('端上读不了这版模型:%s' % probe.reason())
|
||||
# 结果字段先算好:等文件换上去之后再抛异常,就没人能还原了
|
||||
class_count = int(remote.get('class_count') or 0)
|
||||
notes = str(remote.get('notes') or '')
|
||||
# 动正式目录之前,先把旧的一对文件留一份(没有就记 None)
|
||||
os.makedirs(backup_dir, exist_ok=True)
|
||||
for name in MODEL_FILES:
|
||||
dst = os.path.join(self.dir, name)
|
||||
if os.path.isfile(dst):
|
||||
bak = os.path.join(backup_dir, name)
|
||||
shutil.copy2(dst, bak)
|
||||
backups[name] = bak
|
||||
else:
|
||||
backups[name] = None
|
||||
# 两个文件依次换;任一失败(或下面写清单失败)都回滚
|
||||
for name in MODEL_FILES:
|
||||
os.replace(os.path.join(incoming, name),
|
||||
os.path.join(self.dir, name))
|
||||
replaced.append(name)
|
||||
self._write_manifest(version, remote, want)
|
||||
return {'status': 'updated',
|
||||
'version': version,
|
||||
'class_count': class_count,
|
||||
'notes': notes}
|
||||
except Exception as e: # noqa: BLE001
|
||||
self._rollback(replaced, backups)
|
||||
return {'status': 'failed', 'reason': '%s' % e}
|
||||
finally:
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
|
||||
def _rollback(self, replaced, backups):
|
||||
"""把已经换上去的文件还原成替换前的样子(尽力而为,绝不抛异常)。
|
||||
|
||||
调用点只有 `_install` 的 except:走到那里说明「两个文件换到一半」或
|
||||
「文件换完了但清单没写成」。有备份的 copy2 回去;替换前本来没有的,
|
||||
就把刚落下的新文件删掉。回滚自己失败也只能放过 —— 返回给调用方的仍是
|
||||
failed,秤端下次检查会按清单版本重新装一遍。
|
||||
"""
|
||||
for name in reversed(list(replaced)):
|
||||
dst = os.path.join(self.dir, name)
|
||||
bak = backups.get(name)
|
||||
try:
|
||||
if bak and os.path.isfile(bak):
|
||||
shutil.copy2(bak, dst)
|
||||
elif os.path.isfile(dst):
|
||||
os.remove(dst)
|
||||
except OSError:
|
||||
pass
|
||||
# 清单写失败可能留下半个 model.json.tmp,顺手清掉(旧 model.json 没动)
|
||||
try:
|
||||
tmp = self.manifest_path + '.tmp'
|
||||
if os.path.isfile(tmp):
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------ 内部
|
||||
def _remote_files(self, remote):
|
||||
"""服务端清单 → {name: {sha256, size}};缺一个就整单作废。"""
|
||||
listed = remote.get('files')
|
||||
rows = listed if isinstance(listed, list) else []
|
||||
out = {}
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = str(row.get('name') or '')
|
||||
sha = str(row.get('sha256') or '').strip().lower()
|
||||
try:
|
||||
size = int(row.get('size') or 0)
|
||||
except (TypeError, ValueError):
|
||||
size = 0
|
||||
if name in MODEL_FILES and len(sha) == 64 and size > 0:
|
||||
out[name] = {'sha256': sha, 'size': size}
|
||||
return out if len(out) == len(MODEL_FILES) else {}
|
||||
|
||||
def _write_manifest(self, version, remote, files):
|
||||
data = {
|
||||
'schema': 1,
|
||||
'version': version,
|
||||
'created_at': str(remote.get('created_at') or ''),
|
||||
'installed_at': _iso_now(),
|
||||
'imgsz': int(remote.get('imgsz') or 0),
|
||||
'class_count': int(remote.get('class_count') or 0),
|
||||
'notes': str(remote.get('notes') or ''),
|
||||
'source': 'server',
|
||||
'files': {k: {'sha256': v['sha256'], 'size': v['size']}
|
||||
for k, v in files.items()},
|
||||
}
|
||||
tmp = self.manifest_path + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
f.write('\n')
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, self.manifest_path)
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""入库照片送审队列(数据飞轮第二步:秤 → 后台「识别样本」待审核)。
|
||||
|
||||
为什么不是「入库成功后顺手发一张」:
|
||||
|
||||
入库刚成功、秤就断电/断网,那一次发送就永远没了 —— 而这一笔货是真实入账的,
|
||||
照片却再也进不了训练库。反过来,入库还没结论就先送审,可能出现「训练库里
|
||||
挂着一张不属于任何账的图」。
|
||||
|
||||
所以顺序固定为三步:
|
||||
|
||||
1. 提交入库请求**之前**:把「哪次操作、哪张原图、哪条货单」写进本机队列,
|
||||
原图复制一份进来(data/snapshots 会被滚动清理,只记路径靠不住);
|
||||
2. 提交日志(core/submission/journal.py)给出 succeeded 才真的发;
|
||||
3. 入库被拒绝(rejected)→ 队列里这条直接删;断网/重启/断电 → 队列还在盘上,
|
||||
后台线程每 20 秒接着查、接着传。
|
||||
|
||||
幂等靠操作号:它同时当 sample_id 和 event_id,服务端 event_id 同图重复提交
|
||||
只会返回 duplicate,不会产生第二行。回执还要核对照片 sha256、单号、货单,
|
||||
对不上就当没送到(留队列重试,不删)。
|
||||
|
||||
目录(一个操作一个目录,方便人眼看、也方便整条丢弃):
|
||||
data/review_pending/<操作号>/meta.json
|
||||
data/review_pending/<操作号>/photo.jpg
|
||||
data/review_rejected.json 永久失败(数据本身有问题)的清单,交人工
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import uuid
|
||||
import shutil
|
||||
import time
|
||||
|
||||
from core.storage import atomic
|
||||
from core.submission.journal import (JOURNAL_DIR, STATE_REJECTED,
|
||||
STATE_SUCCEEDED)
|
||||
|
||||
PENDING_DIR = 'data/review_pending'
|
||||
REJECTED_FILE = 'data/review_rejected.json'
|
||||
RETRY_SECONDS = 20 # 后台线程多久回来看一次「这笔入库结了吗」
|
||||
BACKOFF_SECONDS = 120 # 上传失败的退避
|
||||
MAX_BACKOFF_SECONDS = 900
|
||||
MAX_TRIES = 5 # 回执连续对不上这么多次就转人工,别无限重试
|
||||
# 明确「数据有问题」的状态码:重传也一样会被拒,留着只会无限刷日志
|
||||
PERMANENT_HTTP = (400, 409, 413, 422)
|
||||
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}'
|
||||
r'-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)
|
||||
_SAFE = re.compile(r'[^A-Za-z0-9._:-]')
|
||||
|
||||
|
||||
def _iso(epoch_sec):
|
||||
"""本地时区的 ISO 时间(服务端 new Date() 直接能解析)。"""
|
||||
t = time.localtime(epoch_sec)
|
||||
off = -(time.altzone if t.tm_isdst > 0 else time.timezone)
|
||||
sign = '+' if off >= 0 else '-'
|
||||
off = abs(int(off))
|
||||
return '%s%s%02d:%02d' % (time.strftime('%Y-%m-%dT%H:%M:%S', t),
|
||||
sign, off // 3600, (off % 3600) // 60)
|
||||
|
||||
|
||||
def build_fields(api, op, row, source, captured_at):
|
||||
"""把一条入库行翻成 /mobile/recognition/samples 的字段(全部字符串)。
|
||||
|
||||
这里只描述事实:货单名原样送(「外地芹菜」就是「外地芹菜」),
|
||||
训练用名的翻译在后台审核页做,不动订单、SKU、台账。
|
||||
"""
|
||||
row = row or {}
|
||||
item = str(row.get('item_name') or '').strip()
|
||||
fields = {
|
||||
'sample_id': op,
|
||||
'event_id': op,
|
||||
'scene': 'stock_inbound',
|
||||
'trigger_reason': str(source or '')[:40],
|
||||
'label_name': item[:200],
|
||||
'sku_code': str(row.get('sku_code') or '').strip()[:50],
|
||||
'business_item_id': str(row.get('id') or '').strip()[:100],
|
||||
'order_code': str(row.get('order_code') or '').strip()[:50],
|
||||
'captured_at': _iso(captured_at) if captured_at else '',
|
||||
}
|
||||
# 整组入库:一张照片代表多行验收,单号不是唯一的那一个,
|
||||
# 不瞎填(填错比空着更难查),只在样本上标明这是整组。
|
||||
ids = row.get('inspection_ids')
|
||||
if isinstance(ids, (list, tuple)) and len(ids) > 1:
|
||||
fields['scene'] = 'stock_inbound_group'
|
||||
fields['order_code'] = ''
|
||||
order_item = str(row.get('order_item_id') or '').strip()
|
||||
if _UUID.match(order_item):
|
||||
fields['order_item_id'] = order_item # 服务端只认 UUID,别送别的
|
||||
if '人工' in str(source or ''):
|
||||
# 员工现场选的名字(不是模型认的):审核页要知道「这是人选的」
|
||||
fields['employee_label_name'] = item[:200]
|
||||
return {k: v for k, v in fields.items() if v not in ('', None)}
|
||||
|
||||
|
||||
class ReviewQueue:
|
||||
"""本机待送审队列(一个操作一个目录,原图复制一份进去)。"""
|
||||
|
||||
def __init__(self, root=None):
|
||||
# root 显式传才生效;默认值在调用时取模块常量(测试里能改指向临时目录)
|
||||
self.root = PENDING_DIR if root is None else root
|
||||
|
||||
# ------------------------------------------------ 路径
|
||||
def _dir(self, op):
|
||||
return os.path.join(self.root, _SAFE.sub('_', str(op))[:80])
|
||||
|
||||
def _meta(self, op):
|
||||
return os.path.join(self._dir(op), 'meta.json')
|
||||
|
||||
def _photo(self, op):
|
||||
return os.path.join(self._dir(op), 'photo.jpg')
|
||||
|
||||
def pending_ops(self):
|
||||
try:
|
||||
return sorted(op for op in os.listdir(self.root) if not op.startswith('.stage-'))
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
# ------------------------------------------------ 登记
|
||||
def stage(self, api, op, row, source, path, captured_at=None):
|
||||
"""入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。
|
||||
|
||||
写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理:
|
||||
宁可这笔不发,也不发一笔事后无法追溯的入库。
|
||||
"""
|
||||
d = self._dir(op)
|
||||
existing = atomic.read_json(self._meta(op))
|
||||
if existing:
|
||||
return existing.get('error') or ''
|
||||
if os.path.isdir(d):
|
||||
# 旧版本(原子改名之前)断电留下的半截目录:同名目录占着这个操作号,
|
||||
# 新的改名永远进不来。挪到人工区留档,别让它一直卡在这儿。
|
||||
self._reject(op, {'op': op, 'fields': {}}, '旧版本留下的半截送审记录')
|
||||
os.makedirs(self.root, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='.stage-', dir=self.root) as temp:
|
||||
work = os.path.join(temp, 'record')
|
||||
os.mkdir(work)
|
||||
error = self._write_stage(work, api, op, row, source, path, captured_at)
|
||||
try:
|
||||
os.rename(work, d)
|
||||
except OSError:
|
||||
existing = atomic.read_json(self._meta(op))
|
||||
if not existing:
|
||||
raise
|
||||
return existing.get('error') or ''
|
||||
return error
|
||||
|
||||
def _write_stage(self, d, api, op, row, source, path, captured_at):
|
||||
blob, error = b'', ''
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
blob = f.read()
|
||||
if not blob:
|
||||
error = '原图是空文件'
|
||||
elif len(blob) > 5 * 1024 * 1024:
|
||||
# 服务端上限 5MB;塞进去只会被 413 拒,不如当场记清楚
|
||||
error = '原图 %d 字节,超过服务端 5MB 上限' % len(blob)
|
||||
except (TypeError, OSError) as exc:
|
||||
error = '读不到原图:%s' % exc
|
||||
if blob:
|
||||
tmp = os.path.join(d, 'photo.tmp')
|
||||
with open(tmp, 'wb') as f:
|
||||
f.write(blob)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, os.path.join(d, 'photo.jpg'))
|
||||
if not captured_at:
|
||||
try:
|
||||
captured_at = os.path.getmtime(path)
|
||||
except (TypeError, OSError):
|
||||
captured_at = None
|
||||
meta = {
|
||||
'op': op,
|
||||
'account': str(getattr(api, 'user_id', '') or ''),
|
||||
'server': str(getattr(api, 'base_url', '') or ''),
|
||||
'branch': str(getattr(api, 'review_branch', '') or ''),
|
||||
'fields': build_fields(api, op, row, source, captured_at),
|
||||
'sha256': hashlib.sha256(blob).hexdigest() if blob else '',
|
||||
'bytes': len(blob),
|
||||
'error': error,
|
||||
'retry_at': 0,
|
||||
'tries': 0,
|
||||
'staged_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
}
|
||||
if not atomic.write_json(os.path.join(d, 'meta.json'), meta):
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
raise OSError('送审队列写入失败:%s' % d)
|
||||
return error
|
||||
|
||||
# ------------------------------------------------ 后台核对/补传
|
||||
def drain(self, api, log=None):
|
||||
"""检查入库结论 + 补传。返回本次处理掉的条数(成功或作废)。"""
|
||||
if not api or getattr(api, 'mock', False) or not getattr(api, 'token', ''):
|
||||
return 0
|
||||
now = time.time()
|
||||
handled = 0
|
||||
for op in self.pending_ops():
|
||||
meta = atomic.read_json(self._meta(op))
|
||||
if not meta:
|
||||
self._say(log, '待审记录不完整,原件已保留:%s' % op)
|
||||
continue
|
||||
# 换账号/换服务器:这条不属于当前会话,原样留着等原账号登录
|
||||
if (meta.get('account'), meta.get('server')) != (
|
||||
getattr(api, 'user_id', ''), getattr(api, 'base_url', '')):
|
||||
continue
|
||||
if float(meta.get('retry_at') or 0) > now:
|
||||
continue
|
||||
state = self._journal_state(op)
|
||||
if state == STATE_REJECTED:
|
||||
shutil.rmtree(self._dir(op), ignore_errors=True)
|
||||
handled += 1
|
||||
self._say(log, '入库被拒绝,取消送审:%s' % op)
|
||||
continue
|
||||
if state != STATE_SUCCEEDED:
|
||||
# 入库还没结论(在途/结果不明/待核实):下一轮再看,别抢跑。
|
||||
# 不写盘:这个分支每 20 秒会走一次,写盘只会磨损 SD 卡。
|
||||
continue
|
||||
if float(meta.get('retry_at') or 0) > now:
|
||||
continue # 上次上传失败,退避中
|
||||
if meta.get('bytes', 0) > 5 * 1024 * 1024:
|
||||
self._reject(op, meta, '照片超过后台 5MB 上限')
|
||||
handled += 1
|
||||
self._say(log, '超大原图已转人工:%s' % op)
|
||||
continue
|
||||
try:
|
||||
with open(self._photo(op), 'rb') as f:
|
||||
photo = f.read()
|
||||
except OSError:
|
||||
photo = b''
|
||||
if not photo:
|
||||
self._reject(op, meta, meta.get('error') or '原图已不在本机')
|
||||
handled += 1
|
||||
self._say(log, '本笔没有可送审的原图,已转人工:%s' % op)
|
||||
continue
|
||||
try:
|
||||
ack = api.upload_review_sample(dict(meta.get('fields') or {}),
|
||||
photo)
|
||||
problem = self._ack_problem(meta, ack)
|
||||
if problem:
|
||||
raise ValueError(problem)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if getattr(exc, 'code', None) in PERMANENT_HTTP:
|
||||
self._reject(op, meta, str(exc))
|
||||
handled += 1
|
||||
self._say(log, '送审被拒绝,已转人工:%s(%s)' % (op, exc))
|
||||
else:
|
||||
self._backoff(op, meta, exc, log)
|
||||
continue
|
||||
shutil.rmtree(self._dir(op), ignore_errors=True)
|
||||
handled += 1
|
||||
self._say(log, '入库照片已送审:%s(%s)'
|
||||
% (op, (meta.get('fields') or {}).get('label_name') or ''))
|
||||
return handled
|
||||
|
||||
# ------------------------------------------------ 内部
|
||||
def _journal_state(self, op):
|
||||
rec = atomic.read_json(os.path.join(
|
||||
JOURNAL_DIR, _SAFE.sub('_', str(op)) + '.json'))
|
||||
return str((rec or {}).get('state') or '')
|
||||
|
||||
def _save(self, op, meta, **fields):
|
||||
meta.update(fields)
|
||||
atomic.write_json(self._meta(op), meta)
|
||||
|
||||
def _ack_problem(self, meta, ack):
|
||||
"""回执核对:样本号、照片字节、这一笔的关联资料,全对上才算送到。"""
|
||||
if not isinstance(ack, dict):
|
||||
return '回执不是 JSON 对象'
|
||||
fields = meta.get('fields') or {}
|
||||
if str(ack.get('sample_id') or '') != str(meta.get('op') or ''):
|
||||
return '回执样本号不一致'
|
||||
sha = str(ack.get('image_sha256') or '')
|
||||
if not sha or sha != meta.get('sha256'):
|
||||
return '回执照片内容不一致'
|
||||
branch = str(meta.get('branch') or '')
|
||||
if branch and str(ack.get('branch_code') or '') != branch:
|
||||
return '回执分公司不一致'
|
||||
for key in ('event_id', 'order_code', 'business_item_id',
|
||||
'label_name', 'sku_code'):
|
||||
want = str(fields.get(key) or '')
|
||||
got = str(ack.get(key) or '')
|
||||
if want and want != got:
|
||||
return '回执资料不一致:%s(送 %s / 回 %s)' % (key, want, got)
|
||||
return ''
|
||||
|
||||
def _backoff(self, op, meta, exc, log):
|
||||
tries = int(meta.get('tries') or 0) + 1
|
||||
msg = str(exc)[:300]
|
||||
if isinstance(exc, ValueError) and tries >= MAX_TRIES:
|
||||
# 回执一直对不上:不是网络问题,是数据/接口不对,交人工
|
||||
self._reject(op, meta, msg)
|
||||
self._say(log, '送审连续 %d 次对不上,已转人工:%s(%s)'
|
||||
% (tries, op, msg))
|
||||
return
|
||||
wait = min(MAX_BACKOFF_SECONDS, BACKOFF_SECONDS * (2 ** (tries - 1)))
|
||||
self._save(op, meta, tries=tries, error=msg,
|
||||
retry_at=time.time() + wait)
|
||||
self._say(log, '入库照片还没送出去 %s:%s' % (op, msg))
|
||||
|
||||
def _reject(self, op, meta, reason):
|
||||
"""按操作号保留失败原因、关联资料和原图,供人工重新处理。"""
|
||||
archive = os.path.join(os.path.dirname(self.root), 'review_manual')
|
||||
os.makedirs(archive, exist_ok=True)
|
||||
target = os.path.join(archive, os.path.basename(self._dir(op)))
|
||||
if os.path.exists(target):
|
||||
target += '-' + uuid.uuid4().hex
|
||||
meta = dict(meta, reason=reason, failed_at=time.strftime('%Y-%m-%d %H:%M:%S'))
|
||||
if not atomic.write_json(self._meta(op), meta):
|
||||
raise OSError('人工归档写入失败,保留待传记录:' + op)
|
||||
os.rename(self._dir(op), target)
|
||||
# 兼容以前的最近失败列表;完整记录和原图保存在上面的独立目录。
|
||||
recent = atomic.read_json(REJECTED_FILE) or []
|
||||
if isinstance(recent, list):
|
||||
recent.append(dict(op=op, reason=reason, fields=meta['fields'],
|
||||
at=meta['failed_at'], archive=target))
|
||||
atomic.write_json(REJECTED_FILE, recent[-200:])
|
||||
|
||||
@staticmethod
|
||||
def _say(log, msg):
|
||||
if log:
|
||||
try:
|
||||
log(msg)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,62 @@
|
||||
# 20261201 入库照片送审(数据飞轮:秤 → 后台待审核)
|
||||
|
||||
## 目标
|
||||
|
||||
一笔货在秤上称完、入库成功之后,这张照片要自己出现在后台「识别样本」的待审核列表里,
|
||||
审核员改个训练用名就能收进训练库。**不再靠人拷照片、靠人说是哪一单。**
|
||||
|
||||
## 顺序为什么是这个顺序
|
||||
|
||||
```
|
||||
入库请求发出前 → 本机登记:操作号 + 货单 + 原图副本
|
||||
入库成功(日志 succeeded) → 20 秒内自动送审
|
||||
入库被拒绝(日志 rejected) → 队列里这条删掉
|
||||
断网/重启/断电 → 队列在盘上,开机接着传
|
||||
```
|
||||
|
||||
- 只「成功后补发一次」不行:入库刚成功、秤就断电,这一次发送就永远没了。
|
||||
- 反过来「还没入库就先送」也不行:训练库里会出现一张不属于任何账的图。
|
||||
- 所以先登记(一定要落盘)、等结论(只有 succeeded 才发)、再送。
|
||||
|
||||
## 涉及的文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `core/submission/review_queue.py` | 待送审队列:登记、等结论、补传、转人工 |
|
||||
| `core/flow.py` → `_review_stage()` | 两个入库入口(独立入库 / 有单验收)发请求前调用 |
|
||||
| `core/flow.py` → `_review_retry_loop()` | 每 20 秒核对一次并补传(分拣工位不起这个线程) |
|
||||
| `core/api/client.py` → `upload_review_sample()` | multipart 打 `/mobile/recognition/samples` |
|
||||
| `tools/_test_review_queue.py` | 离线回归(不需要秤/相机/网络) |
|
||||
|
||||
## 盘上留了什么
|
||||
|
||||
```
|
||||
data/review_pending/<操作号>/meta.json 这次操作、货单、单号、拍摄时间、账号、服务器
|
||||
data/review_pending/<操作号>/photo.jpg 原图副本(相机目录会被滚动清理,路径靠不住)
|
||||
data/review_rejected.json 永久失败的那几条(含原因),交人工
|
||||
```
|
||||
|
||||
`meta.json` 里的 `tries`/`error`/`retry_at` 是自己看的:为什么还没送出去、下次什么时候再试。
|
||||
|
||||
## 幂等与核对
|
||||
|
||||
- `sample_id` = `event_id` = 操作号。服务端同一分公司内 `event_id` 唯一,
|
||||
同一张图重复提交只返回 `duplicate`,不会多出一行。
|
||||
- 回执要核对:样本号、照片 `image_sha256`、分公司、`event_id`、单号、货单、SKU。
|
||||
对不上就算「没送到」,留着重试;连续 5 次对不上转人工(不是网络问题,是数据/接口问题)。
|
||||
|
||||
## 日志里会看到什么
|
||||
|
||||
| 日志 | 意思 | 要不要管 |
|
||||
| --- | --- | --- |
|
||||
| `照片已登记待送审(op-…)` | 入库请求要发出去了,照片已在队列 | 不用 |
|
||||
| `入库照片已送审:op-…(芹菜)` | 后台已收到,去审核页就能看到 | 不用 |
|
||||
| `入库被拒绝,取消送审:op-…` | 这笔货没入账,照片不发 | 不用 |
|
||||
| `本笔没有可送审的原图(…),入库照常` | 没抓到合格原图 / 图太大 | 货照收;这一笔不进训练库 |
|
||||
| `入库照片还没送出去 op-…:…` | 网络/服务端问题,退避重试中 | 网络恢复后自己会好 |
|
||||
| `送审被拒绝,已转人工:op-…(…)` | 数据本身有问题(4xx) | 看 `data/review_rejected.json` 的原因 |
|
||||
|
||||
## 分拣工位不送审
|
||||
|
||||
分拣(picking)的照片已经走 `/mobile/picking/weigh-station/photo` 归档,
|
||||
飞轮先只做入库。`_review_stage()` 第一行就按工位短路,不会误发。
|
||||
@@ -0,0 +1,95 @@
|
||||
# 20261201 本地模型自动更新(服务器托管 YOLO-cls)
|
||||
|
||||
## 目标
|
||||
|
||||
模型每攒一批审核图就重训一版,而现场十来台秤分散在几个库房。
|
||||
人工拷 U 盘的结果是「三台新、两台旧,谁也说不出哪台是哪版」。
|
||||
这一轮把「哪一版」变成可比对的版本号:**服务器托管一份,秤端登录后自己对**。
|
||||
|
||||
## 顺序为什么是这个顺序
|
||||
|
||||
```
|
||||
登录成功 → 后台线程问一句「服务器是哪一版」(不挡登录)
|
||||
版本相同 → 什么都不做(一个字节都不下)
|
||||
版本不同 → 下到 models/cls/.incoming/ → 复核 sha256/大小
|
||||
→ 用 local_cls.py 真加载一遍 → 全部通过才替换
|
||||
→ 写 model.json(最后一步)→ 重建分类器
|
||||
任何一步失败 → 丢弃整批,继续用旧版,日志一行
|
||||
```
|
||||
|
||||
三条底线:
|
||||
|
||||
1. **先验后用**:sha256 对不上、或 cv2.dnn 加载不了,一律不换 ——
|
||||
「半个 onnx」比没有 onnx 更坏:读得进来、推理全错,还不报错。
|
||||
2. **原子替换**:两个文件都落在 `.incoming/`,验过才 `os.replace` 到正式路径,
|
||||
`model.json` 最后写。中途断电最坏是版本号对不上、下次重装一遍。
|
||||
3. **绝不挡流程**:所有异常都吞成一行日志。登录、称重、提交一步都不等它。
|
||||
|
||||
## 涉及的文件
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `core/recognition/model_sync.py` | 比对版本、下载、校验、原子替换(本轮新增) |
|
||||
| `core/api/client.py` → `cls_model_manifest()` / `download_cls_model_file()` | 调两个只读接口,流式落盘并复核 sha256 |
|
||||
| `core/recognition/assist.py` → `reload_local()` | 换版后重建分类器(旧实例的 net/names 是上一版) |
|
||||
| `core/flow.py` → `sync_model()` / `_model_sync_loop()` | 登录后查一次 + 每 6 小时复查(后台线程) |
|
||||
| `config.json` → `vision.assist` | `auto_update` / `update_interval_sec` / `update_timeout` |
|
||||
| `tools/sync_cls_model.py` | 现场手工同步/查版本(排障用) |
|
||||
| `tools/_test_cls_model_sync.py` | 离线回归:本机 HTTP 模拟后台,21 项 |
|
||||
| 后台 | `server/src/services/clsModelService.ts` + `routes/mobile/mobileWeighModelRoutes.ts` |
|
||||
|
||||
## 盘上留了什么
|
||||
|
||||
```
|
||||
models/cls/product_cls.onnx 网络权重(10 MB 量级)
|
||||
models/cls/classes.json 类别表 + imgsz(与 onnx 必须同一次训练)
|
||||
models/cls/model.json 本机这一版的版本号、sha256、装于何时
|
||||
models/cls/.incoming/ 下载中转(成功/失败都会清掉)
|
||||
```
|
||||
|
||||
`model.json` 由端上自己写(`source: server`),和训练机 `publish_cls_model.py`
|
||||
写的那份同格式 —— 现场只要比 `version` 就知道新旧。
|
||||
|
||||
## 配置
|
||||
|
||||
```json
|
||||
"vision": {
|
||||
"assist": {
|
||||
"enabled": false,
|
||||
"auto_update": true,
|
||||
"update_interval_sec": 21600,
|
||||
"update_timeout": 180,
|
||||
"model": "models/cls/product_cls.onnx",
|
||||
"classes": "models/cls/classes.json"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `auto_update=false`:不联网,只用手工放进 `models/cls` 的文件(适合无网车间)。
|
||||
- `vision.assist.enabled` 与自动更新**互不影响**:建议模式关着也照样同步模型,
|
||||
这样「哪天打开建议模式」不用先去现场拷文件。
|
||||
- mock 模式(`server.mock=true`)不发任何请求。
|
||||
|
||||
## 现场怎么验(不需要等 6 小时)
|
||||
|
||||
```powershell
|
||||
cd D:\入库分拣工作台
|
||||
python tools\sync_cls_model.py # 打印 本地版本 / 服务器版本 / 结果
|
||||
python tools\sync_cls_model.py --status # 只看本地版本,不联网
|
||||
```
|
||||
|
||||
期望:
|
||||
|
||||
1. 新装秤端(`models/cls` 为空)跑一次后出现三个文件,`model.json.version`
|
||||
与服务端清单一致;
|
||||
2. 服务器再发一版(`publish_cls_model.py`)后,再跑一次 `sync_cls_model.py`
|
||||
得到 `[ok] 已更新到 <version>`,`models/cls/product_cls.onnx` 的 sha256 变了;
|
||||
3. 把服务器清单里的 sha256 故意改错 → `[x] 更新失败:模型 sha256 不符…`,
|
||||
本地文件与版本号**保持不变**(这条比「能更新」更重要)。
|
||||
|
||||
## 还没验证的
|
||||
|
||||
- 没有在实体秤上跑过登录后的自动更新(本机只用本地 HTTP 模拟后台,
|
||||
走的是真 `ApiClient` 的流式下载 + sha256 校验)。
|
||||
- 4G 现场 10 MB 的实际耗时未测(超时默认 180 秒,可按现场调 `update_timeout`)。
|
||||
- 后台两条接口的鉴权只做了代码层面验证(无 `node_modules`,未跑 typecheck/单测)。
|
||||
+5
-3
@@ -1,12 +1,12 @@
|
||||
; ============================================================
|
||||
; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.71.exe
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.72.exe
|
||||
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
|
||||
; ============================================================
|
||||
|
||||
#define AppName "入库分拣工作站"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "1.0.71"
|
||||
#define AppVersion "1.0.72"
|
||||
#endif
|
||||
#define AppExe "入库分拣工作站.exe"
|
||||
#define SrcDir "dist\入库分拣工作站"
|
||||
@@ -41,7 +41,7 @@ CloseApplications=yes
|
||||
RestartApplications=no
|
||||
AllowNoIcons=yes
|
||||
ShowLanguageDialog=no
|
||||
VersionInfoVersion=1.0.71.0
|
||||
VersionInfoVersion=1.0.72.0
|
||||
VersionInfoDescription={#AppName} 安装程序
|
||||
VersionInfoProductName={#AppName}
|
||||
|
||||
@@ -111,6 +111,8 @@ Source: "{#SrcDir}\{#AppExe}"; DestDir: "{app}"; Flags: ignoreversion
|
||||
Source: "{#SrcDir}\使用说明.txt"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 卡片兜底图片(data 下其它内容属于现场台账,升级时不覆盖)
|
||||
Source: "{#SrcDir}\data\photos\*"; DestDir: "{app}\data\photos"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist
|
||||
; 本地识别模型(可选):装包时若带了 models\cls 就一起装;不带也行,秤端登录后自动下载
|
||||
Source: "{#SrcDir}\models\cls\*"; DestDir: "{app}\models\cls"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist
|
||||
; 现场配置:已存在就不动(保住 COM 口、账号、打印机设置)
|
||||
Source: "{#SrcDir}\config.json"; DestDir: "{app}"; Flags: onlyifdoesntexist
|
||||
; VC++ 运行库兜底(仅当目标机缺失时才装)
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据飞轮体检(只读):看看秤端到底有没有把照片/样本记下来
|
||||
|
||||
跑法(在 windows-fenjian 目录下):
|
||||
python tools\\_flywheel_status.py # 打印体检报告
|
||||
python tools\\_flywheel_status.py --open # 顺手用资源管理器打开 data 目录
|
||||
|
||||
飞轮在代码里是三段,本脚本逐段查盘(不写任何文件):
|
||||
① 本地样本库 data/learn/<品名>/<时间>_<来源>_<sha8>.jpg + index.json
|
||||
→ 下次识别当「样例图」喂给模型(few-shot)
|
||||
落盘时机:人点头记账那一刻;camera.simulate=true 时跳过
|
||||
② 入库照片送审 data/review_pending/<操作号>/meta.json + photo.jpg
|
||||
→ 入库成功后台线程送 /mobile/recognition/samples 待人工审核
|
||||
落盘时机:发入库请求之前;server.mock 或模拟相机时跳过
|
||||
③ 抓拍留档 data/snapshots/xxx.jpg(滚动清理,不是训练库)
|
||||
台账 data/records*.csv 记着「哪一笔对应哪张图」
|
||||
|
||||
结论怎么看:① 有张数才是真攒到样本;② 有目录才是真排上了送审。
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
APP = os.path.dirname(HERE)
|
||||
os.chdir(APP)
|
||||
sys.path.insert(0, APP)
|
||||
|
||||
LEARN_INDEX = os.path.join('data', 'learn', 'index.json')
|
||||
LEARN_DIR = os.path.join('data', 'learn')
|
||||
PENDING_DIR = os.path.join('data', 'review_pending')
|
||||
REJECTED = os.path.join('data', 'review_rejected.json')
|
||||
SNAP_DIR = os.path.join('data', 'snapshots')
|
||||
|
||||
ON, OFF = '开', '关'
|
||||
|
||||
|
||||
def _w(s):
|
||||
"""显示宽度:CJK 算 2 列"""
|
||||
return sum(2 if ord(ch) > 0x2E80 else 1 for ch in s)
|
||||
|
||||
|
||||
def col(s, n):
|
||||
s = str(s)
|
||||
return s + ' ' * max(1, n - _w(s))
|
||||
|
||||
|
||||
def sec(title):
|
||||
print('')
|
||||
print('=' * 74)
|
||||
print(title)
|
||||
print('=' * 74)
|
||||
|
||||
|
||||
def kv(k, v):
|
||||
print(' %s%s%s' % (k, ' ' * max(2, 18 - _w(k)), v))
|
||||
|
||||
|
||||
def fmt_size(n):
|
||||
return '%.1f MB' % (n / 1048576.0) if n >= 1048576 else '%d KB' % (n / 1024)
|
||||
|
||||
|
||||
def fmt_at(ts):
|
||||
try:
|
||||
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(ts)))
|
||||
except (TypeError, ValueError):
|
||||
return '-'
|
||||
|
||||
|
||||
def load_json(path, default=None):
|
||||
try:
|
||||
with open(path, encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 现场条件
|
||||
def gates():
|
||||
cfg = load_json('config.json', {}) or {}
|
||||
cam = cfg.get('camera') or {}
|
||||
return {
|
||||
'mock': bool((cfg.get('server') or {}).get('mock')),
|
||||
'role': (cfg.get('account') or {}).get('role') or '',
|
||||
'cam_sim': bool(cam.get('simulate')),
|
||||
'replay': str(cam.get('replay_dir') or '').strip(),
|
||||
'api_key': str((cfg.get('vision') or {}).get('api_key') or '').strip(),
|
||||
'scale_sim': bool((cfg.get('scale') or {}).get('simulate')),
|
||||
}
|
||||
|
||||
|
||||
def show_gates(g):
|
||||
sec('现场条件:三段飞轮各自被什么挡着')
|
||||
kv('server.mock', '%s(%s)' % ('True' if g['mock'] else 'False',
|
||||
'提交不走真服务端' if g['mock'] else '真服务端'))
|
||||
kv('account.role', g['role'] or '(未配)')
|
||||
kv('camera.simulate', '%s(%s)' % ('True' if g['cam_sim'] else 'False',
|
||||
'画面是模拟的' if g['cam_sim'] else '真相机'))
|
||||
kv('camera.replay_dir', g['replay'] or '(空)')
|
||||
kv('scale.simulate', 'True' if g['scale_sim'] else 'False')
|
||||
kv('vision.api_key', '(空)' if not g['api_key'] else '已填(%d 位)'
|
||||
% len(g['api_key']))
|
||||
print('')
|
||||
ok1 = not (g['cam_sim'] or g['replay'])
|
||||
kv('① 本地样本库落盘', '%s%s' % (ON if ok1 else OFF,
|
||||
'' if ok1 else ' camera.simulate/replay 开着 → _learn_sample 直接 return'))
|
||||
ok2 = (not g['mock']) and (not (g['cam_sim'] or g['replay'])) \
|
||||
and g['role'] == 'inspector'
|
||||
kv('② 入库照片送审', '%s%s' % (ON if ok2 else OFF,
|
||||
'' if ok2 else ' _review_stage 前置条件不满足 → 不登记'))
|
||||
kv('③ 抓拍留档', '%s(不管什么模式都会存)' % ON)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ① 样本库
|
||||
def show_learn():
|
||||
sec('① 本地样本库 data/learn(识别时当样例图,反哺模型)')
|
||||
idx = load_json(LEARN_INDEX, {})
|
||||
items = (idx or {}).get('items') or {}
|
||||
rows = []
|
||||
for name, lst in items.items():
|
||||
for r in (lst or []):
|
||||
if isinstance(r, dict) and r.get('file'):
|
||||
rows.append((str(name), r))
|
||||
if not rows:
|
||||
kv('索引', '没有 %s' % LEARN_INDEX.replace(os.sep, '/'))
|
||||
kv('样本', '0 张')
|
||||
if not os.path.isdir(LEARN_DIR):
|
||||
kv('目录', 'data/learn 还不存在')
|
||||
print(' → 没有任何一张图进过样本库,模型下次识别不会看到任何现场样例')
|
||||
return
|
||||
kv('索引', LEARN_INDEX.replace(os.sep, '/'))
|
||||
kv('样本', '%d 张 / %d 个品名' % (len(rows), len(items)))
|
||||
stat = {}
|
||||
for name, r in rows:
|
||||
src = r.get('source') or 'weak'
|
||||
stat.setdefault(name, {}).setdefault(src, 0)
|
||||
stat[name][src] += 1
|
||||
print('')
|
||||
print(' ' + col('品名', 14) + col('weak(AI+人确认)', 18)
|
||||
+ col('fix(人改判)', 14) + '合计')
|
||||
for name in sorted(stat, key=lambda n: -sum(stat[n].values())):
|
||||
s = stat[name]
|
||||
print(' ' + col(name, 14) + col(s.get('weak', 0), 18)
|
||||
+ col(s.get('fix', 0), 14) + str(sum(s.values())))
|
||||
rows.sort(key=lambda x: -(x[1].get('at') or 0))
|
||||
print('')
|
||||
print(' 最近 5 张:')
|
||||
for name, r in rows[:5]:
|
||||
print(' ' + col(fmt_at(r.get('at')), 21) + col(name, 12)
|
||||
+ col(r.get('source') or 'weak', 7) + (r.get('file') or '')
|
||||
+ ((' (原认成 %s)' % r.get('was')) if r.get('was') else ''))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ② 送审
|
||||
def show_pending():
|
||||
sec('② 入库照片送审 data/review_pending(秤 → 后台「识别样本」待审核)')
|
||||
try:
|
||||
ops = sorted(x for x in os.listdir(PENDING_DIR) if not x.startswith('.'))
|
||||
except OSError:
|
||||
ops = []
|
||||
if not ops:
|
||||
kv('队列', '没有 %s' % PENDING_DIR.replace(os.sep, '/'))
|
||||
kv('待审', '0 条')
|
||||
else:
|
||||
kv('队列', PENDING_DIR.replace(os.sep, '/'))
|
||||
kv('待审', '%d 条' % len(ops))
|
||||
print('')
|
||||
for op in ops:
|
||||
d = os.path.join(PENDING_DIR, op)
|
||||
meta = load_json(os.path.join(d, 'meta.json'), {}) or {}
|
||||
photo = os.path.join(d, 'photo.jpg')
|
||||
size = os.path.getsize(photo) if os.path.isfile(photo) else 0
|
||||
fld = meta.get('fields') or {}
|
||||
print(' ' + col(op, 34) + col(fld.get('label_name') or '-', 12)
|
||||
+ col(fld.get('order_code') or '-', 14)
|
||||
+ col(('%d KB' % (size / 1024)) if size else '缺图', 8)
|
||||
+ 'tries=%s %s' % (meta.get('tries', 0),
|
||||
meta.get('error') or ''))
|
||||
rej = load_json(REJECTED, [])
|
||||
kv('被永久拒收', '%d 条(%s)' % (len(rej or []), REJECTED.replace(os.sep, '/')))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ③ 抓拍
|
||||
def show_snapshots():
|
||||
sec('③ 抓拍留档 data/snapshots(不是训练库,滚到一定数量会被清)')
|
||||
files = []
|
||||
try:
|
||||
files = [os.path.join(SNAP_DIR, f) for f in os.listdir(SNAP_DIR)]
|
||||
files = [p for p in files if os.path.isfile(p)]
|
||||
except OSError:
|
||||
pass
|
||||
files.sort(key=lambda p: os.path.getmtime(p))
|
||||
kv('张数', '%d 张 / %s' % (len(files),
|
||||
fmt_size(sum(os.path.getsize(p) for p in files))
|
||||
if files else '0 KB'))
|
||||
print('')
|
||||
print(' 最近 6 张:')
|
||||
for p in files[-6:]:
|
||||
print(' ' + col(time.strftime('%Y-%m-%d %H:%M:%S',
|
||||
time.localtime(os.path.getmtime(p))), 21)
|
||||
+ col(os.path.basename(p), 34)
|
||||
+ '%7d KB' % (os.path.getsize(p) / 1024))
|
||||
|
||||
|
||||
def show_records():
|
||||
sec('记账留痕 data/records*.csv(和飞轮不是一回事,但能对上「哪笔对应哪张图」)')
|
||||
for name in ('records.csv', 'records_demo.csv'):
|
||||
p = os.path.join('data', name)
|
||||
if not os.path.isfile(p):
|
||||
kv(name, '没有')
|
||||
continue
|
||||
try:
|
||||
with open(p, encoding='utf-8-sig') as f:
|
||||
lines = [x for x in f.read().splitlines() if x.strip()]
|
||||
except OSError:
|
||||
lines = []
|
||||
kv(name, '%d 行(含表头)' % len(lines))
|
||||
if len(lines) > 1:
|
||||
print(' 最后一行:' + lines[-1])
|
||||
|
||||
|
||||
def conclude(g):
|
||||
sec('结论')
|
||||
idx = load_json(LEARN_INDEX, {})
|
||||
items = (idx or {}).get('items') or {}
|
||||
n_learn = sum(len(v or []) for v in items.values())
|
||||
try:
|
||||
n_pend = len([x for x in os.listdir(PENDING_DIR) if not x.startswith('.')])
|
||||
except OSError:
|
||||
n_pend = 0
|
||||
try:
|
||||
n_snap = len([x for x in os.listdir(SNAP_DIR)
|
||||
if os.path.isfile(os.path.join(SNAP_DIR, x))])
|
||||
except OSError:
|
||||
n_snap = 0
|
||||
kv('样本库里的图', '%d 张' % n_learn)
|
||||
kv('排队等送审', '%d 条' % n_pend)
|
||||
kv('抓拍留档', '%d 张' % n_snap)
|
||||
print('')
|
||||
if n_learn or n_pend:
|
||||
print(' → 飞轮有记录,见上面 ① / ② 的明细')
|
||||
return
|
||||
print(' → 飞轮一条也没进来:图只落在 data/snapshots 和 records*.csv 里,')
|
||||
print(' 那是「对账留痕」,不会变成训练样本。')
|
||||
if g['cam_sim'] or g['replay']:
|
||||
print(' 原因:camera.simulate=True —— 模拟画面存进去等于拿占位图当教材')
|
||||
if g['mock']:
|
||||
print(' 原因:server.mock=True —— 送审要发到后台,模拟服务端没有收图的地方')
|
||||
print(' 想看飞轮真转起来:真相机(camera.simulate=false)+ 真服务端'
|
||||
'(server.mock=false)+ 入库站(account.role=inspector)')
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--open', action='store_true', help='顺手打开 data 目录')
|
||||
args = ap.parse_args()
|
||||
print('#' * 74)
|
||||
print('# 数据飞轮体检 %s' % time.strftime('%Y-%m-%d %H:%M:%S'))
|
||||
print('#' * 74)
|
||||
g = gates()
|
||||
show_gates(g)
|
||||
show_learn()
|
||||
show_pending()
|
||||
show_snapshots()
|
||||
show_records()
|
||||
conclude(g)
|
||||
print('')
|
||||
if args.open:
|
||||
subprocess.Popen(['explorer', os.path.join(APP, 'data')])
|
||||
print(' 已在资源管理器打开 data 目录')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,293 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""回归测试:本地模型自动更新(模型分发 + 校验 + 替换,不需要秤/相机/真库)。
|
||||
|
||||
盯的是五件事,每一件现场都会发生:
|
||||
1. 服务器有新版本 → 下载、校验、替换、写 model.json;
|
||||
2. 版本没变 → 一个字节都不下(现场十来台秤同时开机,别把带宽吃满);
|
||||
3. 清单 sha256 对不上 → 拒绝替换,本地保持旧版;
|
||||
4. 服务器给的是「端上读不了」的 onnx → 拒绝替换(半个/坏模型比没有更坏);
|
||||
5. 两个文件换到一半失败(第二个 os.replace 失败)→ 回滚,磁盘回到旧版完整
|
||||
状态,不留「新 onnx + 旧 classes + 旧 manifest」混合态(红队 B-2)。
|
||||
|
||||
用本机 HTTP 服务模拟后台,走的是真 `ApiClient`(含真实 multipart 之外的
|
||||
流式下载与 sha256 校验),不 mock 掉被测代码。第 5 条是唯一打桩的用例:
|
||||
它只验回滚,不验加载,所以把 LocalClassifier 换成永远可用的假类。
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
from core.api.client import ApiClient # noqa: E402
|
||||
from core.recognition.local_cls import LocalClassifier # noqa: E402
|
||||
from core.recognition.model_sync import ModelSync # noqa: E402
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(HERE)) # 项目根(…\嵌入式识别)
|
||||
PY_TRAIN = os.path.join(ROOT, 'yolo-training')
|
||||
REAL_ONNX = os.path.join(PY_TRAIN, 'runs', 'cls', 'product', 'weights', 'best.onnx')
|
||||
REAL_CLASSES = os.path.join(PY_TRAIN, 'datasets', 'cls', 'classes.json')
|
||||
|
||||
SRV = {'manifest': None, 'files': {}, 'hits': {}}
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
"""只实现两个只读接口,形状与 mobileWeighModelRoutes 一致。"""
|
||||
|
||||
def log_message(self, *args): # 别把测试输出刷满
|
||||
return
|
||||
|
||||
def _json(self, code, payload):
|
||||
body = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', 'application/json; charset=utf-8')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self): # noqa: N802 http.server 的命名
|
||||
path = self.path.split('?')[0]
|
||||
SRV['hits'][path] = SRV['hits'].get(path, 0) + 1
|
||||
if path == '/api/mobile/weigh/cls-model/manifest':
|
||||
if not SRV.get('manifest'):
|
||||
return self._json(404, {'error': 'model_not_installed'})
|
||||
return self._json(200, {'success': True, 'data': SRV['manifest']})
|
||||
prefix = '/api/mobile/weigh/cls-model/file/'
|
||||
if path.startswith(prefix):
|
||||
name = path[len(prefix):]
|
||||
data = (SRV.get('files') or {}).get(name)
|
||||
if data is None:
|
||||
return self._json(404, {'error': 'model_not_installed'})
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'application/octet-stream')
|
||||
self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
return self._json(404, {'error': 'unknown'})
|
||||
|
||||
|
||||
def publish(version, files, corrupt_sha=False, drop_file=''):
|
||||
"""在「服务器」上发布一版:files = {name: bytes}。"""
|
||||
SRV['files'] = dict(files)
|
||||
rows = []
|
||||
for name, data in files.items():
|
||||
rows.append({'name': name,
|
||||
'sha256': hashlib.sha256(data).hexdigest(),
|
||||
'size': len(data),
|
||||
'url': '/api/mobile/weigh/cls-model/file/' + name})
|
||||
if corrupt_sha and rows:
|
||||
rows[0]['sha256'] = 'f' * 64
|
||||
if drop_file:
|
||||
rows = [r for r in rows if r['name'] != drop_file]
|
||||
SRV['manifest'] = {'schema': 1, 'version': version,
|
||||
'created_at': '2026-12-01T20:00:00+08:00',
|
||||
'imgsz': 320, 'class_count': 875, 'notes': '',
|
||||
'files': rows}
|
||||
SRV['hits'] = {}
|
||||
|
||||
|
||||
def unpublish():
|
||||
SRV['manifest'] = None
|
||||
SRV['files'] = {}
|
||||
SRV['hits'] = {}
|
||||
|
||||
|
||||
def main():
|
||||
ok_n, bad_n = [0], [0]
|
||||
|
||||
def ok(name, cond, extra=''):
|
||||
if cond:
|
||||
ok_n[0] += 1
|
||||
print(' [ok] %s' % name)
|
||||
else:
|
||||
bad_n[0] += 1
|
||||
print(' [x ] %s %s' % (name, extra))
|
||||
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
base = 'http://127.0.0.1:%d/api' % server.server_address[1]
|
||||
|
||||
work = tempfile.mkdtemp(prefix='cls_sync_')
|
||||
old_cwd = os.getcwd()
|
||||
os.chdir(work)
|
||||
try:
|
||||
os.makedirs('models/cls', exist_ok=True)
|
||||
cfg = {'server': {'base_url': base, 'mock': False},
|
||||
'account': {'username': 't'},
|
||||
'vision': {'assist': {
|
||||
'model': 'models/cls/product_cls.onnx',
|
||||
'classes': 'models/cls/classes.json',
|
||||
'auto_update': True, 'update_timeout': 60}}}
|
||||
api = ApiClient(cfg)
|
||||
api.token = 'test-token' # 跳过登录:本测试只验下载链路
|
||||
ms = ModelSync(cfg)
|
||||
|
||||
# 1) 服务器还没发布模型 → skipped,且不动本地目录
|
||||
unpublish()
|
||||
r = ms.run(api, force=True)
|
||||
ok('未发布模型 → skipped', r['status'] == 'skipped', r)
|
||||
ok('未发布时没有下载请求',
|
||||
not any('/file/' in k for k in SRV['hits']), SRV['hits'])
|
||||
ok('未发布时不生成 model.json',
|
||||
not os.path.exists('models/cls/model.json'))
|
||||
|
||||
# 2) 服务器版本清单不完整(少了 classes.json)→ failed,不下载
|
||||
publish('v-broken', {'product_cls.onnx': b'whatever'},
|
||||
drop_file='classes.json')
|
||||
r = ms.run(api, force=True)
|
||||
ok('清单缺文件 → failed', r['status'] == 'failed', r)
|
||||
ok('清单缺文件时不下载',
|
||||
not any('/file/' in k for k in SRV['hits']), SRV['hits'])
|
||||
|
||||
# 3) 坏 onnx(sha 对得上但 cv2 读不了)→ failed,本地不变
|
||||
publish('v-junk', {'product_cls.onnx': b'\x08\x01not-onnx',
|
||||
'classes.json': b'{"names":["a"],"imgsz":320}'})
|
||||
r = ms.run(api, force=True)
|
||||
ok('坏模型 → failed', r['status'] == 'failed', r)
|
||||
ok('坏模型没有被换上去',
|
||||
not os.path.exists('models/cls/product_cls.onnx'))
|
||||
ok('坏模型没留下 .incoming',
|
||||
not os.path.isdir('models/cls/.incoming'))
|
||||
|
||||
# 4) 真模型:发布 → 下载 → 替换
|
||||
if os.path.isfile(REAL_ONNX) and os.path.isfile(REAL_CLASSES):
|
||||
with open(REAL_ONNX, 'rb') as f:
|
||||
onnx_bytes = f.read()
|
||||
with open(REAL_CLASSES, 'rb') as f:
|
||||
classes_bytes = f.read()
|
||||
good = {'product_cls.onnx': onnx_bytes,
|
||||
'classes.json': classes_bytes}
|
||||
|
||||
publish('v1', good)
|
||||
r = ms.run(api, force=True)
|
||||
ok('新版本 → updated', r['status'] == 'updated', r)
|
||||
ok('版本号写进 model.json', ms.local_version() == 'v1',
|
||||
ms.local_version())
|
||||
with open('models/cls/product_cls.onnx', 'rb') as f:
|
||||
got = hashlib.sha256(f.read()).hexdigest()
|
||||
ok('落盘字节与清单一致',
|
||||
got == hashlib.sha256(onnx_bytes).hexdigest())
|
||||
lc = LocalClassifier({'assist': {
|
||||
'model': 'models/cls/product_cls.onnx',
|
||||
'classes': 'models/cls/classes.json'}})
|
||||
ok('换上去的模型端上能加载', lc.available(), lc.reason())
|
||||
|
||||
# 5) 同版本再跑 → current,一个字节都不下
|
||||
before = SRV['hits'].get(
|
||||
'/api/mobile/weigh/cls-model/file/product_cls.onnx', 0)
|
||||
r = ms.run(api, force=True)
|
||||
after = SRV['hits'].get(
|
||||
'/api/mobile/weigh/cls-model/file/product_cls.onnx', 0)
|
||||
ok('同版本 → current', r['status'] == 'current', r)
|
||||
ok('同版本不重复下载', before == after, SRV['hits'])
|
||||
|
||||
# 6) 清单 sha256 对不上 → failed,本地保留 v1
|
||||
publish('v2', good, corrupt_sha=True)
|
||||
r = ms.run(api, force=True)
|
||||
ok('sha256 不符 → failed', r['status'] == 'failed', r)
|
||||
ok('sha256 不符时版本仍是 v1', ms.local_version() == 'v1',
|
||||
ms.local_version())
|
||||
with open('models/cls/product_cls.onnx', 'rb') as f:
|
||||
still = hashlib.sha256(f.read()).hexdigest()
|
||||
ok('sha256 不符时文件没被动过',
|
||||
still == hashlib.sha256(onnx_bytes).hexdigest())
|
||||
|
||||
# 7) 新版本(同字节不同版本号)→ 正常换版
|
||||
publish('v3', good)
|
||||
r = ms.run(api, force=True)
|
||||
ok('换到 v3', r['status'] == 'updated' and ms.local_version() == 'v3',
|
||||
r)
|
||||
|
||||
# 7.5) 同版本但文件被删(人为清目录 / 上次拷一半)→ 自动补装
|
||||
os.remove('models/cls/product_cls.onnx')
|
||||
r = ms.run(api, force=True)
|
||||
ok('同版本但文件缺失 → 重新安装',
|
||||
r['status'] == 'updated'
|
||||
and os.path.isfile('models/cls/product_cls.onnx'), r)
|
||||
|
||||
# 7.6) 两个 os.replace 只成功第一个:第二个失败 → 必须回滚,不能留下
|
||||
# 「新 onnx + 旧 classes + 旧 manifest」混合态(红队 B-2)。
|
||||
# 真模型只有一份,这里打桩成「永远能加载」,只为让替换走到一半。
|
||||
import core.recognition.model_sync as MS
|
||||
with open('models/cls/product_cls.onnx', 'rb') as f:
|
||||
old_onnx = f.read()
|
||||
with open('models/cls/classes.json', 'rb') as f:
|
||||
old_classes = f.read()
|
||||
old_manifest = ms.local_manifest()
|
||||
publish('v4', {'product_cls.onnx': b'\x08fake-new-onnx-b2',
|
||||
'classes.json': b'{"names":["x"],"imgsz":320}'})
|
||||
|
||||
class _AlwaysLoadable: # 只测回滚,加载用例在上面 4)
|
||||
def __init__(self, cfg=None):
|
||||
pass
|
||||
|
||||
def available(self):
|
||||
return True
|
||||
|
||||
def reason(self):
|
||||
return ''
|
||||
|
||||
real_replace = os.replace
|
||||
calls = {'n': 0}
|
||||
|
||||
def flaky_replace(src, dst):
|
||||
calls['n'] += 1
|
||||
if calls['n'] == 2: # 第 1 个文件已换、第 2 个换不动
|
||||
raise OSError('模拟第二个文件替换失败')
|
||||
return real_replace(src, dst)
|
||||
|
||||
saved_probe = MS.LocalClassifier
|
||||
MS.LocalClassifier = _AlwaysLoadable
|
||||
os.replace = flaky_replace
|
||||
try:
|
||||
r = ms.run(api, force=True)
|
||||
finally:
|
||||
os.replace = real_replace
|
||||
MS.LocalClassifier = saved_probe
|
||||
ok('第二个文件替换失败 → failed', r['status'] == 'failed', r)
|
||||
with open('models/cls/product_cls.onnx', 'rb') as f:
|
||||
b2_onnx = f.read()
|
||||
with open('models/cls/classes.json', 'rb') as f:
|
||||
b2_classes = f.read()
|
||||
ok('失败后 onnx 回滚成旧版', b2_onnx == old_onnx)
|
||||
ok('失败后 classes 仍是旧版', b2_classes == old_classes)
|
||||
ok('失败后 model.json 仍是旧版', ms.local_manifest() == old_manifest,
|
||||
ms.local_manifest())
|
||||
ok('失败后不留 .incoming', not os.path.isdir('models/cls/.incoming'))
|
||||
else:
|
||||
print(' [--] 缺 %s 或 %s,跳过真实模型用例' % (REAL_ONNX, REAL_CLASSES))
|
||||
|
||||
# 8) auto_update=false → 不发请求
|
||||
off = json.loads(json.dumps(cfg))
|
||||
off['vision']['assist']['auto_update'] = False
|
||||
unpublish()
|
||||
r = ModelSync(off).run(api, force=True)
|
||||
ok('auto_update=false → skipped', r['status'] == 'skipped', r)
|
||||
ok('auto_update=false 时没有请求', SRV['hits'] == {}, SRV['hits'])
|
||||
|
||||
# 9) mock 模式 → skipped
|
||||
mock_cfg = json.loads(json.dumps(cfg))
|
||||
mock_cfg['server']['mock'] = True
|
||||
r = ModelSync(mock_cfg).run(ApiClient(mock_cfg), force=True)
|
||||
ok('mock → skipped', r['status'] == 'skipped', r)
|
||||
finally:
|
||||
os.chdir(old_cwd)
|
||||
server.shutdown()
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
print()
|
||||
print('通过 %d 项,失败 %d 项' % (ok_n[0], bad_n[0]))
|
||||
return 1 if bad_n[0] else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,215 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""回归测试:入库照片送审队列(不需要秤/相机/网络)。
|
||||
|
||||
盯的是三件事,每一件都是「现场会真的发生」的:
|
||||
1. 入库没成功 → 一张都不许送(否则训练图会挂在不存在的账上);
|
||||
2. 入库成功但当场断电/断网 → 重启后照样送,且只送一次;
|
||||
3. 数据本身有问题(4xx)→ 转人工,别无限刷日志。
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from core.storage import atomic
|
||||
from core.submission import journal as J
|
||||
from core.submission import review_queue as R
|
||||
|
||||
|
||||
class FakeApiError(Exception):
|
||||
"""与 core.api.client.ApiError 同形(只用到 .code/.message)。
|
||||
|
||||
这里不 import 真客户端:那个模块要 requests,本机 python 未必装了,
|
||||
而这条队列本身跟网络库无关 —— 测试要能在任何一台机器上跑。
|
||||
"""
|
||||
|
||||
def __init__(self, code, message):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
class FakeApi:
|
||||
"""只实现队列用到的那几样。ack 按服务端真实回执的形状复刻。"""
|
||||
mock = False
|
||||
token = 'tok'
|
||||
user_id = 'u-1'
|
||||
base_url = 'http://127.0.0.1:3000/api'
|
||||
review_branch = 'B01'
|
||||
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self.fail = None # None / FakeApiError / 'ack_bad'
|
||||
|
||||
def upload_review_sample(self, fields, image):
|
||||
if self.fail is not None and self.fail != 'ack_bad':
|
||||
raise self.fail
|
||||
import hashlib
|
||||
ack = dict(fields)
|
||||
ack['image_sha256'] = hashlib.sha256(image).hexdigest()
|
||||
ack['branch_code'] = 'B01'
|
||||
if self.fail == 'ack_bad':
|
||||
ack['order_code'] = 'NOT-THE-SAME'
|
||||
self.sent.append((dict(fields), image))
|
||||
return ack
|
||||
|
||||
|
||||
logs = []
|
||||
|
||||
|
||||
def say(msg):
|
||||
logs.append(msg)
|
||||
|
||||
|
||||
def fresh_env():
|
||||
root = tempfile.mkdtemp(prefix='review_q_')
|
||||
R.PENDING_DIR = os.path.join(root, 'pending')
|
||||
R.REJECTED_FILE = os.path.join(root, 'rejected.json')
|
||||
# 队列模块在 import 时就把 JOURNAL_DIR 绑进了自己的命名空间,两个都要改
|
||||
J.JOURNAL_DIR = os.path.join(root, 'journal')
|
||||
R.JOURNAL_DIR = J.JOURNAL_DIR
|
||||
os.makedirs(R.PENDING_DIR, exist_ok=True)
|
||||
os.makedirs(J.JOURNAL_DIR, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def photo(root, name='shot.jpg', blob=b'\xff\xd8\xff\xe0PHOTO'):
|
||||
p = os.path.join(root, name)
|
||||
with open(p, 'wb') as f:
|
||||
f.write(blob)
|
||||
return p
|
||||
|
||||
|
||||
def journal(op, state):
|
||||
atomic.write_json(os.path.join(J.JOURNAL_DIR, op + '.json'),
|
||||
{'operationId': op, 'state': state})
|
||||
|
||||
|
||||
def ops():
|
||||
return R.ReviewQueue().pending_ops()
|
||||
|
||||
|
||||
ROW = {'id': 'item-1', 'item_name': '外地芹菜', 'sku_code': 'SKU-1',
|
||||
'order_code': 'O-1', 'order_item_id': 'not-a-uuid'}
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond, detail=''):
|
||||
print((' ok ' if cond else ' [x] ') + name
|
||||
+ ('' if cond else ' ' + detail))
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
print('1) 字段翻译:货单名原样送,训练名不在这里改')
|
||||
f = R.build_fields(FakeApi(), 'op-1', ROW, 'AI识别', time.time())
|
||||
check('label_name 是货单名', f['label_name'] == '外地芹菜', f.get('label_name'))
|
||||
check('带单号', f['order_code'] == 'O-1')
|
||||
check('非 UUID 的 order_item_id 不送', 'order_item_id' not in f, str(f))
|
||||
check('captured_at 是 ISO', 'T' in f['captured_at'] and ':' in f['captured_at'],
|
||||
f.get('captured_at'))
|
||||
group = dict(ROW, inspection_ids=['i-1', 'i-2', 'i-3'])
|
||||
g = R.build_fields(FakeApi(), 'op-2', group, 'AI识别', time.time())
|
||||
check('整组入库标成 group 且不瞎填单号',
|
||||
g['scene'] == 'stock_inbound_group' and not g.get('order_code'), str(g))
|
||||
manual = R.build_fields(FakeApi(), 'op-3', ROW, '人工选中+拿走自动提交', time.time())
|
||||
check('人工选的名字另存 employee_label_name',
|
||||
manual.get('employee_label_name') == '外地芹菜')
|
||||
|
||||
print('2) 入库没结论 → 一张都不送')
|
||||
root = fresh_env()
|
||||
api = FakeApi()
|
||||
qp = R.ReviewQueue()
|
||||
err = qp.stage(api, 'op-a', ROW, 'AI识别', photo(root))
|
||||
check('登记成功', err == '', err)
|
||||
check('磁盘上有原图', os.path.isfile(qp._photo('op-a')))
|
||||
qp.drain(api, say)
|
||||
check('没送', not api.sent)
|
||||
check('还在队列里', ops() == ['op-a'], str(ops()))
|
||||
|
||||
print('3) 入库成功 → 送一次,回执核对通过后出队;再跑不重发')
|
||||
journal('op-a', J.STATE_SUCCEEDED)
|
||||
qp.drain(api, say)
|
||||
check('送了一张', len(api.sent) == 1, str(len(api.sent)))
|
||||
check('出队了', ops() == [], str(ops()))
|
||||
qp.drain(api, say)
|
||||
check('再跑不重发', len(api.sent) == 1, str(len(api.sent)))
|
||||
|
||||
print('4) 断电重启:新进程照样能接着送')
|
||||
qp.stage(api, 'op-b', ROW, 'AI识别', photo(root, 'b.jpg'))
|
||||
journal('op-b', J.STATE_SUCCEEDED)
|
||||
R.ReviewQueue().drain(api, say) # 模拟重启后的新实例
|
||||
check('重启后补上', any(s[0].get('sample_id') == 'op-b' for s in api.sent))
|
||||
|
||||
print('5) 入库被拒绝 → 取消送审,不留垃圾')
|
||||
qp.stage(api, 'op-c', ROW, 'AI识别', photo(root, 'c.jpg'))
|
||||
journal('op-c', J.STATE_REJECTED)
|
||||
before = len(api.sent)
|
||||
qp.drain(api, say)
|
||||
check('没送', len(api.sent) == before)
|
||||
check('队列清干净', 'op-c' not in ops(), str(ops()))
|
||||
|
||||
print('6) 断网 → 留在队列里等下次')
|
||||
qp.stage(api, 'op-d', ROW, 'AI识别', photo(root, 'd.jpg'))
|
||||
journal('op-d', J.STATE_SUCCEEDED)
|
||||
api.fail = FakeApiError(-1, '连接未建立')
|
||||
qp.drain(api, say)
|
||||
check('还在队列', 'op-d' in ops(), str(ops()))
|
||||
meta = atomic.read_json(qp._meta('op-d'))
|
||||
check('记了错因并退避', bool(meta.get('error')) and meta.get('retry_at') > time.time(),
|
||||
str(meta.get('retry_at')))
|
||||
api.fail = None
|
||||
|
||||
print('7) 回执对不上 → 先重试,连错 5 次才转人工')
|
||||
api.fail = 'ack_bad'
|
||||
for _ in range(R.MAX_TRIES):
|
||||
if 'op-d' not in ops():
|
||||
break
|
||||
meta = atomic.read_json(qp._meta('op-d'))
|
||||
atomic.write_json(qp._meta('op-d'), dict(meta, retry_at=0))
|
||||
qp.drain(api, say)
|
||||
check('转人工清单里有它',
|
||||
any(x.get('op') == 'op-d'
|
||||
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
|
||||
check('队列里没有了', 'op-d' not in ops())
|
||||
api.fail = None
|
||||
|
||||
print('8) 数据被服务端明确拒绝(400)→ 直接转人工')
|
||||
qp.stage(api, 'op-e', ROW, 'AI识别', photo(root, 'e.jpg'))
|
||||
journal('op-e', J.STATE_SUCCEEDED)
|
||||
api.fail = FakeApiError(400, '业务拒绝 400: invalid_captured_at')
|
||||
qp.drain(api, say)
|
||||
check('没无限重试', 'op-e' not in ops(), str(ops()))
|
||||
check('人工清单里能查到原因',
|
||||
any('invalid_captured_at' in str(x.get('reason'))
|
||||
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
|
||||
api.fail = None
|
||||
|
||||
print('9) 原图丢了 → 入库照常,但这一笔转人工(不静默丢)')
|
||||
qp.stage(api, 'op-f', ROW, 'AI识别', os.path.join(root, 'no-such.jpg'))
|
||||
journal('op-f', J.STATE_SUCCEEDED)
|
||||
qp.drain(api, say)
|
||||
check('转人工', any(x.get('op') == 'op-f'
|
||||
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
|
||||
check('一条都没发', not any(s[0].get('sample_id') == 'op-f' for s in api.sent))
|
||||
|
||||
print('10) 换账号:别人的队列不碰')
|
||||
qp.stage(api, 'op-g', ROW, 'AI识别', photo(root, 'g.jpg'))
|
||||
journal('op-g', J.STATE_SUCCEEDED)
|
||||
other = FakeApi()
|
||||
other.user_id = 'u-2'
|
||||
qp.drain(other, say)
|
||||
check('原账号的仍留着', 'op-g' in ops(), str(ops()))
|
||||
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
print()
|
||||
if fails:
|
||||
print('[x] %d 项没过:%s' % (len(fails), '、'.join(fails)))
|
||||
sys.exit(1)
|
||||
print('全部通过(%d 条日志)' % len(logs))
|
||||
@@ -0,0 +1,255 @@
|
||||
# -*- 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())
|
||||
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)
|
||||
@@ -0,0 +1,98 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""手工同步本地模型(现场验收/排障用;正常情况下秤端登录后自己会做)。
|
||||
|
||||
用法(在 windows-fenjian 目录下):
|
||||
|
||||
python tools\\sync_cls_model.py # 查一次,服务器有新版就下载替换
|
||||
python tools\\sync_cls_model.py --status # 只看本地版本,不联网
|
||||
python tools\\sync_cls_model.py --config D:\\入库分拣工作台\\config.json
|
||||
|
||||
它和秤端开机做的是同一件事(`core/recognition/model_sync.py`),
|
||||
区别只是把结果打印到控制台,方便现场一眼看清「现在跑的是哪一版、服务器是哪一版」。
|
||||
"""
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
from core.api.client import ApiClient, ApiError # noqa: E402
|
||||
from core.recognition.model_sync import ModelSync # noqa: E402
|
||||
|
||||
|
||||
def load_config(path):
|
||||
for cand in (path, os.path.join(HERE, 'config.json'),
|
||||
os.path.join(HERE, 'config.sanitized.json')):
|
||||
if cand and os.path.isfile(cand):
|
||||
with open(cand, 'r', encoding='utf-8') as f:
|
||||
return cand, json.load(f)
|
||||
raise SystemExit('[x] 找不到 config.json(用 --config 指定)')
|
||||
|
||||
|
||||
def print_local(ms):
|
||||
m = ms.local_manifest()
|
||||
if not m:
|
||||
print('本地模型:未安装(%s 下没有 model.json)' % ms.dir)
|
||||
return
|
||||
print('本地模型:%s(%s 类,装于 %s)'
|
||||
% (m.get('version') or '?', m.get('class_count') or '?',
|
||||
m.get('installed_at') or m.get('created_at') or '?'))
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description='手工同步秤端本地识别模型')
|
||||
ap.add_argument('--config', default='', help='config.json 路径')
|
||||
ap.add_argument('--status', action='store_true', help='只看本地版本,不联网')
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
path, cfg = load_config(a.config)
|
||||
print('配置:%s' % path)
|
||||
ms = ModelSync(cfg)
|
||||
print_local(ms)
|
||||
if a.status:
|
||||
return 0
|
||||
|
||||
api = ApiClient(cfg)
|
||||
if getattr(api, 'mock', False):
|
||||
print('[x] 这份配置是 mock 模式(server.mock=true),不会联网')
|
||||
return 2
|
||||
try:
|
||||
api.login()
|
||||
except ApiError as e:
|
||||
print('[x] 登录失败(%s):%s' % (e.code, e.message))
|
||||
return 2
|
||||
try:
|
||||
remote = api.cls_model_manifest()
|
||||
except ApiError as e:
|
||||
print('[x] 取服务器版本失败(%s):%s' % (e.code, e.message))
|
||||
return 2
|
||||
if not remote:
|
||||
print('服务器:还没有发布模型(404)—— 本地保持现状')
|
||||
return 0
|
||||
print('服务器:%s(%s 类,发布于 %s%s)'
|
||||
% (remote.get('version') or '?', remote.get('class_count') or '?',
|
||||
remote.get('created_at') or '?',
|
||||
',' + remote['notes'] if remote.get('notes') else ''))
|
||||
|
||||
res = ms.run(api, force=True)
|
||||
status = res.get('status')
|
||||
if status == 'updated':
|
||||
print('[ok] 已更新到 %s —— 重启秤端后生效(正在运行的界面仍用旧模型)'
|
||||
% res.get('version'))
|
||||
return 0
|
||||
if status == 'current':
|
||||
print('[ok] 已是最新,无需下载')
|
||||
return 0
|
||||
if status == 'skipped':
|
||||
print('[!] 跳过:%s' % res.get('reason'))
|
||||
return 0
|
||||
print('[x] 更新失败:%s(本地仍是原版本)' % res.get('reason'))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -39,7 +39,7 @@ class _BoolVar:
|
||||
self._sw.set(v)
|
||||
|
||||
|
||||
APP_VERSION = '1.0.71'
|
||||
APP_VERSION = '1.0.72'
|
||||
|
||||
# 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。
|
||||
# Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏
|
||||
|
||||
@@ -25,7 +25,31 @@
|
||||
build_assets/ 打包素材(VC++ 运行库 vc_redist.x64.exe)
|
||||
打包.bat 双击打包
|
||||
dist/ 产物:dist\入库分拣工作站\(绿色版)
|
||||
dist\入库分拣工作站_安装程序_v1.0.71.exe(安装包)
|
||||
dist\入库分拣工作站_安装程序_v1.0.72.exe(安装包)
|
||||
|
||||
【v1.0.72 本地模型自动更新 + 数据飞轮(2026-12-02)】
|
||||
|
||||
◆ 本地识别模型可以「服务器换版、秤端自动跟上」了
|
||||
· 秤端登录后在后台问一句服务器上是哪一版(不挡登录);版本相同就一个字节都不下。
|
||||
· 版本不同 → 下到 models\cls\.incoming\ → 核对 sha256 与大小 → 用本机 cv2.dnn
|
||||
真加载一遍 → 全部通过才替换,model.json 最后写。任一步失败就整批丢弃、
|
||||
继续用旧版,日志一行,不影响称重与提交。
|
||||
· models\cls\ 里没有模型也不报错:本地建议功能等于没开,其余流程不变。
|
||||
· 手工同步 / 看版本:python tools\sync_cls_model.py(--status 只看本地版本)。
|
||||
· 自动更新开关:config.json → vision.assist.auto_update(默认 true)。
|
||||
|
||||
◆ 数据飞轮:入库照片自动送审(不再靠人拷照片)
|
||||
· 入库请求发出前先在本机登记(操作号 + 货单 + 原图副本);入库成功(日志
|
||||
succeeded)后 20 秒内自动传到后台「识别样本」待审核;被拒绝则从队列删掉。
|
||||
· 断网 / 重启 / 断电:队列在盘上,开机接着传;4xx 明确拒绝的转人工处理。
|
||||
· 只送「入库成功」的货:没成功记账的照片不会出现在训练库里。
|
||||
|
||||
◆ assist 留痕(每笔确认一行,数据不出本机)
|
||||
· data\assist\cycles\YYYY-MM-DD.jsonl:抓拍图及其 sha/修改时间、秤读数、
|
||||
当时完整的待办名单快照、本地建议与云端返回、您最后选的那一行、是否改判。
|
||||
· 前提、四个出口与可调项见下面【本地引擎给建议(v1.1.0,vision.assist)】一节。
|
||||
|
||||
◆ 查看飞轮状态:python tools\_flywheel_status.py
|
||||
|
||||
【v1.0.71 入库「手动确认」按账号开关(2026-11-29)】
|
||||
|
||||
@@ -431,6 +455,36 @@
|
||||
|
||||
◆ 不想用飞轮:vision.few_shot_max 设 0,识别就回到"只用文字规则"。
|
||||
|
||||
【本地引擎给建议(v1.1.0,vision.assist)】
|
||||
一句话:**本地模型只是在旁边说一句"我看着像苹果",记账永远是您点的。**
|
||||
◆ 98% 是什么:只是「这次还要不要额外问一次云端」的开关,**不是准确率声明**。
|
||||
本地 ≥98% → 这一单省一次云端调用;本地 <98% 或本地没意见 → 照旧问云端。
|
||||
两个引擎都说苹果,也仍然要您点一下确认(force_confirm,默认开)。
|
||||
◆ 四个出口,一个都不会卡住流程:
|
||||
① 本地够 98% → 不问云端,界面预选那一行,等人确认
|
||||
② 本地不到 98% → 问云端,两边意见都写进日志,等人确认
|
||||
③ 云端答不上(名单外/超时/断网)→ 本地建议顶着预选,云端那格留空
|
||||
④ 两边都没有 → 人工确认页,跟没有这个功能时一模一样
|
||||
◆ 前提(没有就是"本地没意见",功能等于没开,不会报错):
|
||||
models\cls\product_cls.onnx 分类模型(cv2.dnn 直接跑,不装 onnxruntime)
|
||||
models\cls\classes.json 类别表,顺序必须和模型输出一致
|
||||
由 yolo-training\scripts\export_cls.py 生成;没模型时日志会写一行原因。
|
||||
◆ 记录(飞轮的本体,每笔确认一行,数据不出本机):
|
||||
data\assist\cycles\2026-11-30.jsonl
|
||||
一行里有:抓拍图 + 它的 sha/修改时间(证明这张图确实属于这次称重)、
|
||||
秤读数、**当时的完整待办名单快照**、本地建议的名字+分数、云端返回的
|
||||
name/conf/alt(没调用就空着)、**您最后选的那一行**、以及您有没有改判。
|
||||
图对不上就整条丢掉 —— 错标签不报错,只会安静地把训练集喂歪。
|
||||
◆ 可调(config.json 的 vision.assist,改完重启):
|
||||
enabled 总开关,默认 false
|
||||
ask_cloud_below 默认 0.98;设高=几乎每单都问云端(配对数据更多)
|
||||
force_confirm 默认 true;开了就强制人工确认,别关
|
||||
model / classes onnx 与类别表路径
|
||||
imgsz 320(要和 classes.json 里的一致)
|
||||
topk 日志里保留几个候选,默认 3
|
||||
◆ 怎么停:enabled 改回 false,行为立刻回到加这个功能之前(建议模式的代码
|
||||
全部在旁路上,不碰任何记账逻辑)。
|
||||
|
||||
【按「秤上实际重量」记账、打印(v1.0.54)】
|
||||
现场(11-05 20:25):小青辣椒走在免称重那条路上(画面自动识别 → 点名单
|
||||
里那一行),记进系统的量是这一行的应量 5.00 斤,货其实压在秤上 2.810 kg
|
||||
|
||||
Reference in New Issue
Block a user