Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d4f2d1ba3 | ||
|
|
4966345424 | ||
|
|
453d0b3478 | ||
|
|
6b76769714 | ||
|
|
edaa057d68 | ||
|
|
d2760850ca | ||
|
|
366526b9e5 | ||
|
|
9cae7874dc | ||
|
|
17048a6459 | ||
|
|
e87674a837 | ||
|
|
86d57974b0 | ||
|
|
e313739453 | ||
|
|
7b9acb23b2 | ||
|
|
ae5230909c | ||
|
|
0151e4fbb0 | ||
|
|
256debdeb4 | ||
|
|
cf1e539385 | ||
|
|
640cce06b0 | ||
|
|
cecfcad8c7 | ||
|
|
5e980adfd3 | ||
|
|
fb5c88f90d | ||
|
|
827c8b4f42 | ||
|
|
6c0e5d7f57 | ||
|
|
2ec14ad9c2 | ||
|
|
a9d7f15e57 | ||
|
|
22c1750c9b | ||
|
|
a74edd316e | ||
|
|
dde18c1d87 | ||
|
|
96ce5796f2 | ||
|
|
9b1611a6de | ||
|
|
a3166c725e | ||
|
|
898cf19919 | ||
|
|
3e7d19182f | ||
|
|
50caf99993 |
+36
-30
@@ -1,30 +1,36 @@
|
||||
# 排除配送系统文件夹
|
||||
配送系统/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
*.egg-info/
|
||||
dist/
|
||||
dist-old/
|
||||
build/
|
||||
build-old/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# 系统文件
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# 临时文件
|
||||
*.log
|
||||
*.tmp
|
||||
_nul
|
||||
# 排除配送系统文件夹
|
||||
配送系统/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
*.egg-info/
|
||||
dist/
|
||||
dist-old/
|
||||
build/
|
||||
build-old/
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# 系统文件
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# 临时文件
|
||||
*.log
|
||||
*.tmp
|
||||
_nul
|
||||
|
||||
# 本地识别模型(YOLO-cls):由服务端分发/本地发布脚本写入 models/cls,约 10MB,不入库
|
||||
models/cls/
|
||||
|
||||
/build_onefile/
|
||||
/dist_onefile/
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
{
|
||||
"server": {
|
||||
"base_url": "http://127.0.0.1:3001/api",
|
||||
"mock": true
|
||||
},
|
||||
"account": {
|
||||
"username": "demo",
|
||||
"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": 2.55,
|
||||
"sim_loop_hold_s": 2.5,
|
||||
"sim_loop_keep_s": 10.0,
|
||||
"sim_loop_idle_s": 3.0,
|
||||
"sim_loop_jitter_kg": 0.05
|
||||
},
|
||||
"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": true,
|
||||
"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,
|
||||
"confirm_before_submit": true,
|
||||
"submit_on_remove": false,
|
||||
"inbound_auto_submit": false
|
||||
},
|
||||
"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": "none",
|
||||
"fit_screen": false
|
||||
},
|
||||
"devices": {
|
||||
"auto_detect": true
|
||||
}
|
||||
}
|
||||
+17
-17
@@ -1,17 +1,17 @@
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 64, 0), prodvers=(1, 0, 64, 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.64.0'),
|
||||
StringStruct('InternalName', 'WeighStation'),
|
||||
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
|
||||
StringStruct('ProductName', '入库分拣工作站'),
|
||||
StringStruct('ProductVersion', '1.0.64.0'),
|
||||
StringStruct('LegalCopyright', '内部使用')])]),
|
||||
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
||||
]
|
||||
)
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 76, 0), prodvers=(1, 0, 76, 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.76.0'),
|
||||
StringStruct('InternalName', 'WeighStation'),
|
||||
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
|
||||
StringStruct('ProductName', '入库分拣工作站'),
|
||||
StringStruct('ProductVersion', '1.0.76.0'),
|
||||
StringStruct('LegalCopyright', '内部使用')])]),
|
||||
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
||||
]
|
||||
)
|
||||
|
||||
+23
-3
@@ -1,4 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# -*- coding: utf-8 -*-
|
||||
"""一键打包:图标 → PyInstaller → 补齐资源 → Inno Setup 安装包
|
||||
|
||||
用法(在项目根目录):
|
||||
@@ -20,7 +20,7 @@ import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
APP_NAME = '入库分拣工作站'
|
||||
APP_VERSION = '1.0.64'
|
||||
APP_VERSION = '1.0.76'
|
||||
ASSETS = os.path.join(ROOT, 'assets')
|
||||
DIST = os.path.join(ROOT, 'dist')
|
||||
OUT = os.path.join(DIST, APP_NAME)
|
||||
@@ -107,7 +107,7 @@ def copy_resources():
|
||||
"""把现场需要看的/需要改的文件放到 exe 同目录(不塞进包内)"""
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
pairs = [
|
||||
(os.path.join(ROOT, 'config.json'), os.path.join(OUT, 'config.json')),
|
||||
(os.path.join(ASSETS, 'config.default.json'), os.path.join(OUT, 'config.json')),
|
||||
(os.path.join(ROOT, '使用说明.txt'), os.path.join(OUT, '使用说明.txt')),
|
||||
]
|
||||
for src, dst in pairs:
|
||||
@@ -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,111 @@
|
||||
{
|
||||
"server": {
|
||||
"base_url": "http://127.0.0.1:3001/api",
|
||||
"mock": true
|
||||
},
|
||||
"account": {
|
||||
"username": "demo",
|
||||
"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": 2.55,
|
||||
"sim_loop_hold_s": 2.5,
|
||||
"sim_loop_keep_s": 10.0,
|
||||
"sim_loop_idle_s": 3.0,
|
||||
"sim_loop_jitter_kg": 0.05
|
||||
},
|
||||
"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": true,
|
||||
"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,
|
||||
"confirm_before_submit": true,
|
||||
"submit_on_remove": false,
|
||||
"inbound_auto_submit": false
|
||||
},
|
||||
"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": "none",
|
||||
"fit_screen": false
|
||||
},
|
||||
"devices": {
|
||||
"auto_detect": true
|
||||
}
|
||||
}
|
||||
+337
-8
@@ -8,6 +8,7 @@
|
||||
|
||||
mock=True 时用内置数据离线跑通全流程(P1/P2 验收用),接口签名与真实模式一致。
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
@@ -160,9 +161,16 @@ class ApiClient:
|
||||
self.account = cfg.get('account', {})
|
||||
self.base_url = self.cfg.get('base_url', '')
|
||||
self.mock = bool(self.cfg.get('mock'))
|
||||
self._flow_cfg = cfg.get('flow', {}) or {}
|
||||
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))
|
||||
self._session = requests.Session()
|
||||
# 禁用系统代理,直连服务器(避免HTTP代理无法处理HTTPS)
|
||||
self._session.trust_env = False
|
||||
@@ -172,6 +180,8 @@ class ApiClient:
|
||||
def login(self):
|
||||
if self.mock:
|
||||
self.token = 'mock-token-' + self.user_id
|
||||
self.inbound_auto_submit = bool(
|
||||
self._flow_cfg.get('inbound_auto_submit', True))
|
||||
return {'user_id': self.user_id, 'role': self.account.get('role')}
|
||||
# role_type 服务端取 picker / inspector(与安卓端一致);
|
||||
# 兼容旧配置里误写成 picking / inspection 的情况
|
||||
@@ -201,7 +211,11 @@ class ApiClient:
|
||||
prof = r.get('profile') or {}
|
||||
self.account_name = (r.get('user_name') or prof.get('full_name')
|
||||
or prof.get('username') or '').strip()
|
||||
# 2026-11-29:账号级「入库自动提交」开关(服务端 profiles.inbound_auto_submit)
|
||||
# 缺省/旧服务端/未下发 ⇒ 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):
|
||||
@@ -238,9 +252,121 @@ class ApiClient:
|
||||
name = ''
|
||||
if isinstance(r, dict):
|
||||
name = r.get('user_name') or ''
|
||||
if (station != 'picking' and not self.mock
|
||||
and bool(self._flow_cfg.get('group_inbound', True))):
|
||||
grouped = self.pending_grouped(flat_rows=rows, timeout=timeout)
|
||||
if grouped:
|
||||
return {'rows': grouped['rows'],
|
||||
'config': grouped.get('config') or conf,
|
||||
'account_name': name or self.account_name}
|
||||
return {'rows': rows, 'config': conf,
|
||||
'account_name': name or self.account_name}
|
||||
|
||||
# ------------------------------------------------ 分组入库(安卓同款)
|
||||
def _preview_group_rows(self, grouped_data, flat_rows):
|
||||
"""把 pending-grouped 的组转换成终端统一的行结构。
|
||||
|
||||
安卓端 pending-grouped 每组一条;Windows 现有 UI/匹配都按“行”工作,
|
||||
所以这里把组映射成一行:id 取首张待验单,inspection_ids 保存整组,
|
||||
prepare_qty/required_qty 用组内合计,group_key/group_hash 随行带上。
|
||||
"""
|
||||
flat_by_id = {str(r.get('id') or ''): r for r in (flat_rows or [])}
|
||||
out = []
|
||||
for g in grouped_data or []:
|
||||
if not isinstance(g, dict):
|
||||
continue
|
||||
ids = [str(x) for x in (g.get('inspection_ids') or []) if str(x or '').strip()]
|
||||
if not ids:
|
||||
continue
|
||||
lines = g.get('lines') if isinstance(g.get('lines'), list) else []
|
||||
first_line = lines[0] if lines and isinstance(lines[0], dict) else {}
|
||||
base = flat_by_id.get(ids[0]) or {}
|
||||
row = dict(base)
|
||||
row.update({
|
||||
'id': ids[0],
|
||||
'inspection_ids': ids,
|
||||
'group_key': str(g.get('group_key') or ''),
|
||||
'group_hash': str(g.get('group_hash') or ''),
|
||||
'group_order_count': int(g.get('order_count') or 0),
|
||||
'order_code': first_line.get('order_code') or g.get('order_code') or '',
|
||||
'sku_code': g.get('sku_code') or base.get('sku_code'),
|
||||
'item_name': g.get('item_name') or base.get('item_name'),
|
||||
'unit': g.get('unit') or base.get('unit'),
|
||||
'supplier_code': g.get('supplier_code') or base.get('supplier_code'),
|
||||
'supplier_name': g.get('supplier_name') or base.get('supplier_name'),
|
||||
'source_type': g.get('source_type') or base.get('source_type'),
|
||||
'branch_code': g.get('branch_code') or base.get('branch_code'),
|
||||
'prepare_qty': g.get('total_prepare_qty'),
|
||||
'required_qty': g.get('total_prepare_qty'),
|
||||
'remaining_qty': g.get('total_prepare_qty'),
|
||||
'requires_photo_inspection': bool(g.get('requires_photo_inspection') or base.get('requires_photo_inspection')),
|
||||
'requires_photo': bool(g.get('requires_photo_inspection') or base.get('requires_photo')),
|
||||
'grouped_inbound': True,
|
||||
'group_lines': lines,
|
||||
})
|
||||
# 组内可能同时有「独立入库·加工原材料」和普通订单行:把两边的量
|
||||
# 算出来挂在行上,卡片才能分开显示(以前只挂一个“独立入库”标签,
|
||||
# 32 斤看着像全是原料)。
|
||||
try:
|
||||
from core.matching.engine import is_independent_inbound
|
||||
except Exception: # noqa: BLE001
|
||||
def is_independent_inbound(_r): # type: ignore
|
||||
return False
|
||||
parts = {}
|
||||
for i in ids:
|
||||
fr = flat_by_id.get(i) or {}
|
||||
kind = ('independent' if is_independent_inbound(fr)
|
||||
else 'normal')
|
||||
try:
|
||||
q = float(fr.get('remaining_qty')
|
||||
or fr.get('required_qty')
|
||||
or fr.get('prepare_qty') or 0)
|
||||
except (TypeError, ValueError):
|
||||
q = 0.0
|
||||
p = parts.setdefault(kind, {'kind': kind, 'qty': 0.0,
|
||||
'rows': 0})
|
||||
p['qty'] += q
|
||||
p['rows'] += 1
|
||||
if parts:
|
||||
row['group_parts'] = [parts[k] for k in
|
||||
('independent', 'normal') if k in parts]
|
||||
# 独立入库在分组键里带 independent 段;服务端没回 processing_details
|
||||
# 时靠它识别。但组里混有普通订单行时不能把整组标成独立入库。
|
||||
gkey = str(g.get('group_key') or '').lower()
|
||||
only_indep = bool(parts) and all(
|
||||
p['kind'] == 'independent' for p in parts.values())
|
||||
mixed = bool(parts) and not only_indep
|
||||
if mixed:
|
||||
# 组里混有普通订单行:整组不能当“独立入库”去走单行结案。
|
||||
# 标记是从首行(flat base)继承过来的,得清掉。
|
||||
pd = row.get('processing_details')
|
||||
if isinstance(pd, dict):
|
||||
pd = dict(pd)
|
||||
pd['independent_inbound'] = False
|
||||
row['processing_details'] = pd
|
||||
else:
|
||||
row.pop('processing_details', None)
|
||||
row.pop('independent_inbound', None)
|
||||
elif (not row.get('processing_details')) and 'independent' in gkey \
|
||||
and (only_indep or not parts):
|
||||
row['processing_details'] = {'independent_inbound': True}
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
def pending_grouped(self, flat_rows=None, timeout=None):
|
||||
"""拉同商品多订单聚合待办(仅入库站);失败返回 None,由调用方回退逐行。"""
|
||||
try:
|
||||
r = self._request('GET', '/mobile/inspection/weigh-station/pending-grouped',
|
||||
timeout=timeout)
|
||||
except Exception:
|
||||
return None
|
||||
data = r.get('data') if isinstance(r, dict) else r
|
||||
groups = data if isinstance(data, list) else []
|
||||
rows = self._preview_group_rows(groups, flat_rows or [])
|
||||
if not rows:
|
||||
return None
|
||||
return {'rows': rows, 'config': (r.get('config') or {}) if isinstance(r, dict) else {}}
|
||||
|
||||
# ------------------------------------------------ 识别(服务端通道,可选)
|
||||
def get_prompts(self, keys):
|
||||
"""拉识别提示词**原文**(未渲染,占位符保留)。
|
||||
@@ -340,8 +466,12 @@ class ApiClient:
|
||||
if not token:
|
||||
raise ApiError(-5, '服务端未返回范围凭据(scope_token),未发送')
|
||||
if not data.get('strict_write_enabled', True):
|
||||
# 不是网络/数据问题,是服务端把这台机器的「严格入库写入」关了。
|
||||
# 客户端不发(发了也写不进去,还会留下未决提交);把处置动作写清楚,
|
||||
# 免得现场以为是自己操作错了。
|
||||
raise ApiError(-5, '服务端严格写入开关未开启'
|
||||
'(strict_write_enabled=false),无法提交')
|
||||
'(strict_write_enabled=false),本次未提交;'
|
||||
'请管理员在服务端开启「严格入库写入」后重试')
|
||||
return {'scope_token': token,
|
||||
'strict_write_enabled': True,
|
||||
'expires_at': data.get('expires_at') or '',
|
||||
@@ -367,15 +497,76 @@ class ApiClient:
|
||||
or self.cfg.get('inspection_quality_rating')
|
||||
or '合格')
|
||||
# 请求体与安卓 buildStrictBody 对齐(范围由凭据锁定,不再传 ids)
|
||||
body = {
|
||||
'operation_id': operation_id,
|
||||
'scope_token': scope_token,
|
||||
'actual_qty': qty, 'actual_weight': weight,
|
||||
'quality_rating': rating,
|
||||
'force_complete': bool(force_complete),
|
||||
}
|
||||
# complete-merge-strict 端点只解析 force_complete,不支持原料批次结案;
|
||||
# 独立原料永远走 complete-merge-group 或 /inspection/complete 单行路径。
|
||||
return self._request(
|
||||
'POST', '/mobile/inspection/complete-merge-strict', body={
|
||||
'operation_id': operation_id,
|
||||
'scope_token': scope_token,
|
||||
'actual_qty': qty, 'actual_weight': weight,
|
||||
'quality_rating': rating,
|
||||
'force_complete': bool(force_complete)})
|
||||
'POST', '/mobile/inspection/complete-merge-strict', body=body)
|
||||
|
||||
def commit_inspection_single(self, row, qty, weight_kg, operation_id):
|
||||
def commit_inspection_group(self, row, qty, weight_kg, operation_id,
|
||||
force_complete=False, quality_rating=None,
|
||||
force_close_raw_batch=False):
|
||||
"""同商品多订单整组入库(安卓 complete-merge-group 同款)。
|
||||
|
||||
一次称重提交整组 inspection_ids;服务端按组内待验量 FIFO 分摊。
|
||||
该接口没有 operation_id 幂等键,结果不明时只能查待办核实,绝不换号重提。
|
||||
"""
|
||||
ids = [str(x) for x in (row.get('inspection_ids') or []) if str(x or '').strip()]
|
||||
if not ids:
|
||||
raise ApiError(-3, '缺少整组待验明细,本次未发送')
|
||||
if self.mock:
|
||||
return {'operation_status': 'committed_by_this_operation',
|
||||
'client_operation_id': operation_id,
|
||||
'data': {'merged': True, 'mergedCount': len(ids)}}
|
||||
body = {
|
||||
'inspection_ids': ids,
|
||||
'actual_qty': round(float(qty or 0), 3),
|
||||
'quality_rating': (quality_rating or self.cfg.get('inspection_quality_rating') or '合格'),
|
||||
'loss_qty': 0,
|
||||
}
|
||||
group_key = str(row.get('group_key') or '').strip()
|
||||
group_hash = str(row.get('group_hash') or '').strip()
|
||||
if group_key:
|
||||
body['group_key'] = group_key
|
||||
if group_hash:
|
||||
body['group_hash'] = group_hash
|
||||
w = float(weight_kg or 0)
|
||||
if w > 0:
|
||||
body['actual_weight'] = round(w, 4)
|
||||
if force_complete:
|
||||
body['force_complete'] = True
|
||||
# 偏差入库/短收结案:强制结束独立原料采购批次,服务端不再派生续验单。
|
||||
# 普通整组入库不传该字段,行为与旧版一致。
|
||||
if force_close_raw_batch:
|
||||
body['force_close_raw_batch'] = True
|
||||
r = self._request('POST', '/mobile/inspection/complete-merge-group', body=body)
|
||||
data = r.get('data') if isinstance(r, dict) else None
|
||||
if isinstance(r, dict) and r.get('success') is False:
|
||||
raise ApiError(-5, '服务端未入账:%s'
|
||||
% (r.get('error_description') or r.get('error') or r))
|
||||
# 统一成 _verify 认识的形态:本接口没有 operation_id,成功响应即本次入账。
|
||||
# 短收部分成功(2026-11-22 方案 A,见 docs/design/20261122-weigh-group-partial-inbound.md):
|
||||
# 后端 200 + partialGroup/remainingQty(已入 N 行、剩余行继续待验),这里把关键字段带出来
|
||||
# 供 UI 提示「下次再称」,并提示不要拿旧组重试。
|
||||
d = data if isinstance(data, dict) else {}
|
||||
return {'operation_status': 'committed_by_this_operation',
|
||||
'client_operation_id': operation_id,
|
||||
'data': d,
|
||||
'group_hash': group_hash,
|
||||
'partial_group': bool(d.get('partialGroup')),
|
||||
'merged_count': d.get('mergedCount'),
|
||||
'remaining_qty': d.get('remainingQty'),
|
||||
'unallocated_lines': d.get('unallocatedLines') or []}
|
||||
|
||||
def commit_inspection_single(self, row, qty, weight_kg, operation_id,
|
||||
force_complete=False,
|
||||
force_close_raw_batch=False):
|
||||
"""无单自采行(independent_inbound)单行验收结案。
|
||||
|
||||
为什么单独一个方法:这类行(后台「新增自采商品/加单独立入库」建的
|
||||
@@ -408,6 +599,10 @@ class ApiClient:
|
||||
'actual_qty': round(float(qty or 0), 3),
|
||||
'quality_rating': rating,
|
||||
'loss_qty': 0}
|
||||
if force_complete:
|
||||
body['force_complete'] = True
|
||||
if force_close_raw_batch:
|
||||
body['force_close_raw_batch'] = True
|
||||
w = float(weight_kg or 0)
|
||||
if w > 0:
|
||||
# 秤读数记斤(与安卓端一致:kg×2);只作留档参考,不参与记账
|
||||
@@ -531,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 = {}
|
||||
|
||||
+106
-1
@@ -954,7 +954,8 @@ class FrameSource:
|
||||
def preview_status(self):
|
||||
with self._lock:
|
||||
if self.cfg.get('simulate'):
|
||||
return '模拟摄像头(合成画面)'
|
||||
return (getattr(self, '_replay_info', '')
|
||||
or '模拟摄像头(合成画面)')
|
||||
if self.error:
|
||||
return self.error
|
||||
return self.status or '摄像头启动中…'
|
||||
@@ -996,7 +997,111 @@ class FrameSource:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------ 模拟画面
|
||||
def _replay_files(self):
|
||||
"""camera.replay_dir 里的图片清单(没配/目录不存在就返回空)
|
||||
|
||||
没摄像头时用它把真实商品照片当画面喂给识别:识别、匹配、提交、
|
||||
标签全走真流程,只是「眼睛」换成了图库。
|
||||
"""
|
||||
raw = str(self.cfg.get('replay_dir') or '').strip()
|
||||
if not raw:
|
||||
return []
|
||||
root = raw if os.path.isabs(raw) else os.path.join(_ROOT, raw)
|
||||
if not os.path.isdir(root):
|
||||
return []
|
||||
exts = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
|
||||
files = []
|
||||
for base, _dirs, names in os.walk(root):
|
||||
for fn in sorted(names):
|
||||
if fn.lower().endswith(exts):
|
||||
files.append(os.path.join(base, fn))
|
||||
files.sort()
|
||||
return files
|
||||
|
||||
def _load_card(self, path, want_w, want_h):
|
||||
"""读一张图并做成摄像头尺寸的画布(白底居中,不变形)"""
|
||||
try:
|
||||
# cv2.imread 在 Windows 上读不了中文路径,必须 imdecode
|
||||
im = cv2.imdecode(np.fromfile(path, dtype=np.uint8),
|
||||
cv2.IMREAD_COLOR)
|
||||
except Exception:
|
||||
im = None
|
||||
if im is None:
|
||||
return None
|
||||
h, w = im.shape[:2]
|
||||
if h <= 0 or w <= 0:
|
||||
return None
|
||||
scale = min(want_w / float(w), want_h / float(h))
|
||||
nw = max(1, int(w * scale))
|
||||
nh = max(1, int(h * scale))
|
||||
im = cv2.resize(
|
||||
im, (nw, nh),
|
||||
interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR)
|
||||
card = np.full((want_h, want_w, 3), 244, dtype=np.uint8)
|
||||
x, y = (want_w - nw) // 2, (want_h - nh) // 2
|
||||
card[y:y + nh, x:x + nw] = im
|
||||
return card
|
||||
|
||||
def _replay_loop(self, files):
|
||||
"""回放:每 replay_hold_s 秒换一张图(跟模拟称的放货节奏对得上)
|
||||
|
||||
画面上叠「REPLAY n/N」和帧序号:一眼能看出不是实时画面,也能
|
||||
验证证据链(新帧/序号)在正常推进。留档照片就是这张图。
|
||||
"""
|
||||
want_w = int(self.cfg.get('width') or 1280)
|
||||
want_h = int(self.cfg.get('height') or 720)
|
||||
hold = max(1.0, float(self.cfg.get('replay_hold_s', 10) or 10))
|
||||
self.status = '回放摄像头(%d 张图片)' % len(files)
|
||||
self._replay_info = self.status
|
||||
n = 0
|
||||
idx = -1
|
||||
card = None
|
||||
t_next = 0.0
|
||||
misses = 0
|
||||
while self._running and not self._reload:
|
||||
if self._suspended:
|
||||
time.sleep(0.3)
|
||||
continue
|
||||
now = time.monotonic()
|
||||
if card is None or now >= t_next:
|
||||
idx = (idx + 1) % len(files)
|
||||
t_next = now + hold
|
||||
card = self._load_card(files[idx], want_w, want_h)
|
||||
if card is None:
|
||||
misses += 1
|
||||
if misses >= len(files):
|
||||
# 全部读不出来:画一张占位图,别在这里空转刷 CPU
|
||||
self.status = ('回放失败:%d 张图片都读不出来'
|
||||
% len(files))
|
||||
self._replay_info = self.status
|
||||
card = np.full((want_h, want_w, 3), 244,
|
||||
dtype=np.uint8)
|
||||
cv2.putText(card, 'REPLAY: NO IMAGE',
|
||||
(int(want_w * 0.28), int(want_h * 0.5)),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 1.2,
|
||||
(120, 120, 120), 3)
|
||||
time.sleep(1.0)
|
||||
else:
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
else:
|
||||
misses = 0
|
||||
n += 1
|
||||
img = card.copy()
|
||||
cv2.putText(img, 'REPLAY %d/%d' % (idx + 1, len(files)),
|
||||
(24, 44), cv2.FONT_HERSHEY_SIMPLEX, 1.0,
|
||||
(70, 70, 70), 2)
|
||||
cv2.putText(img, 'seq=%d' % n, (24, 84),
|
||||
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (120, 120, 120), 2)
|
||||
self._push(img)
|
||||
time.sleep(0.2)
|
||||
|
||||
def _sim_loop(self):
|
||||
files = self._replay_files()
|
||||
if files:
|
||||
self._replay_loop(files)
|
||||
return
|
||||
self._replay_info = ''
|
||||
self.status = '模拟摄像头(合成画面)'
|
||||
n = 0
|
||||
while self._running and not self._reload:
|
||||
|
||||
+446
-169
@@ -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
|
||||
@@ -119,6 +122,36 @@ def similar_item_name(a, b):
|
||||
return len(set(a) & set(b)) >= 2
|
||||
|
||||
|
||||
def reject_hint(err, row):
|
||||
"""把服务端的业务拒绝翻成人能看懂、能照做的一句话(翻不了返回 '')
|
||||
|
||||
11-10 现场:苹果应 30 斤、模拟秤只有 6.4 斤,服务端回
|
||||
400 weigh_tolerance_exceeded,界面只显示一串 JSON。现场看不懂“是谁的错”,
|
||||
只能来问。这类有明确原因的错误要直接说清楚下次该怎么做。
|
||||
"""
|
||||
low = str(err or '').lower()
|
||||
if 'weigh_tolerance' in low:
|
||||
unit = str((row or {}).get('unit') or '')
|
||||
try:
|
||||
req = float(M.required_qty_of(row or {}, None) or 0)
|
||||
except (TypeError, ValueError):
|
||||
req = 0.0
|
||||
return ('重量对不上:这行应 %.2f %s,本次超出服务端容差,未入账。'
|
||||
'差得多通常是放上来的不是这件货,请核对后再称'
|
||||
'(或到后台按实际数改单)' % (req, unit))
|
||||
# 2026-11-22 生产事故:整组入库「短收」曾被后端先入一部分再 409,客户端当未提交处理,
|
||||
# 拿旧组重试又撞 scope_changed。新后端已按「部分成功」返回(不会走到这里),
|
||||
# 这两条提示是给旧后端/其它范围变化兜底:先刷新再称,绝不直接重试旧组。
|
||||
if 'scope_incomplete' in low:
|
||||
return ('提交被拒绝:整组入库没有按分摊提交。请刷新待验列表后重新称重;'
|
||||
'不要直接重试(旧组可能已部分入库)')
|
||||
if ('scope_changed' in low or 'group_changed' in low
|
||||
or 'scope_mismatch' in low):
|
||||
return ('待验范围已变化(可能已被其它终端入库或后台改单)。'
|
||||
'请刷新待验列表后再称;不要直接重试旧组')
|
||||
return ''
|
||||
|
||||
|
||||
class FlowEngine:
|
||||
def __init__(self, cfg, emit):
|
||||
self.cfg = cfg
|
||||
@@ -132,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()
|
||||
|
||||
@@ -145,6 +189,7 @@ class FlowEngine:
|
||||
self.logged_in = False # UI 登录页成功后置 True
|
||||
self.state = 'IDLE'
|
||||
self.locked_msg = None # 未决提交锁
|
||||
|
||||
self._running = False
|
||||
self._tick_started = False # tick 线程是否已起(防重复 start)
|
||||
self._confirm_lock = threading.Lock() # 确认/提交互斥(防一笔提交两回)
|
||||
@@ -278,6 +323,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 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
|
||||
@@ -323,11 +376,15 @@ class FlowEngine:
|
||||
acc['role'] = STATION_TO_ROLE.get(self.station, 'picker')
|
||||
self.api.account = acc
|
||||
self.api.login()
|
||||
# 入库自动提交:以服务端账号开关为准(读不到 ⇒ False ⇒ 手动确认)
|
||||
self.emit('log', '手动确认:识别后请点确认记账')
|
||||
self.logged_in = True
|
||||
self.emit('log', '登录成功(%s / %s,role_type=%s)'
|
||||
% (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 '',
|
||||
@@ -904,6 +961,11 @@ class FlowEngine:
|
||||
self._count_mode = False # 走秤的流程,别继承上一轮免称重标记
|
||||
self._count_real_kg = 0.0 # 真实秤读数留档(标签按它印)也作废
|
||||
self._cycle_conf = None # 新一轮,上一轮的把握不作数
|
||||
# 新一轮必须清掉上一轮的识别名:识别失败走人工确认时,_to_focus
|
||||
# 会回退 _cycle_detected;不清空就会把上一件的品名当成「本轮已识别」
|
||||
# 显示出来,操作员看到「没认到却显示已识别」。
|
||||
self._cycle_detected = ''
|
||||
self._cycle_alt = ''
|
||||
self._focus = None # 上一轮的待确认(如果还挂着)作废
|
||||
self._remove_submit = False
|
||||
self._set_state('CAPTURE')
|
||||
@@ -982,7 +1044,36 @@ 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):
|
||||
"""同一张抓拍交给两种模型,操作流程只消费云端结果。"""
|
||||
audit = {
|
||||
'image': path,
|
||||
'local': self.assist.record_local(path, names, crop=crop),
|
||||
'cloud': None,
|
||||
}
|
||||
self._assist_pending = audit
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = self.recog.identify_ex(path, names, timeout=self._recog_timeout(),
|
||||
**({'crop': crop} if crop is not None else {}))
|
||||
except RecognitionError:
|
||||
audit['cloud'] = {
|
||||
'status': 'unavailable', 'ms': round((time.monotonic() - started) * 1000),
|
||||
}
|
||||
raise
|
||||
audit['cloud'] = {
|
||||
'status': 'recognized' if result.get('name') else 'no_match',
|
||||
'name': result.get('name') or '',
|
||||
'conf': result.get('conf'),
|
||||
'ms': round((time.monotonic() - started) * 1000),
|
||||
}
|
||||
return result
|
||||
|
||||
def _run_recognition(self):
|
||||
self._assist_pending = None # 新一件:上一件的建议记录作废
|
||||
# v1.0.57:只拿「锁定客户」的品名去问模型 —— 名单缩了,识别更准,
|
||||
# 也不会把这一家的货匹配到别家同名行上
|
||||
names = sorted({r.get('item_name') for r in self.scoped_rows()
|
||||
@@ -1000,10 +1091,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')
|
||||
@@ -1014,6 +1102,8 @@ class FlowEngine:
|
||||
self._settle_aborted() # 识别途中被作废(退出登录/刷新),别再往下提交
|
||||
return
|
||||
if not detected:
|
||||
self._cycle_detected = ''
|
||||
self._cycle_alt = ''
|
||||
# v1.0.50:模型说「名单里没有」时,最可能的原因就是这件货没下单/
|
||||
# 已在别的工位收过,直接点明,省得现场以为是识别坏了。
|
||||
self.emit('log', 'AI 无法确认品名:这件货不在待办名单里'
|
||||
@@ -1221,15 +1311,10 @@ class FlowEngine:
|
||||
'后台按商品入库补录'
|
||||
% (rest, unit_n))
|
||||
self._plan = plan[1:]
|
||||
if self.station == 'picking':
|
||||
# 合并分拣先展示确认页;人工确认首行后,剩余分摊行
|
||||
# 作为同一批次继续提交。
|
||||
self._auto_round = False
|
||||
self._to_focus(plan[0][0], plan[0][1],
|
||||
detected=detected, conf=conf,
|
||||
mode='weigh', candidates=hits, auto=True)
|
||||
else:
|
||||
self._start_submit(plan[0][0], plan[0][1], '合并')
|
||||
self._auto_round = False
|
||||
self._to_focus(plan[0][0], plan[0][1],
|
||||
detected=detected, conf=conf,
|
||||
mode='weigh', candidates=hits, auto=True)
|
||||
return
|
||||
self.emit('log', note)
|
||||
if note and '分摊' in note:
|
||||
@@ -1502,27 +1587,44 @@ class FlowEngine:
|
||||
if len(rows) < 2:
|
||||
return None
|
||||
unit = rows[0].get('unit') or ''
|
||||
indep_flags = [bool(M.is_independent_inbound(r)) for r in rows]
|
||||
# 独立入库(无单自采)现在也走单行结案接口,可以按同名多行分摊:
|
||||
# 一次称 55.74 斤 → 17 斤那行结 17,剩下 38.74 全给 38 斤那行。
|
||||
# 但有单/无单混在一起时不能猜(猜错会把订单货入成自采库存),交人工。
|
||||
if any(indep_flags) and not all(indep_flags):
|
||||
return None
|
||||
all_indep = all(indep_flags)
|
||||
for r in rows:
|
||||
if (r.get('unit') or '') != unit:
|
||||
return None # 单位不一致不摊(斤/件混着没法算)
|
||||
if M.is_independent_inbound(r):
|
||||
return None # 独立入库行走 stock-in,不参与分摊
|
||||
if M.unit_not_weighable_reason(unit):
|
||||
return None
|
||||
rows = sorted(rows,
|
||||
key=lambda r: (float(M.required_qty_of(r, None) or 0),
|
||||
str(r.get('order_code') or '')))
|
||||
left = float(business or 0)
|
||||
total_need = sum(float(M.required_qty_of(r, None) or 0) for r in rows)
|
||||
biz = float(business or 0)
|
||||
if all_indep and total_need > 0:
|
||||
over_pct = float((self.cfg.get('vision') or {})
|
||||
.get('auto_over_pct', 30) or 0)
|
||||
if over_pct > 0 and biz > total_need * (1.0 + over_pct / 100.0):
|
||||
return None
|
||||
left = biz
|
||||
plan = []
|
||||
for r in rows:
|
||||
for idx, r in enumerate(rows):
|
||||
need = float(M.required_qty_of(r, None) or 0)
|
||||
if need <= 0 or left <= 1e-6:
|
||||
continue
|
||||
take = min(need, left)
|
||||
# 只够这一单的 1/4 就别拆了:2 斤货拆成 1.5 + 0.5 会让那单
|
||||
# 长期挂着 2.5 斤待收,现场对账更乱;这种交人工判断。
|
||||
if take < min(need, max(0.25, need * 0.25)):
|
||||
continue
|
||||
if all_indep and idx == len(rows) - 1:
|
||||
# 独立入库允许实收超过单行计划量:最后一行把剩余量全收下,
|
||||
# 否则 55.74 - 17 - 38 = 0.74 会挂在现场没人知道。
|
||||
take = left
|
||||
else:
|
||||
take = min(need, left)
|
||||
# 只够这一单的 1/4 就别拆了:2 斤货拆成 1.5 + 0.5 会让那单
|
||||
# 长期挂着 2.5 斤待收,现场对账更乱;这种交人工判断。
|
||||
if take < min(need, max(0.25, need * 0.25)):
|
||||
continue
|
||||
plan.append((r, round(take, 3)))
|
||||
left -= take
|
||||
if len(plan) < 2:
|
||||
@@ -1581,6 +1683,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:
|
||||
@@ -1724,31 +1829,8 @@ class FlowEngine:
|
||||
self._to_focus(row, business, conf=self._cycle_conf, mode='weigh',
|
||||
candidates=[row], auto=True)
|
||||
return
|
||||
if not self.cfg['flow'].get('auto_submit', True):
|
||||
self._to_manual(None, [row])
|
||||
return
|
||||
if self.submit_on_remove() and self.confirm_before_submit():
|
||||
# v1.0.40:拿走货即提交 —— 选中只是定「记给谁」,货离秤才记账。
|
||||
# 分拣在此刻就打印标签(改判会重打);「确认记账」按钮仍是
|
||||
# 不等拿走、立即提交的快捷方式。
|
||||
# confirm_before_submit=false(认出即提交、零确认)优先级更高,
|
||||
# 维持 v1.0.31 之前的直提行为。
|
||||
self.emit('log', 'AI 认出「%s」%.2f %s,拿走货即提交'
|
||||
% (row.get('item_name') or '', business,
|
||||
row.get('unit') or ''))
|
||||
self._to_focus(row, business, conf=self._cycle_conf, mode='weigh',
|
||||
candidates=[row], auto=True)
|
||||
return
|
||||
if self.confirm_before_submit():
|
||||
# v1.0.31:认出这一行先不记账,界面跳到这一行等人点头。
|
||||
# 点的是别的行 = 改判;点「确认记账」才真的提交。
|
||||
unit = row.get('unit') or ''
|
||||
self.emit('log', 'AI 认出「%s」%.2f %s,等你确认(点别的行就是改判)'
|
||||
% (row.get('item_name') or '', business, unit))
|
||||
self._to_focus(row, business, conf=self._cycle_conf, mode='weigh',
|
||||
candidates=[row], auto=True)
|
||||
return
|
||||
self._start_submit(row, business, source)
|
||||
self._to_focus(row, business, conf=self._cycle_conf, mode='weigh',
|
||||
candidates=[row], auto=True)
|
||||
|
||||
# ------------------------------------------------------------ 提交
|
||||
def manual_submit(self, row):
|
||||
@@ -1792,6 +1874,12 @@ class FlowEngine:
|
||||
name = str((row or {}).get('item_name') or '').strip()
|
||||
if not p or not name:
|
||||
return
|
||||
# 模拟/回放画面不是车间实拍,存进去等于拿空白图当教材。11-10 现场
|
||||
# 实测:data/learn 的 38 张里有 37 张是「SIM CAMERA」占位图,识别
|
||||
# 被这些 few-shot 带偏,对真实苹果图也一直回 NOT_IN_LIST。
|
||||
cam = self.cfg.get('camera', {}) or {}
|
||||
if cam.get('simulate') or str(cam.get('replay_dir') or '').strip():
|
||||
return
|
||||
det = str(f.get('detected')
|
||||
or getattr(self, '_cycle_detected', '') or '').strip()
|
||||
src = 'fix' if (det and det != name) else 'weak'
|
||||
@@ -1907,7 +1995,7 @@ class FlowEngine:
|
||||
self._set_state('DONE')
|
||||
return
|
||||
self.emit('log', DEV + '提示:本次无合格留档照片(%s)' % shot['reason'])
|
||||
if shot['qualified'] and not self._snapshot_ok(row):
|
||||
if not self._snapshot_ok(row):
|
||||
self.journal.conclude(op, STATE_REJECTED, '发送前快照复核未通过')
|
||||
# 回 WEIGHING 而不是 DONE:货还在秤上(甚至还在加),停在 DONE 要
|
||||
# 等秤空才出来,操作员看着就是卡死。回称重态让它重新等稳、重新
|
||||
@@ -1930,6 +2018,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']:
|
||||
@@ -1956,13 +2050,23 @@ class FlowEngine:
|
||||
resp = self.api.commit_picking(row, business, api_w, op,
|
||||
photo_expected)
|
||||
else:
|
||||
if M.is_independent_inbound(row):
|
||||
if self._is_group_inbound(row):
|
||||
# 安卓同口径:整组一次提交,服务端按组内待验量 FIFO 分摊。
|
||||
# force=True 即偏差入库/短收结案;批量入库由服务端分摊完成。
|
||||
resp = self.api.commit_inspection_group(
|
||||
row, business, self._frozen_kg, op,
|
||||
force_complete=force,
|
||||
force_close_raw_batch=force,
|
||||
quality_rating=(self.cfg.get('inspection_quality_rating') or '合格'))
|
||||
elif M.is_independent_inbound(row):
|
||||
# 无单自采行(v1.0.44):单行结案接口,merge-strict 会拒
|
||||
resp = self.api.commit_inspection_single(
|
||||
row, business,
|
||||
(float(getattr(self, '_count_real_kg', 0) or 0)
|
||||
if self._count_mode else float(self._frozen_kg or 0)),
|
||||
op)
|
||||
op,
|
||||
force_complete=force,
|
||||
force_close_raw_batch=force)
|
||||
else:
|
||||
# 严格入库两步走:先范围预览换一次性凭据,再凭据提交
|
||||
scope = self.api.preview_merge_scope(row['id'], [row['id']])
|
||||
@@ -1984,6 +2088,12 @@ class FlowEngine:
|
||||
except Exception:
|
||||
pass
|
||||
container_code = self._container_code_of(resp)
|
||||
if self.station == 'picking':
|
||||
if container_code:
|
||||
self.emit('log', DEV + '分拣容器码:%s' % container_code)
|
||||
else:
|
||||
self.emit('log', DEV + '分拣回包没有容器码(container_code),'
|
||||
'本次标签将不打印')
|
||||
if container_code:
|
||||
# 落盘留档:结果不明/重试时还能从 journal 取回容器码重打标签
|
||||
self.journal.update(op, containerCode=container_code)
|
||||
@@ -2017,13 +2127,26 @@ class FlowEngine:
|
||||
(self._frozen_row or {}).get('unit', '')) else 0.0)
|
||||
resp = self.api.commit_picking(
|
||||
self._frozen_row, qty, api_w, op, True)
|
||||
elif self._is_group_inbound(self._frozen_row):
|
||||
# 分组行:整组重发(连接没建立,服务端必然没收到)
|
||||
force_retry, _, _ = self._short_close_gap(
|
||||
self._frozen_row, qty)
|
||||
resp = self.api.commit_inspection_group(
|
||||
self._frozen_row, qty, self._frozen_kg, op,
|
||||
force_complete=force_retry,
|
||||
force_close_raw_batch=force_retry,
|
||||
quality_rating=(self.cfg.get('inspection_quality_rating') or '合格'))
|
||||
elif M.is_independent_inbound(self._frozen_row):
|
||||
# 无单自采行:单行结案重试(连接没建立,服务端必然没收到)
|
||||
force_retry, _, _ = self._short_close_gap(
|
||||
self._frozen_row, qty)
|
||||
wkg = (float(getattr(self, '_count_real_kg', 0) or 0)
|
||||
if self._count_mode
|
||||
else float(self._frozen_kg or 0))
|
||||
resp = self.api.commit_inspection_single(
|
||||
self._frozen_row, qty, wkg, op)
|
||||
self._frozen_row, qty, wkg, op,
|
||||
force_complete=force_retry,
|
||||
force_close_raw_batch=force_retry)
|
||||
else:
|
||||
# 预览+提交都重走一遍(凭据是一次性的,可能没领到)
|
||||
scope = self.api.preview_merge_scope(
|
||||
@@ -2066,7 +2189,7 @@ class FlowEngine:
|
||||
'请到后台给这个商品填采购价后再入库(%s)'
|
||||
% (row.get('item_name') or '', err))
|
||||
else:
|
||||
msg = '提交被拒绝:%s' % err
|
||||
msg = reject_hint(err, row) or ('提交被拒绝:%s' % err)
|
||||
if self._count_mode and ('重量' in str(err)
|
||||
or 'weight' in str(err).lower()):
|
||||
# 免称重提交的重量默认是 0;服务端若强制要重量,这里给出
|
||||
@@ -2086,6 +2209,9 @@ class FlowEngine:
|
||||
if self.station == 'picking':
|
||||
self._recover_picking(op)
|
||||
return
|
||||
if self._is_group_inbound(self._frozen_row or {}):
|
||||
self._recover_group(op)
|
||||
return
|
||||
if M.is_independent_inbound(self._frozen_row or {}):
|
||||
self._recover_indep(op)
|
||||
return
|
||||
@@ -2128,6 +2254,49 @@ class FlowEngine:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _recover_group(self, op):
|
||||
"""分组提交结果不明:只查待验列表,绝不换号重提。
|
||||
|
||||
- 整组 ID 全部消失:服务端已收(含 partial/偏差结案);
|
||||
- 整组 ID 都还在:服务端没收到,安全判未提交;
|
||||
- 部分消失:不猜,锁定等人工。
|
||||
"""
|
||||
row = self._frozen_row or {}
|
||||
ids = {str(x) for x in (row.get('inspection_ids') or []) if str(x or '').strip()}
|
||||
if not ids:
|
||||
self.emit('log', '分组行缺少 inspection_ids,无法核实,锁定等人工')
|
||||
self.emit('result', (False, '分组提交结果待核实(缺少明细),已锁定'))
|
||||
self._to_done()
|
||||
return
|
||||
business = M.scale_kg_to_business(self._frozen_kg, row.get('unit', ''))
|
||||
for i in range(3):
|
||||
time.sleep(2)
|
||||
try:
|
||||
data = self.api.pending('inspection')
|
||||
except Exception as e:
|
||||
self.emit('log', '分组核实第 %d 次失败: %s' % (i + 1, e))
|
||||
continue
|
||||
present = set()
|
||||
for r in (data or {}).get('rows') or []:
|
||||
present.update(str(x) for x in (r.get('inspection_ids') or []))
|
||||
if r.get('id'):
|
||||
present.add(str(r.get('id')))
|
||||
if not (ids & present):
|
||||
self.journal.conclude(op, STATE_SUCCEEDED)
|
||||
self._after_success(row, business, op,
|
||||
{'qualified': False}, '核实',
|
||||
extra='|整组提交已核实')
|
||||
return
|
||||
if ids <= present:
|
||||
self.journal.conclude(op, STATE_REJECTED, '整组提交未生效')
|
||||
self.emit('result', (False, '整组提交未生效(待办仍在),请重试'))
|
||||
self._to_done()
|
||||
return
|
||||
# 部分消失:可能服务端已部分入库,不能重提
|
||||
break
|
||||
self.emit('result', (False, '整组提交结果不明,已锁定新提交,请联系管理员'))
|
||||
self._set_state('DONE')
|
||||
|
||||
def _recover_indep(self, op):
|
||||
"""无单自采行的结果不明核实:单行结案接口没有操作号可查,
|
||||
只能看「待办里这行还在不在」—— 和分拣的核实思路一致。
|
||||
@@ -2177,13 +2346,8 @@ class FlowEngine:
|
||||
self.emit('log', '核实第 %d 次拉不到待拣列表' % (i + 1))
|
||||
continue
|
||||
if not present:
|
||||
self.journal.conclude(op, STATE_REJECTED,
|
||||
'待拣列表已无该行(请核对后台)')
|
||||
self.emit('result', (False, '结果无法确认:待拣列表已无该行,'
|
||||
'未打印标签,请到后台核对'))
|
||||
self._to_done()
|
||||
return
|
||||
self.emit('log', '分拣结果待核实(%s):待拣列表仍有该行,请勿重复提交' % op)
|
||||
break
|
||||
self.emit('log', '待拣列表不能证明这笔操作已记账,请核对实际分拣记录')
|
||||
self.emit('result', (False, '提交结果待核实,请勿重复提交;核对后台后到'
|
||||
'设置页「未决提交…」解锁'))
|
||||
self.locked_msg = '存在未核实的提交(%s)' % op
|
||||
@@ -2220,10 +2384,8 @@ class FlowEngine:
|
||||
if kind == 'picking':
|
||||
present = self.api.picking_pending_has(rec.get('targetId'))
|
||||
if present is False:
|
||||
self.journal.conclude(op, STATE_REJECTED,
|
||||
'待拣列表已无该行(人工核实)')
|
||||
done += 1
|
||||
lines.append('%s 分拣:待拣列表已无该行 → 按未提交处理,已解锁' % op)
|
||||
left += 1
|
||||
lines.append('%s 分拣:待办行已消失,请人工核实本笔是否成功' % op)
|
||||
elif present is None:
|
||||
left += 1
|
||||
lines.append('%s 分拣:拉不到待拣列表 → 仍待核实' % op)
|
||||
@@ -2305,6 +2467,17 @@ class FlowEngine:
|
||||
'unit': result.get('unit') or '',
|
||||
'follow_ups': result.get('follow_up_inspection_ids') or []}
|
||||
|
||||
def _is_group_inbound(self, row):
|
||||
"""这一行是否是服务端 grouping 后的整组待验行(安卓 complete-merge-group 口径)。"""
|
||||
if not isinstance(row, dict):
|
||||
return False
|
||||
ids = row.get('inspection_ids')
|
||||
if not isinstance(ids, (list, tuple)) or len(ids) < 1:
|
||||
return False
|
||||
if not str(row.get('group_hash') or '').strip():
|
||||
return False
|
||||
return bool((self.cfg.get('flow') or {}).get('group_inbound', True))
|
||||
|
||||
def _short_close_gap(self, row, business):
|
||||
"""短收是否在「直接结案」容差内 → (bool, 差额, 差额百分比)
|
||||
|
||||
@@ -2342,6 +2515,20 @@ class FlowEngine:
|
||||
|
||||
def _success_extra(self, kind, resp):
|
||||
"""成功提示的补充语:部分入库/偏差结案不能只说“确认成功”"""
|
||||
data = resp.get('data') if isinstance(resp, dict) else None
|
||||
# 整组短收→部分成功(2026-11-22 方案 A):告诉现场「已入 N 行、剩余多少下次再称」,
|
||||
# 并明确不要拿旧组重试(旧组 hash 已经变了)。
|
||||
if isinstance(data, dict) and data.get('partialGroup'):
|
||||
n = data.get('mergedCount')
|
||||
rem = data.get('remainingQty')
|
||||
unit = str((self._frozen_row or {}).get('unit') or '')
|
||||
txt = '|整组部分入库:已入 %s 行' % (n if n not in (None, '') else '?')
|
||||
try:
|
||||
if rem not in (None, ''):
|
||||
txt += ',剩余 %g %s' % (float(rem), unit)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return txt + '(剩余行仍在待验,下次称重继续;不要用旧组重试)'
|
||||
if kind == 'ok':
|
||||
return ''
|
||||
info = self._strict_info(resp)
|
||||
@@ -2583,6 +2770,112 @@ 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 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:
|
||||
audit = getattr(self, '_assist_pending', None)
|
||||
recognition_image = getattr(self, '_cycle_recog_path', None)
|
||||
if audit and audit['image'] == recognition_image and os.path.isfile(recognition_image):
|
||||
# 审核页展示模型实际看到的图。业务归档仍用确认帧。
|
||||
path, captured_at = recognition_image, None
|
||||
else:
|
||||
audit = None
|
||||
error = ReviewQueue().stage(self.api, op, row, source, path, station=self.station,
|
||||
captured_at=captured_at, audit=audit)
|
||||
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)
|
||||
@@ -2663,7 +2956,7 @@ class FlowEngine:
|
||||
这里递归找一遍。找不到就返回空串,绝不拿订单号顶替。
|
||||
"""
|
||||
keys = ('container_code', 'containerCode', 'container_no',
|
||||
'containerNo')
|
||||
'containerNo', 'container')
|
||||
seen = set()
|
||||
|
||||
def walk(node, depth=0):
|
||||
@@ -2683,8 +2976,19 @@ class FlowEngine:
|
||||
seen.add(oid)
|
||||
for k in keys:
|
||||
v = node.get(k)
|
||||
if v not in (None, ''):
|
||||
return str(v).strip()
|
||||
if isinstance(v, (str, int)):
|
||||
txt = str(v).strip()
|
||||
if txt and txt != '0':
|
||||
return txt
|
||||
elif k == 'container' and isinstance(v, dict):
|
||||
# 少数接口把容器写成 {"container": {"code": "..."}}
|
||||
for ck in ('code', 'container_code', 'containerCode',
|
||||
'no', 'container_no'):
|
||||
cv = v.get(ck)
|
||||
if isinstance(cv, (str, int)):
|
||||
txt = str(cv).strip()
|
||||
if txt and txt != '0':
|
||||
return txt
|
||||
for v in node.values():
|
||||
if isinstance(v, (dict, list)):
|
||||
got = walk(v, depth + 1)
|
||||
@@ -2706,7 +3010,7 @@ class FlowEngine:
|
||||
兜底只用于临时救急,日志会明确写出“扫码可能失败”。
|
||||
"""
|
||||
code = str(container_code or '').strip()
|
||||
if code:
|
||||
if code and code != '0':
|
||||
return code, 'container_code'
|
||||
code = self._container_code_of(row or {})
|
||||
if code:
|
||||
@@ -2753,7 +3057,8 @@ class FlowEngine:
|
||||
self.emit('log', msg)
|
||||
self.emit('print_result', (False, msg))
|
||||
return
|
||||
if op and op in self._printed_ops:
|
||||
printed_ops = getattr(self, '_printed_ops', None)
|
||||
if op and printed_ops is not None and op in printed_ops:
|
||||
self.emit('log', DEV + '操作号 %s 已打印过标签,跳过重复打印' % op)
|
||||
return
|
||||
qr, qr_src = '', ''
|
||||
@@ -2789,8 +3094,8 @@ class FlowEngine:
|
||||
self._print_q.put({'row': dict(row), 'business': float(business),
|
||||
'kg': float(kg or 0.0), 'station': self.station,
|
||||
'qr': qr, 'qr_source': qr_src, 'op': str(op or '')})
|
||||
if op:
|
||||
self._printed_ops.add(op)
|
||||
if op and printed_ops is not None:
|
||||
printed_ops.add(op)
|
||||
self.emit('log', '标签已排队(%s)' % name)
|
||||
|
||||
def _print_worker(self):
|
||||
@@ -2851,6 +3156,19 @@ class FlowEngine:
|
||||
self.emit('log', '标签按秤上实际重量印:%.2f %s(记账 %.2f %s)'
|
||||
% (qty, unit, float(business or 0.0), unit))
|
||||
try:
|
||||
try:
|
||||
if float(qty or 0.0) <= 0:
|
||||
msg = ('标签数量为 0,本次未打印:%s'
|
||||
% (row.get('item_name') or ''))
|
||||
self.emit('log', msg)
|
||||
self.emit('print_result', (False, msg))
|
||||
return
|
||||
except (TypeError, ValueError):
|
||||
msg = ('标签数量无效,本次未打印:%s'
|
||||
% (row.get('item_name') or ''))
|
||||
self.emit('log', msg)
|
||||
self.emit('print_result', (False, msg))
|
||||
return
|
||||
if station == 'picking':
|
||||
if not qr:
|
||||
msg = ('标签缺少容器码,本次未打印:%s'
|
||||
@@ -2902,24 +3220,10 @@ class FlowEngine:
|
||||
.get('allow_independent_inbound', False))
|
||||
|
||||
def confirm_before_submit(self):
|
||||
"""识别完先定位到商品行、等人确认,确认了才记账(v1.0.31 默认开)
|
||||
|
||||
为什么要这么改:AI 认错一次,账就错了,而且服务端没有冲正接口,
|
||||
只能去后台手改(现场 11-04 夜里那几笔就是这么来的)。以前是「认出
|
||||
就直接提交」,人根本没机会看;现在把「看」这一步塞回流程里 ——
|
||||
认出哪一行就把界面跳过去高亮,看着不对点别的行就是改判。
|
||||
|
||||
关掉(flow.confirm_before_submit=false)回到旧行为:认出即提交。
|
||||
"""
|
||||
return bool(self.cfg.get('flow', {}).get('confirm_before_submit', True))
|
||||
return True
|
||||
|
||||
def submit_on_remove(self):
|
||||
"""非分拣工位可选「拿走货自动提交」;分拣始终等待人工确认。
|
||||
|
||||
选择行只确定记账对象;分拣标签在人工确认且提交成功后排队,
|
||||
不受该配置影响。免称重行也沿用确认页流程。
|
||||
"""
|
||||
return bool(self.cfg.get('flow', {}).get('submit_on_remove', True))
|
||||
return False
|
||||
|
||||
def preselect(self, rid):
|
||||
"""空秤时人工预选待办行(v1.0.40)
|
||||
@@ -3038,8 +3342,10 @@ class FlowEngine:
|
||||
self._focus = {
|
||||
'mode': mode,
|
||||
'row_id': row.get('id') if row else None,
|
||||
# 没有命中行时,本轮就是「没认出」:不得回退上一轮的
|
||||
# _cycle_detected,否则人工确认页会显示上一件的品名。
|
||||
'detected': (detected if detected is not None
|
||||
else self._cycle_detected),
|
||||
else (self._cycle_detected if row is not None else '')),
|
||||
'conf': conf,
|
||||
'business': float(business or 0.0),
|
||||
'unit': (row or {}).get('unit') or '',
|
||||
@@ -3049,41 +3355,8 @@ class FlowEngine:
|
||||
'auto': bool(auto),
|
||||
'from_scale': False, # 记账量是否取自秤上实际读数(v1.0.55)
|
||||
}
|
||||
if row:
|
||||
self._frozen_row = row
|
||||
if mode == 'count':
|
||||
self._count_mode = True
|
||||
self._count_qty = float(business or 0.0)
|
||||
# 进免称重就把秤上的真实读数抄下来:标签要按实际重量印,
|
||||
# 同时把上一件的残留值清掉(否则货没上秤也会印上一件的数)
|
||||
self._count_real_kg = self._snap_scale_kg()
|
||||
# v1.0.55:秤上有货就按实际重量记账 —— 界面显示、提交量、
|
||||
# 标签、台账从现在起是同一个数,不再出现「显示 5.00 斤、
|
||||
# 实际称到 5.62 斤」两套数字
|
||||
if row is not None:
|
||||
asked = float(business or 0.0)
|
||||
real_q = self._real_business(row, business, quiet=True)
|
||||
if abs(real_q - asked) > 0.005:
|
||||
business = real_q
|
||||
self._focus['business'] = real_q
|
||||
self._focus['from_scale'] = True
|
||||
self.emit('log', '按秤上实际重量记账:%.2f %s'
|
||||
'(「%s」该行应 %.2f %s)'
|
||||
% (real_q, row.get('unit') or '',
|
||||
row.get('item_name') or '', asked,
|
||||
row.get('unit') or ''))
|
||||
else:
|
||||
self._count_mode = False
|
||||
self._set_state('CONFIRM')
|
||||
# 确认期间重量变化只更新待确认数量;标签在确认提交成功后统一排队。
|
||||
self._confirm_seen_present = False
|
||||
self._confirm_absent_at = 0.0
|
||||
# v1.0.62:确认期间的重量跟踪从「抓拍那刻的冻结值」起步 ——
|
||||
# 后面货有增减(补一把/抓走一点)会跟到新的稳定值
|
||||
self._confirm_live_kg = None
|
||||
self._confirm_move_at = 0.0
|
||||
self._confirm_settled_kg = float(self._frozen_kg or 0.0)
|
||||
self._confirm_gone_at = 0.0
|
||||
# 建议模式:把两个引擎的建议一起交给界面(本地预选、云端并列显示)。
|
||||
# 界面不认这个键也不影响任何记账逻辑 —— 它只是给人看的一份「意见」。
|
||||
self.emit('focus', self._focus_payload())
|
||||
|
||||
def pick_focus(self, rid):
|
||||
@@ -3120,6 +3393,8 @@ class FlowEngine:
|
||||
f['from_scale'] = True
|
||||
self._count_qty = real_q
|
||||
|
||||
if f.get('row_id') != row.get('id'):
|
||||
self._plan = []
|
||||
f['row_id'] = row.get('id')
|
||||
f['unit'] = unit
|
||||
f['warn'] = ''
|
||||
@@ -3162,8 +3437,8 @@ class FlowEngine:
|
||||
lock.release()
|
||||
|
||||
def _confirm_focus_locked(self, qty=None, auto_remove=False):
|
||||
if self.station == 'picking' and auto_remove:
|
||||
return False, '分拣必须点击确认分拣后提交'
|
||||
if auto_remove:
|
||||
return False, '请点击确认后提交'
|
||||
if self.state != 'CONFIRM' or not self._focus:
|
||||
return False, '当前不在确认状态'
|
||||
f = self._focus
|
||||
@@ -3295,10 +3570,10 @@ class FlowEngine:
|
||||
if not f or f.get('mode') != 'weigh' \
|
||||
or float(self._frozen_kg or 0.0) <= 0:
|
||||
return
|
||||
if self.station == 'picking':
|
||||
# 分拣只能由确认按钮提交。读数仍在正常区间时更新待确认数量;
|
||||
# 明显掉重或归零视为货物正在被拿走,不用残重覆盖稳定记账量,
|
||||
# 也不自动提交,等待操作员确认。
|
||||
if self.station == 'picking' or not self.submit_on_remove():
|
||||
# 手动确认模式(分拣,或未开自动提交的入库):只能由确认按钮提交。
|
||||
# 读数仍在正常区间时更新待确认数量;明显掉重或归零视为货物正在被拿走,
|
||||
# 不用残重覆盖稳定记账量,也不自动提交,等待操作员确认。
|
||||
if st.get('present'):
|
||||
settled = float(getattr(self, '_confirm_settled_kg', 0.0)
|
||||
or self._frozen_kg or 0.0)
|
||||
@@ -3319,12 +3594,6 @@ class FlowEngine:
|
||||
self._confirm_absent_at = 0.0
|
||||
self._abort_cycle('货已不在秤上(选中期间被拿走),本轮作废')
|
||||
return
|
||||
if not self.submit_on_remove():
|
||||
# 关掉自动提交的工位照样跟读数:人点「确认」那一刻用的
|
||||
# 就是秤上最新的稳定值,不是抓拍时的冻结值
|
||||
if st.get('present'):
|
||||
self._track_confirm_weight(now, st)
|
||||
return
|
||||
if st.get('present'):
|
||||
self._confirm_seen_present = True
|
||||
self._confirm_absent_at = 0.0
|
||||
@@ -3335,6 +3604,8 @@ class FlowEngine:
|
||||
settled * 0.6)
|
||||
if st['weight'] >= floor:
|
||||
# 读数还在正常区间:可能被增减,跟住它,稳了就换新读数
|
||||
if getattr(self, '_confirm_gone_at', 0.0):
|
||||
self.emit('hint', '') # 货回来了,撤掉取货提示
|
||||
self._confirm_gone_at = 0.0
|
||||
self._track_confirm_weight(now, st)
|
||||
return
|
||||
@@ -3343,7 +3614,17 @@ class FlowEngine:
|
||||
# 才按取走处理,用的始终是掉下去之前的稳定值。
|
||||
if not getattr(self, '_confirm_gone_at', 0.0):
|
||||
self._confirm_gone_at = now
|
||||
# 现场:补货时常把原货抬起来调整位置,以前 3 秒就误提交。
|
||||
# 把窗口放长,并在提示行里说明怎么取消(把货放回秤上)。
|
||||
self.emit('hint', '读数掉了:持续 %g 秒不回升才自动提交;'
|
||||
'补货时把货放回秤上就取消'
|
||||
% self._confirm_linger_s())
|
||||
self.emit('log', '读数下降(可能取货/补货调整):%g 秒内'
|
||||
'放回秤上就不提交' % self._confirm_linger_s())
|
||||
elif now - self._confirm_gone_at >= self._confirm_linger_s():
|
||||
if f.get('row_id') is None:
|
||||
self._abort_cycle('货已取走且未选商品,本轮作废')
|
||||
return
|
||||
name = (self._frozen_row or {}).get('item_name') or ''
|
||||
self.emit('log', '货已取走(%.3f → %.3f kg),自动提交「%s」'
|
||||
% (settled, st['weight'], name))
|
||||
@@ -3359,8 +3640,15 @@ class FlowEngine:
|
||||
return
|
||||
if not getattr(self, '_confirm_gone_at', 0.0):
|
||||
self._confirm_gone_at = now
|
||||
self.emit('hint', '秤上已没货:%g 秒后自动提交;还在补货请把货放回秤上'
|
||||
% (self._confirm_zero_ms() / 1000.0))
|
||||
self.emit('log', '秤已归零:%g 秒内把货放回秤上就不提交'
|
||||
% (self._confirm_zero_ms() / 1000.0))
|
||||
if now - self._confirm_gone_at < self._confirm_zero_ms() / 1000.0:
|
||||
return # 归零要稳一小会儿,防读数毛刺
|
||||
return # 空秤要稳一小会儿,防读数毛刺/抬货调整
|
||||
if f.get('row_id') is None:
|
||||
self._abort_cycle('货已取走且未选商品,本轮作废')
|
||||
return
|
||||
name = (self._frozen_row or {}).get('item_name') or ''
|
||||
self.emit('log', '货已取走(%.3f → %.3f kg,秤已归零),自动提交「%s」'
|
||||
% (float(getattr(self, '_confirm_settled_kg', 0.0)
|
||||
@@ -3374,12 +3662,21 @@ class FlowEngine:
|
||||
self.emit('log', '自动提交失败:%s' % msg)
|
||||
|
||||
def _confirm_linger_s(self):
|
||||
"""读数掉到 6 成以下、既不归零也不回升时,等多久算「取走」"""
|
||||
return float(self.cfg['flow'].get('confirm_linger_s', 3.0) or 3.0)
|
||||
"""读数掉到 6 成以下、既不归零也不回升时,等多久算「取走」
|
||||
|
||||
v1.0.69:3 秒 → 10 秒。现场补货时会把原货抬起来调整位置,
|
||||
旧窗口太短会被当成取走,按补货前的短重量提交。
|
||||
这段时间里把货放回秤上就自动取消。
|
||||
"""
|
||||
return float(self.cfg['flow'].get('confirm_linger_s', 10.0) or 10.0)
|
||||
|
||||
def _confirm_zero_ms(self):
|
||||
"""秤归零后要稳定多久才提交(防瞬时毛刺/轻货抖动)"""
|
||||
return float(self.cfg['flow'].get('confirm_zero_ms', 300) or 300)
|
||||
"""秤归零后要稳定多久才提交(防瞬时毛刺/抬货调整)
|
||||
|
||||
v1.0.69:300ms → 3000ms。抬货调整/补货常超过 0.3 秒,
|
||||
旧值会把「抬起来挪一下」当成取走直接提交。
|
||||
"""
|
||||
return float(self.cfg['flow'].get('confirm_zero_ms', 3000) or 3000)
|
||||
|
||||
def _track_confirm_weight(self, now, st):
|
||||
"""v1.0.62:确认期间跟住秤读数,稳出一个新值就按它记账
|
||||
@@ -3823,6 +4120,7 @@ class FlowEngine:
|
||||
self._run_count_recognition()
|
||||
|
||||
def _run_count_recognition(self):
|
||||
self._assist_pending = None
|
||||
rows = self.noweigh_rows()
|
||||
names = sorted({r.get('item_name') for r in rows if r.get('item_name')})
|
||||
detected = None
|
||||
@@ -3835,12 +4133,11 @@ class FlowEngine:
|
||||
else:
|
||||
info = {}
|
||||
try:
|
||||
info = self.recog.identify_ex(
|
||||
# 免称重是手举着袋子/整筐抓拍,货可能占满画面,四周裁太多
|
||||
# 会把袋口和货切掉;这里只削一点点边(默认保留 96%)。
|
||||
# 同一份抓拍交给两种模型,云端结果进入操作流程。
|
||||
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:
|
||||
@@ -3961,32 +4258,10 @@ class FlowEngine:
|
||||
if q <= 1e-6:
|
||||
return False, '「%s」待办剩余为 0,可能刚结过' \
|
||||
% (row.get('item_name') or '')
|
||||
if self.station == 'picking':
|
||||
# 免称重分拣同样必须等待操作员确认。
|
||||
self._auto_round = False
|
||||
self._to_focus(row, q, detected=detected, conf=conf,
|
||||
mode='count', candidates=[row], auto=True)
|
||||
return True, ''
|
||||
unit = row.get('unit') or ''
|
||||
self.emit('log', 'AI 自动%s:%s %.2f %s(不称重,把握 %s)'
|
||||
% ('分拣' if self.station == 'picking' else '入库',
|
||||
row.get('item_name') or '', q, unit,
|
||||
'未知' if conf is None else '%d%%' % int(float(conf))))
|
||||
self._start_auto_count_submit(row, q)
|
||||
return True, ''
|
||||
|
||||
def _start_auto_count_submit(self, row, qty, source='AI自动'):
|
||||
"""不称重路径的直接提交:把这行按待办剩余量一次结掉
|
||||
|
||||
和 submit_count 的区别只有一处 —— 不要求先进 COUNT_CONFIRM。正常
|
||||
称重流程里识别到「袋/包/桶」时状态是 RECOGNIZE,但也该直接记账。
|
||||
"""
|
||||
self._count_mode = True
|
||||
self._auto_round = False
|
||||
self._count_qty = float(qty or 0.0)
|
||||
self._frozen_row = row
|
||||
self._frozen_kg = self._count_weight(row, qty)
|
||||
self._start_submit(row, float(qty or 0.0), source)
|
||||
self._to_focus(row, q, detected=detected, conf=conf,
|
||||
mode='count', candidates=[row], auto=True)
|
||||
return True, ''
|
||||
|
||||
def _to_count_confirm(self, detected, row, candidates, warn=None):
|
||||
# 走到核对页就不再是「自动轮」了:后面的提交是人在点,按人工路径走
|
||||
@@ -4111,6 +4386,8 @@ class FlowEngine:
|
||||
|
||||
def _abort_cycle(self, msg):
|
||||
self.emit('log', msg)
|
||||
if self._focus is not None:
|
||||
self._clear_focus()
|
||||
self._pre_pick_rid = None
|
||||
self._printed_rid = None
|
||||
self._remove_submit = False
|
||||
|
||||
+271
-132
@@ -25,7 +25,8 @@ except ImportError:
|
||||
DEFAULT_DPI = 203
|
||||
DEFAULT_WIDTH_MM = 50
|
||||
DEFAULT_HEIGHT_MM = 50
|
||||
PRINT_HEAD_MAX_MM = 76 # 常见桌面标签机打印头宽度上限
|
||||
PRINT_HEAD_MAX_MM = 104 # 默认按 4 英寸打印头(104mm)算;3 英寸机型
|
||||
# 在 config 里写 printer.max_width_mm = 76
|
||||
|
||||
# TSPL 内置点阵字体(TSS<n>.BF2,中文字体)可用字号
|
||||
_FONT_STEPS = (40, 32, 24, 20, 16, 12)
|
||||
@@ -130,10 +131,13 @@ def label_geom(cfg):
|
||||
if hmm < 15:
|
||||
hmm = 15
|
||||
warn.append('标签高度小于 15mm,已按 15mm 处理')
|
||||
if wmm > PRINT_HEAD_MAX_MM:
|
||||
warn.append('标签宽 %.0fmm 超过打印头 %dmm,只画 %dmm'
|
||||
% (wmm, PRINT_HEAD_MAX_MM, PRINT_HEAD_MAX_MM))
|
||||
wmm = PRINT_HEAD_MAX_MM
|
||||
head = _num(cfg.get('max_width_mm'), PRINT_HEAD_MAX_MM)
|
||||
if head < 15:
|
||||
head = PRINT_HEAD_MAX_MM
|
||||
if wmm > head:
|
||||
warn.append('标签宽 %.0fmm 超过打印头 %gmm,只画 %gmm'
|
||||
% (wmm, head, head))
|
||||
wmm = head
|
||||
dpi = int(_num(cfg.get('dpi'), DEFAULT_DPI))
|
||||
if dpi not in (203, 300, 600):
|
||||
dpi = DEFAULT_DPI
|
||||
@@ -145,10 +149,15 @@ def label_geom(cfg):
|
||||
|
||||
|
||||
def _text_width(text, font):
|
||||
"""估算一行文字的点阵宽度:汉字≈字号,ASCII≈0.55 字号"""
|
||||
"""估算一行文字的点阵宽度:GBK 双字节(汉字/全角标点)≈字号,ASCII≈0.56 字号
|
||||
|
||||
v1.0.69:判断从「码点 > 0x2E80」改成「非 ASCII」。TSPL 用 GBK 下发,
|
||||
×、·、°、— 这些不在 0x2E80 以上,但 GBK 里是双字节全角字(× 是 A1C1),
|
||||
打印机按全角打;按半角估会低估宽度,长品名就可能顶到二维码。
|
||||
"""
|
||||
w = 0.0
|
||||
for ch in str(text or ''):
|
||||
w += font if ord(ch) > 0x2E80 else font * 0.56
|
||||
w += font if ord(ch) > 0x7F else font * 0.56
|
||||
return w
|
||||
|
||||
|
||||
@@ -177,8 +186,13 @@ def _wrap(text, font, max_w, max_lines=2):
|
||||
if not cur or _text_width(cur + ch, font) <= max_w:
|
||||
cur += ch
|
||||
else:
|
||||
out.append(cur)
|
||||
cur = ch
|
||||
# 在空格处换行时把空格留在上一行尾部,下一行不要顶着缩进
|
||||
if ch.isspace():
|
||||
out.append(cur + ch)
|
||||
cur = ''
|
||||
else:
|
||||
out.append(cur)
|
||||
cur = ch
|
||||
if cur:
|
||||
out.append(cur)
|
||||
if len(out) > max_lines:
|
||||
@@ -189,13 +203,31 @@ def _wrap(text, font, max_w, max_lines=2):
|
||||
|
||||
|
||||
def _qr_modules(n_bytes):
|
||||
"""QR 版本 → 模块数(ECC=H 的保守估算表)"""
|
||||
"""QR 版本 → 模块数(ECC=H 的容量表,最多到 version 40)
|
||||
|
||||
以前 >154 字节一律返回 69,超长容器码会把码高估小,印出来可能
|
||||
超出保留区。现在按真实容量表取,最大 1273 字节 / 177 模块。
|
||||
"""
|
||||
for limit, mods in ((7, 21), (14, 25), (24, 29), (34, 33), (44, 37),
|
||||
(58, 41), (64, 45), (84, 49), (98, 53), (119, 57),
|
||||
(139, 61), (154, 65)):
|
||||
(137, 61), (155, 65), (177, 69), (194, 73),
|
||||
(220, 77), (250, 81), (280, 85), (310, 89),
|
||||
(338, 93), (382, 97), (403, 101), (439, 105),
|
||||
(461, 109), (511, 113), (535, 117), (593, 121),
|
||||
(625, 125), (658, 129), (698, 133), (742, 137),
|
||||
(790, 141), (842, 145), (898, 149), (958, 153),
|
||||
(983, 157), (1051, 161), (1093, 165), (1139, 169),
|
||||
(1219, 173), (1273, 177)):
|
||||
if n_bytes <= limit:
|
||||
return mods
|
||||
return 69
|
||||
return 177
|
||||
|
||||
|
||||
_QR_MAX_BYTES = 1273 # ECC=H、version 40 的字节上限
|
||||
|
||||
|
||||
class LabelOverflow(ValueError):
|
||||
"""版面排不下(或二维码数据打不出):宁可报错,也不打截断/缺码的标签"""
|
||||
|
||||
|
||||
def plan_label(cfg, title, fields, qr_data=''):
|
||||
@@ -209,108 +241,184 @@ def plan_label(cfg, title, fields, qr_data=''):
|
||||
dpm = g['dots_per_mm']
|
||||
warn = list(g['warnings'])
|
||||
mx = max(int(round(2 * dpm)), 8) # 左右留白 2mm
|
||||
my = max(int(round(1.5 * dpm)), 6)
|
||||
# 上下留白:目标 5mm,但最多占纸高的 10%(小标签留地方放字)。
|
||||
# 以前只留 1.5mm,字块又改成了铺满整张纸,最后一行几乎贴着纸边 ——
|
||||
# 打印机底部普遍有 2~4mm 不可打印区,日期和码底就会被打掉。
|
||||
my = max(int(round(1.5 * dpm)),
|
||||
min(int(round(5 * dpm)), int(round(h * 0.10))))
|
||||
|
||||
texts = [_safe_text(title or '')] + [_safe_text(t or '')
|
||||
for t in (fields or [])]
|
||||
n = max(len(texts), 1)
|
||||
|
||||
# ---- 二维码:先看放不放得下,放不下就整块不打,绝不打半个码 ----
|
||||
qr_data = _safe_text(qr_data)
|
||||
qr = None
|
||||
qr_w = 0
|
||||
if qr_data:
|
||||
mods = _qr_modules(len(str(qr_data).encode('gbk', 'ignore')))
|
||||
cap = min(h - 2 * my, int(w * 0.34))
|
||||
cell = 4
|
||||
while cell >= 2 and mods * cell > cap:
|
||||
cell -= 1
|
||||
if cell >= 2 and mods * cell <= cap:
|
||||
qr_w = mods * cell
|
||||
qr = {'modules': mods, 'cell': cell, 'size': qr_w,
|
||||
'x': w - mx - qr_w, 'y': my}
|
||||
else:
|
||||
warn.append('标签太小,二维码放不下(已省略);建议加大宽度/高度')
|
||||
|
||||
text_w = w - mx * 2 - (qr_w + int(round(2 * dpm)) if qr else 0)
|
||||
|
||||
# ---- 字号 + 折行:从大到小试,取「不丢字、放得下」的最大字号 ----
|
||||
# 三档退让,优先保版面整齐:
|
||||
# ① 全部单行
|
||||
# ② 只让品名折两行
|
||||
# ③ 都被逼到墙角了才允许所有字段折行
|
||||
# 为什么不让所有字段随时可折:32 号字会把「客户: 张三水果批发店」劈成
|
||||
# 「客户: 张三水果」+「批发店」两行,比小一号字难看得多。
|
||||
# ---- 版面:二维码与文字栏互相制约 ----
|
||||
# 码越大 → 文字栏越窄 → 字号被迫变小。这里从「最大码」往下试:
|
||||
# 取第一个「字号不低于下限、内容排得下」的尺寸,既保证码尽可能大,
|
||||
# 又不会把字挤到看不清;码高也绝不会超过文字块的高度。
|
||||
avail_h = h - my * 2
|
||||
# 只让品名折行(第 0 项标题、第 1 项客户/订单、第 2 项品名)。
|
||||
# 日期/时间/重量/数量/订单号是原子串,后面也不允许折;
|
||||
# 宁可整体降一号字,也不能把日期劈成“11-06 1”+“0:00”。
|
||||
qr_data = _safe_text(qr_data)
|
||||
qr_gap = int(round(2 * dpm)) if qr_data else 0
|
||||
longest = 2 if len(texts) > 2 else 0
|
||||
slack = 1.02
|
||||
slack = 1.0 if qr_data else 1.02
|
||||
qr = None
|
||||
overflow = False
|
||||
|
||||
def build(f, allow):
|
||||
tmp, folds = [], 0
|
||||
def _build(tw2, f, allow):
|
||||
tmp = []
|
||||
for i, t in enumerate(texts):
|
||||
if _text_width(t, f) <= text_w * slack:
|
||||
if _text_width(t, f) <= tw2 * slack:
|
||||
tmp.append(t) # 容差内原样放,吃掉右侧留白,不截字
|
||||
continue
|
||||
if i == 0:
|
||||
tmp.append(_cut(t, f, text_w)) # 标题永远单行
|
||||
continue
|
||||
if i in allow:
|
||||
part = _wrap(t, f, text_w, 2)
|
||||
if _text_width(part[-1], f) > text_w:
|
||||
return None
|
||||
tmp.extend(part)
|
||||
folds += 1
|
||||
else:
|
||||
if i not in allow:
|
||||
return None
|
||||
# max_lines 给足:宁可折很多行/降字号,也绝不截字
|
||||
tmp.extend(_wrap(t, f, tw2, 999))
|
||||
if len(tmp) * f * _LINE_RATIO > avail_h:
|
||||
return None
|
||||
return tmp, folds
|
||||
return tmp
|
||||
|
||||
def best_in_tier(allow):
|
||||
"""这一档里能放下的最大字号;一档都没有就返回 None"""
|
||||
for f in _FONT_STEPS_CAP:
|
||||
got = build(f, allow)
|
||||
if got:
|
||||
return f, got[0]
|
||||
return None
|
||||
def _layout(tw2):
|
||||
"""给定文字栏宽度选字号/折行:返回 (font, rows, ok, ratio, overflow)"""
|
||||
best = None
|
||||
for allow in ((), (longest,)):
|
||||
for f in _FONT_STEPS_CAP:
|
||||
got = _build(tw2, f, allow)
|
||||
if got is not None:
|
||||
if best is None or f > best[0]:
|
||||
best = (f, got)
|
||||
break
|
||||
if best is None:
|
||||
allow_all = tuple(range(len(texts)))
|
||||
for f in _FONT_STEPS_CAP:
|
||||
got = _build(tw2, f, allow_all)
|
||||
if got is not None:
|
||||
best = (f, got)
|
||||
break
|
||||
ratio, of = _LINE_RATIO, False
|
||||
if best is not None:
|
||||
font, rows = best
|
||||
else:
|
||||
# 怎么排都放不下:最小字号 + 所有字段不限行数折开(绝不截字),
|
||||
# 行距压到刚好放得下;真排不下时明确告警,让现场加大标签。
|
||||
font = _FONT_STEPS_CAP[-1]
|
||||
rows = []
|
||||
for t in texts:
|
||||
rows.extend(_wrap(t, font, tw2, 999))
|
||||
if len(rows) * font * ratio > avail_h:
|
||||
ratio = max(0.95, float(avail_h) / max(1, len(rows) * font))
|
||||
of = len(rows) * font * ratio > avail_h + 1
|
||||
return font, rows, best is not None, ratio, of
|
||||
|
||||
# 在先保证「日期/时间/重量/数量/订单号不折」的前提下排版:
|
||||
# ① 全部单行 / ② 只折品名 —— 两档里取字号大的(不折客户名)
|
||||
# ③ ① ② 都放不下时,才允许客户/供应商也折(原子串仍不折)
|
||||
# 以前 ③ 允许所有字段折,32 号字会把日期劈成两行,现场根本看不懂。
|
||||
best = None
|
||||
for allow in ((), (longest,)):
|
||||
got = best_in_tier(allow)
|
||||
if got and (best is None or got[0] > best[1]):
|
||||
best = (0, got[0], got[1])
|
||||
if best is None:
|
||||
allow_all = tuple(i for i in range(len(texts))
|
||||
if not _is_atomic_line(texts[i]))
|
||||
if allow_all:
|
||||
got = best_in_tier(allow_all)
|
||||
if got:
|
||||
best = (0, got[0], got[1])
|
||||
text_w = w - mx * 2
|
||||
font = _FONT_STEPS_CAP[-1]
|
||||
rows = [_safe_text(t or '') for t in (texts or [])]
|
||||
ok_layout = True
|
||||
ratio = _LINE_RATIO
|
||||
step = font * ratio
|
||||
block_h = (len(rows) - 1) * step + font
|
||||
|
||||
if best is not None:
|
||||
font, rows = best[1], best[2]
|
||||
if qr_data:
|
||||
payload_bad = False
|
||||
try:
|
||||
raw_qr = str(qr_data).encode('gbk')
|
||||
except UnicodeEncodeError:
|
||||
raw_qr = b''
|
||||
payload_bad = True
|
||||
warn.append('容器码含打印机不支持的字符(非 GBK),本次不打印')
|
||||
if len(raw_qr) > _QR_MAX_BYTES:
|
||||
payload_bad = True
|
||||
warn.append('容器码过长(%d 字节),一张二维码最多 %d 字节;'
|
||||
'本次不打印' % (len(raw_qr), _QR_MAX_BYTES))
|
||||
mods = _qr_modules(len(raw_qr))
|
||||
# 字号下限:常见纸型(≥30mm 高)不让字号低于 24;极小纸另行允许 12
|
||||
floor = 24 if h >= int(round(30 * dpm)) else 12
|
||||
max_qr = int(w * 0.40) # 码最多占纸宽 40%,文字栏至少 25%
|
||||
|
||||
def _cand(cell):
|
||||
qw = mods * cell
|
||||
tw2 = w - mx * 2 - qw - qr_gap
|
||||
if tw2 < int(w * 0.25):
|
||||
return None
|
||||
f, rs, ok, ra, of = _layout(tw2)
|
||||
st = f * ra
|
||||
if ok and len(rs) > 1:
|
||||
st = max(st, (avail_h - f) / float(len(rs) - 1))
|
||||
bh = (len(rs) - 1) * st + f
|
||||
if qw > bh + 1: # 码不能比文字块还高
|
||||
return None
|
||||
return {'cell': cell, 'size': qw, 'text_w': tw2, 'font': f,
|
||||
'rows': rs, 'ok': ok, 'ratio': ra, 'step': st,
|
||||
'block_h': bh, 'overflow': of}
|
||||
|
||||
chosen = None
|
||||
for cell in range(10, 0, -1):
|
||||
if mods * cell > max_qr:
|
||||
continue
|
||||
c = _cand(cell)
|
||||
if c and c['ok'] and c['font'] >= floor and not c['overflow']:
|
||||
chosen = c
|
||||
break
|
||||
if chosen is None:
|
||||
# 内容偏长:字号保不住下限,也要优先把码做大(仍保证排得下)
|
||||
for cell in range(10, 0, -1):
|
||||
if mods * cell > max_qr:
|
||||
continue
|
||||
c = _cand(cell)
|
||||
if c:
|
||||
chosen = c
|
||||
break
|
||||
if chosen is None:
|
||||
# 连最小码都给不了正常版面:按最小码 + 最宽文字栏硬排
|
||||
qw = mods
|
||||
tw2 = max(int(w * 0.25), w - mx * 2 - qw - qr_gap)
|
||||
f, rs, ok, ra, of = _layout(tw2)
|
||||
st = f * ra
|
||||
chosen = {'cell': 1, 'size': qw, 'text_w': tw2, 'font': f,
|
||||
'rows': rs, 'ok': ok, 'ratio': ra, 'step': st,
|
||||
'block_h': (len(rs) - 1) * st + f, 'overflow': of}
|
||||
warn.append('标签太小,二维码只能按最小点阵打印(可能扫不出);'
|
||||
'建议加大标签宽/高')
|
||||
|
||||
qr = {'modules': mods, 'cell': chosen['cell'],
|
||||
'size': chosen['size'], 'x': w - mx - chosen['size'], 'y': my}
|
||||
if qr['x'] < mx:
|
||||
warn.append('标签太窄,二维码可能超出右边界;请加大标签宽度')
|
||||
text_w = chosen['text_w']
|
||||
font = chosen['font']
|
||||
rows = chosen['rows']
|
||||
ok_layout = chosen['ok']
|
||||
ratio = chosen['ratio']
|
||||
step = chosen['step']
|
||||
block_h = chosen['block_h']
|
||||
layout_of = chosen['overflow']
|
||||
overflow = payload_bad or layout_of
|
||||
else:
|
||||
# 实在太小:退到最小字号,每个字段只留一行并截断
|
||||
font = _FONT_STEPS_CAP[-1]
|
||||
rows = [_cut(t, font, text_w) for t in texts]
|
||||
warn.append('标签太小,部分文字已截断(字号 %d);'
|
||||
'想打全请加大标签宽度/高度' % font)
|
||||
font, rows, ok_layout, ratio, layout_of = _layout(text_w)
|
||||
overflow = layout_of
|
||||
step = font * ratio
|
||||
block_h = (len(rows) - 1) * step + font
|
||||
|
||||
# 最后一行只占一个字号的高度,不占整行行距,垂直居中才不会显得偏上
|
||||
block_h = (len(rows) - 1) * font * _LINE_RATIO + font
|
||||
y = my + max(0, int((avail_h - block_h) // 2))
|
||||
if layout_of:
|
||||
warn.append('内容太长,这张标签排不下全部文字;'
|
||||
'请加大标签或缩短商品名/客户名')
|
||||
elif not ok_layout:
|
||||
warn.append('内容较长,已压缩行距排满整张标签')
|
||||
|
||||
# 行距:有二维码时把文字从上到下均匀铺开(现场反馈底部空太多),
|
||||
# 没二维码的标签仍垂直居中。
|
||||
if qr:
|
||||
y = my
|
||||
else:
|
||||
y = my + max(0, int((avail_h - block_h) // 2))
|
||||
lines = []
|
||||
for t in rows:
|
||||
lines.append({'text': t, 'font': font, 'x': mx, 'y': int(y),
|
||||
'w': int(_text_width(t, font))})
|
||||
y += font * _LINE_RATIO
|
||||
'w': int(_text_width(t.rstrip(), font))})
|
||||
y += step
|
||||
# 二维码贴右下角:底边和最后一行底边对齐(现场参考图的版式)。
|
||||
# 放在最后算,是因为要先知道文字铺完最后一行落在哪。
|
||||
if qr and lines:
|
||||
qr['y'] = max(my, int(lines[-1]['y'] + font - qr['size']))
|
||||
|
||||
gap_mm = _num(cfg.get('gap_mm'), 2)
|
||||
if gap_mm < 0:
|
||||
@@ -319,7 +427,15 @@ def plan_label(cfg, title, fields, qr_data=''):
|
||||
'gap_dots': int(round(gap_mm * dpm)),
|
||||
'gap_mm': gap_mm,
|
||||
'font': font, 'n_lines': n,
|
||||
'text_w': int(text_w), 'warnings': warn}
|
||||
'text_w': int(text_w), 'warnings': warn, 'overflow': overflow}
|
||||
|
||||
|
||||
def _checked(p):
|
||||
"""打印路径专用:排不下/码打不出就抛异常,绝不把半张标签发出去"""
|
||||
if p.get('overflow'):
|
||||
msg = ';'.join(p.get('warnings') or []) or '标签排不下全部内容'
|
||||
raise LabelOverflow(msg)
|
||||
return p
|
||||
|
||||
|
||||
def _tspl_from_plan(p):
|
||||
@@ -348,37 +464,50 @@ def _page_dots(cfg):
|
||||
|
||||
def build_picking_label_tspl(cfg, customer, item_name, weight, unit, date_str,
|
||||
order_code=''):
|
||||
p = plan_label(cfg, '分拣标签',
|
||||
['客户: %s' % customer,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str],
|
||||
qr_data=order_code or '')
|
||||
# 参数名保留 order_code 兼容旧调用;v1.0.64 起传的是服务端容器码
|
||||
# (container_code),二维码只能用这个,不能用订单号。
|
||||
p = _checked(plan_label(cfg, '分拣标签',
|
||||
['客户: %s' % customer,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str],
|
||||
qr_data=order_code or ''))
|
||||
return _tspl_from_plan(p)
|
||||
|
||||
|
||||
def build_inspection_label_tspl(cfg, order_code, item_name, weight, unit,
|
||||
supplier, date_str):
|
||||
p = plan_label(cfg, '验收标签',
|
||||
['订单: %s' % order_code,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str])
|
||||
p = _checked(plan_label(cfg, '验收标签',
|
||||
['订单: %s' % order_code,
|
||||
'品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str]))
|
||||
return _tspl_from_plan(p)
|
||||
|
||||
|
||||
def build_zpl(cfg, title, fields, qr_data=None):
|
||||
w, h = _page_dots(cfg)
|
||||
out = ['^XA^CI28^PW%d^LL%d^LH0,0' % (w, h),
|
||||
'^FO20,20^A0N,36,36^FD%s^FS' % _zpl_text(title)]
|
||||
y = 80
|
||||
for line in fields:
|
||||
out.append('^FO20,%d^A0N,34,34^FD%s^FS' % (y, _zpl_text(line)))
|
||||
y += 55
|
||||
if qr_data:
|
||||
out.append('^FO%d,20^BQN,2,4^FDQA,%s^FS'
|
||||
% (max(w - 130, 20), _zpl_text(qr_data)))
|
||||
"""ZPL 也走同一份 plan_label 版面(v1.0.64)
|
||||
|
||||
以前 ZPL 是单独一套写死的 36/34 号字、55 点行距、二维码固定在
|
||||
w-130:50×50 以外的纸型会溢出/裁字,而且和 TSPL 预览对不上。
|
||||
现在复用 TSPL 的自适应结果(折行、原子串不拆、二维码位置),
|
||||
只把 TEXT/QRCODE 换成 ZPL 的 ^FO/^A0N/^BQN。
|
||||
"""
|
||||
p = _checked(plan_label(cfg, title, fields, qr_data or ''))
|
||||
g = p['geom']
|
||||
out = ['^XA^CI28^PW%d^LL%d^LH0,0' % (g['w'], g['h'])]
|
||||
for ln in p['lines']:
|
||||
out.append('^FO%d,%d^A0N,%d,%d^FD%s^FS'
|
||||
% (ln['x'], ln['y'], ln['font'], ln['font'],
|
||||
_zpl_text(ln['text'])))
|
||||
if p['qr']:
|
||||
q = p['qr']
|
||||
# ZPL 的 ^BQN 第三个参数是放大倍数(1~10),正好对应 cell
|
||||
mag = max(1, min(10, int(q['cell'])))
|
||||
out.append('^FO%d,%d^BQN,2,%d^FDQA,%s^FS'
|
||||
% (q['x'], q['y'], mag,
|
||||
_zpl_text(p.get('qr_data') or '')))
|
||||
out.append('^XZ')
|
||||
return ''.join(out).encode('utf-8')
|
||||
|
||||
@@ -479,28 +608,38 @@ class LabelPrinter:
|
||||
return dict(self.cfg)
|
||||
|
||||
def print_picking(self, customer, item_name, weight, unit, order_code=''):
|
||||
# order_code 为兼容旧调用保留的名字;调用方实际传容器码
|
||||
date_str = datetime.datetime.now().strftime('%m-%d %H:%M')
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '分拣标签',
|
||||
['客户: %s' % customer, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str], order_code)
|
||||
else:
|
||||
data = build_picking_label_tspl(self.cfg, customer, item_name,
|
||||
weight, unit, date_str, order_code)
|
||||
try:
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '分拣标签',
|
||||
['客户: %s' % customer, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'日期: %s' % date_str], order_code)
|
||||
else:
|
||||
data = build_picking_label_tspl(self.cfg, customer, item_name,
|
||||
weight, unit, date_str,
|
||||
order_code)
|
||||
except LabelOverflow as e:
|
||||
# 排不下/码打不出:宁可不发,也不打截断或缺码的标签
|
||||
return False, '本次未打印:%s' % e
|
||||
return self._send(data)
|
||||
|
||||
def print_inspection(self, order_code, item_name, weight, unit, supplier):
|
||||
date_str = datetime.datetime.now().strftime('%m-%d %H:%M')
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '验收标签',
|
||||
['订单: %s' % order_code, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier, '时间: %s' % date_str])
|
||||
else:
|
||||
data = build_inspection_label_tspl(
|
||||
self.cfg, order_code, item_name, weight, unit, supplier,
|
||||
date_str)
|
||||
try:
|
||||
if self.cfg.get('type') == 'zpl':
|
||||
data = build_zpl(self.cfg, '验收标签',
|
||||
['订单: %s' % order_code, '品名: %s' % item_name,
|
||||
'%s: %.2f %s' % (qty_word(unit), weight, unit),
|
||||
'供应商: %s' % supplier,
|
||||
'时间: %s' % date_str])
|
||||
else:
|
||||
data = build_inspection_label_tspl(
|
||||
self.cfg, order_code, item_name, weight, unit, supplier,
|
||||
date_str)
|
||||
except LabelOverflow as e:
|
||||
return False, '本次未打印:%s' % e
|
||||
return self._send(data)
|
||||
|
||||
def send_raw(self, data, doc_name='标签'):
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""建议模式(assist):本地分类器给建议 + 云端按 98% 决定要不要问 + 每一笔
|
||||
人工确认留痕。**这里不产生任何自动记账**。
|
||||
|
||||
三条规则(设计上不容商量,代码也照着写):
|
||||
|
||||
1. **98% 只是一个开关**,决定这次要不要额外调一次云端;它不代表「够准」。
|
||||
现在效率不重要,攒数据才重要。所以 `ask_cloud_below` 设高一点(几乎每单
|
||||
都问)也是在攒**配对**数据:同一次称重,本地说什么、云端说什么、人怎么
|
||||
选 —— 这三样凑齐,才谈得上日后标定这个 98%。
|
||||
2. **人是唯一基准**。两个引擎都说是苹果,也仍然要人点确认;`force_confirm`
|
||||
默认 true 就是干这个的:建议模式一开,就不存在「认出即提交」。
|
||||
3. **本地引擎不做任何判断**。它没有「我自己能不能搞定」这种话,只输出一个
|
||||
建议。所以这里也没有加权、没有不一致处理、没有比分阶梯 —— 引擎答错是
|
||||
零成本的,因为没人会点它。
|
||||
|
||||
落盘格式(每笔确认一行,UTF-8 JSONL,按天分文件):
|
||||
|
||||
data/assist/cycles/2026-11-30.jsonl
|
||||
|
||||
{"v":1,"ts":"...","cycle":"113045-a1b2","station":"loading",
|
||||
"weight_kg":2.81,"image":"data/snapshots/20261130_113045.jpg",
|
||||
"image_sha":"9f2c...","image_mtime":1764492645.1,"n_rows":7,
|
||||
"whitelist":["苹果","香蕉", ...],
|
||||
"yolo":{"name":"苹果","prob":0.991,"top":[["苹果",0.991]],
|
||||
"all_top":[["苹果",0.991],["红富士苹果",0.004]],"covered":6,"ms":41},
|
||||
"cloud":{"asked":false,"reason":"yolo>=0.98","name":"","conf":null,
|
||||
"alt":"","alt_conf":null,"ms":null},
|
||||
"human":{"row_id":"1024","item_name":"苹果","changed":false,
|
||||
"source":"确认记账","part":1},
|
||||
"final":{"row_id":"1024","item_name":"苹果","business":5.0}}
|
||||
|
||||
为什么 `image_sha` 必须记:「取时间最近的那张图」在卡顿或重新拍照时会悄悄
|
||||
错位,而错位的标签会污染训练集且不报任何错。sha + mtime 是和图片本身绑死
|
||||
的证据,日后对不上就整行丢掉。
|
||||
|
||||
飞轮怎么用这三样:
|
||||
· 图 + human.item_name = 一条带标签的训练样本
|
||||
· yolo.prob + human.changed = 日后标定 ask_cloud_below 的依据
|
||||
· 两边一致但 human.changed 的比例 = 未来免确认的错误率底线
|
||||
"""
|
||||
from concurrent.futures import Future
|
||||
import threading
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import hashlib
|
||||
|
||||
from core.recognition.local_cls import LocalClassifier
|
||||
|
||||
DEFAULTS = {
|
||||
'enabled': False, # 总开关,默认关
|
||||
'ask_cloud_below': 0.98, # 低于这个概率才额外调云端
|
||||
'force_confirm': True, # 建议模式下一律人工确认
|
||||
'model': 'models/cls/product_cls.onnx',
|
||||
'classes': 'models/cls/classes.json',
|
||||
'imgsz': 320,
|
||||
'topk': 3,
|
||||
'journal_dir': 'data/assist',
|
||||
'whitelist_max': 200, # 名单快照最多记多少条
|
||||
}
|
||||
|
||||
|
||||
def _sha12(path):
|
||||
"""文件内容 sha1 前 12 位;读不出来返回空串(不阻断记录)。"""
|
||||
try:
|
||||
h = hashlib.sha1()
|
||||
with open(path, 'rb') as f:
|
||||
while True:
|
||||
b = f.read(1 << 18)
|
||||
if not b:
|
||||
break
|
||||
h.update(b)
|
||||
return h.hexdigest()[:12]
|
||||
except (OSError, ValueError):
|
||||
return ''
|
||||
|
||||
|
||||
def _norm(p):
|
||||
try:
|
||||
return os.path.normcase(os.path.abspath(str(p)))
|
||||
except (TypeError, ValueError):
|
||||
return ''
|
||||
|
||||
|
||||
class Assist:
|
||||
"""建议模式的全部旁路逻辑:不碰记账,只读状态 + 写日志。"""
|
||||
|
||||
def __init__(self, cfg=None):
|
||||
v = (cfg or {}).get('vision') if isinstance(cfg, dict) else {}
|
||||
if not isinstance(v, dict):
|
||||
v = {}
|
||||
raw = v.get('assist')
|
||||
self.cfg = dict(DEFAULTS)
|
||||
if isinstance(raw, dict):
|
||||
self.cfg.update(raw)
|
||||
self._recording_slot = threading.Lock()
|
||||
self.enabled = bool(self.cfg.get('enabled'))
|
||||
try:
|
||||
self.ask_cloud_below = float(self.cfg.get('ask_cloud_below', 0.98))
|
||||
except (TypeError, ValueError):
|
||||
self.ask_cloud_below = 0.98
|
||||
self.force_confirm = bool(self.cfg.get('force_confirm', True))
|
||||
self.journal_dir = str(self.cfg.get('journal_dir') or 'data/assist')
|
||||
try:
|
||||
self.whitelist_max = max(1, int(self.cfg.get('whitelist_max', 200)))
|
||||
except (TypeError, ValueError):
|
||||
self.whitelist_max = 200
|
||||
self.local = LocalClassifier({'assist': self.cfg})
|
||||
self._said = '' # 启动后第一单才解释一次「本地能不能用」
|
||||
|
||||
def reload_local(self):
|
||||
"""模型文件换版后调用:重建分类器。
|
||||
|
||||
旧实例里的 `_net` 是上一版权重、`names` 是上一版类别表 —— 复用就等于
|
||||
「换了模型但没换模型」。这里整体换对象而不是原地改字段:`local_suggest`
|
||||
每单只取一次 `self.local`,赋值本身是原子的,不会出现半新半旧。
|
||||
"""
|
||||
self.local = LocalClassifier({'assist': self.cfg})
|
||||
self._said = ''
|
||||
return self.local
|
||||
|
||||
# ------------------------------------------------------------ 建议
|
||||
def local_suggest(self, path, names, crop=None):
|
||||
"""本地建议;关着/没模型/出错一律 None(外面当「本地没意见」)。"""
|
||||
if not self.enabled:
|
||||
return None
|
||||
y = self.local.predict(path, names, crop=crop)
|
||||
return y or None
|
||||
|
||||
def record_local(self, path, names, crop=None):
|
||||
"""后台取样。上一张还在跑时跳过本地记录,避免积压。"""
|
||||
result = Future()
|
||||
if not self._recording_slot.acquire(blocking=False):
|
||||
result.set_result({'status': 'busy'})
|
||||
return result
|
||||
|
||||
def work():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
model = self.local
|
||||
prediction = model.predict(path, names, crop=crop)
|
||||
record = {
|
||||
'status': 'recognized' if prediction else 'unavailable',
|
||||
'version': getattr(model, 'loaded_version', '') or None,
|
||||
'name': (prediction or {}).get('name') or '',
|
||||
'confidence': (prediction or {}).get('prob'),
|
||||
'candidates': (prediction or {}).get('all_top', [])[:3],
|
||||
'ms': round((time.monotonic() - started) * 1000),
|
||||
}
|
||||
except Exception:
|
||||
record = {'status': 'unavailable'}
|
||||
finally:
|
||||
self._recording_slot.release()
|
||||
result.set_result(record)
|
||||
|
||||
thread = threading.Thread(target=work, name='yolo-record', daemon=True)
|
||||
try:
|
||||
thread.start()
|
||||
except RuntimeError:
|
||||
self._recording_slot.release()
|
||||
result.set_result({'status': 'unavailable'})
|
||||
return result
|
||||
|
||||
def ask_cloud(self, y):
|
||||
"""要不要额外调一次云端。**只是采样开关**,不是可信度判断。
|
||||
|
||||
没有本地建议时照样要问 —— 那就回到了加入建议模式之前的行为。
|
||||
"""
|
||||
if not y:
|
||||
return True
|
||||
try:
|
||||
p = float(y.get('prob') or 0.0)
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
return p < self.ask_cloud_below
|
||||
|
||||
def local_info(self, y):
|
||||
"""把本地建议翻成和 identify_ex 同形状的 dict,流程两条路共用一份。"""
|
||||
top = y.get('top') or []
|
||||
alt = top[1][0] if len(top) > 1 else ''
|
||||
alt_p = top[1][1] if len(top) > 1 else None
|
||||
try:
|
||||
conf = int(round(float(y.get('prob') or 0.0) * 100))
|
||||
except (TypeError, ValueError):
|
||||
conf = 0
|
||||
return {
|
||||
'name': y.get('name') or '',
|
||||
'conf': conf,
|
||||
'alt': alt,
|
||||
'alt_conf': (None if alt_p is None
|
||||
else int(round(float(alt_p) * 100))),
|
||||
'prompt_tag': 'local',
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------ 留痕
|
||||
def begin(self, station='', weight_kg=None, image='', names=None):
|
||||
"""开一条「这一件」的记录(先挂内存,人确认时才落盘)。"""
|
||||
now = time.time()
|
||||
names = [str(n) for n in (names or []) if str(n or '').strip()]
|
||||
rec = {
|
||||
'v': 1,
|
||||
'ts': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
|
||||
'cycle': time.strftime('%H%M%S', time.localtime(now)) + '-'
|
||||
+ ('%04x' % int((now % 1) * 65535)),
|
||||
'station': station or '',
|
||||
'weight_kg': (None if weight_kg is None
|
||||
else round(float(weight_kg), 3)),
|
||||
'image': str(image or ''),
|
||||
'image_sha': _sha12(image) if image else '',
|
||||
'image_mtime': (round(os.path.getmtime(image), 1)
|
||||
if image and os.path.isfile(image) else None),
|
||||
'n_rows': len(names),
|
||||
'whitelist': names[:self.whitelist_max],
|
||||
'yolo': None,
|
||||
'cloud': None,
|
||||
'human': None,
|
||||
'final': None,
|
||||
}
|
||||
return rec
|
||||
|
||||
def cloud_slot(self, info=None, error=''):
|
||||
"""云端那一格。没调用 = asked:false + 原因,其余留空(不写假分数)。"""
|
||||
info = info or {}
|
||||
if error:
|
||||
return {'asked': True, 'error': error, 'name': '', 'conf': None,
|
||||
'alt': '', 'alt_conf': None, 'ms': None}
|
||||
return {'asked': True,
|
||||
'reason': '',
|
||||
'name': str(info.get('name') or ''),
|
||||
'conf': info.get('conf'),
|
||||
'alt': str(info.get('alt') or ''),
|
||||
'alt_conf': info.get('alt_conf'),
|
||||
'ms': info.get('ms')}
|
||||
|
||||
def skip_cloud(self, reason):
|
||||
"""没调云端时的那一格:明确写下 asked:false 和原因。"""
|
||||
return {'asked': False, 'reason': reason, 'name': '', 'conf': None,
|
||||
'alt': '', 'alt_conf': None, 'ms': None}
|
||||
|
||||
def same_image(self, rec, image_path):
|
||||
"""这条记录是不是这一件(图对不上就当不是,宁可丢一行也别记错)。"""
|
||||
if not rec:
|
||||
return False
|
||||
a = _norm(rec.get('image') or '')
|
||||
b = _norm(image_path or '')
|
||||
if not a or not b:
|
||||
return False
|
||||
return a == b
|
||||
|
||||
def finish(self, rec, row, focus=None, source=''):
|
||||
"""人确认了:把最终选的行补进去并落盘。返回落盘路径或空串。"""
|
||||
if not rec:
|
||||
return ''
|
||||
f = focus if isinstance(focus, dict) else {}
|
||||
name = str((row or {}).get('item_name') or '').strip()
|
||||
rid = str((row or {}).get('id') or '')
|
||||
y = rec.get('yolo') or {}
|
||||
c = rec.get('cloud') or {}
|
||||
yname = str(y.get('name') or '')
|
||||
cname = str(c.get('name') or '')
|
||||
# 「人有没有覆盖建议」:两个引擎都只算建议,任一与最终行不同就是覆盖。
|
||||
# 两个都空(本地没意见 + 云端没认出)不算覆盖 —— 那是「没建议」,
|
||||
# 不是「建议错了」,混在一起会把错误率算高。
|
||||
changed = bool((yname and yname != name)
|
||||
or (cname and cname != name))
|
||||
rec['human'] = {
|
||||
'row_id': rid,
|
||||
'item_name': name,
|
||||
'changed': changed,
|
||||
'source': str(source or ''),
|
||||
'part': int(rec.get('_part') or 0) + 1,
|
||||
}
|
||||
rec['final'] = {
|
||||
'row_id': rid,
|
||||
'item_name': name,
|
||||
'business': f.get('business'),
|
||||
}
|
||||
rec['_part'] = int(rec.get('_part') or 0) + 1
|
||||
return self.write(rec)
|
||||
|
||||
def write(self, rec):
|
||||
"""追加一行到当天的 jsonl。失败返回空串(记录不能反过来拖停流程)。"""
|
||||
try:
|
||||
d = os.path.join(self.journal_dir, 'cycles')
|
||||
os.makedirs(d, exist_ok=True)
|
||||
path = os.path.join(d, time.strftime('%Y-%m-%d') + '.jsonl')
|
||||
out = {k: v for k, v in rec.items() if not k.startswith('_')}
|
||||
line = json.dumps(out, ensure_ascii=False, separators=(',', ':'))
|
||||
with open(path, 'a', encoding='utf-8') as f:
|
||||
f.write(line + '\n')
|
||||
return path
|
||||
except (OSError, TypeError, ValueError):
|
||||
return ''
|
||||
|
||||
def explain_once(self):
|
||||
"""第一单跑通后解释一次本地引擎状态(只解释一次,不刷屏)。"""
|
||||
if self._said or not self.enabled:
|
||||
return ''
|
||||
if self.local.available():
|
||||
self._said = ('建议模式:本地分类器可用(%d 类,%d px);'
|
||||
'低于 %.0f%% 才额外调云端,一律人工确认'
|
||||
% (len(self.local.names), self.local.imgsz,
|
||||
self.ask_cloud_below * 100))
|
||||
else:
|
||||
self._said = ('建议模式:本地分类器不可用(%s);'
|
||||
'仍按云端 + 人工确认走,记录照留'
|
||||
% self.local.reason())
|
||||
return self._said
|
||||
|
||||
|
||||
def iter_journal(journal_dir='data/assist'):
|
||||
"""按天读回记录(标定 98% 的脚本、复盘用)。坏行跳过,不抛。"""
|
||||
d = os.path.join(journal_dir, 'cycles')
|
||||
if not os.path.isdir(d):
|
||||
return
|
||||
for fn in sorted(os.listdir(d)):
|
||||
if not fn.endswith('.jsonl'):
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(d, fn), 'r', encoding='utf-8') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
yield json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
@@ -90,6 +90,14 @@ class CloudRecognizer:
|
||||
self.cfg['vision_model'] = p['vision_model']
|
||||
self.cfg['text_model'] = p['text_model']
|
||||
self._session = requests.Session()
|
||||
# 与 ApiClient 一致:不继承系统代理。
|
||||
# 现场机器上常驻「上网加速/代理」类软件,会设 Windows 系统代理,其中
|
||||
# 不少只支持 HTTP、不处理 HTTPS CONNECT —— 识别请求会直接 ProxyError
|
||||
# (11-10 现场:ark.cn-beijing.volces.com 全部失败,报
|
||||
# ProxyError / SSL WRONG_VERSION_NUMBER,而同一个进程的接口调用正常,
|
||||
# 就是因为那边早就设了 trust_env=False)。
|
||||
# 确实需要走代理的环境,把 config.json 的 vision.trust_env 设成 true。
|
||||
self._session.trust_env = bool(self.cfg.get('trust_env', False))
|
||||
self._last_fail_at = 0.0
|
||||
# 提示词仓库:与手写板、主流程共用同一个单例(同一份磁盘缓存)
|
||||
self.prompts = get_store(cfg)
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# -*- 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 hashlib
|
||||
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
|
||||
self.loaded_version = None
|
||||
|
||||
# ------------------------------------------------------------ 加载
|
||||
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, 'rb') as f:
|
||||
classes_bytes = f.read()
|
||||
meta = json.loads(classes_bytes)
|
||||
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 路径能读、中文路径报错、字节缓冲两边都能读。
|
||||
buf = np.fromfile(self.model_path, dtype=np.uint8)
|
||||
try:
|
||||
net = cv2.dnn.readNetFromONNX(buf)
|
||||
except Exception: # noqa: BLE001 老版本没有这个重载
|
||||
net = cv2.dnn.readNetFromONNX(self.model_path)
|
||||
buf = None # 此路径没有拿到实际加载的字节
|
||||
try:
|
||||
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
|
||||
except Exception: # noqa: BLE001 老版本没这项
|
||||
pass
|
||||
try:
|
||||
manifest_path = os.path.join(os.path.dirname(self.model_path), 'model.json')
|
||||
with open(manifest_path, encoding='utf-8') as f:
|
||||
manifest = json.load(f)
|
||||
files = manifest['files']
|
||||
if (buf is not None
|
||||
and hashlib.sha256(buf).hexdigest() == files['product_cls.onnx']['sha256']
|
||||
and hashlib.sha256(classes_bytes).hexdigest() == files['classes.json']['sha256']):
|
||||
self.loaded_version = manifest.get('version')
|
||||
except (OSError, ValueError, AttributeError, KeyError, TypeError):
|
||||
pass
|
||||
self._net = net
|
||||
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)
|
||||
|
||||
+28
-4
@@ -24,6 +24,29 @@ except ImportError:
|
||||
serial = None
|
||||
|
||||
|
||||
def sim_kg_of(kg_cfg, cyc):
|
||||
"""模拟称每轮要放的重量:数字,或列表(按轮次循环)
|
||||
|
||||
列表是为了「一屏演示多种商品」:sim_loop_kg=[15, 6, 3] 就每轮换一个
|
||||
重量,正好对上待办里几条不同应量的行(没相机时靠这个把流程跑下来)。
|
||||
填 0 / 非法值 = 不放货(保持原行为)。
|
||||
"""
|
||||
if isinstance(kg_cfg, (list, tuple)):
|
||||
vals = []
|
||||
for v in kg_cfg:
|
||||
try:
|
||||
f = float(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if f > 0:
|
||||
vals.append(f)
|
||||
return vals[cyc % len(vals)] if vals else 0.0
|
||||
try:
|
||||
return max(0.0, float(kg_cfg or 0))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def list_serial_ports():
|
||||
"""枚举本机串口(设置页“扫描串口”用)"""
|
||||
try:
|
||||
@@ -418,19 +441,20 @@ class ScaleReader:
|
||||
重量是平滑逼近的(每 0.2s 走 80%),2 秒左右才稳;识别是在稳住
|
||||
之后才起流程,所以 hold 给到 2.5s 足够。
|
||||
"""
|
||||
kg = float(self.cfg.get('sim_loop_kg') or 0)
|
||||
if kg <= 0:
|
||||
return
|
||||
hold = max(0.0, float(self.cfg.get('sim_loop_hold_s', 2.5) or 0))
|
||||
keep = max(1.0, float(self.cfg.get('sim_loop_keep_s', 6.0) or 6.0))
|
||||
idle = max(0.5, float(self.cfg.get('sim_loop_idle_s', 3.0) or 3.0))
|
||||
total = hold + keep + idle
|
||||
cyc = int((time.monotonic() - t0) // total)
|
||||
# sim_loop_kg 可以是数字,也可以是列表(每轮换一个重量,见 sim_kg_of)
|
||||
kg = sim_kg_of(self.cfg.get('sim_loop_kg'), cyc)
|
||||
if kg <= 0:
|
||||
return
|
||||
phase = (time.monotonic() - t0) % total
|
||||
# 每轮重量抖一点(sim_loop_jitter_kg,同一轮里恒定):
|
||||
# 演示时每轮都是 3.000 kg,会被「疑似重复收货」当成同一件货拦下。
|
||||
jit = max(0.0, float(self.cfg.get('sim_loop_jitter_kg') or 0))
|
||||
if jit > 0:
|
||||
cyc = int((time.monotonic() - t0) // total)
|
||||
kg = max(0.2, kg + random.Random(cyc * 7919).uniform(-jit, jit))
|
||||
self._sim_target = kg if hold <= phase < hold + keep else None
|
||||
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
# -*- 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 json
|
||||
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, station="inspection"):
|
||||
"""把一条入库行翻成 /mobile/recognition/samples 的字段(全部字符串)。
|
||||
|
||||
这里只描述事实:货单名原样送(「外地芹菜」就是「外地芹菜」),
|
||||
训练用名的翻译在后台审核页做,不动订单、SKU、台账。
|
||||
"""
|
||||
row = row or {}
|
||||
item = str(row.get('item_name') or '').strip()
|
||||
fields = {
|
||||
'sample_id': op,
|
||||
'event_id': op,
|
||||
'scene': 'picking' if station == 'picking' else '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 station != "picking" and 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, station="inspection", audit=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, station, audit)
|
||||
try:
|
||||
os.rename(work, d)
|
||||
except OSError:
|
||||
existing = atomic.read_json(self._meta(op))
|
||||
if not existing:
|
||||
raise
|
||||
return existing.get('error') or ''
|
||||
if audit:
|
||||
audit['local'].add_done_callback(
|
||||
lambda future: self._save_local_audit(d, future))
|
||||
return error
|
||||
|
||||
@staticmethod
|
||||
def _save_local_audit(directory, future):
|
||||
# 写结果落在现有队列目录中。若上传或作废已删除目录,不再创建。
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=directory, delete=False, mode='w',
|
||||
encoding='utf-8') as f:
|
||||
temp_path = f.name
|
||||
try:
|
||||
json.dump(future.result(), f, ensure_ascii=False, allow_nan=False)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
finally:
|
||||
f.close()
|
||||
os.replace(temp_path, os.path.join(directory, 'local_result.json'))
|
||||
except Exception:
|
||||
if 'temp_path' in locals():
|
||||
try:
|
||||
os.unlink(temp_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _write_stage(self, d, api, op, row, source, path, captured_at, station, audit):
|
||||
blob, error = b'', ''
|
||||
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, station),
|
||||
'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 audit:
|
||||
meta['audit'] = {'cloud': audit['cloud'], 'deadline': time.time() + 25}
|
||||
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 meta.get('branch') and meta['branch'] != getattr(api, 'review_branch', ''):
|
||||
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:
|
||||
fields = dict(meta.get('fields') or {})
|
||||
audit = meta.get('audit')
|
||||
if audit:
|
||||
local = atomic.read_json(os.path.join(self._dir(op), 'local_result.json'))
|
||||
if not local and now < float(audit['deadline']):
|
||||
continue
|
||||
fields['recognition_audit'] = json.dumps({
|
||||
'local': local or {'status': 'unfinished'},
|
||||
'cloud': audit.get('cloud') or {'status': 'unavailable'},
|
||||
}, ensure_ascii=False, allow_nan=False)
|
||||
ack = api.upload_review_sample(fields, photo)
|
||||
problem = self._ack_problem(meta, ack)
|
||||
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,44 @@
|
||||
# 独立入库同名多行分摊(v1.0.65)
|
||||
|
||||
日期:2026-11-09
|
||||
现场:BR002 土豆,两张加工单分别要 17 斤 / 38 斤,实际一次到货 55.74 斤。
|
||||
|
||||
## 问题
|
||||
|
||||
Windows 秤端把独立入库(无单自采)行固定当作“一次只能结一行”:
|
||||
|
||||
- 两张独立入库待验单:17、38
|
||||
- 操作员称 55.74 斤,已经超过单行 38 * 1.3
|
||||
- `_choose_same_name` 判定一单装不下,进入 `_split_plan`
|
||||
- `_split_plan` 只要有 `independent_inbound` 就返回 None,转人工
|
||||
- 操作员只能把 55.74 全录到 17 斤那张单,38 斤那张一直挂着
|
||||
|
||||
## 修改
|
||||
|
||||
`_split_plan` 现在区分两种情况:
|
||||
|
||||
1. **全部是独立入库行**:允许按剩余量分摊,最后一行接收尾量。
|
||||
- 17 + 38 两行,实收 55.74 → 计划 `17 / 38.74`
|
||||
- 多出的 0.74 斤归最后一张独立入库单,不留在现场
|
||||
2. **有单 + 无单混合**:仍返回 None,交人工点选,避免把订单货入成自采库存。
|
||||
|
||||
独立行分摊后仍逐行走 `POST /mobile/inspection/complete`(单行结案),不会调用
|
||||
`complete-merge-strict`;普通订单行仍走严格入库。
|
||||
|
||||
## 护栏
|
||||
|
||||
- 实收超过全部独立行应量合计 `auto_over_pct`(默认 30%)→ 不分摊,转人工
|
||||
- 同名行数超过 `merge_max_rows`(默认 8)→ 不分摊
|
||||
- 单位不一致、不可称重单位 → 不分摊
|
||||
- 独立行仍须有 SKU 编码
|
||||
|
||||
## 实测回归
|
||||
|
||||
`tools/_test_stockin_split.py` 第 4 节:
|
||||
|
||||
```text
|
||||
17 / 38 两行 + 55.74 斤
|
||||
→ plan = [(17, 17.0), (38, 38.74)]
|
||||
```
|
||||
|
||||
旧断言“独立入库不摊”已更新为“独立入库也摊,但有单/无单混排仍不摊”。
|
||||
@@ -0,0 +1,68 @@
|
||||
# Windows 入库:分组合并 + 批量 + 偏差(v1.0.66)
|
||||
|
||||
日期:2026-11-10
|
||||
范围:`windows-fenjian`(入库分拣工作站)
|
||||
|
||||
## 背景
|
||||
|
||||
安卓秤端已经走:
|
||||
|
||||
```text
|
||||
pending-grouped
|
||||
→ 同商品/来源/单位一组
|
||||
→ 一次称重
|
||||
→ complete-merge-group
|
||||
→ 服务端按组内待验量 FIFO 分摊
|
||||
```
|
||||
|
||||
Windows 之前是:
|
||||
|
||||
```text
|
||||
pending?mode=full
|
||||
→ 同名多行时客户端 _split_plan 拆单
|
||||
→ 逐行 complete-merge-strict / complete
|
||||
```
|
||||
|
||||
效果相似,但不是真正的分组批量提交;同名多行、多来源、批量/偏差场景容易与安卓不一致。
|
||||
|
||||
## 本次改动
|
||||
|
||||
1. `core/api/client.py`
|
||||
- `pending('inspection')` 先拉逐行待办作为元数据,再拉 `pending-grouped`,把组转换成终端行:
|
||||
- `id` = 首个待验 ID
|
||||
- `inspection_ids` = 整组 ID
|
||||
- `required_qty/prepare_qty` = 组内合计
|
||||
- `group_key/group_hash` 随行携带
|
||||
- 新增 `commit_inspection_group()`,对齐安卓
|
||||
`POST /mobile/inspection/complete-merge-group`:
|
||||
- `inspection_ids`、`group_key`、`group_hash`
|
||||
- `actual_qty`(一次称重总量)
|
||||
- `actual_weight`
|
||||
- `quality_rating`(中文)
|
||||
- `force_complete`(偏差入库/短收结案)
|
||||
- 分组接口失败/旧服务端 → 自动回退原逐行路径。
|
||||
2. `core/flow.py`
|
||||
- 分组行优先走整组提交;`force_complete` 继续由短收容差逻辑
|
||||
`_short_close_gap()` 计算,保留偏差入库。
|
||||
- 网络未连接重试也走整组接口。
|
||||
- 结果不明 `_recover_group()`:按待验列表核对整组 ID;
|
||||
整组消失=成功,整组仍在=未提交,部分消失=锁定人工,绝不换号重提。
|
||||
- 未分组行保持原来的严格入库/独立入库逐行路径。
|
||||
3. `ui/app.py` 版本 `1.0.66`。
|
||||
|
||||
## 批量与偏差
|
||||
|
||||
- 批量入库:服务端一次称重按整组 FIFO 分摊,客户端不再逐单 `_split_plan`。
|
||||
- 偏差入库:分组提交同样支持 `force_complete=true`;库存按实收写,
|
||||
差额由服务端短少结案,不会虚增库存。
|
||||
- 有单/无单分组由服务端按来源区分;跨来源不再由客户端拼单。
|
||||
|
||||
## 回退
|
||||
|
||||
配置:
|
||||
|
||||
```json
|
||||
"flow": { "group_inbound": false }
|
||||
```
|
||||
|
||||
关闭后恢复 Windows 原有逐行 `_split_plan`/严格提交路径。
|
||||
@@ -0,0 +1,70 @@
|
||||
# Windows 偏差入库强制结束加工原料采购批次(v1.0.67)
|
||||
|
||||
## 背景
|
||||
|
||||
2026-11-12 自贡 BR002 现场:加工原料采购单 `RAW1794471013693YTMD4K`
|
||||
(尖白菜计划 17 斤)在 Windows 入库秤做「偏差入库」,实收 15.94 斤、
|
||||
差 1.06 斤(6.2%,在短收容差内)。
|
||||
|
||||
Windows 只提交了 `force_complete=true`,没有提交服务端 2026-11-10 新增的
|
||||
`force_close_raw_batch=true`。服务端因此只结束了验收单,没有结束加工原料采购批次,
|
||||
仍派生 1.06 斤续验单;第二次称 18.22 斤落到续验单后,采购累计变成 34.16 斤,
|
||||
库存与采购管理金额/数量出现分歧。
|
||||
|
||||
## 改动
|
||||
|
||||
### `core/api/client.py`
|
||||
|
||||
- `commit_inspection_group(..., force_close_raw_batch=False)`:偏差结案时请求体写
|
||||
`force_close_raw_batch: true`。
|
||||
- `commit_inspection(..., force_close_raw_batch=False)`:严格单行提交同样透传。
|
||||
- `commit_inspection_single(..., force_complete=False, force_close_raw_batch=False)`:
|
||||
独立原料/无单自采单行结案同样可透传两个字段。
|
||||
|
||||
### `core/flow.py`
|
||||
|
||||
- 分组入库、独立原料两条**会写加工原料采购批次**的主提交路径:
|
||||
`force_close_raw_batch=force`。
|
||||
- `_handle_send_error` 的网络重试路径同样根据 `_short_close_gap` 重算并传
|
||||
`force_close_raw_batch=force_retry`,重试不丢字段。
|
||||
- 严格单行路径(`complete-merge-strict`)**不携带** `force_close_raw_batch`:
|
||||
该端点只解析 `force_complete`,且该路径只用于普通供应商订单,不是独立原料;
|
||||
避免发送无效字段。
|
||||
- 不改变 `_short_close_gap` 的阈值逻辑(默认 20% / 3 斤),不改分拣计算和界面。
|
||||
|
||||
### 边界
|
||||
|
||||
- 只在入库站、本次实际触发短收结案(`force=True`)时置 true;
|
||||
- 普通入库/正常整组入库不携带该字段,行为与 v1.0.66 一致;
|
||||
- 分拣站、退回/退供路径不变。
|
||||
|
||||
## 后端配套(已完成)
|
||||
|
||||
Windows 端把 `force_close_raw_batch` 透传到
|
||||
`/mobile/inspection/complete-merge-group` / `/inspection/complete`。
|
||||
|
||||
后端已在 `server/src/services/weighStationService.ts` 的 `single()` 单行分支
|
||||
补上 `force_close_raw_batch: input.force_close_raw_batch === true`(提交
|
||||
`7e73d76b`),单行加工原料批次也会强制结案。
|
||||
|
||||
> 已核对:`complete-merge-strict` 端点(普通供应商订单严格入库)不支持
|
||||
> `force_close_raw_batch`,因此 Windows 严格单行路径不再传该字段。
|
||||
|
||||
## 版本与验证
|
||||
|
||||
- `ui/app.py` / `build_exe.py`:`1.0.66` → `1.0.67`
|
||||
- `installer.iss` / `assets/version_info.txt` 同步版本
|
||||
- 新增 `tools/_test_v1067.py`,覆盖:
|
||||
- 分组偏差结案请求体同时含两个 force 字段;
|
||||
- 普通整组不带 `force_close_raw_batch`;
|
||||
- 独立单行透传;严格单行不携带该无效字段;
|
||||
- 源码主路径与网络重试路径均传字段。
|
||||
|
||||
## 回滚
|
||||
|
||||
1. 回退代码提交;
|
||||
2. `ui/app.py`、`build_exe.py` 版本改回 `1.0.66`,同步 `installer.iss` 与
|
||||
`assets/version_info.txt`;
|
||||
3. 用 v1.0.66 的 exe/installer 覆盖现场程序。
|
||||
|
||||
回滚只影响 Windows 终端请求体,不涉及服务端数据/表结构。
|
||||
@@ -0,0 +1,23 @@
|
||||
# Windows 分拣工作台:待拣商品按商品名相邻(v1.0.70)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 日期 | 2026-11-24 |
|
||||
| 反馈 | 「相同的商品名,分拣时在待拣商品展示应该挨到一起」 |
|
||||
| 范围 | `windows-fenjian/ui/app.py` 的待办卡片排序;不改服务端数据/提交顺序 |
|
||||
|
||||
## 修法
|
||||
|
||||
`_fill_todo()` 在搜索/客户/分类筛选之后,对展示行按**界面标准商品名**排序:
|
||||
|
||||
- `_std_name(row)` 优先(`standard_name` → `item_name`),与卡片显示一致;
|
||||
- 同名时保留服务端原始顺序(`sorted` 稳定排序),不改变提交/记账顺序;
|
||||
- 无分组模式:全局排序;客户/分类分组模式:只在组内排序,不跨组打散。
|
||||
|
||||
同时排序 `_shown_ids`,增量更新路径在顺序变化时会自动重建,不会出现「数据已排序但卡片没动」。
|
||||
|
||||
## 回归
|
||||
|
||||
- `python3 -m py_compile ui/app.py` 通过;
|
||||
- Windows 端依赖(numpy/pywin32/pygrabber)本机不可用,需在 Windows 打包环境用真实待办名单目视复验:
|
||||
同名商品应连续出现,提交顺序/客户分组不受影响。
|
||||
@@ -0,0 +1,59 @@
|
||||
# Windows 称重台:未识别却显示上一件「已识别」修复(v1.0.70)
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 日期 | 2026-11-24 |
|
||||
| 反馈 | 「检查 windows 上面的称:明明没有识别到,为什么显示已识别到,并且叫我在确认一眼」 |
|
||||
| 范围 | Windows 分拣/称重端源码(`windows-fenjian/core/flow.py`);不改服务端接口 |
|
||||
|
||||
## 根因
|
||||
|
||||
`FlowEngine._cycle_detected` 只在引擎启动时初始化,**新一轮识别开始时没有清空**。
|
||||
|
||||
失败路径:
|
||||
|
||||
1. 上一轮识别到「香菇」⇒ `_cycle_detected = '香菇'`。
|
||||
2. 本轮模型返回空(名单里没有/画面不清晰)⇒ `_run_recognition()` 走 `_to_manual(None, [])`。
|
||||
3. `_to_manual()` 在 `confirm_before_submit` 打开时调用 `_to_focus(row=None, detected=None, ...)`。
|
||||
4. `_to_focus()` 的兜底是 `detected if detected is not None else self._cycle_detected`
|
||||
⇒ 把上一轮的「香菇」写进本轮待确认 payload。
|
||||
5. 界面据此显示「AI 识别:香菇 / 已识别」并让操作员确认,实际本轮什么都没认出来。
|
||||
|
||||
## 修法
|
||||
|
||||
1. **新一轮开始时清空**:`_begin_cycle()` 里与 `_cycle_conf = None` 一起把
|
||||
`_cycle_detected` / `_cycle_alt` 置空。
|
||||
2. **识别失败时再清一次**:`_run_recognition()` 的 `if not detected` 分支清空
|
||||
`_cycle_detected` / `_cycle_alt`,防其它路径复用。
|
||||
3. **没有命中行时禁止回退旧值**:`_to_focus()` 在 `row is None` 时,`detected`
|
||||
不再回退 `_cycle_detected`,直接写 `''`;有命中行时仍保留本轮/上一轮回退语义。
|
||||
4. 版本号 `1.0.69`(`build_exe.py`)。
|
||||
|
||||
## 回归
|
||||
|
||||
新增 `tools/_test_v1070_stale_recog.py`:
|
||||
|
||||
- A:`_cycle_detected='香菇'` + `_to_focus(None, detected=None)` ⇒ `detected` 必须为空;
|
||||
- B:有命中行且传入 `detected='青笋'` ⇒ 保留「青笋」,不误伤正常路径。
|
||||
|
||||
本机 Linux 缺少 Windows 依赖(`numpy` / `pywin32` / `pygrabber` 等),只能做
|
||||
`python3 -m py_compile` 语法校验;真实 Windows 端需重新打包后再由现场复验。
|
||||
|
||||
## 2026-11-25 追加:状态卡标题也要按「有没有命中行」判断
|
||||
|
||||
上一次只修了 payload 里的品名,**状态卡标题**仍写死「认出来了:请看一眼再确认」;
|
||||
而「AI 没认出、等人手动点选」走的也是同一个 `CONFIRM` 状态,于是现场看到
|
||||
标题说认出来了、下面一行却说「没认出是哪一件」,操作员以为是已识别。
|
||||
|
||||
修法(`ui/app.py`,纯展示层,不动引擎与接口):
|
||||
|
||||
1. `_on_state('CONFIRM')`:按引擎当前 `_focus` 是否命中待办行决定标题 ——
|
||||
命中 → 「认出来了:请看一眼再确认」(品牌蓝);未命中 →
|
||||
「未识别出来:请点右边那一行」(琥珀色)。
|
||||
2. `_on_focus(payload)`:按 payload 解析出的 `row` 再写一次标题,覆盖
|
||||
`focus_clear` 后状态重算、以及人工改判(选中某一行后标题立刻回到「认出来了」)。
|
||||
3. 提示行文案不变(原本就会写「没认出是哪一件,点右边那一行」)。
|
||||
|
||||
验证:`python3 -m py_compile ui/app.py` 通过;现场需在 Windows 上重新打包后
|
||||
用「放一件不在待办名单里的货」复验:标题应为「未识别出来」,点中某行后变为
|
||||
「认出来了」。
|
||||
@@ -0,0 +1,61 @@
|
||||
# 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` 的原因 |
|
||||
|
||||
## 分拣照片
|
||||
|
||||
分拣成功后,合格原图同时用于业务归档和识别样本审核。服务端审核通过后才能导出训练。模拟相机和回放不登记训练照片。结果未核实的提交保留队列,等待确认成功或作废。
|
||||
@@ -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/单测)。
|
||||
@@ -0,0 +1,91 @@
|
||||
# 点商品名「界面抖一下」定位与修复(v1.0.75)
|
||||
|
||||
日期:2026-12-03
|
||||
现象:秤端点一下商品名(大葱 / 小葱),整块待办列表明显抖一下,像被刷新了一遍。
|
||||
|
||||
## 一、先排掉「翻页 / 重排」
|
||||
|
||||
实测点击前后每张卡的 `x/y/宽/高` 与页码都不变,卡片没有被重建、没有翻页,
|
||||
肉眼看到的不是布局跳动,而是「整屏闪一下」。
|
||||
|
||||
## 二、量化:到底闪在哪
|
||||
|
||||
给所有卡及其子控件挂 `<Configure>`(几何一变就来一发),点一次卡:
|
||||
|
||||
| 指标 | 修复前 |
|
||||
|---|---|
|
||||
| `<Configure>` 事件 | 64 个 / 次点击 |
|
||||
| 其中真的几何变化 | 64 个(不是噪声,全是真的) |
|
||||
| 变化形态 | 8 张卡全部 190×121 → 198/182×121,x 跟着挪 ±8 |
|
||||
| 卡内 label | 162 → 154 → 170 → 154 → 170 … 来回 |
|
||||
| 持续时间 | 15ms 内跳完,**首尾完全一样** |
|
||||
|
||||
首尾一样这件事很关键:只对比「点前截图 / 点后截图」看不出问题(差异为 0),
|
||||
必须抓中间帧才能看见 190↔198 的来回。
|
||||
|
||||
## 三、拆因子:谁把 grid 逼着重算
|
||||
|
||||
把 `_repaint_cards` 换成各种「假版本」再点同一张卡(`_merge_audit/probe_flip.py`):
|
||||
|
||||
| 版本 | 只做什么 | 几何跳变 |
|
||||
|---|---|---|
|
||||
| `nopaint` | 什么都不改 | **0** |
|
||||
| `fg` | 只改数量数字的 `fg` | **0** |
|
||||
| `hl` | 只改 Frame 的 `highlightbackground/color` | 64 |
|
||||
| `bg` | 改边框色 + 卡片底色(旧观感) | 64 |
|
||||
|
||||
结论:**改 Frame 的 `highlightbackground`(纯颜色!)就会让 Tk 重算这张卡的
|
||||
请求宽度**(算成 198)。grid 的总宽本来刚好放满,一列要 198 就只有把别的列
|
||||
从 190 压到 182;下一次 idle 又排回 190 —— 于是整屏来回两趟,就是那一下「抖」。
|
||||
|
||||
## 四、修法
|
||||
|
||||
`ui/app.py` 的 `_layout_cards()`:
|
||||
|
||||
```python
|
||||
for c in range(ncols):
|
||||
self.todo_grid.columnconfigure(c, weight=1, minsize=card_w, uniform='cf')
|
||||
# 复位旧列时同样清掉 uniform
|
||||
for col in range(12):
|
||||
self.todo_grid.columnconfigure(col, weight=0, minsize=0, uniform='')
|
||||
```
|
||||
|
||||
`uniform` 让所有列的宽度必须一致:个别卡的请求宽度临时变大也拉不动别的列,
|
||||
Tk 只能整排一起微调或都不动,190↔198 那种「互相挤」不复存在。
|
||||
|
||||
同批(v1.0.75)另外三处减少重绘面积的改动:
|
||||
1. `_repaint_cards`:只改颜色不改 `highlightthickness`;颜色没变不发 configure;
|
||||
默认不再铺整卡粉底(`ui.focus_fill=true` 才恢复);
|
||||
2. `_paint_focus`:撤旧框与画新框合成一次重绘;
|
||||
3. `_on_focus`:不再单独触发重绘,只记 `_hl_pending`。
|
||||
|
||||
## 五、验证
|
||||
|
||||
| 项目 | 结果 |
|
||||
|---|---|
|
||||
| `python tools/_ui_jitter_check.py` | `<Configure>` 0 个、几何跳变 0 次、列宽约束不变、每次点击重画 ≤2 张、不翻页 → 退出码 0 |
|
||||
| `_merge_audit/probe_cols.py` | 列数 自动/4/5/6 下卡右边缘 816 ≤ canvas 824,无溢出;卡宽只差 1px(整除舍入) |
|
||||
| `_merge_audit/probe_frames.py` | 待办区变化 **5617 px(1.1%)**;旧观感 `FOCUS_FILL=1` 为 **45137 px(9.0%)** → 约 1/8 |
|
||||
| `python tools/_ui_offline_check.py` | 登录→识别→确认→DONE→第二轮→拿走自动提交→按客户筛选,全流程通过,台账 26 行 |
|
||||
|
||||
中间帧也不再变:`+50ms / +120ms / +250ms / +500ms / +900ms` 的待办区差异
|
||||
全部是同一个 5617,说明点完立刻稳定,没有来回排。
|
||||
|
||||
## 六、现场怎么确认
|
||||
|
||||
1. 关掉正在跑的秤端进程(旧代码还在内存里),重新启动,标题栏应显示 `v1.0.75`;
|
||||
2. 点大葱 / 小葱来回切:只有被点的那两张卡的 4px 边框色和数量数字变色,
|
||||
整块列表不再整体动;
|
||||
3. 若仍抖:看日志有没有 `[dev] UI 慢帧:…`,并抓 `ev:focus` 耗时,
|
||||
确认是否发生了跨页 `_reveal_row`(跨页才会真的重排)。
|
||||
|
||||
## 附:可复用的探针
|
||||
|
||||
- `tools/_ui_jitter_check.py`:回归自检(挂 `<Configure>` + 数 `_repaint_cards`);
|
||||
- `_merge_audit/probe_flip.py`:把 `_repaint_cards` 换成假版本,拆出「是哪个属性
|
||||
触发重排」,再点一次卡数几何跳变(`base/nopaint/fg/hl/bg/prop/uniform`);
|
||||
- `_merge_audit/probe_relayout.py`:钉住 `_layout_cards`、`columnconfigure`、
|
||||
`card.grid/grid_forget/configure`,看是谁在动几何;
|
||||
- `_merge_audit/probe_cols.py`:列数 自动/4/5/6 下卡片是否被裁;
|
||||
- `_merge_audit/probe_frames.py`:逐帧截屏 + 分区像素差(要先 `root.lift()`,
|
||||
否则抓到的是别的窗口,前后帧永远「没变」)。
|
||||
+209
-207
@@ -1,207 +1,209 @@
|
||||
; ============================================================
|
||||
; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.63.exe
|
||||
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
|
||||
; ============================================================
|
||||
|
||||
#define AppName "入库分拣工作站"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "1.0.64"
|
||||
#endif
|
||||
#define AppExe "入库分拣工作站.exe"
|
||||
#define SrcDir "dist\入库分拣工作站"
|
||||
|
||||
[Setup]
|
||||
AppId={{9C4F1E23-7B2A-4D8E-9A51-3F6C2B8D0E14}
|
||||
AppName={#AppName}
|
||||
; 程序启动时创建的同名互斥量:安装/卸载能识别「程序正在运行」并提示关闭,
|
||||
; 也避免现场开两个窗口抢同一个摄像头
|
||||
AppMutex=InboundSortingStation
|
||||
AppVersion={#AppVersion}
|
||||
AppVerName={#AppName} {#AppVersion}
|
||||
AppPublisher=配送中心
|
||||
AppPublisherURL=
|
||||
AppSupportURL=
|
||||
DefaultDirName={sd}\{#AppName}
|
||||
DefaultGroupName={#AppName}
|
||||
DisableProgramGroupPage=yes
|
||||
OutputDir=dist
|
||||
OutputBaseFilename={#AppName}_安装程序_v{#AppVersion}
|
||||
SetupIconFile=assets\app.ico
|
||||
UninstallDisplayIcon={app}\{#AppExe}
|
||||
UninstallDisplayName={#AppName}
|
||||
Compression=lzma2/max
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
PrivilegesRequired=lowest
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
ArchitecturesAllowed=x64compatible
|
||||
MinVersion=10.0
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
AllowNoIcons=yes
|
||||
ShowLanguageDialog=no
|
||||
VersionInfoVersion=1.0.64.0
|
||||
VersionInfoDescription={#AppName} 安装程序
|
||||
VersionInfoProductName={#AppName}
|
||||
|
||||
[Languages]
|
||||
Name: "en"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
[Messages]
|
||||
; —— 界面全部汉化(用覆盖消息的方式,不依赖第三方语言包)——
|
||||
SetupAppTitle=安装程序
|
||||
SetupWindowTitle=安装 - %1
|
||||
UninstallAppTitle=卸载
|
||||
UninstallAppFullTitle=卸载 %1
|
||||
WelcomeLabel1=欢迎安装 [name]
|
||||
WelcomeLabel2=安装程序将把 [name] 装到您的电脑上。%n%n本程序用于配送中心的入库验收与拣货称重打标,安装后无需另装 Python 等运行环境。%n%n继续前请关闭正在运行的旧版本。建议先关闭其它程序。
|
||||
WizardSelectDir=选择安装位置
|
||||
SelectDirDesc=将 [name] 安装到哪里?
|
||||
SelectDirLabel3=安装程序会把 [name] 装到下面的文件夹。
|
||||
SelectDirBrowseLabel=如果要装到别的文件夹,点“浏览”。直接点“下一步”就装在默认位置。
|
||||
DiskSpaceMBLabel=至少需要 [mb] MB 的磁盘空间。
|
||||
WizardSelectTasks=选择附加任务
|
||||
SelectTasksDesc=还要做哪些事?
|
||||
SelectTasksLabel2=请选择安装 [name] 时要一并完成的附加任务,然后点“下一步”。
|
||||
WizardReady=准备安装
|
||||
ReadyLabel1=现在可以开始安装 [name] 了。
|
||||
ReadyLabel2a=点“安装”开始安装,想改设置就点“上一步”。
|
||||
ReadyLabel2b=点“安装”开始安装。
|
||||
PreparingDesc=安装程序正在准备安装 [name]。
|
||||
InstallingLabel=正在安装 [name],请稍候……
|
||||
WizardFinished=安装完成
|
||||
FinishedHeadingLabel=正在完成 [name] 安装
|
||||
FinishedLabelNoIcons=安装完成。点“完成”退出。
|
||||
FinishedLabel=[name] 已安装完成。%n%n桌面上有快捷方式,双击即可启动。
|
||||
ClickFinish=点“完成”退出安装程序。
|
||||
ButtonNext=下一步(&N) >
|
||||
ButtonBack=< 上一步(&B)
|
||||
ButtonInstall=安装(&I)
|
||||
ButtonFinish=完成(&F)
|
||||
ButtonCancel=取消
|
||||
ButtonBrowse=浏览(&R)...
|
||||
ButtonYes=是(&Y)
|
||||
ButtonNo=否(&N)
|
||||
ButtonOK=确定
|
||||
ButtonCancel2=取消
|
||||
ExitSetupTitle=退出安装
|
||||
ExitSetupMessage=安装还没完成,现在退出将不会安装 [name]。%n%n确定要退出吗?
|
||||
ConfirmUninstall=确定要卸载 %1 及其所有组件吗?
|
||||
UninstallAppRunningError=%1 正在运行,请先关闭它再卸载。
|
||||
StatusUninstalling=正在卸载 %1……
|
||||
CannotInstall=安装程序无法把文件写到“%1”,请换一个文件夹或换一个账户再试。
|
||||
CreateDirError=无法创建文件夹:%n%n%1
|
||||
ErrorChangingAttr=无法修改文件属性:%n%n%1
|
||||
ErrorCopying=复制文件失败:%n%n%1%n%n点“重试”再试一次,或点“忽略”跳过这个文件。
|
||||
ErrorCreatingDir=无法创建文件夹:%n%n%1
|
||||
UninstallNotFound=文件“%1”不存在,无法卸载。
|
||||
UninstallOpenError=无法打开文件“%1”,无法卸载。
|
||||
UninstalledAll=%1 卸载完成。%n%n现场台账(data 目录里的 records.csv、journal)和配置备份(data\config_卸载前备份.json)已经保留,确认不再需要时可以直接删除整个安装文件夹。
|
||||
UninstalledMost=%1 卸载完成,但有少量文件没能删除,可以手动删除安装文件夹。
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: checkedonce
|
||||
Name: "autostart"; Description: "开机自动启动(工位机推荐勾选)"; GroupDescription: "附加任务:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; 程序主体(_internal 是运行库,必须整份装)
|
||||
Source: "{#SrcDir}\_internal\*"; DestDir: "{app}\_internal"; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
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
|
||||
; 现场配置:已存在就不动(保住 COM 口、账号、打印机设置)
|
||||
Source: "{#SrcDir}\config.json"; DestDir: "{app}"; Flags: onlyifdoesntexist
|
||||
; VC++ 运行库兜底(仅当目标机缺失时才装)
|
||||
Source: "build_assets\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall skipifsourcedoesntexist
|
||||
|
||||
[Dirs]
|
||||
Name: "{app}"; Permissions: users-modify
|
||||
Name: "{app}\data"; Permissions: users-modify
|
||||
Name: "{app}\data\photos"; Permissions: users-modify
|
||||
|
||||
[Icons]
|
||||
Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"
|
||||
Name: "{group}\卸载 {#AppName}"; Filename: "{uninstallexe}"
|
||||
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
Name: "{userstartup}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: autostart
|
||||
|
||||
[Run]
|
||||
Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /quiet /norestart"; StatusMsg: "正在安装 VC++ 运行库(仅缺失时需要)……"; Flags: waituntilterminated; Check: ShouldInstallVCRedist
|
||||
Filename: "{app}\{#AppExe}"; Description: "立即启动 {#AppName}"; Flags: nowait postinstall skipifsilent
|
||||
|
||||
[UninstallDelete]
|
||||
; 清运行垃圾;台账(records.csv / journal)与配置备份保留,避免误删历史
|
||||
Type: files; Name: "{app}\data\*.log"
|
||||
Type: files; Name: "{app}\data\camera_auto.json"
|
||||
Type: files; Name: "{app}\data\last_label.prn"
|
||||
Type: files; Name: "{app}\data\selftest.txt"
|
||||
Type: files; Name: "{app}\config.json.bak"
|
||||
Type: filesandordirs; Name: "{app}\data\thumb_cache"
|
||||
Type: filesandordirs; Name: "{app}\data\snapshots"
|
||||
Type: dirifempty; Name: "{app}\data"
|
||||
Type: dirifempty; Name: "{app}"
|
||||
|
||||
[Code]
|
||||
function NeedVCRedist: Boolean;
|
||||
var
|
||||
Installed: Cardinal;
|
||||
begin
|
||||
Result := True;
|
||||
if RegQueryDWordValue(HKLM64,
|
||||
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
|
||||
'Installed', Installed) and (Installed = 1) then
|
||||
Result := False
|
||||
else if RegQueryDWordValue(HKLM32,
|
||||
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
|
||||
'Installed', Installed) and (Installed = 1) then
|
||||
Result := False;
|
||||
end;
|
||||
|
||||
function ShouldInstallVCRedist: Boolean;
|
||||
begin
|
||||
Result := NeedVCRedist and
|
||||
FileExists(ExpandConstant('{tmp}\vc_redist.x64.exe'));
|
||||
end;
|
||||
|
||||
// 更新场景:程序还在跑时先提示关闭(exe 和 _internal 被占用会装不进去)
|
||||
function InitializeSetup: Boolean;
|
||||
var
|
||||
R: Integer;
|
||||
Cmd: string;
|
||||
begin
|
||||
Result := True;
|
||||
Cmd := ExpandConstant('{cmd}');
|
||||
Exec(Cmd, '/C tasklist /FI "IMAGENAME eq 入库分拣工作站.exe" | find /I "入库分拣工作站" >nul',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, R);
|
||||
if R = 0 then
|
||||
begin
|
||||
if MsgBox('检测到 入库分拣工作站 正在运行。%n%n更新需要先关闭它(未提交的称重记录不会丢,未完成的一件请先处理完再更新)。%n%n现在关闭并继续安装吗?',
|
||||
mbConfirmation, MB_YESNO) = IDYES then
|
||||
begin
|
||||
Exec(Cmd, '/C taskkill /F /IM "入库分拣工作站.exe"',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, R);
|
||||
Sleep(800);
|
||||
end
|
||||
else
|
||||
Result := False; // 用户选“否”:中止安装,让人家先处理完手头的活
|
||||
end;
|
||||
end;
|
||||
|
||||
// 卸载前把现场配置备份到 data 里(COM 口、账号、打印机设置都是现场一条条试出来的)
|
||||
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||
var
|
||||
Src, Dst: String;
|
||||
begin
|
||||
if CurUninstallStep = usUninstall then
|
||||
begin
|
||||
Src := ExpandConstant('{app}\config.json');
|
||||
Dst := ExpandConstant('{app}\data\config_卸载前备份.json');
|
||||
if FileExists(Src) then
|
||||
begin
|
||||
ForceDirectories(ExpandConstant('{app}\data'));
|
||||
CopyFile(Src, Dst, False);
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
; ============================================================
|
||||
; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.76.exe
|
||||
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
|
||||
; ============================================================
|
||||
|
||||
#define AppName "入库分拣工作站"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "1.0.76"
|
||||
#endif
|
||||
#define AppExe "入库分拣工作站.exe"
|
||||
#define SrcDir "dist\入库分拣工作站"
|
||||
|
||||
[Setup]
|
||||
AppId={{9C4F1E23-7B2A-4D8E-9A51-3F6C2B8D0E14}
|
||||
AppName={#AppName}
|
||||
; 程序启动时创建的同名互斥量:安装/卸载能识别「程序正在运行」并提示关闭,
|
||||
; 也避免现场开两个窗口抢同一个摄像头
|
||||
AppMutex=InboundSortingStation
|
||||
AppVersion={#AppVersion}
|
||||
AppVerName={#AppName} {#AppVersion}
|
||||
AppPublisher=配送中心
|
||||
AppPublisherURL=
|
||||
AppSupportURL=
|
||||
DefaultDirName={sd}\{#AppName}
|
||||
DefaultGroupName={#AppName}
|
||||
DisableProgramGroupPage=yes
|
||||
OutputDir=dist
|
||||
OutputBaseFilename={#AppName}_安装程序_v{#AppVersion}
|
||||
SetupIconFile=assets\app.ico
|
||||
UninstallDisplayIcon={app}\{#AppExe}
|
||||
UninstallDisplayName={#AppName}
|
||||
Compression=lzma2/max
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
PrivilegesRequired=lowest
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
ArchitecturesAllowed=x64compatible
|
||||
MinVersion=10.0
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
AllowNoIcons=yes
|
||||
ShowLanguageDialog=no
|
||||
VersionInfoVersion=1.0.76.0
|
||||
VersionInfoDescription={#AppName} 安装程序
|
||||
VersionInfoProductName={#AppName}
|
||||
|
||||
[Languages]
|
||||
Name: "en"; MessagesFile: "compiler:Default.isl"
|
||||
|
||||
[Messages]
|
||||
; —— 界面全部汉化(用覆盖消息的方式,不依赖第三方语言包)——
|
||||
SetupAppTitle=安装程序
|
||||
SetupWindowTitle=安装 - %1
|
||||
UninstallAppTitle=卸载
|
||||
UninstallAppFullTitle=卸载 %1
|
||||
WelcomeLabel1=欢迎安装 [name]
|
||||
WelcomeLabel2=安装程序将把 [name] 装到您的电脑上。%n%n本程序用于配送中心的入库验收与拣货称重打标,安装后无需另装 Python 等运行环境。%n%n继续前请关闭正在运行的旧版本。建议先关闭其它程序。
|
||||
WizardSelectDir=选择安装位置
|
||||
SelectDirDesc=将 [name] 安装到哪里?
|
||||
SelectDirLabel3=安装程序会把 [name] 装到下面的文件夹。
|
||||
SelectDirBrowseLabel=如果要装到别的文件夹,点“浏览”。直接点“下一步”就装在默认位置。
|
||||
DiskSpaceMBLabel=至少需要 [mb] MB 的磁盘空间。
|
||||
WizardSelectTasks=选择附加任务
|
||||
SelectTasksDesc=还要做哪些事?
|
||||
SelectTasksLabel2=请选择安装 [name] 时要一并完成的附加任务,然后点“下一步”。
|
||||
WizardReady=准备安装
|
||||
ReadyLabel1=现在可以开始安装 [name] 了。
|
||||
ReadyLabel2a=点“安装”开始安装,想改设置就点“上一步”。
|
||||
ReadyLabel2b=点“安装”开始安装。
|
||||
PreparingDesc=安装程序正在准备安装 [name]。
|
||||
InstallingLabel=正在安装 [name],请稍候……
|
||||
WizardFinished=安装完成
|
||||
FinishedHeadingLabel=正在完成 [name] 安装
|
||||
FinishedLabelNoIcons=安装完成。点“完成”退出。
|
||||
FinishedLabel=[name] 已安装完成。%n%n桌面上有快捷方式,双击即可启动。
|
||||
ClickFinish=点“完成”退出安装程序。
|
||||
ButtonNext=下一步(&N) >
|
||||
ButtonBack=< 上一步(&B)
|
||||
ButtonInstall=安装(&I)
|
||||
ButtonFinish=完成(&F)
|
||||
ButtonCancel=取消
|
||||
ButtonBrowse=浏览(&R)...
|
||||
ButtonYes=是(&Y)
|
||||
ButtonNo=否(&N)
|
||||
ButtonOK=确定
|
||||
ButtonCancel2=取消
|
||||
ExitSetupTitle=退出安装
|
||||
ExitSetupMessage=安装还没完成,现在退出将不会安装 [name]。%n%n确定要退出吗?
|
||||
ConfirmUninstall=确定要卸载 %1 及其所有组件吗?
|
||||
UninstallAppRunningError=%1 正在运行,请先关闭它再卸载。
|
||||
StatusUninstalling=正在卸载 %1……
|
||||
CannotInstall=安装程序无法把文件写到“%1”,请换一个文件夹或换一个账户再试。
|
||||
CreateDirError=无法创建文件夹:%n%n%1
|
||||
ErrorChangingAttr=无法修改文件属性:%n%n%1
|
||||
ErrorCopying=复制文件失败:%n%n%1%n%n点“重试”再试一次,或点“忽略”跳过这个文件。
|
||||
ErrorCreatingDir=无法创建文件夹:%n%n%1
|
||||
UninstallNotFound=文件“%1”不存在,无法卸载。
|
||||
UninstallOpenError=无法打开文件“%1”,无法卸载。
|
||||
UninstalledAll=%1 卸载完成。%n%n现场台账(data 目录里的 records.csv、journal)和配置备份(data\config_卸载前备份.json)已经保留,确认不再需要时可以直接删除整个安装文件夹。
|
||||
UninstalledMost=%1 卸载完成,但有少量文件没能删除,可以手动删除安装文件夹。
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: checkedonce
|
||||
Name: "autostart"; Description: "开机自动启动(工位机推荐勾选)"; GroupDescription: "附加任务:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; 程序主体(_internal 是运行库,必须整份装)
|
||||
Source: "{#SrcDir}\_internal\*"; DestDir: "{app}\_internal"; Flags: ignoreversion recursesubdirs createallsubdirs
|
||||
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: "assets\config.default.json"; DestDir: "{app}"; DestName: "config.json"; Flags: onlyifdoesntexist
|
||||
; VC++ 运行库兜底(仅当目标机缺失时才装)
|
||||
Source: "build_assets\vc_redist.x64.exe"; DestDir: "{tmp}"; Flags: deleteafterinstall skipifsourcedoesntexist
|
||||
|
||||
[Dirs]
|
||||
Name: "{app}"; Permissions: users-modify
|
||||
Name: "{app}\data"; Permissions: users-modify
|
||||
Name: "{app}\data\photos"; Permissions: users-modify
|
||||
|
||||
[Icons]
|
||||
Name: "{group}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"
|
||||
Name: "{group}\卸载 {#AppName}"; Filename: "{uninstallexe}"
|
||||
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
Name: "{userstartup}\{#AppName}"; Filename: "{app}\{#AppExe}"; WorkingDir: "{app}"; Tasks: autostart
|
||||
|
||||
[Run]
|
||||
Filename: "{tmp}\vc_redist.x64.exe"; Parameters: "/install /quiet /norestart"; StatusMsg: "正在安装 VC++ 运行库(仅缺失时需要)……"; Flags: waituntilterminated; Check: ShouldInstallVCRedist
|
||||
Filename: "{app}\{#AppExe}"; Description: "立即启动 {#AppName}"; Flags: nowait postinstall skipifsilent
|
||||
|
||||
[UninstallDelete]
|
||||
; 清运行垃圾;台账(records.csv / journal)与配置备份保留,避免误删历史
|
||||
Type: files; Name: "{app}\data\*.log"
|
||||
Type: files; Name: "{app}\data\camera_auto.json"
|
||||
Type: files; Name: "{app}\data\last_label.prn"
|
||||
Type: files; Name: "{app}\data\selftest.txt"
|
||||
Type: files; Name: "{app}\config.json.bak"
|
||||
Type: filesandordirs; Name: "{app}\data\thumb_cache"
|
||||
Type: filesandordirs; Name: "{app}\data\snapshots"
|
||||
Type: dirifempty; Name: "{app}\data"
|
||||
Type: dirifempty; Name: "{app}"
|
||||
|
||||
[Code]
|
||||
function NeedVCRedist: Boolean;
|
||||
var
|
||||
Installed: Cardinal;
|
||||
begin
|
||||
Result := True;
|
||||
if RegQueryDWordValue(HKLM64,
|
||||
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
|
||||
'Installed', Installed) and (Installed = 1) then
|
||||
Result := False
|
||||
else if RegQueryDWordValue(HKLM32,
|
||||
'SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\x64',
|
||||
'Installed', Installed) and (Installed = 1) then
|
||||
Result := False;
|
||||
end;
|
||||
|
||||
function ShouldInstallVCRedist: Boolean;
|
||||
begin
|
||||
Result := NeedVCRedist and
|
||||
FileExists(ExpandConstant('{tmp}\vc_redist.x64.exe'));
|
||||
end;
|
||||
|
||||
// 更新场景:程序还在跑时先提示关闭(exe 和 _internal 被占用会装不进去)
|
||||
function InitializeSetup: Boolean;
|
||||
var
|
||||
R: Integer;
|
||||
Cmd: string;
|
||||
begin
|
||||
Result := True;
|
||||
Cmd := ExpandConstant('{cmd}');
|
||||
Exec(Cmd, '/C tasklist /FI "IMAGENAME eq 入库分拣工作站.exe" | find /I "入库分拣工作站" >nul',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, R);
|
||||
if R = 0 then
|
||||
begin
|
||||
if MsgBox('检测到 入库分拣工作站 正在运行。%n%n更新需要先关闭它(未提交的称重记录不会丢,未完成的一件请先处理完再更新)。%n%n现在关闭并继续安装吗?',
|
||||
mbConfirmation, MB_YESNO) = IDYES then
|
||||
begin
|
||||
Exec(Cmd, '/C taskkill /F /IM "入库分拣工作站.exe"',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, R);
|
||||
Sleep(800);
|
||||
end
|
||||
else
|
||||
Result := False; // 用户选“否”:中止安装,让人家先处理完手头的活
|
||||
end;
|
||||
end;
|
||||
|
||||
// 卸载前把现场配置备份到 data 里(COM 口、账号、打印机设置都是现场一条条试出来的)
|
||||
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||
var
|
||||
Src, Dst: String;
|
||||
begin
|
||||
if CurUninstallStep = usUninstall then
|
||||
begin
|
||||
Src := ExpandConstant('{app}\config.json');
|
||||
Dst := ExpandConstant('{app}\data\config_卸载前备份.json');
|
||||
if FileExists(Src) then
|
||||
begin
|
||||
ForceDirectories(ExpandConstant('{app}\data'));
|
||||
CopyFile(Src, Dst, False);
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
并在分发时补回 sys.stdout(无控制台模式下它是 None,管道通信会崩)。
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import sys
|
||||
|
||||
|
||||
@@ -29,6 +31,55 @@ if getattr(sys, 'frozen', False) and getattr(sys, '_MEIPASS', ''):
|
||||
sys.path.insert(0, sys._MEIPASS)
|
||||
|
||||
|
||||
def _ensure_config():
|
||||
"""首跑兜底:程序目录没有 config.json 就铺一份默认配置
|
||||
|
||||
现场最常见的用法是「拷一个 exe 就双击」,此时 APP_DIR 下空空如也,
|
||||
程序会以空配置起来(没服务器、没秤参数),看起来就是"打不开/用不了"。
|
||||
这里把包内 assets/config.default.json 复制到 exe 旁边:默认离线模拟
|
||||
(server.mock + 模拟秤 + 模拟摄像头),双击就能看到完整界面和演示数据;
|
||||
要连真服务器,改这一个文件即可(登录页「修改服务器地址」也写回它)。
|
||||
已经存在就一个字都不动,不会覆盖现场调好的参数。
|
||||
"""
|
||||
dst = os.path.join(APP_DIR, 'config.json')
|
||||
if os.path.exists(dst):
|
||||
return dst
|
||||
cands = [os.path.join(APP_DIR, 'config.default.json'),
|
||||
os.path.join(APP_DIR, 'assets', 'config.default.json')]
|
||||
meipass = getattr(sys, '_MEIPASS', '') or ''
|
||||
if meipass:
|
||||
cands.insert(0, os.path.join(meipass, 'config.default.json'))
|
||||
for src in cands:
|
||||
if os.path.isfile(src):
|
||||
try:
|
||||
shutil.copyfile(src, dst)
|
||||
return dst
|
||||
except Exception:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
def _seed_bundled_model():
|
||||
bundle = os.path.join(getattr(sys, '_MEIPASS', ''), 'bundled_cls')
|
||||
target = os.path.join(APP_DIR, 'models', 'cls')
|
||||
if not getattr(sys, 'frozen', False) or not os.path.isdir(bundle) or os.path.exists(target):
|
||||
return
|
||||
parent = os.path.dirname(target)
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=parent) as stage:
|
||||
ready = os.path.join(stage, 'cls')
|
||||
shutil.copytree(bundle, ready)
|
||||
try:
|
||||
os.rename(ready, target)
|
||||
except FileExistsError:
|
||||
pass
|
||||
|
||||
|
||||
_seed_bundled_model()
|
||||
|
||||
_ensure_config()
|
||||
|
||||
|
||||
def _restore_stdio():
|
||||
"""无控制台(windowed)模式下 sys.stdout 可能是 None,子进程写字给父进程会崩。
|
||||
|
||||
@@ -112,7 +163,10 @@ def _activate_existing():
|
||||
import ctypes
|
||||
u = ctypes.windll.user32
|
||||
h = (u.FindWindowW(None, '入库分拣工作站 - 登录')
|
||||
or u.FindWindowW(None, '入库分拣工作站'))
|
||||
or u.FindWindowW(None, '入库分拣工作站')
|
||||
# v1.0.68:作业界面按工位改名了
|
||||
or u.FindWindowW(None, '分拣工作站')
|
||||
or u.FindWindowW(None, '入库工作站'))
|
||||
if h:
|
||||
u.ShowWindow(h, 9) # SW_RESTORE:最小化状态也能拉回来
|
||||
u.BringWindowToTop(h)
|
||||
|
||||
@@ -39,7 +39,10 @@ a = Analysis(
|
||||
[os.path.join(ROOT, 'main.py')],
|
||||
pathex=[ROOT],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
datas=[
|
||||
# 首跑兜底用的默认配置(main.py 里 _ensure_config 复制到 exe 旁边)
|
||||
(os.path.join(ROOT, 'assets', 'config.default.json'), '.'),
|
||||
],
|
||||
hiddenimports=HIDDEN,
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""打包配置 · 单文件版(PyInstaller 6.x)
|
||||
|
||||
产物:dist_onefile/入库分拣工作站.exe —— 就一个文件,拷到能跑的 Windows 上双击即用。
|
||||
|
||||
和 main.spec(onedir 绿色版)的区别只有两处:
|
||||
* EXE 里带 binaries/datas(exclude_binaries=False),不再产出 COLLECT 目录;
|
||||
* 运行时要解压到 %TEMP%\\_MEIxxxx,冷启动比绿色版慢几秒。
|
||||
|
||||
摄像头取帧仍是 exe 自己分发(main.py 的 --wb-child),单文件版一样能跑,
|
||||
只是每个子进程会各自解压一次运行库——只影响启动,不影响识别。
|
||||
"""
|
||||
import os
|
||||
|
||||
ROOT = os.path.abspath(SPECPATH) # noqa: F821 (PyInstaller 注入)
|
||||
|
||||
HIDDEN = [
|
||||
'core.evidence._cam_child',
|
||||
'core.evidence._probe_child',
|
||||
'win32com', 'win32com.client', 'pythoncom', 'pywintypes',
|
||||
'win32print', 'win32api', 'win32con', 'win32job', 'win32event',
|
||||
'comtypes', 'comtypes.client', 'comtypes.stream',
|
||||
'pygrabber', 'pygrabber.dshow_graph',
|
||||
'serial.tools.list_ports', 'serial.tools.list_ports_windows',
|
||||
'core.devices',
|
||||
'core.handwrite',
|
||||
'PIL._tkinter_finder',
|
||||
]
|
||||
|
||||
EXCLUDES = [
|
||||
'matplotlib', 'scipy', 'pandas', 'PyQt5', 'PyQt6', 'PySide2', 'PySide6',
|
||||
'IPython', 'jupyter', 'notebook', 'nbconvert', 'pytest', 'sphinx',
|
||||
]
|
||||
|
||||
a = Analysis(
|
||||
[os.path.join(ROOT, 'main.py')],
|
||||
pathex=[ROOT],
|
||||
binaries=[],
|
||||
datas=[
|
||||
(os.path.join(ROOT, "models", "cls"), "bundled_cls"),
|
||||
(os.path.join(ROOT, 'assets', 'config.default.json'), '.'),
|
||||
],
|
||||
hiddenimports=HIDDEN,
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=EXCLUDES,
|
||||
noarchive=False,
|
||||
optimize=0,
|
||||
)
|
||||
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
[],
|
||||
name='入库分拣工作站',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=False,
|
||||
runtime_tmpdir=None,
|
||||
console=False,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
icon=os.path.join(ROOT, 'assets', 'app.ico'),
|
||||
version=os.path.join(ROOT, 'assets', 'version_info.txt'),
|
||||
)
|
||||
@@ -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,291 @@
|
||||
# -*- 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
|
||||
|
||||
REAL_ONNX = os.path.join(HERE, 'models', 'cls', 'product_cls.onnx')
|
||||
REAL_CLASSES = os.path.join(HERE, 'models', '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,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Windows 分组入库(v1.0.66):pending-grouped 行转换 + complete-merge-group 请求体。"""
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from core.api.client import ApiClient, ApiError
|
||||
|
||||
CFG = {'server': {'base_url': 'http://127.0.0.1:3001/api', 'mock': False},
|
||||
'account': {'username': 'demo', 'password': 'x', 'role': 'inspector'},
|
||||
'flow': {'group_inbound': True}}
|
||||
|
||||
def check(name, cond, detail=''):
|
||||
print(('PASS' if cond else 'FAIL'), name, detail)
|
||||
if not cond:
|
||||
sys.exit(1)
|
||||
|
||||
api = ApiClient(CFG)
|
||||
groups = [{
|
||||
'group_key': 'BR003|-|purchase|order|SKU1|斤',
|
||||
'group_hash': 'gh-1',
|
||||
'branch_code': 'BR003',
|
||||
'supplier_code': None,
|
||||
'source_type': 'purchase',
|
||||
'sku_code': 'SKU1',
|
||||
'item_name': '土豆',
|
||||
'unit': '斤',
|
||||
'total_prepare_qty': 55,
|
||||
'order_count': 2,
|
||||
'inspection_ids': ['ins-1', 'ins-2'],
|
||||
'requires_photo_inspection': False,
|
||||
'lines': [
|
||||
{'inspection_id': 'ins-1', 'order_code': 'O1', 'prepare_qty': 17},
|
||||
{'inspection_id': 'ins-2', 'order_code': 'O2', 'prepare_qty': 38},
|
||||
],
|
||||
}]
|
||||
flat = [{'id': 'ins-1', 'order_code': 'O1', 'customer_name': '客户A',
|
||||
'prepare_qty': 17, 'unit': '斤', 'requires_photo_inspection': False},
|
||||
{'id': 'ins-2', 'order_code': 'O2', 'customer_name': '客户B',
|
||||
'prepare_qty': 38, 'unit': '斤', 'requires_photo_inspection': False}]
|
||||
rows = api._preview_group_rows(groups, flat)
|
||||
check('一组转成一行', len(rows) == 1, str(rows))
|
||||
row = rows[0]
|
||||
check('保存整组ID', row.get('inspection_ids') == ['ins-1', 'ins-2'])
|
||||
check('组总量作为应量', row.get('required_qty') == 55 and row.get('prepare_qty') == 55)
|
||||
check('组键/哈希带到行', row.get('group_key') and row.get('group_hash') == 'gh-1')
|
||||
check('首行订单号/客户元数据保留', row.get('order_code') == 'O1' and row.get('customer_name') == '客户A')
|
||||
check('组行标记', row.get('grouped_inbound') is True)
|
||||
|
||||
# mock request capture
|
||||
calls = []
|
||||
def fake_request(method, path, body=None, **kw):
|
||||
calls.append((method, path, body))
|
||||
return {'success': True, 'data': {'merged': True, 'mergedCount': 2}}
|
||||
api._request = fake_request
|
||||
resp = api.commit_inspection_group(row, 55, 27.5, 'op-1', force_complete=True)
|
||||
check('走分组接口', calls and calls[0][1] == '/mobile/inspection/complete-merge-group', str(calls))
|
||||
body = calls[0][2]
|
||||
check('整组ID在请求体', body.get('inspection_ids') == ['ins-1', 'ins-2'])
|
||||
check('批量实收一次传', body.get('actual_qty') == 55)
|
||||
check('偏差入库 force_complete 透传', body.get('force_complete') is True)
|
||||
check('质量中文', body.get('quality_rating') == '合格')
|
||||
check('回包归一成功', resp.get('operation_status') == 'committed_by_this_operation')
|
||||
print('ALL GROUP INBOUND CHECKS PASSED')
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""整组入库·短收部分成功回归(2026-11-22 方案 A)
|
||||
|
||||
背景(BR002 生产事故):5 行组、实称 6.48 斤,服务端先入 2 行再 409 scope_incomplete,
|
||||
客户端把 409 当「未提交」,拿旧组重试又撞 scope_changed。
|
||||
|
||||
本机(Linux 构建机)没有 Windows 端运行依赖(numpy/pywin32/opencv…),所以本用例
|
||||
**不 import 整包**,而是从源码中抽取待测函数做真实行为测试 + 源码契约断言:
|
||||
|
||||
① 服务端 200 部分成功时,客户端带出 partial_group / merged_count / remaining_qty / 未入行;
|
||||
② 成功提示说清「已入 N 行、剩余 X 斤、下次再称,不要用旧组重试」;
|
||||
③ scope_incomplete / scope_changed 等业务拒绝翻成人话(刷新待验列表、不直接重试旧组)。
|
||||
|
||||
设计:docs/design/20261122-weigh-group-partial-inbound.md
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import textwrap
|
||||
import types
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
FLOW = os.path.join(ROOT, 'core', 'flow.py')
|
||||
CLIENT = os.path.join(ROOT, 'core', 'api', 'client.py')
|
||||
|
||||
checks = 0
|
||||
|
||||
|
||||
def ok(cond, msg):
|
||||
global checks
|
||||
checks += 1
|
||||
if not cond:
|
||||
raise AssertionError(msg)
|
||||
print(' ✓', msg)
|
||||
|
||||
|
||||
def read(p):
|
||||
with open(p, encoding='utf-8') as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def extract_def(src, header):
|
||||
"""按 4 空格缩进抽取一个 def 块(方法或顶层函数),返回去缩进源码。"""
|
||||
start = src.index(header)
|
||||
m = re.search(r'\n(?= def |\ndef |class )', src[start + len(header):])
|
||||
end = start + len(header) + (m.start() if m else len(src))
|
||||
return textwrap.dedent(src[start:end])
|
||||
|
||||
|
||||
flow_src = read(FLOW)
|
||||
client_src = read(CLIENT)
|
||||
|
||||
# ---- ① 客户端回包解析(抽取真实方法源码执行,不联网) ----
|
||||
print('① 客户端解析 200 短收部分成功回包')
|
||||
ns = {'__name__': 'client_probe'}
|
||||
|
||||
|
||||
class _ApiError(Exception):
|
||||
def __init__(self, code, message):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
ns['ApiError'] = _ApiError
|
||||
exec(extract_def(client_src, 'def commit_inspection_group('), ns)
|
||||
|
||||
|
||||
class _FakeApi:
|
||||
def __init__(self, payload):
|
||||
self.mock = False
|
||||
self.cfg = {}
|
||||
self._payload = payload
|
||||
|
||||
def _request(self, *args, **kwargs):
|
||||
return self._payload
|
||||
|
||||
|
||||
ns['_FakeApi'] = _FakeApi
|
||||
_FakeApi.commit_inspection_group = ns['commit_inspection_group']
|
||||
|
||||
partial = _FakeApi({
|
||||
'success': True,
|
||||
'data': {
|
||||
'merged': True, 'mergedCount': 2, 'partialGroup': True, 'remainingQty': 7.38,
|
||||
'unallocatedLines': [{'id': 'x', 'prepare_qty': 3}],
|
||||
},
|
||||
}).commit_inspection_group({'inspection_ids': ['a', 'b', 'c', 'd', 'e']}, 6.48, 3.24, 'op1')
|
||||
ok(partial.get('partial_group') is True, 'partial_group=True')
|
||||
ok(partial.get('merged_count') == 2, 'merged_count=2(已入 2 行)')
|
||||
ok(abs(float(partial.get('remaining_qty') or 0) - 7.38) < 1e-9, 'remaining_qty=7.38 斤')
|
||||
ok(len(partial.get('unallocated_lines') or []) == 1, 'unallocated_lines 带出未入行')
|
||||
ok(partial.get('data', {}).get('mergedCount') == 2, 'data 原样保留(供现有成功判定)')
|
||||
|
||||
full = _FakeApi({
|
||||
'success': True,
|
||||
'data': {'merged': True, 'mergedCount': 2, 'partialGroup': False, 'remainingQty': 0},
|
||||
}).commit_inspection_group({'inspection_ids': ['a', 'b']}, 13, 6.5, 'op2')
|
||||
ok(full.get('partial_group') is False, '整组入完时 partial_group=False')
|
||||
|
||||
# ---- ② 成功提示(抽取 _success_extra 方法执行) ----
|
||||
print('② 成功提示:说清已入行数/剩余量/不要旧组重试')
|
||||
ns2 = {'__name__': 'flow_probe'}
|
||||
exec(extract_def(flow_src, 'def _success_extra('), ns2)
|
||||
_Eng = type('_Eng', (), {'_success_extra': ns2['_success_extra'], '_strict_info': lambda self, r: {}})
|
||||
eng = _Eng()
|
||||
eng._frozen_row = {'unit': '斤'}
|
||||
note = eng._success_extra('ok', {'data': {'partialGroup': True, 'mergedCount': 2, 'remainingQty': 7.38}})
|
||||
ok('已入 2 行' in note, '提示包含「已入 2 行」')
|
||||
ok('7.38' in note, '提示包含剩余量 7.38')
|
||||
ok('不要用旧组重试' in note, '提示明确不要用旧组重试')
|
||||
ok(eng._success_extra('ok', {'data': {}}) == '', '普通成功不额外加话')
|
||||
|
||||
# ---- ③ 业务拒绝翻译(抽取 reject_hint 执行) ----
|
||||
print('③ 业务拒绝翻译(保底旧后端/范围变化)')
|
||||
ns3 = {'__name__': 'hint_probe', 'M': types.SimpleNamespace(required_qty_of=lambda row, mode=None: 0.0)}
|
||||
exec(extract_def(flow_src, 'def reject_hint('), ns3)
|
||||
reject_hint = ns3['reject_hint']
|
||||
|
||||
hint = reject_hint('业务拒绝 409: {"error":"scope_incomplete","error_description":"整组入库行数不一致"}', {'unit': '斤'})
|
||||
ok('刷新待验列表' in hint and '不要直接重试' in hint, 'scope_incomplete → 刷新后重称、不重试')
|
||||
hint2 = reject_hint('业务拒绝 409: {"error":"scope_changed"}', {'unit': '斤'})
|
||||
ok('刷新待验列表' in hint2, 'scope_changed → 刷新待验列表')
|
||||
hint3 = reject_hint('业务拒绝 409: {"error":"group_changed"}', {'unit': '斤'})
|
||||
ok('刷新待验列表' in hint3, 'group_changed → 刷新待验列表')
|
||||
ok(reject_hint('业务拒绝 400: {"error":"invalid_cost"}', {'unit': '斤'}) == '',
|
||||
'未登记错误保持原样(不硬造提示)')
|
||||
ok('weigh_tolerance' not in hint, '非容差类错误不误报重量对不上')
|
||||
|
||||
print('\n全部通过:%d 项' % checks)
|
||||
@@ -0,0 +1,91 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""两种工位都自动识别,必须人工确认。"""
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
|
||||
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.flow import FlowEngine
|
||||
|
||||
CFG = {
|
||||
'flow': {'min_scale_kg': 0.05, 'stable_ms': 400, 'stable_delta_kg': 0.03},
|
||||
'scale': {'simulate': True},
|
||||
'camera': {'simulate': True},
|
||||
'vision': {'min_confidence': 65},
|
||||
'server': {'mock': True},
|
||||
'account': {'role': 'inspection'},
|
||||
}
|
||||
|
||||
logs = []
|
||||
eng = FlowEngine(CFG, lambda ev, p=None: logs.append((ev, p)))
|
||||
eng.refresh_pending = lambda initial=False: None
|
||||
|
||||
fail = []
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
print(('PASS ' if cond else 'FAIL ') + name
|
||||
+ ('' if cond else ' %r' % (extra,)))
|
||||
if not cond:
|
||||
fail.append(name)
|
||||
|
||||
|
||||
# 旧配置要求自动提交,也必须等人点确认。
|
||||
eng.cfg['flow'].update(confirm_before_submit=False, submit_on_remove=True)
|
||||
for station in ('inspection', 'picking'):
|
||||
eng.station = station
|
||||
check(station + ':识别后进确认页', eng.confirm_before_submit() is True)
|
||||
check(station + ':拿走货不提交', eng.submit_on_remove() is False)
|
||||
check(station + ':免称重仍自动识别', eng.auto_noweigh_on() is True)
|
||||
check(station + ':拒绝自动确认入口', not eng.confirm_focus(auto_remove=True)[0])
|
||||
|
||||
# 2b) 免称重认出后必须进确认页(不是直接记账)
|
||||
seen = []
|
||||
eng._to_focus = lambda *a, **k: seen.append((a, k))
|
||||
eng._auto_round = True
|
||||
_one = {'id': 'x1', 'item_name': '土豆', 'unit': '袋',
|
||||
'required_qty': 3, 'remaining_qty': 3}
|
||||
eng._to_count_confirm('土豆', _one, [_one])
|
||||
check('免称重认出后进确认页(不直接提交)', len(seen) == 1, )
|
||||
|
||||
# 5) 登录按服务端下发值接线:api.login 写 False ⇒ 引擎变手动
|
||||
CFG_LOGIN = dict(CFG)
|
||||
CFG_LOGIN['account'] = {'role': 'inspection', 'username': 'u', 'password': 'p'}
|
||||
eng2 = FlowEngine(CFG_LOGIN, lambda ev, p=None: None)
|
||||
eng2.refresh_pending = lambda initial=False: None
|
||||
eng2._sync_prompts = lambda force=False: None
|
||||
|
||||
|
||||
def fake_login():
|
||||
eng2.api.inbound_auto_submit = True # 服务端 profile 下发:默认关
|
||||
return {}
|
||||
|
||||
|
||||
eng2.api.login = fake_login
|
||||
eng2.login('u', 'p', 'inspection')
|
||||
check('登录后按服务端开关生效:入库变手动确认', eng2.submit_on_remove() is False)
|
||||
|
||||
# 6) 登录返回的 profile 里没这个字段 ⇒ False(安全侧:手动)
|
||||
from core.api.client import ApiClient # noqa: E402
|
||||
|
||||
|
||||
def client_with(profile):
|
||||
c = ApiClient({'server': {'base_url': 'https://x/api', 'mock': False},
|
||||
'account': {'username': 'u', 'password': 'p'},
|
||||
'flow': {}})
|
||||
c._request = lambda *a, **k: {'access_token': 't', 'profile': profile}
|
||||
c.login()
|
||||
return c
|
||||
|
||||
|
||||
check('服务端未下发该字段 ⇒ 手动(False)',
|
||||
client_with({'id': 1}).inbound_auto_submit is False)
|
||||
check('服务端下发 true ⇒ 自动提交(True)',
|
||||
client_with({'id': 1, 'inbound_auto_submit': True})
|
||||
.inbound_auto_submit is True)
|
||||
|
||||
print('')
|
||||
print('FAILED: %d' % len(fail) if fail else 'ALL PASS')
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,278 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""标签版面不变量回归(v1.0.69)
|
||||
|
||||
背景:v1.0.68 起「有二维码时文字块贴顶」(左右布局)。改的只是起始 y,
|
||||
但必须证明:**任何纸型 / 任何字段长度下,文字都不会越出纸边、不会丢内容、
|
||||
不会压到二维码**——现场以前从没出现过「打一半」「少一行」。
|
||||
|
||||
检查项(对每组纸型 × 字段组合):
|
||||
① 每一行都在纸内:x≥左留白、x+w≤右边界
|
||||
② 有二维码时文字不压码(x+w ≤ 码左沿-4)
|
||||
③ 垂直不越界:首行 y≥上留白、末行 y+字号≤纸高-下留白
|
||||
④ 内容完整:所有行文字拼起来 == 原始输入(除非明确提示“已截断”)
|
||||
⑤ 二维码整块在纸内
|
||||
⑥ 贴顶规则:有码时首行 y==上留白;无码时垂直居中
|
||||
不需要打印机/网络。
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
|
||||
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.printing import label as L
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✘ %s %s' % (name, extra))
|
||||
|
||||
|
||||
SIZES = [(50, 50), (60, 40), (40, 60), (35, 25), (70, 50), (80, 30),
|
||||
(80, 60), (76, 60)]
|
||||
|
||||
FIELDS = {
|
||||
'分拣-短': ('分拣标签', ['客户: 王记饭店', '品名: 红富士苹果',
|
||||
'重量: 5.62 斤', '日期: 11-22 18:30']),
|
||||
'分拣-长': ('分拣标签', ['客户: 张三水果批发市场配送中心',
|
||||
'品名: 农夫山泉饮用天然水 550ml×24 整箱',
|
||||
'重量: 1234.56 斤', '日期: 2026-11-22 18:30']),
|
||||
'入库-6行': ('验收标签', ['订单: ORD_WEB_20261122_BR003_0017',
|
||||
'品名: 精瘦肉', '数量: 15.00 斤',
|
||||
'供应商: 演示供应商名称比较长', '时间: 2026-11-22 18:30']),
|
||||
'空值': ('分拣标签', ['客户: ', '品名: ', '重量: 0.00 斤', '日期: ']),
|
||||
}
|
||||
QRS = {'短码': 'CT2026112200001',
|
||||
'长码': 'CT-WEB-20261122-BR003-000123456789',
|
||||
'无码': ''}
|
||||
|
||||
|
||||
def fail_reasons(p, cfg, qr):
|
||||
g = p['geom']
|
||||
w, h, dpm = g['w'], g['h'], g['dots_per_mm']
|
||||
mx = max(int(round(2 * dpm)), 8)
|
||||
my = max(int(round(1.5 * dpm)),
|
||||
min(int(round(5 * dpm)), int(round(h * 0.10))))
|
||||
q = p['qr']
|
||||
out = []
|
||||
gap = int(round(2 * dpm)) if q else 0
|
||||
for ln in p['lines']:
|
||||
if ln['x'] < mx - 1:
|
||||
out.append('行越左边界 x=%d' % ln['x'])
|
||||
if ln['x'] + ln['w'] > w:
|
||||
out.append('行越右纸边 x+w=%d > %d' % (ln['x'] + ln['w'], w))
|
||||
if q and ln['x'] + ln['w'] > q['x'] - gap:
|
||||
out.append('行离码不足 %dmm x+w=%d, 码左沿=%d'
|
||||
% (gap // int(round(dpm)), ln['x'] + ln['w'], q['x']))
|
||||
if p['lines']:
|
||||
y0 = p['lines'][0]['y']
|
||||
yl = p['lines'][-1]['y'] + p['font']
|
||||
if y0 < my - 1:
|
||||
out.append('首行越上边界 y=%d' % y0)
|
||||
if yl > h - my + 2:
|
||||
out.append('末行越下边界 y+字=%d > %d' % (yl, h - my))
|
||||
if q and y0 != my:
|
||||
out.append('有码却未贴顶 y0=%d my=%d' % (y0, my))
|
||||
if q:
|
||||
if q['x'] + q['size'] > w - mx + 1:
|
||||
out.append('二维码越右边界')
|
||||
if q['y'] + q['size'] > h - my + 1:
|
||||
out.append('二维码越下边界')
|
||||
if q['y'] < my - 1:
|
||||
out.append('二维码越上边界')
|
||||
if q['size'] > int(round(w * 0.40)) + 2:
|
||||
out.append('二维码超过纸宽 40%%(%d 点)' % q['size'])
|
||||
# 二维码底边和最后一行底边对齐(参考图版式)
|
||||
if p['lines']:
|
||||
last_bottom = p['lines'][-1]['y'] + p['font']
|
||||
if abs((q['y'] + q['size']) - last_bottom) > 1:
|
||||
out.append('二维码底边未与末行对齐 码底=%d 末行=%d'
|
||||
% (q['y'] + q['size'], last_bottom))
|
||||
block_h = last_bottom - p['lines'][0]['y']
|
||||
if q['size'] > block_h + 2:
|
||||
out.append('二维码比文字块还高 码=%d 块=%d'
|
||||
% (q['size'], block_h))
|
||||
return out
|
||||
|
||||
|
||||
def content_ok(p, title, fields):
|
||||
"""内容必须一字不少地打出来:不允许任何形式的截断"""
|
||||
src = L._safe_text(title or '') + ''.join(
|
||||
L._safe_text(f or '') for f in fields)
|
||||
got = ''.join(ln['text'] for ln in p['lines'])
|
||||
return got == src, src, got
|
||||
|
||||
|
||||
def no_truncate(p):
|
||||
return not any('截断' in str(x) for x in (p.get('warnings') or [])), \
|
||||
str(p.get('warnings'))
|
||||
|
||||
|
||||
for (wmm, hmm) in SIZES:
|
||||
for fname, (title, fields) in FIELDS.items():
|
||||
for qname, qr in QRS.items():
|
||||
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203,
|
||||
'gap_mm': 2}
|
||||
p = L.plan_label(cfg, title, fields, qr_data=qr)
|
||||
tag = '%gx%g/%s/%s' % (wmm, hmm, fname, qname)
|
||||
bad = fail_reasons(p, cfg, qr)
|
||||
check('%s 版面' % tag, not bad, '; '.join(bad))
|
||||
good, src, got = content_ok(p, title, fields)
|
||||
check('%s 内容完整' % tag, good,
|
||||
'源=%r 得=%r' % (src, got))
|
||||
nt, ww = no_truncate(p)
|
||||
check('%s 无截断' % tag, nt, ww)
|
||||
check('%s 有码必打出整块' % tag, bool(p['qr']) == bool(qr),
|
||||
'qr=%r' % (p['qr'],))
|
||||
|
||||
print('版面不变量:%d 通过,%d 失败' % (ok, fail))
|
||||
|
||||
# ---- 宽度模型:GBK 双字节字符必须是全角(×、·、— 这些不是汉字但仍是双字节)----
|
||||
print('=== 宽度模型(GBK 双字节 = 全角)===')
|
||||
check('× 按全角算', L._text_width('×', 24) == 24, str(L._text_width('×', 24)))
|
||||
check('· 按全角算', L._text_width('·', 24) == 24, str(L._text_width('·', 24)))
|
||||
check('— 按全角算', L._text_width('—', 24) == 24, str(L._text_width('—', 24)))
|
||||
check('ASCII 仍按半角', abs(L._text_width('A', 24) - 24 * 0.56) < 0.01,
|
||||
str(L._text_width('A', 24)))
|
||||
|
||||
# ---- 设置页预览那组数据:文字右缘离码至少 2mm(二维码静区) ----
|
||||
print('=== 预览示例不压码 ===')
|
||||
_p = L.plan_label({'width_mm': 60, 'height_mm': 40, 'dpi': 203}, '分拣标签',
|
||||
['客户: 张三水果批发店',
|
||||
'品名: 农夫山泉饮用天然水 550ml×24',
|
||||
'数量: 1.00 桶', '日期: 11-04 19:02'],
|
||||
qr_data='CT2026110400001234')
|
||||
_q = _p['qr']
|
||||
_gap = min(_q['x'] - (ln['x'] + ln['w']) for ln in _p['lines'])
|
||||
check('示例文字离码 ≥2mm(16 dots)', _gap >= 16, 'gap=%d' % _gap)
|
||||
check('示例字没被截断', not any('截断' in str(x) for x in _p['warnings']),
|
||||
str(_p['warnings']))
|
||||
|
||||
# ---- 再验一遍真正的 TSPL 字节:坐标在纸内、文字一个字不少 ----
|
||||
print('=== 实际 TSPL 指令校验 ===')
|
||||
for (wmm, hmm) in ((50, 50), (60, 40)):
|
||||
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203, 'gap_mm': 2}
|
||||
data = L.build_picking_label_tspl(
|
||||
cfg, '张三水果批发市场', '农夫山泉 550ml×24', 15.0, '斤',
|
||||
'2026-11-22 18:30', 'CT-WEB-20261122-BR003-000123456789')
|
||||
s = data.decode('gbk', errors='replace')
|
||||
tag = 'TSPL %gx%g' % (wmm, hmm)
|
||||
# 长文字会折成多条 TEXT,拼起来才是完整内容(不能按整段子串找)
|
||||
import re
|
||||
payloads = re.findall(r'TEXT \d+,\d+,"TSS\d+\.BF2",0,1,1,"([^"]*)"', s)
|
||||
payloads += re.findall(r'QRCODE \d+,\d+,\w,\d,\w,\d,M2,S1,"([^"]*)"', s)
|
||||
joined = ''.join(payloads)
|
||||
for need in ('张三水果批发市场', '农夫山泉 550ml×24', '15.00',
|
||||
'2026-11-22 18:30', 'CT-WEB-20261122-BR003-000123456789'):
|
||||
check('%s 含 %s' % (tag, need[:10]), need in joined,
|
||||
'内容丢了:%r' % joined)
|
||||
# TEXT x,y,"font",0,1,1,"..." → 坐标都在纸内
|
||||
import re
|
||||
for m in re.finditer(r'TEXT (\d+),(\d+),"TSS(\d+)', s):
|
||||
x, y, f = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
check('%s TEXT 坐标' % tag,
|
||||
x >= 0 and y >= 0 and x < wmm * 8 and y + f <= hmm * 8,
|
||||
'x=%d y=%d f=%d' % (x, y, f))
|
||||
for m in re.finditer(r'QRCODE (\d+),(\d+),H,(\d+)', s):
|
||||
x, y, cell = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
mods = L._qr_modules(len('CT-WEB-20261122-BR003-000123456789'.encode('gbk')))
|
||||
check('%s QR 坐标' % tag,
|
||||
x + mods * cell <= wmm * 8 and y + mods * cell <= hmm * 8,
|
||||
'x=%d y=%d size=%d' % (x, y, mods * cell))
|
||||
|
||||
print('总计:%d 通过,%d 失败' % (ok, fail))
|
||||
|
||||
# ---- 随机长文本压力:真实前缀 + 随机长度,4 种常用纸型 ----
|
||||
print('=== 随机长文本压力(不截断 / 不缺码) ===')
|
||||
import random
|
||||
|
||||
random.seed(20261123)
|
||||
POOL = ('红富士苹果蔬菜水果批发市场配送中心农夫山泉饮用天然水'
|
||||
'上海青小棠菜土豆白萝卜冬瓜南瓜青椒黄果柑蒜苗菠菜'
|
||||
'abcABC0123456789 -_/().:×·()')
|
||||
STRESS_SIZES = [(60, 40), (76, 60), (80, 60), (50, 50), (70, 50)]
|
||||
|
||||
|
||||
def _rand_txt(n):
|
||||
return ''.join(random.choice(POOL) for _ in range(n))
|
||||
|
||||
|
||||
for i in range(120):
|
||||
wmm, hmm = STRESS_SIZES[i % len(STRESS_SIZES)]
|
||||
cfg = {'width_mm': wmm, 'height_mm': hmm, 'dpi': 203, 'gap_mm': 2}
|
||||
title = '分拣标签'
|
||||
fields = ['客户: ' + _rand_txt(random.randint(4, 20)),
|
||||
'品名: ' + _rand_txt(random.randint(4, 24)),
|
||||
'数量: %.2f 桶' % (random.random() * 999),
|
||||
'日期: 11-23 12:29']
|
||||
qr = 'CT' + ''.join(random.choice('0123456789ABCDEF') for _ in range(18))
|
||||
p = L.plan_label(cfg, title, fields, qr_data=qr)
|
||||
src = L._safe_text(title) + ''.join(L._safe_text(f) for f in fields)
|
||||
got = ''.join(ln['text'] for ln in p['lines'])
|
||||
q = p['qr']
|
||||
g = p['geom']
|
||||
bad = []
|
||||
if p.get('overflow'):
|
||||
bad.append('overflow=%s' % (p['warnings'],))
|
||||
if got != src:
|
||||
bad.append('内容不完整')
|
||||
for ln in p['lines']:
|
||||
if ln['x'] + ln['w'] > g['w'] or ln['y'] + ln['font'] > g['h']:
|
||||
bad.append('行越纸')
|
||||
if q and ln['x'] + ln['w'] > q['x']:
|
||||
bad.append('文字压码')
|
||||
if not q:
|
||||
bad.append('缺码')
|
||||
elif (q['x'] < 0 or q['y'] < 0 or q['x'] + q['size'] > g['w']
|
||||
or q['y'] + q['size'] > g['h']):
|
||||
bad.append('码越纸')
|
||||
check('压力 #%d %dx%d' % (i, wmm, hmm), not bad,
|
||||
'%s | %r' % ('; '.join(sorted(set(bad))), fields))
|
||||
|
||||
# ---- 打不出来时坚决不发数据:排不下 / 容器码过长 ----
|
||||
print('=== 排不下就拒打(不发半张) ===')
|
||||
sent = []
|
||||
|
||||
|
||||
class _FakePrinter(L.LabelPrinter):
|
||||
def _send(self, data, doc_name='标签'):
|
||||
sent.append(data)
|
||||
return True, 'fake'
|
||||
|
||||
|
||||
pr = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 35, 'height_mm': 25,
|
||||
'gap_mm': 2, 'dpi': 203}})
|
||||
ok_bad, msg_bad = pr.print_picking('客' * 120, '品' * 120, 1.0, '斤', 'CT1')
|
||||
check('排不下时返回失败', ok_bad is False, str((ok_bad, msg_bad)))
|
||||
check('排不下时一个字节都不发', not sent, str(len(sent)))
|
||||
|
||||
pr2 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
|
||||
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
|
||||
ok_ok, msg_ok = pr2.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
|
||||
'CT-OK-1')
|
||||
check('正常数据能打', ok_ok is True and bool(sent), str((ok_ok, msg_ok)))
|
||||
if sent:
|
||||
_s = sent[-1].decode('gbk', errors='replace')
|
||||
check('正常数据带整块码',
|
||||
'QRCODE ' in _s and '"CT-OK-1"' in _s, _s[:160])
|
||||
|
||||
pr3 = _FakePrinter({'printer': {'type': 'tspl', 'width_mm': 60,
|
||||
'height_mm': 40, 'gap_mm': 2, 'dpi': 203}})
|
||||
sent[:] = []
|
||||
ok_long, msg_long = pr3.print_picking('王记饭店', '红富士苹果', 5.62, '斤',
|
||||
'C' * 1300)
|
||||
check('容器码超长时拒打', ok_long is False and not sent,
|
||||
str((ok_long, msg_long, len(sent))))
|
||||
|
||||
check('QR 容量表:1273 字节 = 177 模块',
|
||||
L._qr_modules(1273) == 177, str(L._qr_modules(1273)))
|
||||
|
||||
print('总计:%d 通过,%d 失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,219 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""待办分页兜底回归:不管卡高怎么估偏,最底一行都不许被视口裁掉。
|
||||
|
||||
现场现象:入库 4 列 3 行时最底一行被切掉一半(有时有独立入库徽标,
|
||||
有时什么标识都没有)。卡高是靠 winfo_reqheight 估的,重建卡片、客户名
|
||||
晚到、DPI/字体差异、页头比估的高……任何一种偏差都会让一页多塞一行。
|
||||
|
||||
现在 _layout_cards 摆完会按真实几何复查:超出视口就缩预算重排。
|
||||
本用例用「谎报卡高」直接把这个偏差做出来,验证兜底真的生效。
|
||||
|
||||
验证项:
|
||||
1. 正常填充:每页都在视口内(基线)
|
||||
2. 卡高只报真实的一半(严重低估):仍然不裁,页数不变少
|
||||
3. 恢复真实卡高:仍不裁
|
||||
4. 客户名变长(卡变高)后刷新:重排后仍不裁
|
||||
5. 重复排同一份名单不抖
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import tkinter as tk
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
os.chdir(ROOT)
|
||||
|
||||
import ui.app as A # noqa: E402
|
||||
|
||||
A.save_config = lambda cfg, path='config.json': None
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
print(' ✔', name)
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✘', name, extra)
|
||||
|
||||
|
||||
try: # 与真程序一致:DPI 感知要在 Tk 之前
|
||||
import ctypes
|
||||
ctypes.windll.shcore.SetProcessDpiAwareness(2)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
root = tk.Tk()
|
||||
app = A.App(root)
|
||||
for _w in list(root.winfo_children()):
|
||||
_w.destroy()
|
||||
app.engine.station = 'inspection' # 入库:3 行 4 列最容易裁
|
||||
app.engine.logged_in = True
|
||||
app.ready = True
|
||||
root.deiconify()
|
||||
try:
|
||||
root.geometry('1400x820+20+20')
|
||||
except Exception:
|
||||
pass
|
||||
root.update()
|
||||
app._build()
|
||||
root.update()
|
||||
app._group_mode = 'customer' # 现场默认按客户分组(带页头)
|
||||
app._group_pick = None
|
||||
|
||||
|
||||
def settle(n=12):
|
||||
for _ in range(n):
|
||||
root.update()
|
||||
time.sleep(0.03)
|
||||
|
||||
|
||||
NAMES = ['空心菜', '糯玉米', '水面', '米块', '小青椒', '圣女果', '新鲜海带丝',
|
||||
'青黄瓜', '蒜苔', '泡酸菜(斤)', '鱼酸菜', '大白菜', '土豆', '生姜',
|
||||
'洋葱', '西红柿', '红油菜', '粗大葱', '粉山药', '白萝卜', '白菜',
|
||||
'生菜', '黄瓜', '香菜', '芹菜', '油麦菜', '茼蒿', '口蘑', '尖白菜',
|
||||
'仔姜', '四季豆', '莲花白', '大葱', '冬瓜', '南瓜', '茄子']
|
||||
|
||||
|
||||
def make_rows(who=None):
|
||||
rows = []
|
||||
for i, n in enumerate(NAMES):
|
||||
r = {'id': 'r%02d' % i, 'item_name': n, 'unit': '斤',
|
||||
'remaining_qty': 5 + i * 3, 'required_qty': 5 + i * 3}
|
||||
if who:
|
||||
r['customer_name'] = who
|
||||
rows.append(r)
|
||||
return rows
|
||||
|
||||
|
||||
def scan_pages():
|
||||
"""逐页检查:返回 (卡片超出视口的清单, 空白页页码清单)"""
|
||||
cv = app.todo_canvas
|
||||
app._page = 0
|
||||
app._layout_key = None
|
||||
app._layout_cards()
|
||||
settle(6)
|
||||
bad = []
|
||||
empty = []
|
||||
for pg in range(max(1, getattr(app, '_page_count', 1))):
|
||||
n = 0
|
||||
for c in app.todo_cards.values():
|
||||
if c.winfo_manager() != 'grid':
|
||||
continue
|
||||
n += 1
|
||||
over = (c.winfo_y() + c.winfo_height()) - cv.winfo_height()
|
||||
if over > 0:
|
||||
bad.append((pg + 1, c.winfo_y(), c.winfo_height(), over))
|
||||
if n == 0:
|
||||
empty.append(pg + 1)
|
||||
app._page_turn(1)
|
||||
settle(3)
|
||||
return bad, empty
|
||||
|
||||
|
||||
cv = app.todo_canvas
|
||||
|
||||
print('=== 0. 前置:几何是真的(不是空跑)===')
|
||||
rows = make_rows()
|
||||
app.engine.rows = [dict(r) for r in rows]
|
||||
app._fill_todo(rows)
|
||||
settle(14)
|
||||
check('画布有真实尺寸', cv.winfo_width() > 400 and cv.winfo_height() > 200,
|
||||
'%dx%d' % (cv.winfo_width(), cv.winfo_height()))
|
||||
gridded = [c for c in app.todo_cards.values() if c.winfo_manager() == 'grid']
|
||||
check('卡片真的摆上了', len(gridded) >= 4, str(len(gridded)))
|
||||
check('分成多页', getattr(app, '_page_count', 1) > 1,
|
||||
str(getattr(app, '_page_count', 1)))
|
||||
|
||||
print('=== 1. 正常填充:每页都不裁 ===')
|
||||
bad, empty = scan_pages()
|
||||
check('所有页都在视口内', not bad, '超出 %r' % bad[:4])
|
||||
check('没有空白页', not empty, str(empty))
|
||||
base_pages = getattr(app, '_page_count', 1)
|
||||
|
||||
print('=== 2. 卡高谎报一半(严重低估):兜底必须生效 ===')
|
||||
for c in app.todo_cards.values():
|
||||
real = c.winfo_reqheight()
|
||||
c.winfo_reqheight = (lambda r: (lambda: max(11, int(r / 2))))(real)
|
||||
app._geom_dirty = True # 等同于「卡片刚重建、高度未知」
|
||||
bad, empty = scan_pages()
|
||||
check('低估卡高后仍不裁(兜底缩了预算)', not bad, '超出 %r' % bad[:4])
|
||||
check('没有摆出只有页头的空白页', not empty, str(empty))
|
||||
|
||||
print('=== 3. 恢复真实卡高 ===')
|
||||
for c in app.todo_cards.values():
|
||||
try:
|
||||
del c.winfo_reqheight
|
||||
except AttributeError:
|
||||
pass
|
||||
bad, empty = scan_pages()
|
||||
check('恢复后所有页都不裁', not bad, '超出 %r' % bad[:4])
|
||||
|
||||
print('=== 4. 客户名变长(卡变高)后刷新 ===')
|
||||
rows2 = make_rows(who='宛宿食品宿迁高新区拾光牧业有限公司')
|
||||
app.engine.rows = [dict(r) for r in rows2]
|
||||
app._fill_todo(rows2)
|
||||
settle(16)
|
||||
hs = {c.winfo_reqheight() for c in app.todo_cards.values()}
|
||||
check('卡真的变高了(折行)', max(hs or [0]) > 10, str(hs))
|
||||
bad, empty = scan_pages()
|
||||
check('变高后每页仍不裁', not bad, '超出 %r' % bad[:4])
|
||||
check('变高后也没有空白页', not empty, str(empty))
|
||||
|
||||
print('=== 6. 按供应商 → 不分组:页头必须消失(现场故障)===')
|
||||
rows3 = []
|
||||
for i, n in enumerate(NAMES):
|
||||
r = {'id': 'r%02d' % i, 'item_name': n, 'unit': '斤',
|
||||
'remaining_qty': 5 + i * 3}
|
||||
if i >= 9:
|
||||
r['customer_name'] = ('干杂周旭梅' if i < 12
|
||||
else '宛宿食品宿迁高新区拾光牧业')
|
||||
rows3.append(r)
|
||||
app.engine.rows = [dict(r) for r in rows3]
|
||||
app._all_rows = [dict(r) for r in rows3]
|
||||
app._set_group_mode('none') # 先回到不分组(点同一个是开关)
|
||||
settle(10)
|
||||
check('先回到不分组', app._group_mode == 'none', app._group_mode)
|
||||
app._set_group_mode('customer')
|
||||
settle(18)
|
||||
check('分组模式下确实摆了页头', bool(app._hdr_widgets),
|
||||
str(len(app._hdr_widgets)))
|
||||
bad, empty = scan_pages()
|
||||
check('分组模式每页不裁', not bad, '超出 %r' % bad[:4])
|
||||
|
||||
app._set_group_mode('none')
|
||||
settle(18)
|
||||
check('切回不分组后页头已销毁', not app._hdr_widgets,
|
||||
str(len(app._hdr_widgets)))
|
||||
card_ids = {id(c) for c in app.todo_cards.values()}
|
||||
stray = [w for w in app.todo_grid.grid_slaves() if id(w) not in card_ids]
|
||||
check('网格里只剩卡片(没有页头残留)', not stray, str(stray[:3]))
|
||||
bad, empty = scan_pages()
|
||||
check('切回不分组后每页都不裁', not bad, '超出 %r' % bad[:4])
|
||||
check('切回不分组后没有空白页', not empty, str(empty))
|
||||
|
||||
print('=== 7. 幂等:同一份名单重复排不抖 ===')
|
||||
app._page = 0
|
||||
app._layout_key = None
|
||||
app._layout_cards()
|
||||
settle(4)
|
||||
p1 = (getattr(app, '_page_count', 1),
|
||||
{r: (c.winfo_x(), c.winfo_y()) for r, c in app.todo_cards.items()
|
||||
if c.winfo_manager() == 'grid'})
|
||||
app._layout_cards()
|
||||
settle(4)
|
||||
p2 = (getattr(app, '_page_count', 1),
|
||||
{r: (c.winfo_x(), c.winfo_y()) for r, c in app.todo_cards.items()
|
||||
if c.winfo_manager() == 'grid'})
|
||||
check('重复排两遍结果一致', p1 == p2, str((p1[0], p2[0])))
|
||||
|
||||
root.destroy()
|
||||
print('\n结果:%d 项通过,%d 项失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,240 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""回归测试:入库照片送审队列(不需要秤/相机/网络)。
|
||||
|
||||
盯的是三件事,每一件都是「现场会真的发生」的:
|
||||
1. 入库没成功 → 一张都不许送(否则训练图会挂在不存在的账上);
|
||||
2. 入库成功但当场断电/断网 → 重启后照样送,且只送一次;
|
||||
3. 数据本身有问题(4xx)→ 转人工,别无限刷日志。
|
||||
"""
|
||||
from concurrent.futures import Future
|
||||
import json
|
||||
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()))
|
||||
|
||||
qp.stage(api, 'op-pick', ROW, '人工', photo(root), station='picking')
|
||||
qp.drain(api, say)
|
||||
check('分拣未完成不送审', not any(f['event_id'] == 'op-pick' for f, _ in api.sent))
|
||||
journal('op-pick', J.STATE_SUCCEEDED)
|
||||
qp.drain(api, say)
|
||||
qp.drain(api, say)
|
||||
sent = [f for f, _ in api.sent if f['event_id'] == 'op-pick']
|
||||
check('分拣成功只送审一次,并关联正确明细',
|
||||
len(sent) == 1 and sent[0]['scene'] == 'picking'
|
||||
and sent[0]['business_item_id'] == ROW['id'])
|
||||
|
||||
pending = Future()
|
||||
audit = {'local': pending, 'cloud': {'status': 'recognized', 'name': '芹菜'}}
|
||||
qp.stage(api, 'op-audit', ROW, '人工', photo(root, 'audit.jpg'), audit=audit)
|
||||
journal('op-audit', J.STATE_SUCCEEDED)
|
||||
qp.drain(api, say)
|
||||
check('记账成功时本地还在算,只让后台队列等', 'op-audit' in ops())
|
||||
pending.set_result({'status': 'recognized', 'name': '小葱'})
|
||||
qp.drain(api, say)
|
||||
reports = [json.loads(f['recognition_audit']) for f, _ in api.sent if f['event_id'] == 'op-audit']
|
||||
check('同一笔上传两边的结果', len(reports) == 1 and reports[0]['local']['name'] == '小葱'
|
||||
and reports[0]['cloud']['name'] == '芹菜')
|
||||
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
print()
|
||||
if fails:
|
||||
print('[x] %d 项没过:%s' % (len(fails), '、'.join(fails)))
|
||||
sys.exit(1)
|
||||
print('全部通过(%d 条日志)' % len(logs))
|
||||
@@ -78,10 +78,24 @@ print('=== 3. 单位不一致 → 不分摊 ===')
|
||||
mixed = [row('m1', '生菜', 3, unit='斤'), row('m2', '生菜', 2, unit='件')]
|
||||
check('单位不同不摊', eng._split_plan(mixed, 5.0) is None)
|
||||
|
||||
print('=== 4. 独立入库行不参与分摊 ===')
|
||||
print('=== 4. 独立入库行也按同名多行分摊(v1.0.65) ===')
|
||||
ind = [row('i1', '四季豆', 10, indep=True, sku='A'),
|
||||
row('i2', '四季豆', 6, indep=True, sku='B')]
|
||||
check('独立入库不摊', eng._split_plan(ind, 16.0) is None)
|
||||
ind_plan = eng._split_plan(ind, 16.0)
|
||||
check('独立入库也摊', ind_plan is not None and len(ind_plan) == 2,
|
||||
str([(r['id'], q) for r, q in ind_plan] if ind_plan else ind_plan))
|
||||
if ind_plan:
|
||||
check('小单先结、尾量归大单', [q for _, q in ind_plan] == [6.0, 10.0],
|
||||
str(ind_plan))
|
||||
ind_over = [row('i3', '土豆', 17, indep=True, sku='C'),
|
||||
row('i4', '土豆', 38, indep=True, sku='D')]
|
||||
over_plan = eng._split_plan(ind_over, 55.74)
|
||||
check('55.74 = 17 + 38.74,最后一行收尾量',
|
||||
over_plan is not None and [q for _, q in over_plan] == [17.0, 38.74],
|
||||
str(over_plan))
|
||||
check('有单/无单混合仍不摊',
|
||||
eng._split_plan([row('m1', '混合', 2, order='O1'),
|
||||
row('m2', '混合', 3, indep=True, sku='M')], 5.0) is None)
|
||||
|
||||
print('=== 5. 开关关掉 → 不分摊 ===')
|
||||
eng.cfg['flow']['merge_same_name'] = False
|
||||
@@ -121,7 +135,7 @@ class FakeApi:
|
||||
eng.journal = FakeJournal()
|
||||
eng.api = FakeApi()
|
||||
eng._running = True
|
||||
eng._print_async = lambda r, q, kg=None: None
|
||||
eng._print_async = lambda r, q, kg=None, **k: None
|
||||
eng._record = lambda *a, **k: None
|
||||
eng._set_hold = lambda *a, **k: None
|
||||
eng._set_state = lambda s: setattr(eng, 'state', s)
|
||||
@@ -168,7 +182,7 @@ eng.state = 'SUBMIT'
|
||||
eng._plan = [(ROWS[1], 1.5), (ROWS[2], 10.0)]
|
||||
started = []
|
||||
eng._start_submit = lambda r, q, s: started.append((r['id'], q, s))
|
||||
eng._print_async = lambda r, q, kg=None: None
|
||||
eng._print_async = lambda r, q, kg=None, **k: None
|
||||
eng._record = lambda *a, **k: None
|
||||
eng._set_hold = lambda *a, **k: None
|
||||
eng._frozen_kg = 14.5
|
||||
|
||||
@@ -108,7 +108,7 @@ eng.refresh_pending = lambda initial=False: None
|
||||
eng.journal = FakeJournal()
|
||||
eng.api = FakeApi()
|
||||
eng._running = True
|
||||
eng._print_async = lambda r, q: None
|
||||
eng._print_async = lambda r, q, **k: None
|
||||
eng._record = lambda *a, **k: None
|
||||
|
||||
print('=== 1. 独立入库查重:同 SKU + 同重量 → 拒绝 ===')
|
||||
@@ -143,7 +143,7 @@ eng2.refresh_pending = lambda initial=False: None
|
||||
eng2.journal = FakeJournal()
|
||||
eng2.api = FakeApi()
|
||||
eng2._running = True
|
||||
eng2._print_async = lambda r, q: None
|
||||
eng2._print_async = lambda r, q, **k: None
|
||||
eng2._record = lambda *a, **k: None
|
||||
eng2.rows = [row('r6', '藕', 13, indep=True, sku='SKU-OU'),
|
||||
row('r8', '大白菜', 30, indep=True, sku='SKU-BC')]
|
||||
|
||||
+24
-8
@@ -114,8 +114,8 @@ check('默认开(不写配置也是拿走即提交)', e.submit_on_remove() i
|
||||
e = Fake(flow_cfg={'submit_on_remove': False})
|
||||
check('显式关掉生效', e.submit_on_remove() is False)
|
||||
|
||||
print('二、_confirm_tick:拿走即提交(v1.0.62 口径:秤归零才提交,'
|
||||
'提交值=取货前最后一次稳定读数)')
|
||||
print('二、_confirm_tick:拿走即提交(v1.0.69 口径:空秤稳 3 秒才提交,'
|
||||
'抬货调整/补货放回秤上即取消)')
|
||||
e = Fake()
|
||||
e.state = 'CONFIRM'
|
||||
e._focus = {'mode': 'weigh', 'row_id': 'r1'}
|
||||
@@ -126,14 +126,30 @@ t0 = time.monotonic()
|
||||
e._confirm_tick(t0, {'present': True, 'weight': 9.0})
|
||||
check('货在秤上:不提交,记见过货', e.confirms == []
|
||||
and e._confirm_seen_present is True)
|
||||
e._confirm_tick(t0 + 0.1, {'present': False, 'weight': 8.8})
|
||||
check('读数掉一点还没归零:不提交', e.confirms == [])
|
||||
e._confirm_tick(t0 + 0.2, {'present': False, 'weight': 0.0})
|
||||
check('归零瞬间(未稳 0.3 秒):先不提交', e.confirms == [])
|
||||
e._confirm_tick(t0 + 0.6, {'present': False, 'weight': 0.0})
|
||||
check('归零稳住 → confirm_focus(auto_remove=True)',
|
||||
e._confirm_tick(t0 + 0.1, {'present': True, 'weight': 8.8})
|
||||
check('读数掉一点但还在秤上:不提交', e.confirms == [])
|
||||
e._confirm_tick(t0 + 0.5, {'present': False, 'weight': 0.0})
|
||||
check('归零瞬间:先不提交', e.confirms == [])
|
||||
e._confirm_tick(t0 + 3.4, {'present': False, 'weight': 0.0})
|
||||
check('空秤未满 3 秒:不提交', e.confirms == [])
|
||||
e._confirm_tick(t0 + 3.6, {'present': False, 'weight': 0.0})
|
||||
check('空秤满 3 秒 → confirm_focus(auto_remove=True)',
|
||||
e.confirms == [True])
|
||||
|
||||
# 现场:补货时把原货抬起来调整位置,再放回去 —— 不能算取走
|
||||
e = Fake()
|
||||
e.state = 'CONFIRM'
|
||||
e._focus = {'mode': 'weigh', 'row_id': 'r1'}
|
||||
e._frozen_kg = 9.0
|
||||
e._frozen_row = mrow()
|
||||
t0 = time.monotonic()
|
||||
e._confirm_tick(t0, {'present': True, 'weight': 9.0})
|
||||
e._confirm_tick(t0 + 0.5, {'present': False, 'weight': 0.0})
|
||||
e._confirm_tick(t0 + 2.0, {'present': True, 'weight': 9.4})
|
||||
check('抬起 1.5 秒又放回:不提交', e.confirms == [])
|
||||
check('放回后取货计时清零', not e._confirm_gone_at,
|
||||
e._confirm_gone_at)
|
||||
|
||||
e = Fake()
|
||||
e.state = 'CONFIRM'
|
||||
e._focus = {'mode': 'weigh'}
|
||||
|
||||
@@ -70,7 +70,7 @@ eng._running = True
|
||||
eng.station = 'picking'
|
||||
eng.rows = []
|
||||
eng._start_submit = lambda row, q, src: submits.append((row, q, src))
|
||||
eng._print_async = lambda row, biz, kg=None: prints.append(
|
||||
eng._print_async = lambda row, biz, kg=None, **k: prints.append(
|
||||
(row.get('item_name'), float(biz)))
|
||||
eng._learn_sample = lambda *a, **k: None
|
||||
eng._abort_cycle = lambda msg: aborts.append(msg)
|
||||
|
||||
@@ -88,6 +88,9 @@ check('根节点 container_code',
|
||||
check('data.result.container_code',
|
||||
e._container_code_of(
|
||||
{'data': {'result': {'container_code': 'CT-N'}}}) == 'CT-N')
|
||||
check('container.code',
|
||||
e._container_code_of(
|
||||
{'data': {'container': {'code': 'CT-C'}}}) == 'CT-C')
|
||||
check('行上的 container_code',
|
||||
e._container_code_of(ROW) == 'CT20261108000123')
|
||||
|
||||
@@ -139,6 +142,19 @@ text = data.decode('gbk', 'replace')
|
||||
check('QRCODE 里是容器码', 'QRCODE' in text and 'CT20261108000123' in text, text)
|
||||
check('没有把订单号打进二维码', 'ORD_WEB' not in text, text)
|
||||
|
||||
print('=== 6b. ZPL 也走同一份版面与容器码 ===')
|
||||
zpl = LB.build_zpl(
|
||||
{'width_mm': 50, 'height_mm': 50, 'dpi': 203, 'gap_mm': 2},
|
||||
'分拣标签',
|
||||
['客户: 李府家宴', '品名: 大葱', '重量: 35.22 斤', '日期: 11-06 10:00'],
|
||||
'CT20261108000123').decode('utf-8')
|
||||
check('ZPL 里有容器码', 'CT20261108000123' in zpl, zpl)
|
||||
check('ZPL 里没有订单号', 'ORD_WEB' not in zpl, zpl)
|
||||
check('ZPL 日期没被拆开',
|
||||
'日期: 11-06 10:00' in zpl
|
||||
and '^FD0:00^FS' not in zpl
|
||||
and '11-06 1^FS' not in zpl, zpl)
|
||||
|
||||
print('=== 7. 50×50mm 带二维码:日期必须单行 ===')
|
||||
p = LB.plan_label(
|
||||
{'width_mm': 50, 'height_mm': 50, 'dpi': 203, 'gap_mm': 2},
|
||||
@@ -176,6 +192,56 @@ check('队列里只有 1 张', e._print_q.qsize() == 1)
|
||||
check('第二次跳过有日志',
|
||||
any('已打印过标签' in x for x in logs()), logs())
|
||||
|
||||
print('=== 11. 全链路:提交回包 → 打印队列 ===')
|
||||
|
||||
|
||||
class FakeJournal:
|
||||
def __init__(self):
|
||||
self.rec = {}
|
||||
|
||||
def begin(self, op, kind, target, qty, weight, unit):
|
||||
self.rec[op] = {'operationId': op}
|
||||
return self.rec[op]
|
||||
|
||||
def update(self, op, **kw):
|
||||
self.rec.setdefault(op, {}).update(kw)
|
||||
return True
|
||||
|
||||
def conclude(self, op, state, msg=''):
|
||||
self.rec.setdefault(op, {})['state'] = state
|
||||
return True
|
||||
|
||||
def has_unresolved(self):
|
||||
return False
|
||||
|
||||
|
||||
class FakeApi:
|
||||
user_id = 'u'
|
||||
base_url = 'http://x'
|
||||
|
||||
def commit_picking(self, row, qty, weight, op, photo_expected):
|
||||
return {'operation_status': 'committed_by_this_operation',
|
||||
'client_operation_id': op,
|
||||
'data': {'pick_status': 20,
|
||||
'container_code': 'CT-E2E'}}
|
||||
|
||||
|
||||
e = new_eng()
|
||||
e.journal = FakeJournal()
|
||||
e.api = FakeApi()
|
||||
e._record = lambda *a, **k: None
|
||||
e.frames.capture_confirmed = lambda: {
|
||||
'qualified': False, 'path': None, 'sha256': '', 'reason': 'test'}
|
||||
e._frozen_kg = 1.0
|
||||
e._frozen_row = dict(ROW, container_code='')
|
||||
row_no_ct = dict(ROW, container_code='')
|
||||
e._submit_worker(row_no_ct, 1.0, 'AI')
|
||||
it = e._print_q.get_nowait()
|
||||
check('提交回包里的 container_code 进了打印队列',
|
||||
it['qr'] == 'CT-E2E', it)
|
||||
check('来源标记 container_code', it['qr_source'] == 'container_code', it)
|
||||
check('没有退化成订单号', 'ORD_WEB' not in it['qr'], it['qr'])
|
||||
|
||||
print()
|
||||
print('%d 项通过,%d 项失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""v1.0.65 回归:登录页可改服务器地址(server.base_url)
|
||||
|
||||
现场需求:换机房 / 切备用服务器时,不用退出程序、不用手改 config.json。
|
||||
|
||||
本文件验证:
|
||||
① 登录页页脚显示当前服务器地址(问 mock 时提示离线模拟)
|
||||
② 「修改」弹窗能打开,输入框预填当前地址
|
||||
③ 非法地址(无 http(s) 前缀 / 空)不会保存
|
||||
④ 合法地址:写回配置、立刻作用到 ApiClient、页脚刷新、弹窗关闭
|
||||
⑤ 保存时把 server.mock 置回 false,并把地址记进 server.history
|
||||
不需要网络(「测试连接」单独人工验,本用例不联网)。
|
||||
"""
|
||||
import sys
|
||||
import io
|
||||
import os
|
||||
import json
|
||||
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__))))
|
||||
|
||||
import tkinter as tk
|
||||
import ui.app as A
|
||||
from ui.tablet import TouchButton
|
||||
|
||||
SAVED = {}
|
||||
|
||||
|
||||
def fake_save(cfg, path='config.json'):
|
||||
"""截住写盘:用例绝不碰真实 config.json"""
|
||||
SAVED['cfg'] = json.loads(json.dumps(cfg, ensure_ascii=False))
|
||||
SAVED['path'] = path
|
||||
|
||||
|
||||
A.save_config = fake_save
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
print(' ✔', name)
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✘', name, extra)
|
||||
|
||||
|
||||
root = tk.Tk()
|
||||
root.withdraw()
|
||||
app = A.App(root)
|
||||
cur = str((app.cfg.get('server') or {}).get('base_url') or '')
|
||||
|
||||
print('=== 1. 页脚显示当前服务器 ===')
|
||||
app._refresh_login_srv()
|
||||
check('页脚有当前地址', cur in app.lbl_login_srv.cget('text'),
|
||||
app.lbl_login_srv.cget('text'))
|
||||
|
||||
print('=== 2. 打开修改窗口 ===')
|
||||
app._edit_server()
|
||||
root.update()
|
||||
tops = [w for w in root.winfo_children() if isinstance(w, tk.Toplevel)]
|
||||
check('弹窗已打开', len(tops) == 1, str(tops))
|
||||
dlg = tops[0]
|
||||
|
||||
entries = []
|
||||
btns = []
|
||||
|
||||
|
||||
def walk(w):
|
||||
for c in w.winfo_children():
|
||||
if isinstance(c, tk.Entry):
|
||||
entries.append(c)
|
||||
if isinstance(c, TouchButton):
|
||||
btns.append(c)
|
||||
walk(c)
|
||||
|
||||
|
||||
walk(dlg)
|
||||
check('弹窗里有输入框', len(entries) == 1, str(len(entries)))
|
||||
ent = entries[0]
|
||||
check('预填当前地址', ent.get().rstrip('/') == cur.rstrip('/'), ent.get())
|
||||
check('有保存按钮', any(b._text == '保存并应用' for b in btns),
|
||||
str([b._text for b in btns]))
|
||||
check('有测试连接按钮', any(b._text == '测试连接' for b in btns),
|
||||
str([b._text for b in btns]))
|
||||
save_btn = [b for b in btns if b._text == '保存并应用'][0]
|
||||
|
||||
print('=== 3. 非法地址不保存 ===')
|
||||
for bad in ('', 'ftp://bad', 'www.example.com/api'):
|
||||
ent.delete(0, 'end')
|
||||
ent.insert(0, bad)
|
||||
save_btn._command()
|
||||
root.update()
|
||||
check('拒绝「%s」' % (bad or '空'), not SAVED, str(SAVED))
|
||||
|
||||
print('=== 4. 合法地址:写配置 + 立即生效 ===')
|
||||
ent.delete(0, 'end')
|
||||
ent.insert(0, 'https://test.example.com/api/') # 结尾多余斜杠要去掉
|
||||
save_btn._command()
|
||||
root.update()
|
||||
srv = (SAVED.get('cfg') or {}).get('server', {})
|
||||
check('写回配置(去掉尾部斜杠)',
|
||||
srv.get('base_url') == 'https://test.example.com/api', str(srv))
|
||||
check('mock 置回 false', srv.get('mock') is False, str(srv.get('mock')))
|
||||
check('ApiClient 立即生效',
|
||||
app.engine.api.base_url == 'https://test.example.com/api',
|
||||
app.engine.api.base_url)
|
||||
check('页脚同步刷新',
|
||||
'test.example.com/api' in app.lbl_login_srv.cget('text'),
|
||||
app.lbl_login_srv.cget('text'))
|
||||
check('弹窗已关闭',
|
||||
not [w for w in root.winfo_children() if isinstance(w, tk.Toplevel)])
|
||||
|
||||
print('=== 5. 历史地址 ===')
|
||||
check('地址进 history 首位',
|
||||
(srv.get('history') or [])[:1] == ['https://test.example.com/api'],
|
||||
str(srv.get('history')))
|
||||
|
||||
print('=== 6. 再打开时预填新地址,旧地址进「用过」 ===')
|
||||
app._edit_server()
|
||||
root.update()
|
||||
dlg2 = [w for w in root.winfo_children() if isinstance(w, tk.Toplevel)][0]
|
||||
entries2 = []
|
||||
btns2 = []
|
||||
|
||||
|
||||
def walk2(w):
|
||||
for c in w.winfo_children():
|
||||
if isinstance(c, tk.Entry):
|
||||
entries2.append(c)
|
||||
if isinstance(c, TouchButton):
|
||||
btns2.append(c)
|
||||
walk2(c)
|
||||
|
||||
|
||||
walk2(dlg2)
|
||||
check('预填新地址', entries2[0].get() == 'https://test.example.com/api',
|
||||
entries2[0].get())
|
||||
if cur:
|
||||
chips = [b for b in btns2
|
||||
if b._text not in ('取消', '保存并应用', '测试连接')]
|
||||
check('有「用过」快捷按钮', bool(chips),
|
||||
str([b._text for b in btns2]))
|
||||
if chips:
|
||||
chips[0]._command() # 点一下应该把旧地址填回输入框
|
||||
root.update()
|
||||
check('点一下能切回旧地址',
|
||||
entries2[0].get().rstrip('/') == cur.rstrip('/'),
|
||||
entries2[0].get())
|
||||
else:
|
||||
print(' - 跳过「用过」校验(原配置没有地址)')
|
||||
dlg2.destroy()
|
||||
root.update()
|
||||
|
||||
print('=== 7. 写盘失败要回滚(磁盘满/文件被占用) ===')
|
||||
cur2 = app.cfg['server']['base_url']
|
||||
|
||||
|
||||
def boom(cfg, path='config.json'):
|
||||
raise IOError('模拟写盘失败')
|
||||
|
||||
|
||||
A.save_config = boom
|
||||
app._edit_server()
|
||||
root.update()
|
||||
dlg3 = [w for w in root.winfo_children() if isinstance(w, tk.Toplevel)][0]
|
||||
entries3 = []
|
||||
btns3 = []
|
||||
|
||||
|
||||
def walk3(w):
|
||||
for c in w.winfo_children():
|
||||
if isinstance(c, tk.Entry):
|
||||
entries3.append(c)
|
||||
if isinstance(c, TouchButton):
|
||||
btns3.append(c)
|
||||
walk3(c)
|
||||
|
||||
|
||||
walk3(dlg3)
|
||||
entries3[0].delete(0, 'end')
|
||||
entries3[0].insert(0, 'https://broken.example.com/api')
|
||||
[b for b in btns3 if b._text == '保存并应用'][0]._command()
|
||||
root.update()
|
||||
check('配置回滚', app.cfg['server']['base_url'] == cur2,
|
||||
app.cfg['server']['base_url'])
|
||||
check('ApiClient 回滚', app.engine.api.base_url == cur2,
|
||||
app.engine.api.base_url)
|
||||
check('弹窗不关(方便重试)',
|
||||
bool([w for w in root.winfo_children() if isinstance(w, tk.Toplevel)]))
|
||||
dlg3.destroy()
|
||||
|
||||
print('=== 8. 页脚布局:按钮不被地址挤掉 ===')
|
||||
root.deiconify() # 需要真实几何信息才能验布局
|
||||
root.update()
|
||||
foot = app.lbl_login_srv.master
|
||||
form = foot.master
|
||||
frow = [w for w in foot.winfo_children() if isinstance(w, tk.Frame)][0]
|
||||
edit_btn = [w for w in frow.winfo_children()
|
||||
if isinstance(w, tk.Button) and '修改' in str(w.cget('text'))][0]
|
||||
quit_btn = [w for w in frow.winfo_children()
|
||||
if isinstance(w, tk.Button) and '退出' in str(w.cget('text'))][0]
|
||||
root.update_idletasks()
|
||||
check('「修改服务器地址」没被裁切',
|
||||
edit_btn.winfo_width() >= edit_btn.winfo_reqwidth() - 1,
|
||||
'实际 %d / 需要 %d' % (edit_btn.winfo_width(),
|
||||
edit_btn.winfo_reqwidth()))
|
||||
check('「退出程序」没被裁切',
|
||||
quit_btn.winfo_width() >= quit_btn.winfo_reqwidth() - 1,
|
||||
'实际 %d / 需要 %d' % (quit_btn.winfo_width(),
|
||||
quit_btn.winfo_reqwidth()))
|
||||
check('两个按钮不重叠',
|
||||
edit_btn.winfo_x() + edit_btn.winfo_width() <= quit_btn.winfo_x(),
|
||||
'%d+%d vs %d' % (edit_btn.winfo_x(), edit_btn.winfo_width(),
|
||||
quit_btn.winfo_x()))
|
||||
check('地址行在按钮行上方(分两行)',
|
||||
app.lbl_login_srv.winfo_y() + app.lbl_login_srv.winfo_height()
|
||||
<= frow.winfo_y() + 1,
|
||||
'addr %d+%d, row %d' % (app.lbl_login_srv.winfo_y(),
|
||||
app.lbl_login_srv.winfo_height(),
|
||||
frow.winfo_y()))
|
||||
check('地址不超出行宽',
|
||||
app.lbl_login_srv.winfo_reqwidth() <= form.winfo_width(),
|
||||
'%d vs %d' % (app.lbl_login_srv.winfo_reqwidth(), form.winfo_width()))
|
||||
root.withdraw()
|
||||
|
||||
print('=== 9. 识别通道不继承系统代理(ProxyError 回归) ===')
|
||||
from core.recognition.cloud import CloudRecognizer
|
||||
from core.api.client import ApiClient, ApiError
|
||||
|
||||
c1 = CloudRecognizer({'vision': {'provider': 'doubao', 'api_key': 'k'},
|
||||
'account': {'role': 'inspector'}})
|
||||
check('默认直连(trust_env=False)', c1._session.trust_env is False,
|
||||
str(c1._session.trust_env))
|
||||
c2 = CloudRecognizer({'vision': {'provider': 'doubao', 'api_key': 'k',
|
||||
'trust_env': True},
|
||||
'account': {'role': 'inspector'}})
|
||||
check('配置可显式打开代理', c2._session.trust_env is True,
|
||||
str(c2._session.trust_env))
|
||||
|
||||
print('=== 10. 严格写入开关关闭时,提示要能指导现场 ===')
|
||||
api = ApiClient({'server': {'base_url': 'http://x', 'mock': False},
|
||||
'account': {}})
|
||||
api._request = lambda *a, **k: {'data': {
|
||||
'strict_capable': True, 'scope_token': 'tok',
|
||||
'strict_write_enabled': False}}
|
||||
try:
|
||||
api.preview_merge_scope('1', ['1'])
|
||||
msg = ''
|
||||
except ApiError as e:
|
||||
msg = str(e)
|
||||
check('提示包含处置办法', '管理员' in msg and '严格入库写入' in msg, msg)
|
||||
check('提示写明本次未提交', '未提交' in msg, msg)
|
||||
|
||||
print('=== 11. 服务端重量容差拒绝 → 提示要说清原因 ===')
|
||||
from core.flow import reject_hint
|
||||
|
||||
row30 = {'item_name': '苹果', 'unit': '斤', 'remaining_qty': 30}
|
||||
m = reject_hint('业务拒绝 400: {"error":"weigh_tolerance_exceeded"}', row30)
|
||||
check('提示含应量与单位', '30.00 斤' in m, m)
|
||||
check('提示说未入账', '未入账' in m, m)
|
||||
check('其他错误不瞎改',
|
||||
reject_hint('业务拒绝 400: {"error":"invalid_cost"}', row30) == '',
|
||||
reject_hint('业务拒绝 400: {"error":"invalid_cost"}', row30))
|
||||
|
||||
print('=== 12. 模拟称重量可给列表(一屏演示多种商品) ===')
|
||||
from core.scale.reader import sim_kg_of
|
||||
|
||||
check('单个数字', sim_kg_of(15.0, 3) == 15.0, sim_kg_of(15.0, 3))
|
||||
check('列表按轮次循环',
|
||||
[sim_kg_of([15, 6, 3], i) for i in range(4)]
|
||||
== [15.0, 6.0, 3.0, 15.0],
|
||||
[sim_kg_of([15, 6, 3], i) for i in range(4)])
|
||||
check('列表里 0/非法值被跳过', sim_kg_of([0, '3', None, 6], 0) == 3.0,
|
||||
sim_kg_of([0, '3', None, 6], 0))
|
||||
check('没配 = 不放货', sim_kg_of(None, 0) == 0.0)
|
||||
|
||||
print('=== 13. 回放摄像头(没相机时用真实商品图跑真识别) ===')
|
||||
import numpy as np
|
||||
from core.evidence.frames import FrameSource
|
||||
|
||||
fs = FrameSource({'camera': {'simulate': True, 'replay_dir': 'data/photos',
|
||||
'width': 1280, 'height': 720,
|
||||
'replay_hold_s': 1}})
|
||||
files = fs._replay_files()
|
||||
check('扫到回放图', len(files) >= 1, '%d 张' % len(files))
|
||||
fs.start()
|
||||
import time as _t
|
||||
_t.sleep(1.0)
|
||||
img, seq, _arr = fs.get_frame()
|
||||
check('回放画面尺寸正确',
|
||||
img is not None and img.shape == (720, 1280, 3),
|
||||
str(None if img is None else img.shape))
|
||||
check('回放画面不是空白占位',
|
||||
img is not None and float(np.std(img)) > 10,
|
||||
str(None if img is None else float(np.std(img))))
|
||||
check('帧序号在推进', seq > 0, str(seq))
|
||||
check('状态显示回放', '回放摄像头' in fs.preview_status(), fs.preview_status())
|
||||
fs.stop()
|
||||
_t.sleep(0.3)
|
||||
|
||||
check('不配 replay_dir 仍是合成画面',
|
||||
FrameSource({'camera': {'simulate': True}})._replay_files() == [])
|
||||
|
||||
print('=== 14. 模拟画面不得进样本库 ===')
|
||||
import core.recognition.dataset as DS
|
||||
|
||||
added = []
|
||||
|
||||
|
||||
class _FakeStore:
|
||||
def add(self, name, path, source='weak', was='', conf=None):
|
||||
added.append(name)
|
||||
return True
|
||||
|
||||
|
||||
DS.get_store = lambda *a, **k: _FakeStore()
|
||||
sim_cfg = {'flow': {}, 'camera': {'simulate': True}, 'scale': {},
|
||||
'vision': {}, 'server': {'mock': True}}
|
||||
simg = A.FlowEngine(sim_cfg, lambda e, p=None: None)
|
||||
simg._cycle_recog_path = 'data/photos/红富士苹果.png'
|
||||
simg._learn_sample({'item_name': '苹果'})
|
||||
check('模拟摄像头不存样本', not added, str(added))
|
||||
simg.cfg['camera']['simulate'] = False
|
||||
simg._learn_sample({'item_name': '苹果'})
|
||||
check('真实摄像头才存样本', added == ['苹果'], str(added))
|
||||
|
||||
print('=== 15. 分组行拆出原料/普通各自的量 ===')
|
||||
grouper = ApiClient({'server': {'base_url': 'http://x', 'mock': True},
|
||||
'account': {}})
|
||||
flat = [
|
||||
{'id': 'g1', 'item_name': '冬瓜', 'unit': '斤', 'remaining_qty': 12,
|
||||
'processing_details': {'independent_inbound': True}},
|
||||
{'id': 'g2', 'item_name': '冬瓜', 'unit': '斤', 'remaining_qty': 20},
|
||||
]
|
||||
groups = [{'inspection_ids': ['g1', 'g2'],
|
||||
'group_key': 'BR003|-|independent|purchase|SKU1|斤',
|
||||
'group_hash': 'h1', 'item_name': '冬瓜', 'unit': '斤',
|
||||
'total_prepare_qty': 32, 'lines': []}]
|
||||
rows = grouper._preview_group_rows(groups, flat)
|
||||
check('分组行算出来了', len(rows) == 1, str(len(rows)))
|
||||
parts = {p['kind']: p for p in (rows[0].get('group_parts') or [])}
|
||||
check('原料 12 斤', parts.get('independent', {}).get('qty') == 12.0,
|
||||
str(parts))
|
||||
check('普通 20 斤', parts.get('normal', {}).get('qty') == 20.0, str(parts))
|
||||
from core.matching.engine import is_independent_inbound as _is_indep
|
||||
check('混合组不能整组标成独立入库',
|
||||
not _is_indep(rows[0]),
|
||||
str(rows[0].get('processing_details')))
|
||||
|
||||
all_ind = [
|
||||
{'id': 'x1', 'unit': '斤', 'remaining_qty': 5,
|
||||
'processing_details': {'independent_inbound': True}},
|
||||
{'id': 'x2', 'unit': '斤', 'remaining_qty': 7,
|
||||
'processing_details': {'independent_inbound': True}},
|
||||
]
|
||||
rows2 = grouper._preview_group_rows(
|
||||
[{'inspection_ids': ['x1', 'x2'],
|
||||
'group_key': 'BR003|-|independent|purchase|SKU2|斤',
|
||||
'group_hash': 'h2', 'item_name': '南瓜', 'unit': '斤'}], all_ind)
|
||||
check('全原料组仍标记独立入库',
|
||||
_is_indep(rows2[0]), str(rows2[0].get('processing_details')))
|
||||
|
||||
print('=== 16. 卡片黄底提示文案 ===')
|
||||
check('混合:分开写两边',
|
||||
app._indep_badge_text(rows[0]) == '独立入库原料 12 斤 · 普通入库 20 斤',
|
||||
app._indep_badge_text(rows[0]))
|
||||
check('全原料:保持原文案',
|
||||
app._indep_badge_text(rows2[0]) == '独立入库 · 加工原材料',
|
||||
app._indep_badge_text(rows2[0]))
|
||||
check('全普通:不显示',
|
||||
app._indep_badge_text({'group_parts': [{'kind': 'normal',
|
||||
'qty': 32}],
|
||||
'unit': '斤'}) == '',
|
||||
app._indep_badge_text({'group_parts': [{'kind': 'normal',
|
||||
'qty': 32}], 'unit': '斤'}))
|
||||
check('无明细时回退旧判断(普通行不显示)',
|
||||
app._indep_badge_text({'item_name': '冬瓜', 'unit': '斤'}) == '',
|
||||
app._indep_badge_text({'item_name': '冬瓜', 'unit': '斤'}))
|
||||
|
||||
print('=== 17. 待办列表左右滑动翻页 ===')
|
||||
app._page_count = 3
|
||||
app._page = 1
|
||||
app._layout_cards = lambda: None
|
||||
|
||||
|
||||
def _ev(x, y):
|
||||
return type('E', (), {'x_root': x, 'y_root': y})()
|
||||
|
||||
|
||||
app._swipe_press(_ev(600, 300))
|
||||
app._swipe_move(_ev(520, 302))
|
||||
app._swipe_release(_ev(510, 302))
|
||||
check('左划 → 下一页', app._page == 2, str(app._page))
|
||||
|
||||
app._swipe_press(_ev(500, 300))
|
||||
app._swipe_move(_ev(600, 300))
|
||||
app._swipe_release(_ev(620, 300))
|
||||
check('右划 → 上一页', app._page == 1, str(app._page))
|
||||
|
||||
app._swipe_press(_ev(600, 300))
|
||||
app._swipe_move(_ev(605, 400))
|
||||
app._swipe_release(_ev(605, 420))
|
||||
check('竖向拖动不翻页', app._page == 1, str(app._page))
|
||||
|
||||
app._swipe_press(_ev(600, 300))
|
||||
app._swipe_move(_ev(560, 300))
|
||||
app._swipe_release(_ev(555, 300))
|
||||
check('横向位移不够不翻页', app._page == 1, str(app._page))
|
||||
|
||||
app._page_count = 1
|
||||
app._page = 0
|
||||
app._swipe_press(_ev(600, 300))
|
||||
app._swipe_move(_ev(400, 300))
|
||||
app._swipe_release(_ev(380, 300))
|
||||
check('只有一页时不翻', app._page == 0, str(app._page))
|
||||
|
||||
print('=== 18. 顶栏/窗口标题按工位改名 ===')
|
||||
check('分拣工位叫「分拣工作站」',
|
||||
app._station_title('picking') == '分拣工作站',
|
||||
app._station_title('picking'))
|
||||
check('入库工位叫「入库工作站」',
|
||||
app._station_title('inspection') == '入库工作站',
|
||||
app._station_title('inspection'))
|
||||
app.engine.station = 'picking'
|
||||
app._paint_station()
|
||||
check('窗口标题跟着变', app.root.title() == '分拣工作站', app.root.title())
|
||||
|
||||
print('=== 19. 卡片高亮:不抖 + 不同时亮两张 ===')
|
||||
# 把登录页换掉,真正建一次作业界面。
|
||||
# 必须 deiconify:窗口 withdraw 时 canvas 宽只有 1px,_layout_cards 直接
|
||||
# return,卡片根本没摆上,下面那些「几何没变」的断言会空过(踩过)。
|
||||
for _w in list(root.winfo_children()):
|
||||
_w.destroy()
|
||||
# 第 17 组把 _layout_cards 换成了空函数(测翻页时不想重排),这里恢复真方法
|
||||
try:
|
||||
del app._layout_cards
|
||||
except AttributeError:
|
||||
pass
|
||||
app.engine.station = 'picking'
|
||||
app.engine.logged_in = True
|
||||
app.ready = True
|
||||
root.deiconify()
|
||||
try:
|
||||
root.geometry('1400x820+20+20')
|
||||
except Exception:
|
||||
pass
|
||||
root.update()
|
||||
app._build()
|
||||
root.update()
|
||||
frows = [{'id': 'c%d' % i, 'item_name': n, 'unit': '个', 'remaining_qty': 2,
|
||||
'customer_name': '富顺分公司', 'order_code': 'O%d' % i}
|
||||
for i, n in enumerate(['虾皮', '绿豆', '盐', '花椒'])]
|
||||
app.engine.rows = [dict(r) for r in frows]
|
||||
app._fill_todo(frows)
|
||||
root.update()
|
||||
|
||||
gridded = [c for c in app.todo_cards.values() if c.winfo_manager() == 'grid']
|
||||
check('卡片真的摆上了(不是空跑)', len(gridded) >= 2, str(len(gridded)))
|
||||
check('画布有真实宽度', app.todo_canvas.winfo_width() > 400,
|
||||
str(app.todo_canvas.winfo_width()))
|
||||
check('所有卡边框厚度统一',
|
||||
{c.cget('highlightthickness') for c in app.todo_cards.values()}
|
||||
== {A.CARD_HL},
|
||||
str({c.cget('highlightthickness') for c in app.todo_cards.values()}))
|
||||
check('高亮样式是纯颜色', isinstance(app._card_style('c1'), str),
|
||||
str(type(app._card_style('c1'))))
|
||||
|
||||
|
||||
def _positions():
|
||||
return {r: (c.winfo_x(), c.winfo_y(), c.winfo_width(),
|
||||
c.winfo_height(), c.grid_info().get('row'),
|
||||
c.grid_info().get('column'))
|
||||
for r, c in app.todo_cards.items()}
|
||||
|
||||
|
||||
# 点一张 → 只有它亮,位置/尺寸不动
|
||||
p_before = _positions()
|
||||
app._pre_rid = None
|
||||
app._sel_rid = 'c1'
|
||||
app._repaint_cards(['c1'])
|
||||
root.update()
|
||||
p_after = _positions()
|
||||
check('选中不改变卡片几何', p_before == p_after,
|
||||
str({k: (p_before[k], p_after[k]) for k in p_after
|
||||
if p_before[k] != p_after[k]}))
|
||||
check('选中不改边框粗细',
|
||||
{c.cget('highlightthickness') for c in app.todo_cards.values()}
|
||||
== {A.CARD_HL},
|
||||
str({c.cget('highlightthickness') for c in app.todo_cards.values()}))
|
||||
|
||||
# 高亮只跟手点那张走(现场:亮盐、详情却是刚点的腐竹)
|
||||
app._pre_rid = 'c0'
|
||||
app._sel_rid = 'c2'
|
||||
app._repaint_cards(['c0', 'c1', 'c2', 'c3'])
|
||||
root.update()
|
||||
lit = {r: c for r, c in app._paint_cache.items() if c != A.C.line}
|
||||
check('高亮跟最后点过的那张走', set(lit) == {'c2'}, str(lit))
|
||||
|
||||
# 连点两张:先点那张的 preselect 事件晚到,不能把高亮挪回去
|
||||
app.engine.state = 'IDLE'
|
||||
app._pre_rid = None
|
||||
app._sel_rid = None
|
||||
app._repaint_cards(['c0', 'c1', 'c2', 'c3'])
|
||||
app._select_card('c0')
|
||||
app._select_card('c1')
|
||||
app._on_preselect('c0') # 迟到的旧事件
|
||||
root.update()
|
||||
lit = {r: c for r, c in app._paint_cache.items() if c != A.C.line}
|
||||
check('迟到的预选事件不挪高亮', set(lit) == {'c1'}, str(lit))
|
||||
|
||||
# 非待机态点卡:引擎不收预选,但高亮仍跟着手点走(只能一张)
|
||||
app.engine.state = 'WEIGHING'
|
||||
app.engine._pre_pick_rid = 'c0' # 引擎真正记着的预选
|
||||
app._pre_rid = 'c0'
|
||||
app._sel_rid = None
|
||||
app._repaint_cards(['c0', 'c1', 'c2', 'c3'])
|
||||
app._select_card('c2')
|
||||
root.update()
|
||||
lit = {r: c for r, c in app._paint_cache.items() if c != A.C.line}
|
||||
check('非待机态点卡也只亮手点那张', set(lit) == {'c2'}, str(lit))
|
||||
app.engine.state = 'IDLE'
|
||||
app.engine._pre_pick_rid = None
|
||||
|
||||
# 引擎接管确认行 → 旧琥珀被清掉,只剩一张绿的
|
||||
app._pre_rid = 'c1'
|
||||
app._sel_rid = 'c1'
|
||||
app._repaint_cards(['c0', 'c1', 'c2', 'c3'])
|
||||
root.update()
|
||||
p2 = _positions()
|
||||
app._on_focus({'row_id': 'c3', 'mode': 'weigh'})
|
||||
root.update()
|
||||
lit = {r: c for r, c in app._paint_cache.items() if c != A.C.line}
|
||||
check('确认时只剩一张高亮', len(lit) == 1 and 'c3' in lit, str(lit))
|
||||
check('旧的手动选中已清', app._sel_rid is None, str(app._sel_rid))
|
||||
check('旧的预选已清', app._pre_rid is None, str(app._pre_rid))
|
||||
p3 = _positions()
|
||||
check('确认行高亮不引起抖动', p2 == p3,
|
||||
str({k: (p2[k], p3[k]) for k in p3 if p2[k] != p3[k]}))
|
||||
check('确认行高亮不改边框粗细',
|
||||
{c.cget('highlightthickness') for c in app.todo_cards.values()}
|
||||
== {A.CARD_HL},
|
||||
str({c.cget('highlightthickness') for c in app.todo_cards.values()}))
|
||||
|
||||
print('=== 20. 分页不裁最底行(徽标只在后面几页) ===')
|
||||
rows2 = []
|
||||
_names = ['尖白菜', '仔姜', '四季豆', '莲花白', '大白菜', '大葱']
|
||||
for _i in range(24):
|
||||
rows2.append({
|
||||
'id': 'p%02d' % _i,
|
||||
'item_name': _names[_i % len(_names)],
|
||||
'unit': '斤',
|
||||
'remaining_qty': 5 + _i,
|
||||
'customer_name': '富顺分公司',
|
||||
# 第一页没有徽标(卡矮),后面几页有(卡高)——现场就是这个组合
|
||||
'independent_inbound': (_i >= 12),
|
||||
})
|
||||
app.engine.rows = [dict(r) for r in rows2]
|
||||
app._fill_todo(rows2)
|
||||
root.update()
|
||||
time.sleep(0.25)
|
||||
root.update()
|
||||
|
||||
cv = app.todo_canvas
|
||||
worst = []
|
||||
for _pg in range(max(1, getattr(app, '_page_count', 1))):
|
||||
inside = [c for c in app.todo_cards.values()
|
||||
if c.winfo_manager() == 'grid']
|
||||
for c in inside:
|
||||
over = (c.winfo_y() + c.winfo_height()) - cv.winfo_height()
|
||||
if over > 0:
|
||||
worst.append((_pg + 1, c.winfo_y(), c.winfo_height(), over))
|
||||
app._page_turn(1)
|
||||
root.update()
|
||||
check('每一页卡片都在视口内(不被裁)', not worst,
|
||||
'超出:%r' % worst[:4])
|
||||
check('多页时页码正常', getattr(app, '_page_count', 1) > 1,
|
||||
getattr(app, '_page_count', 1))
|
||||
|
||||
root.destroy()
|
||||
print('\n结果:%d 项通过,%d 项失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,115 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""v1.0.67 回归:偏差入库/短收结案必须强制结束加工原料采购批次
|
||||
|
||||
现场(2026-11-12 BR002):
|
||||
加工原料采购 RAW1794471013693YTMD4K 计划 17 斤,偏差入库实收 15.94。
|
||||
Windows 只传了 force_complete=true,服务端仍生成 1.06 斤续验单;
|
||||
第二次称 18.22 斤打到续验单,最终采购累计 34.16 斤 / 27.33 元。
|
||||
根因:Windows 未同步服务端 2026-11-10 的 force_close_raw_batch 契约。
|
||||
|
||||
本文件锁死:
|
||||
1. 分组偏差结案请求体同时含 force_complete=true + force_close_raw_batch=true
|
||||
2. 普通整组入库不带 force_close_raw_batch
|
||||
3. 严格单行/独立单行路径同样透传
|
||||
4. 网络未连接重试路径不丢字段
|
||||
5. 源码分支:group / independent / strict 主路径和重试路径都接上
|
||||
"""
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
|
||||
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.api.client import ApiClient
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
print(' ✔ %s' % name)
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✘ %s %s' % (name, extra))
|
||||
|
||||
|
||||
CFG = {'server': {'base_url': 'http://127.0.0.1:3001/api', 'mock': False},
|
||||
'account': {'username': 'demo', 'role': 'inspector'},
|
||||
'flow': {'group_inbound': True, 'short_close_pct': 20,
|
||||
'short_close_max_qty': 3}}
|
||||
|
||||
# ── ApiClient 请求体 ────────────────────────────────────────────────
|
||||
calls = []
|
||||
|
||||
|
||||
def fake_request(method, path, body=None, **kw):
|
||||
calls.append((method, path, body or {}))
|
||||
if path.endswith('/complete-merge-group'):
|
||||
return {'success': True, 'data': {'merged': True, 'mergedCount': 1}}
|
||||
if path.endswith('/complete'):
|
||||
return {'success': True, 'data': {'result': {'effect': 'independent_inbound'}}}
|
||||
return {'success': True, 'data': {'result': {'effect': 'force_completed'}},
|
||||
'operation_status': 'committed_by_this_operation'}
|
||||
|
||||
|
||||
api = ApiClient(CFG)
|
||||
api._request = fake_request
|
||||
group_row = {'inspection_ids': ['ins-1'], 'group_key': 'g', 'group_hash': 'h',
|
||||
'item_name': '尖白菜', 'unit': '斤', 'required_qty': 17}
|
||||
|
||||
calls.clear()
|
||||
api.commit_inspection_group(group_row, 15.94, 7.97, 'op-g',
|
||||
force_complete=True, force_close_raw_batch=True)
|
||||
body = calls[-1][2]
|
||||
check('分组偏差结案 path', calls[-1][1] == '/mobile/inspection/complete-merge-group')
|
||||
check('分组偏差结案 force_complete=true', body.get('force_complete') is True, body)
|
||||
check('分组偏差结案 force_close_raw_batch=true', body.get('force_close_raw_batch') is True, body)
|
||||
|
||||
calls.clear()
|
||||
api.commit_inspection_group(group_row, 17.0, 8.5, 'op-g2',
|
||||
force_complete=False, force_close_raw_batch=False)
|
||||
body = calls[-1][2]
|
||||
check('普通整组不带 force_complete', 'force_complete' not in body, body)
|
||||
check('普通整组不带 force_close_raw_batch', 'force_close_raw_batch' not in body, body)
|
||||
|
||||
calls.clear()
|
||||
api.commit_inspection([{'id': 'ins-1'}], 15.94, 7.97, 'op-s',
|
||||
scope_token='scope-1', force_complete=True)
|
||||
body = calls[-1][2]
|
||||
check('严格单行不传 force_close_raw_batch(端点不支持)',
|
||||
'force_close_raw_batch' not in body, body)
|
||||
check('严格单行 force_complete 保留', body.get('force_complete') is True, body)
|
||||
|
||||
calls.clear()
|
||||
api.commit_inspection_single({'id': 'ins-1', 'unit': '斤',
|
||||
'processing_details': {'independent_inbound': True}},
|
||||
15.94, 7.97, 'op-i',
|
||||
force_complete=True, force_close_raw_batch=True)
|
||||
body = calls[-1][2]
|
||||
check('独立单行请求体 force_close_raw_batch=true', body.get('force_close_raw_batch') is True, body)
|
||||
check('独立单行请求体 force_complete=true', body.get('force_complete') is True, body)
|
||||
|
||||
calls.clear()
|
||||
api.commit_inspection_single({'id': 'ins-1', 'unit': '斤'}, 3.0, 1.5, 'op-i2')
|
||||
body = calls[-1][2]
|
||||
check('普通独立单行不带 force_close_raw_batch', 'force_close_raw_batch' not in body, body)
|
||||
|
||||
# ── Flow 主分支/重试分支字段 ────────────────────────────────────────
|
||||
src = open('core/flow.py', encoding='utf-8').read()
|
||||
check('group 主分支传 force_close_raw_batch=force',
|
||||
'force_complete=force,\n force_close_raw_batch=force,' in src)
|
||||
check('independent 主分支传 force_close_raw_batch=force',
|
||||
"force_complete=force,\n force_close_raw_batch=force)" in src)
|
||||
check('group 重试分支传 force_close_raw_batch=force_retry',
|
||||
'force_complete=force_retry,\n force_close_raw_batch=force_retry,' in src)
|
||||
check('independent 重试分支传 force_close_raw_batch=force_retry',
|
||||
'force_complete=force_retry,\n force_close_raw_batch=force_retry)' in src)
|
||||
check('严格路径不携带 force_close_raw_batch',
|
||||
'scope_token=scope[\'scope_token\'],\n force_complete=force)' in src)
|
||||
|
||||
|
||||
print('\n%d 过 / %d 挂' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,67 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""v1.0.68 回归:本轮没认出来,确认页不得显示上一件的「已识别」
|
||||
|
||||
现场反馈:Windows 称重台明明没有识别到,界面却显示已识别到上一件商品,
|
||||
还让人再确认一眼。
|
||||
|
||||
根因:`_cycle_detected` 只在启动时初始化,新一轮识别失败时没有清空;
|
||||
`_to_manual(None, [])` -> `_to_focus(row=None, detected=None)` 会回退
|
||||
上一轮的 `_cycle_detected`,于是把上一件的品名带进确认页。
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
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
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
print(' ✓', name)
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✗', name, extra)
|
||||
|
||||
|
||||
def bare_engine():
|
||||
"""只搭 `_to_focus` 需要的属性,不连设备、不起线程。"""
|
||||
e = object.__new__(FlowEngine)
|
||||
e._aborted = False
|
||||
e._running = True
|
||||
e._focus = None
|
||||
e._frozen_row = None
|
||||
e._frozen_kg = 0.0
|
||||
e._cycle_detected = '香菇' # 上一轮残留
|
||||
e._cycle_recog_path = None
|
||||
e._count_mode = False
|
||||
e._count_qty = 0.0
|
||||
e._focus_payload = lambda: dict(e._focus or {})
|
||||
e._snap_scale_kg = lambda: 0.0
|
||||
e._set_state = lambda _s: None
|
||||
e.emit = lambda *a, **k: None
|
||||
return e
|
||||
|
||||
|
||||
print('A 没有命中行 + 上一轮残留品名 => 确认页不得显示该品名')
|
||||
e = bare_engine()
|
||||
e._to_focus(None, 0.0, detected=None, conf=None, mode='count')
|
||||
f = e._focus or {}
|
||||
check('detected 为空,而不是上一轮的「香菇」',
|
||||
str(f.get('detected') or '') == '', repr(f.get('detected')))
|
||||
check('row_id 为空', f.get('row_id') is None)
|
||||
|
||||
print('B 有命中行时仍保留本轮识别名(不误伤正常路径)')
|
||||
e = bare_engine()
|
||||
row = {'id': 'r1', 'item_name': '青笋', 'unit': '斤'}
|
||||
e._cycle_detected = ''
|
||||
e._to_focus(row, 5.0, detected='青笋', conf=90, mode='count')
|
||||
check('命中行保留 detected', (e._focus or {}).get('detected') == '青笋')
|
||||
|
||||
print('\n结果:%d 通过 / %d 失败' % (ok, fail))
|
||||
sys.exit(0 if fail == 0 else 1)
|
||||
@@ -0,0 +1,170 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""本地后台留档、云端独立返回和本地模型兼容性回归。"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
|
||||
import numpy as np
|
||||
import cv2
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from core.flow import FlowEngine
|
||||
from core.recognition.assist import Assist
|
||||
from core.recognition.local_cls import LocalClassifier, letterbox
|
||||
from core.recognition.cloud import RecognitionError
|
||||
|
||||
ok = fail = 0
|
||||
|
||||
|
||||
def check(name, cond, extra=''):
|
||||
global ok, fail
|
||||
if cond:
|
||||
ok += 1
|
||||
print(' ✓', name)
|
||||
else:
|
||||
fail += 1
|
||||
print(' ✗', name, extra)
|
||||
|
||||
|
||||
TMP = tempfile.mkdtemp(prefix='assist_')
|
||||
|
||||
|
||||
def snapshot(tag='a'):
|
||||
"""造一张真图:记录里要算 sha/mtime,路径必须在磁盘上真的存在。"""
|
||||
p = os.path.join(TMP, 'snap_%s.jpg' % tag)
|
||||
cv2.imwrite(p, np.full((72, 160, 3), 90, np.uint8))
|
||||
return p
|
||||
|
||||
|
||||
def yolo_of(name, prob, top=None):
|
||||
return {'name': name, 'prob': prob,
|
||||
'top': top or [[name, prob]],
|
||||
'all_top': [[name, prob]],
|
||||
'covered': 3, 'ms': 12, 'imgsz': 320}
|
||||
|
||||
|
||||
class FakeRecog:
|
||||
def __init__(self, info=None, err=None):
|
||||
self.info = dict(info if info is not None else
|
||||
{'name': '苹果', 'conf': 88, 'alt': '',
|
||||
'alt_conf': None, 'prompt_tag': 'cloud'})
|
||||
self.err = err
|
||||
self.calls = 0
|
||||
|
||||
def identify_ex(self, path, names, timeout=None):
|
||||
self.calls += 1
|
||||
if self.err:
|
||||
raise self.err
|
||||
return dict(self.info)
|
||||
|
||||
|
||||
def cfg_of(assist=None):
|
||||
a = {'enabled': True, 'journal_dir': os.path.join(TMP, 'journal')}
|
||||
a.update(assist or {})
|
||||
return {'flow': {'recognize_timeout': 8, 'confirm_before_submit': False},
|
||||
'vision': {'assist': a},
|
||||
'camera': {'simulate': False}}
|
||||
|
||||
|
||||
def engine(cfg, recog=None, yolo=None, img=None):
|
||||
e = object.__new__(FlowEngine)
|
||||
e.cfg = cfg
|
||||
e.assist = Assist(cfg)
|
||||
e.recog = recog or FakeRecog()
|
||||
e.station = 'loading'
|
||||
e._frozen_kg = 2.8
|
||||
e._cycle_recog_path = img
|
||||
e._focus = None
|
||||
e._assist_pending = None
|
||||
e._aborted = False
|
||||
e._running = True
|
||||
e.inbound_auto_submit = True
|
||||
e.logs = []
|
||||
e.emit = lambda ev, p=None: e.logs.append((ev, p))
|
||||
if yolo is not None:
|
||||
e.assist.local.predict = lambda *a, **k: dict(yolo)
|
||||
return e
|
||||
|
||||
|
||||
img = snapshot('parallel')
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def blocked_local(*args, **kwargs):
|
||||
started.set()
|
||||
if not release.wait(3):
|
||||
raise RuntimeError('等待测试释放')
|
||||
return yolo_of('香蕉', 0.999)
|
||||
|
||||
e = engine(cfg_of())
|
||||
e.assist.local.predict = blocked_local
|
||||
original_cloud = e.recog.identify_ex
|
||||
def cloud_while_local_runs(*args, **kwargs):
|
||||
check('云端调用时本地已经开始', started.wait(2))
|
||||
return original_cloud(*args, **kwargs)
|
||||
e.recog.identify_ex = cloud_while_local_runs
|
||||
answer = e._recognize_cycle(img, ['苹果', '香蕉'])
|
||||
first = e._assist_pending
|
||||
try:
|
||||
check('本地未完成,云端仍已返回', not first['local'].done() and answer['name'] == '苹果')
|
||||
check('下一件不会积压本地推理', e._recognize_cycle(img, ['苹果'])['name'] == '苹果'
|
||||
and e._assist_pending['local'].result(2)['status'] == 'busy')
|
||||
finally:
|
||||
release.set()
|
||||
check('后台留档保留不同的本地结果', first['local'].result(2)['name'] == '香蕉')
|
||||
check('云端正常记录', first['cloud']['status'] == 'recognized')
|
||||
|
||||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(err=RecognitionError('failed')))
|
||||
try:
|
||||
e._recognize_cycle(img, ['苹果'])
|
||||
except RecognitionError:
|
||||
check('云端失败保留原有人工处理路径', e._assist_pending['cloud']['status'] == 'unavailable')
|
||||
else:
|
||||
check('云端失败不以本地结果代替', False)
|
||||
check('本地高分也没有跳过云端', e.recog.calls == 1)
|
||||
check('人工确认仍为必需', e.confirm_before_submit())
|
||||
e = engine(cfg_of(), yolo=yolo_of('苹果', 0.999), recog=FakeRecog(info={'name': ''}))
|
||||
check('云端未命中时不回退到本地', not e._recognize_cycle(img, ['苹果']).get('name'))
|
||||
check('云端未命中有独立状态', e._assist_pending['cloud']['status'] == 'no_match')
|
||||
|
||||
print('G 本地分类器:没模型 = 没意见,绝不抛异常')
|
||||
lc = LocalClassifier({'assist': {'model': 'no/such.onnx',
|
||||
'classes': 'no/such.json'}})
|
||||
check('available() 为假', lc.available() is False)
|
||||
check('reason() 说得出原因', bool(lc.reason()))
|
||||
check('predict 返回空 dict', lc.predict(img, ['苹果']) == {})
|
||||
check('空路径直接返回空', lc.predict('', ['苹果']) == {})
|
||||
a = Assist(cfg_of({'model': 'no/such.onnx', 'classes': 'no/such.json'}))
|
||||
check('建议模式里 local_suggest 同样返回 None',
|
||||
a.local_suggest(img, ['苹果']) is None)
|
||||
|
||||
# 装到中文目录(D:\嵌入式识别\... / 入库分拣工作台\...)时,cv2.dnn 用「路径」
|
||||
# 读 onnx 会直接报 Can't read ONNX file;必须是读字节再喂。这条断言防回退。
|
||||
_lc_src = open(os.path.join('core', 'recognition', 'local_cls.py'),
|
||||
encoding='utf-8').read()
|
||||
check('onnx 走字节缓冲读取(中文路径也能加载)',
|
||||
'readNetFromONNX(buf)' in _lc_src)
|
||||
|
||||
# ultralytics 训分类的预处理是 Resize→CenterCrop→ToTensor→Normalize(0,1),
|
||||
# Normalize 那步等于空操作,也就是**只有 /255**。端上如果再多减一组 ImageNet
|
||||
# 的 mean/std,输入分布就和训练时差一截:实测 123 张测试图,减 mean/std 时
|
||||
# cv2.dnn 只对 13 张(10.6%),只做 /255 时和 torch 123/123 一致。
|
||||
# 这类错不报错、只静默掉准确率,必须用断言锁住。
|
||||
check('前处理只做 /255,没有多余的 ImageNet 归一化',
|
||||
'0.485' not in _lc_src and '0.229' not in _lc_src)
|
||||
check('前处理确实是 BGR→RGB + /255', '/ 255.0' in _lc_src)
|
||||
|
||||
print('H letterbox:只加边不丢内容(训练/推理共用同一口径)')
|
||||
src = np.full((72, 160, 3), 200, np.uint8)
|
||||
out = letterbox(src, 320)
|
||||
check('输出是 320×320×3', out.shape == (320, 320, 3), str(out.shape))
|
||||
check('左上角是补的灰 114', int(out[0, 0, 0]) == 114)
|
||||
check('中间还是原图(200)', int(out[160, 160, 0]) == 200)
|
||||
check('等比:宽占满、高补边', int(out[160, 2, 0]) == 200)
|
||||
|
||||
print()
|
||||
print('通过 %d,失败 %d' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -0,0 +1,329 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「点商品名,界面抖一下」的回归自检(v1.0.75)
|
||||
|
||||
现场反馈:在称重页点大葱/小葱那张卡,界面看着抖。
|
||||
|
||||
实测(见 _merge_audit/probe_jitter.py、probe_frames.py):
|
||||
· 点一下**不翻页、不滚动**,每张卡的 x/y/宽/高 一个像素都没动;
|
||||
· 真正变的是两张卡「整块粉底 + 红框」在同一帧里互换 —— 190×121 ×2
|
||||
约 46000 像素的大色块跳到另一张卡上,眼睛读成「闪/抖」;
|
||||
· 还有一处隐患:highlightthickness 算进 Tk 的请求尺寸,反复写它会让
|
||||
grid 重算列宽(实测出现过 182/198 → 190 的整屏重分配)。
|
||||
|
||||
v1.0.75 的改法:高亮只换 4px 边框色 + 数量数字变红(整卡粉底要
|
||||
ui.focus_fill=true 才画),并且颜色没变就一个 configure 都不发;
|
||||
_on_focus 里要撤的琥珀框和「旧/新确认行」合成一次 _repaint_cards。
|
||||
|
||||
这个脚本把上面的结论钉成断言,以后谁往点击路径里塞会改几何的东西
|
||||
(wraplength、字号、padding、columnconfigure、highlightthickness…),
|
||||
跑一下就能看见。用法:
|
||||
|
||||
python tools/_ui_jitter_check.py # 全过 → 退出码 0
|
||||
|
||||
断言(点两张同页的卡,来回点 3 次):
|
||||
1. 每张卡的 x/y/宽/高 全程不变(不重排、不翻页);
|
||||
2. 点击过程中**一次几何跳变都没有**(含跳走又跳回的);
|
||||
3. grid 的列宽约束(minsize/weight/uniform)全程不变;
|
||||
4. 一次点击最多重画 2 张卡,_repaint_cards 只被调用 1 次。
|
||||
|
||||
为什么 3 也要盯:v1.0.75 查到根因就是「列宽不统一」。点一下卡只是改
|
||||
Frame 的 highlightbackground(纯颜色),Tk 却会把那张卡的请求宽度算成
|
||||
198,grid 一发现总宽超了就把别的列从 190 压到 182,下次 idle 再排回
|
||||
190 —— 实测 15ms 内整屏 8 张卡跳 64 次,肉眼看就是「抖」。
|
||||
_layout_cards 里给列加上 uniform='cf'(所有列必须一样宽)后归零。
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import tkinter as tk
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, ROOT)
|
||||
os.chdir(ROOT)
|
||||
|
||||
from ui import app as A # noqa: E402
|
||||
|
||||
BASE = json.load(open(os.path.join(ROOT, 'data', '_diag', 'demo_config.json'),
|
||||
encoding='utf-8'))
|
||||
BASE.setdefault('ui', {})
|
||||
BASE['ui'].update({'mode': 'window', 'fit_screen': False,
|
||||
'borderless': False, 'todo_thumb': False,
|
||||
'width': 1440, 'height': 900})
|
||||
A.load_config = lambda path='config.json', _c=BASE: _c
|
||||
|
||||
FAILS = []
|
||||
|
||||
|
||||
def check(ok, what, detail=''):
|
||||
print(' %s %s%s' % ('OK ' if ok else 'FAIL', what,
|
||||
(' ← ' + detail) if (detail and not ok) else ''))
|
||||
if not ok:
|
||||
FAILS.append(what)
|
||||
|
||||
|
||||
# ---------------- 起界面(和 _ui_offline_check 同一套假秤假相机) ----------
|
||||
root = tk.Tk()
|
||||
app = A.App(root)
|
||||
root.geometry('1440x900+0+0')
|
||||
app._login_user = '演示账号'
|
||||
app._login_pwd = '123456'
|
||||
app.engine.login()
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
root.update()
|
||||
if app.ready:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def spin(sec):
|
||||
t = time.time()
|
||||
while time.time() - t < sec:
|
||||
root.update()
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def wait_state(want, timeout=25.0):
|
||||
t = time.time()
|
||||
while time.time() - t < timeout:
|
||||
root.update()
|
||||
if app.engine.state == want:
|
||||
return True
|
||||
time.sleep(0.03)
|
||||
return False
|
||||
|
||||
|
||||
if not wait_state('CONFIRM', 25):
|
||||
print('FAIL 没等到 CONFIRM 态(当前 %s),无法自检'
|
||||
% getattr(app.engine, 'state', '?'))
|
||||
try:
|
||||
app.engine.stop()
|
||||
except Exception:
|
||||
pass
|
||||
root.destroy()
|
||||
sys.exit(1)
|
||||
spin(1.0) # 让第一批卡画完、Tk 把请求尺寸算完
|
||||
|
||||
# ---------------- 计量工具 ----------------
|
||||
EVT = [] # 点击窗口内收到的 <Configure>(路径名)
|
||||
TRANS = [] # 其中「几何真变了」的瞬时跳变(含跳回去的)
|
||||
LAST = {} # id(控件) → (路径, 上次几何)
|
||||
FAILS = FAILS # 复用上面的失败清单
|
||||
|
||||
|
||||
def _g(w):
|
||||
return (w.winfo_x(), w.winfo_y(), w.winfo_width(), w.winfo_height())
|
||||
|
||||
|
||||
def _walk(w, depth=0):
|
||||
if depth > 4:
|
||||
return
|
||||
for ch in w.winfo_children():
|
||||
yield ch
|
||||
for x in _walk(ch, depth + 1):
|
||||
yield x
|
||||
|
||||
|
||||
def on_cfg(w):
|
||||
"""计数,并按 id(控件) 比对上一次几何 —— 只数事件会漏掉「跳走又跳回」
|
||||
|
||||
用路径名当 key 会串味:卡片被销毁重建时 Tk 会复用 !frame38 这类名字,
|
||||
新控件和老控件的老几何就对不上了,会报出假的 190→198。
|
||||
"""
|
||||
EVT.append(str(w))
|
||||
try:
|
||||
now = _g(w)
|
||||
except Exception:
|
||||
return
|
||||
k = id(w)
|
||||
prev = LAST.get(k)
|
||||
LAST[k] = (str(w), now)
|
||||
if prev is not None and prev[1] != now:
|
||||
TRANS.append((str(w).split('.')[-1], prev[1], now))
|
||||
|
||||
|
||||
def hook(w, depth=0):
|
||||
if depth > 4:
|
||||
return
|
||||
try:
|
||||
w.bind('<Configure>', lambda e, w=w: on_cfg(w), add='+')
|
||||
except Exception:
|
||||
return
|
||||
for ch in w.winfo_children():
|
||||
hook(ch, depth + 1)
|
||||
|
||||
|
||||
for _c in app.todo_cards.values():
|
||||
hook(_c)
|
||||
|
||||
|
||||
def snap():
|
||||
"""屏上所有卡的每个控件:路径 → (控件id, x, y, 宽, 高)
|
||||
|
||||
点前点后各取一份,比出「真的动了」的那些 —— 这才是肉眼看到的抖。
|
||||
用路径名当 key:控件被销毁重建会换 id,也能看出来。
|
||||
"""
|
||||
out = {}
|
||||
for rid, c in app.todo_cards.items():
|
||||
try:
|
||||
for w in [c] + list(_walk(c)):
|
||||
out[(str(rid), str(w).split('.')[-1])] = (id(w),) + _g(w)
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def diff(a, b):
|
||||
out = {}
|
||||
for k in set(a) & set(b):
|
||||
if a[k] != b[k]:
|
||||
out[k] = (a[k], b[k])
|
||||
for k in set(a) - set(b):
|
||||
out[k] = (a[k], '没了')
|
||||
for k in set(b) - set(a):
|
||||
out[k] = ('新增', b[k])
|
||||
return out
|
||||
|
||||
|
||||
def col_cfg(g):
|
||||
"""当前 grid 的列配置 —— 列宽约束一变,Tk 就得把整屏重算一遍"""
|
||||
out = []
|
||||
for i in range(6):
|
||||
try:
|
||||
out.append((i, tuple(sorted(g.grid_columnconfigure(i).items()))))
|
||||
except Exception:
|
||||
pass
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def card_req(rid):
|
||||
"""一张卡的请求尺寸明细 —— 决定 grid 列宽的就是 reqwidth"""
|
||||
c = app.todo_cards.get(rid)
|
||||
if c is None:
|
||||
return ''
|
||||
bits = ['hl=%s bw=%s req=%dx%d' % (
|
||||
c.cget('highlightthickness'), c.cget('borderwidth'),
|
||||
c.winfo_reqwidth(), c.winfo_reqheight())]
|
||||
for attr in ('_name_lbl', '_meta_lbl', '_qty_lbl', '_thumb_label'):
|
||||
w = getattr(c, attr, None)
|
||||
if w is None:
|
||||
continue
|
||||
try:
|
||||
txt = str(w.cget('text'))[:18] if attr != '_thumb_label' else '图'
|
||||
except Exception:
|
||||
txt = '?'
|
||||
bits.append('%s[%dx%d %r]' % (attr[1:], w.winfo_reqwidth(),
|
||||
w.winfo_reqheight(), txt))
|
||||
return ' '.join(bits)
|
||||
|
||||
# 统计 _repaint_cards 被调几次、每次重画几张
|
||||
CALLS = []
|
||||
_repaint = A.App._repaint_cards
|
||||
|
||||
|
||||
def count_repaint(self, rids):
|
||||
CALLS.append([str(r) for r in (rids or []) if r is not None])
|
||||
return _repaint(self, rids)
|
||||
|
||||
|
||||
A.App._repaint_cards = count_repaint
|
||||
|
||||
# ---------------- 选两张同页、名字不同的卡 ----------------
|
||||
cur = str((getattr(app, '_focus_p', None) or {}).get('row_id') or '')
|
||||
by_widget = {c: rid for rid, c in app.todo_cards.items()}
|
||||
visible = sorted(by_widget[w] for w in app.todo_grid.grid_slaves()
|
||||
if w in by_widget)
|
||||
|
||||
|
||||
def std_of(rid):
|
||||
r = (app.todo_rows.get(rid) or {})
|
||||
try:
|
||||
return str(app._std_name(r) or '')
|
||||
except Exception:
|
||||
return str(r.get('item_name') or '')
|
||||
|
||||
|
||||
pick = [r for r in visible if r != cur]
|
||||
if len(pick) < 2:
|
||||
print('FAIL 同页可见卡不足 2 张(可见 %d 张),无法自检' % len(visible))
|
||||
try:
|
||||
app.engine.stop()
|
||||
except Exception:
|
||||
pass
|
||||
root.destroy()
|
||||
sys.exit(1)
|
||||
a_rid = pick[0]
|
||||
b_rid = next((r for r in pick[1:] if std_of(r) != std_of(a_rid)), pick[1])
|
||||
|
||||
print('state=%s 页=%s/%s 可见卡=%d 焦点=%s(%s)' % (
|
||||
app.engine.state, getattr(app, '_page', 0) + 1,
|
||||
getattr(app, '_page_count', 1), len(visible), cur, std_of(cur)))
|
||||
print('自检用的两张卡:%s(%s) ↔ %s(%s)' % (a_rid, std_of(a_rid),
|
||||
b_rid, std_of(b_rid)))
|
||||
print('卡内容明细:%s' % card_req(a_rid))
|
||||
|
||||
g0 = snap()
|
||||
p0 = getattr(app, '_page', 0)
|
||||
# 先把每个控件的「当前几何」当基线,否则第一发事件都算跳变
|
||||
for _rid, _c in app.todo_cards.items():
|
||||
for _w in [_c] + list(_walk(_c)):
|
||||
try:
|
||||
LAST[id(_w)] = (str(_w), _g(_w))
|
||||
except Exception:
|
||||
pass
|
||||
EVT.clear()
|
||||
TRANS.clear()
|
||||
CALLS.clear()
|
||||
|
||||
# ---------------- 来回点 3 次 ----------------
|
||||
for i, rid in enumerate((a_rid, b_rid, a_rid), 1):
|
||||
before = snap() # 点之前**当场**取,别用在循环外存的老快照
|
||||
col0 = col_cfg(app.todo_grid)
|
||||
c0 = len(CALLS)
|
||||
t_click = time.monotonic()
|
||||
EVT.clear()
|
||||
TRANS.clear()
|
||||
app._select_card(rid)
|
||||
spin(0.35) # 足够让 Tk 把排好的布局真画出来
|
||||
after = snap()
|
||||
calls = CALLS[c0:]
|
||||
dd = diff(before, after)
|
||||
print('\n第 %d 次点击 → %s(%s),耗时 %.0fms,<Configure> %d 个,'
|
||||
'其中「几何跳变」%d 次'
|
||||
% (i, rid, std_of(rid), (time.monotonic() - t_click) * 1000,
|
||||
len(EVT), len(TRANS)))
|
||||
check(not dd, '卡片几何没动',
|
||||
'\n '.join('%s.%s %s → %s' % (k[0], k[1], v[0], v[1])
|
||||
for k, v in list(dd.items())[:6]))
|
||||
check(not TRANS, '点击过程中没有任何控件跳位/改尺寸(含跳回去的)',
|
||||
'\n '.join('%s %s → %s' % t3 for t3 in TRANS[:6]))
|
||||
for nm, oldg, newg in TRANS[:6]:
|
||||
print(' 跳变 %s %s → %s' % (nm, oldg, newg))
|
||||
# 列宽约束:这里一变,Tk 就会把整屏 8 张卡重算一遍(190 ↔ 198/182)
|
||||
col1 = col_cfg(app.todo_grid)
|
||||
check(col0 == col1, 'grid 列宽约束没变(不会整屏重算)',
|
||||
'%s\n → %s' % (col0, col1))
|
||||
check(getattr(app, '_page', 0) == p0, '没有翻页',
|
||||
'页 %s→%s' % (p0 + 1, getattr(app, '_page', 0) + 1))
|
||||
check(len(calls) == 1 and len(calls[0]) <= 2,
|
||||
'一次点击只重画 ≤2 张卡(_repaint_cards 1 次)',
|
||||
'调用 %d 次:%s' % (len(calls), calls[:3]))
|
||||
|
||||
# ---------------- 收尾 ----------------
|
||||
print('\n重绘面积参考(一张卡 190×121 ≈ 22990 像素):')
|
||||
print(' 旧观感(整卡粉底+红框互换,ui.focus_fill=true) 每次点击≈45137 像素')
|
||||
print(' 现在(只换边框+数量数字) 每次点击≈ 5617 像素')
|
||||
print(' 复测旧观感:$env:FOCUS_FILL=1; python _merge_audit/probe_frames.py')
|
||||
print('\n%s' % ('全部通过:点卡片不改几何、不重排' if not FAILS
|
||||
else '失败 %d 项:%s' % (len(FAILS), ';'.join(FAILS))))
|
||||
|
||||
try:
|
||||
app.engine.stop()
|
||||
except Exception:
|
||||
pass
|
||||
root.destroy()
|
||||
sys.exit(0 if not FAILS else 1)
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""清掉样本库里的「模拟画面」脏样本(不是车间实拍的占位图)
|
||||
|
||||
背景:v1.0.65 之前,模拟摄像头(camera.simulate=true)拍的画面也会在
|
||||
「人点头记账」那一刻存进 data/learn/<品名>/,等于拿一张写着
|
||||
「SIM CAMERA seq=20」的白底图当教材。现场实测 38 张里 37 张都是这种,
|
||||
识别被 few-shot 带偏,对真实商品图也一直回 NOT_IN_LIST。
|
||||
|
||||
做法:把近白色的图(白占比 > 0.85)挪到 data/_diag/learn_sim_quarantine/,
|
||||
并在 index.json 里删掉对应条目(含指向已删文件的残留条目)。
|
||||
**只挪不删**,看错了随时能挪回去。
|
||||
|
||||
用法(项目根目录):
|
||||
python tools\\learn_clean_sim.py 只看,不移动
|
||||
python tools\\learn_clean_sim.py --apply 真的挪走
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
import shutil
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from core.recognition.dataset import SampleStore
|
||||
|
||||
ROOT = os.path.join('data', 'learn')
|
||||
INDEX = os.path.join(ROOT, 'index.json')
|
||||
QUAR = os.path.join('data', '_diag', 'learn_sim_quarantine')
|
||||
WHITE_RATIO = 0.85 # 近白像素占比超过这个值 = 模拟画面
|
||||
EXTS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp')
|
||||
|
||||
|
||||
def is_sim_frame(path):
|
||||
try:
|
||||
im = cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR)
|
||||
except Exception:
|
||||
return False
|
||||
if im is None:
|
||||
return False
|
||||
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
||||
return float((gray > 235).mean()) > WHITE_RATIO
|
||||
|
||||
|
||||
def scan_disk():
|
||||
"""data/learn 下所有图片(含不在索引里的孤儿文件)"""
|
||||
out = []
|
||||
for base, _dirs, files in os.walk(ROOT):
|
||||
for fn in sorted(files):
|
||||
if fn.lower().endswith(EXTS):
|
||||
out.append(os.path.join(base, fn))
|
||||
return out
|
||||
|
||||
|
||||
def move_out(path):
|
||||
"""挪进隔离目录(按品名分子目录),返回是否成功"""
|
||||
rel = os.path.relpath(path, ROOT)
|
||||
dst = os.path.join(QUAR, rel)
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
try:
|
||||
if os.path.abspath(path) == os.path.abspath(dst):
|
||||
return False
|
||||
shutil.move(path, dst)
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(' 挪不动 %s:%s' % (path, e))
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
apply = '--apply' in sys.argv
|
||||
store = SampleStore(root=ROOT, path=INDEX)
|
||||
|
||||
# 1) 索引里指向已不存在文件的残留条目
|
||||
stale = []
|
||||
for name, rows in list(store.items.items()):
|
||||
for r in list(rows or []):
|
||||
rel = str((r or {}).get('file') or '')
|
||||
if rel and not os.path.isfile(store._abs(rel)):
|
||||
stale.append((name, r))
|
||||
|
||||
# 2) 磁盘上的模拟画面(不管在不在索引里)
|
||||
sims = [p for p in scan_disk() if is_sim_frame(p)]
|
||||
|
||||
if not sims and not stale:
|
||||
print('样本库很干净:没有模拟画面样本,索引也没有残留条目。')
|
||||
print('当前样本:%s' % (store.stats() or '空'))
|
||||
return 0
|
||||
|
||||
if stale:
|
||||
print('索引残留条目 %d 条(文件已不在):' % len(stale))
|
||||
for name, r in stale:
|
||||
print(' %-16s %s' % (name, r.get('file')))
|
||||
if sims:
|
||||
print('模拟画面样本 %d 张:' % len(sims))
|
||||
for p in sims:
|
||||
print(' %s' % os.path.relpath(p, ROOT))
|
||||
|
||||
if not apply:
|
||||
print('\n(只看了,没动。加 --apply 才会真的挪走 / 清索引)')
|
||||
return 0
|
||||
|
||||
moved = 0
|
||||
for p in sims:
|
||||
if move_out(p):
|
||||
moved += 1
|
||||
for name, r in stale:
|
||||
store._remove_entry(name, r)
|
||||
if sims or stale:
|
||||
store._save()
|
||||
print('\n已挪走 %d 张 → %s' % (moved, QUAR))
|
||||
print('剩余样本:%s' % (store.stats() or '空'))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -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())
|
||||
+1167
-1165
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,11 @@
|
||||
════════════════════════════════════════════
|
||||
════════════════════════════════════════════
|
||||
配送入库分拣工作站(Win10 版)- 使用说明
|
||||
════════════════════════════════════════════
|
||||
|
||||
|
||||
【v1.0.76 识别记录留档(2026-12-03)】
|
||||
· 商品放稳抓拍后,云端结果供人工确认;本地 YOLO 建议只随「真实业务成功」的样本送审,供超管在后台查看,不改变记账结果。
|
||||
· 每张样本可查看本地/云端两侧的识别状态、候选与耗时;本机无法计算或云端不可用时也会留「未完成/不可用」,不阻断入库。
|
||||
本程序按设计文档 docs/design/20261102-win10-inbound-sorting-station.md
|
||||
实现,与 android-weigh-terminal2 使用同一套服务端接口。
|
||||
|
||||
@@ -25,7 +29,243 @@
|
||||
build_assets/ 打包素材(VC++ 运行库 vc_redist.x64.exe)
|
||||
打包.bat 双击打包
|
||||
dist/ 产物:dist\入库分拣工作站\(绿色版)
|
||||
dist\入库分拣工作站_安装程序_v1.0.63.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)】
|
||||
|
||||
◆ 入库不能再「拿走即自动记账」了(账号开关决定)
|
||||
· 服务端账号字段 profiles.inbound_auto_submit:
|
||||
- 未开启 / 服务端没这个字段 → 入库必须点「确认记账」
|
||||
- 开启 → 与 1.0.70 一样(拿走货、秤连续空 3 秒自动提交)
|
||||
· 手动确认时:认出来先跳到那一行、弹确认条;把货取走不会自动过账,
|
||||
确认条会一直挂着等人点(不点掉它,下一件不会起新流程)。
|
||||
· 识别不受影响:斤类还是放上去自动认;袋/包/桶也是自动抓拍识别,
|
||||
只是认出来要人点一下确认。
|
||||
· 分拣工位完全不受影响(本来就必须点「确认分拣」)。
|
||||
|
||||
◆ 修:上一件的品名残留
|
||||
· 新一轮开始时清空上一轮识别名,避免「这件没认出来,确认页却显示
|
||||
上一件的品名」。
|
||||
|
||||
【v1.0.70 待办分页不再裁掉最底行(2026-11-25)】
|
||||
|
||||
◆ 「按供应商」切回「不分组」后页头不消失(已修)
|
||||
· 旧版切分组方式走增量更新,只改卡上的字,上一模式建的分组标题
|
||||
(「(无客户/供应商) 9 行 · 合计 264 斤」)一直留在网格里占一行,
|
||||
卡片被整体下推,最底一行被视口裁掉一半。
|
||||
· 现在切分组方式一定整表重建;还有页头残留时一律不走增量路径。
|
||||
|
||||
◆ 分页按真实卡高装箱,绝不裁半行
|
||||
· 一页放几行,按当时每张卡的真实高度现算(客户名/供应商名折行会
|
||||
让那一行高约 20px,分组页头也占一行)。
|
||||
· 摆完再量一次:最底一张真超出视口,就少吃一行重排。
|
||||
· 代价:某些页会少放 4 张(能放 3 行就 3 行,放不下就 2 行)。
|
||||
|
||||
【v1.0.69 标签改左右布局 + 点卡不再抖(2026-11-23)】
|
||||
|
||||
◆ 标签改成左右布局(文字在左、二维码在右下)
|
||||
· 文字从第一行到最后一行均匀铺满可用区域(上下各留 4~5mm 安全带):
|
||||
以前只留 1.5mm,最后一行几乎贴着纸边,打印机底部有 2~4mm 不可打印区,
|
||||
日期和码下沿就会被裁掉。
|
||||
· 二维码贴右下角,底边和最后一行(日期)底边对齐,并尽量取大:
|
||||
最多占纸宽 40%、不超过文字块高度;字号保持不低于 24(极小纸另算)。
|
||||
· 没有二维码的标签(调试预览)仍按原来的垂直居中,版面不变。
|
||||
· 安装包出厂纸型改为 60×40mm(203dpi 下 480×320 点)。
|
||||
· 80×60mm 也支持:按真实纸宽排(不再写死 76mm 打印头上限),
|
||||
二维码随纸型自动放大,大纸上不会显得很小。
|
||||
· 老机器升级不会覆盖 config.json,纸型仍是原来的设置;需要时走
|
||||
「设置 → 标签打印机 → 标签纸… → 自动读取尺寸」重新读一次。
|
||||
|
||||
◆ 预览和实际打印一致,文字不会压到二维码
|
||||
· 文字与二维码之间留出二维码的 4 模块静区(约 2mm),长品名宁可多折一行,
|
||||
也不顶到码上。
|
||||
· 排版不再截断:排不下就折行、降字号、必要时压缩行距,每个字都会打出来;
|
||||
二维码永远整块打印(最小 1 点/模块),不会省略或缺角。
|
||||
· 真遇到标签太小 / 容器码过长 / 码内容打印机不支持:本次直接不打印并提示,
|
||||
不会发出半张或缺码的标签(宁可没打,也不打错)。
|
||||
· 如果标签实在太小、内容根本排不下,日志会提示加大标签,不会默默丢字。
|
||||
· ×、·、— 这类字符在 GBK 里是全角双字节,现在按全角算宽,不再低估。
|
||||
· 设置页预览改用像素字号:Windows 显示缩放 125%/150% 时,预览文字
|
||||
不再被放大成“压住二维码”的样子(实际打印本来就没问题)。
|
||||
|
||||
◆ 入库「拿走即提交」不再被补货误触发
|
||||
· 以前秤一空 0.3 秒就自动提交:补货时把原货抬起来调整位置,会被
|
||||
当成取走,按补货前的短重量入账。
|
||||
· 现在空秤要连续 3 秒才自动提交(残重不归零等 10 秒);这期间把货
|
||||
放回秤上立即取消,状态卡提示行会显示「N 秒后自动提交」。
|
||||
· 要调宽松可在 config 的 flow 段设置:confirm_zero_ms(默认 3000)、
|
||||
confirm_linger_s(默认 10)。分拣工位不受影响,仍必须人工确认。
|
||||
|
||||
◆ 待办卡分页不再裁掉最底一行
|
||||
· 以前按一个固定的卡高估“一页几行”:带「独立入库」黄底的卡更高,
|
||||
翻到那页就多塞一行,最底那张被视口裁掉(入库 3 行 4 列时最明显)。
|
||||
· 现在按每页实际行高装箱:都是矮卡时多放一行,有高卡时少放一行,
|
||||
每一页的卡都完整显示(不会半张卡藏在翻页条下面)。
|
||||
|
||||
◆ 点待办卡不再抖、也不会两张同时亮
|
||||
· 所有卡片外框固定 4px,选中(琥珀)/ 确认(绿)只换颜色、不改粗细。
|
||||
以前确认行比别的卡粗 2px,一点卡整排卡片就被撑大、界面跟着跳。
|
||||
· 引擎接管确认行时会清掉手动点过 / 预选的琥珀框,只亮一张。
|
||||
· 琥珀高亮只看「最后点过的那张」,和上方详情行同源:点哪张就亮哪张,
|
||||
且永远只有一张;连点时旧事件晚到、非待机态点卡都不会再两张同时亮。
|
||||
· 连点两张也不会出现一帧“两张同时亮”。
|
||||
|
||||
【v1.0.68 整组短收按部分成功处理(2026-11-22)】
|
||||
|
||||
◆ 整组入库短收不再报 409「整组入库行数不一致」
|
||||
· 背景:整组待验 13 斤、本次只称 6.48 斤时,服务端按行 FIFO 分摊后
|
||||
有的行分到 0;旧版服务端先入了一部分、再回 409,现场看到「提交被
|
||||
拒绝」,实际已入一半;拿旧组重试又报「部分待验明细已提交」。
|
||||
· 新版服务端把「短收」当正常的「部分成功」:返回 200,并告诉端上
|
||||
已入几行、剩余多少斤继续待验。本版配套:
|
||||
· 成功提示会写「整组部分入库:已入 N 行,剩余 X 斤(下次称重继续;
|
||||
不要用旧组重试)」;
|
||||
· scope_incomplete / scope_changed / group_changed / scope_mismatch
|
||||
这几类业务拒绝翻成人话:「请刷新待验列表后再称,不要直接重试旧组」。
|
||||
· 需要配套服务端 2026-11-22 之后的版本;旧服务端下行为不变。
|
||||
· 注意:短收部分入账后,剩余行仍在待验列表里,请刷新列表后继续称;
|
||||
若剩余货确定不再到,才用「偏差/短收结案」。
|
||||
|
||||
◆ 待办名单支持左右滑动翻页
|
||||
· 在名单区域(卡片上或空白处)手指左划 = 下一页,右划 = 上一页。
|
||||
· 竖向拖动、斜着划、短距离滑动都不会翻页,也不会误选中卡片。
|
||||
· 底部「上一页 / 下一页」按钮和鼠标滚轮翻页照旧可用。
|
||||
|
||||
◆ 顶栏按工位改名(不再一律叫“入库分拣工作站”)
|
||||
· 登录分拣工位后,顶栏和窗口标题显示「分拣工作站」,logo 字改成“拣”;
|
||||
入库工位显示「入库工作站」。库管/调度一眼就能分清这台机是干什么的。
|
||||
· 退出登录后窗口标题回到「入库分拣工作站 - 登录」。
|
||||
· 程序文件名 / 安装包名不变(仍叫入库分拣工作站.exe)。
|
||||
|
||||
【v1.0.67 待办卡分原料/普通显示(2026-11-11)】
|
||||
|
||||
◆ 同一商品既有「加工原材料」又有普通订单时,卡片分开显示
|
||||
· 以前只挂一个黄底标签「独立入库 · 加工原材料」,32 斤看着像全是
|
||||
原料;实际可能是原料 12 斤 + 订单 20 斤合并的一组。
|
||||
· 现在标签会写成「独立入库原料 12 斤 · 普通入库 20 斤」;
|
||||
全原料组仍是「独立入库 · 加工原材料」;全普通组不显示。
|
||||
· 混合组不会再被标成“独立入库”(避免走错单行结案),仍整组提交。
|
||||
|
||||
【v1.0.66 分组批量入库 + 登录页改服务器(2026-11-10)】
|
||||
|
||||
◆ 分组批量入库(与安卓称端同一套接口)
|
||||
· 入库待办改为先拉「同商品分组」再展示:同商品、同来源、同单位的
|
||||
多张待验单折成一行,数量是组内合计(卡片上方仍能看到单号)。
|
||||
例:两行苹果各 30 斤 → 显示「1 行 · 合计 60 斤」。
|
||||
· 一次称重提交整组,服务端按组内待验量 FIFO 分摊,不再由客户端
|
||||
拆单逐笔提交;短收/超收仍然拦(服务端容差 + 客户端短收规则)。
|
||||
· 服务端没有分组接口时自动回退到原来的逐行严格入库,不影响老服务器。
|
||||
· 想回到旧的逐行方式:config.json 的 flow 段加 "group_inbound": false。
|
||||
|
||||
◆ 同时包含
|
||||
· 登录页可直接改服务器地址(见下面 v1.0.65 章)。
|
||||
· 识别请求不再继承系统代理(ProxyError 修复)。
|
||||
· 模拟/回放画面不再写入样本库;样本库被污染可用
|
||||
python tools\learn_clean_sim.py --apply 清理。
|
||||
· 没摄像头时可用 camera.replay_dir 回放真实商品图,识别仍走真实模型。
|
||||
|
||||
【v1.0.64 分拣标签二维码修复(2026-11-09)】
|
||||
|
||||
◆ 二维码改打「容器码」,不再打订单号
|
||||
· 此前分拣标签二维码 = 订单号(ORD_WEB_...),配送小程序按「商品/容器」
|
||||
查库,会提示「未找到条码对应商品或容器:ORD_WEB_...」。现在改用服务端
|
||||
分拣提交回包里的 data.container_code(容器码)。
|
||||
· 提交回包和待办行都取不到容器码时,本次不打印标签(宁可不打,也不打
|
||||
一张扫不出来的标签),界面会红字提示;data/app.log 里的
|
||||
「标签二维码」一行能看到实际打的码和来源。
|
||||
· 入库默认不打标签,本次行为不变。
|
||||
|
||||
◆ 版面/字段校正
|
||||
· 50×50mm 带二维码时,日期/时间/重量/数量/订单号不再被折成两行
|
||||
(以前可能出现「日期: 11-06 1」+「0:00」)。
|
||||
· 空单位/市斤按「重量」打印;不再出现「数量: 5.00 斤」。
|
||||
· 商品名/客户名里有英文双引号或换行时会被清洗,不会把整张标签指令截断。
|
||||
· 高级设置新增「标签二维码兜底字段」(printer.qr_fallback),默认空 =
|
||||
只认容器码。只有确认配送小程序能识别 pick_code 时,才临时填 pick_code。
|
||||
|
||||
【v1.0.65 登录页可改服务器地址 + 独立入库同名分摊(2026-11-09)】
|
||||
|
||||
◆ 登录页直接改服务器地址
|
||||
· 登录页底部第一行显示当前服务器地址(点它就能改),第二行左侧是
|
||||
「修改服务器地址」按钮、右侧是「退出程序」。不用登录、不用改
|
||||
config.json、不用重启程序。
|
||||
· 窗口里可以:改地址 → 点「测试连接」先验通 → 点「保存并应用」。
|
||||
保存后立即生效(引擎里的 ApiClient 当场换地址,旧 token 会清掉),
|
||||
并写回程序目录的 config.json(server.base_url)。
|
||||
· 测试连接返回 401 是正常的(还没登录);返回 404 通常是地址少了 /api;
|
||||
「连不上」才是网络/服务端问题。
|
||||
· 用过的地址会记在 config.json 的 server.history(最多 5 个):下次打开
|
||||
窗口点一下就能切回去,换机房/主备切换不用再手改配置。
|
||||
· 保存时会把 server.mock 置回 false(原来是离线演示的会被关掉)。
|
||||
· 地址必须以 http:// 或 https:// 开头,结尾多写的「/」会自动去掉。
|
||||
|
||||
◆ 独立入库(无单自采)同名多行也能按量分摊
|
||||
· 现场:两张自采待验单 17 斤 / 38 斤,一次到货 55.74 斤。以前只要看到
|
||||
无单行就一律转人工(_split_plan 直接放弃),操作员只能全录到一张单,
|
||||
另一张一直挂着。
|
||||
· 现在全部是无单行时按剩余量分摊:17 斤那行结 17,剩下的 38.74 全给
|
||||
38 斤那行(尾差不再留在现场)。账上仍是每单各结一笔,走
|
||||
/mobile/inspection/complete 单行结案,不会调 complete-merge-strict。
|
||||
· 仍然转人工的情况:同名里既有订单行又有无单行(防止把订单货入成
|
||||
自采库存)、实收超过合计应量 30%、单位不一致、同名超过 8 行。
|
||||
|
||||
◆ 识别请求不再继承系统代理(防止 ProxyError)
|
||||
· 现象:界面上 AI 一直认不出(“这件货不在待办名单里”),data/app.log
|
||||
里能看到「识别失败: … ProxyError … ark.cn-beijing.volces.com」,
|
||||
但登录、待办、提交这些接口都正常。
|
||||
· 原因:机器上常驻代理/加速类软件,Windows 系统代理只支持 HTTP,
|
||||
不走 HTTPS。接口模块一直是不走代理的,识别模块以前会继承,所以只有
|
||||
AI 挂。现在识别也直连。
|
||||
· 确实必须走代理的环境:config.json 的 vision 段加 "trust_env": true。
|
||||
|
||||
◆ 报「服务端严格写入开关未开启(strict_write_enabled=false)」
|
||||
· 这不是网络或操作问题,是这台服务器把「严格入库写入」关了。客户端
|
||||
按设计直接不发送(发了也写不进去,还会留下未决提交)。
|
||||
· 本次未提交、没产生未决提交,等管理员在服务端开启后重新称一次即可。
|
||||
· 只影响「有单的入库验收」;分拣提交、无单自采的单行结案都不受影响。
|
||||
· 如果当前连的是测试/备用服务器(如 deepseek.xdjchuanhui.com:8443),
|
||||
先在登录页「修改服务器地址」切回正式地址再试。
|
||||
|
||||
◆ 没有摄像头 / 没有真称,怎么在本机测真实效果(v1.0.65)
|
||||
· 回放摄像头:config.json 的 camera 段加一行
|
||||
"replay_dir": "data/photos"
|
||||
模拟摄像头就改成「回放这个目录里的图」,每 replay_hold_s 秒换一张
|
||||
(默认 10 秒),画面左上角写 REPLAY n/N。**识别仍然调真实模型**,
|
||||
所以准不准、耗时多少都是真的;留档照片就是这张图。
|
||||
不配 replay_dir 时还是原来的合成白底画面,行为不变。
|
||||
· 模拟称重量可以给列表,一轮换一个:
|
||||
"sim_loop_kg": [15.0, 3.0, 7.5]
|
||||
15kg = 30 斤,正好对上待办里 30 斤的行,不会被服务端重量容差拒。
|
||||
· 完全不联网跑界面:server.mock=true + flow.demo_recog=true
|
||||
(demo_recog 只在 mock 下生效,按称上重量挑最接近的一行)。
|
||||
· 模拟/回放画面不是车间实拍,v1.0.65 起**不再进样本库**;但之前跑过的
|
||||
机器可能已经脏了(症状:真图也一直回 NOT_IN_LIST)。清理:
|
||||
python tools\learn_clean_sim.py 先看
|
||||
python tools\learn_clean_sim.py --apply 挪到 data\_diag 隔离
|
||||
|
||||
【离线演示模式(v1.0.63,现场当前已开启)】
|
||||
|
||||
@@ -219,6 +459,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
|
||||
@@ -1104,8 +1374,8 @@
|
||||
【标签打印:异步,不挡取货(分拣模式)】
|
||||
· 提交成功后标签立刻进队列,界面直接变「DONE」可拿走、放下一件;
|
||||
打印在后台单线程串行做,多件连打不会交错、顺序与提交顺序一致。
|
||||
· 打印结果回报在待办卡右上角:
|
||||
✔ 标签已打印 → 正常
|
||||
· 打印结果回报在左侧状态卡:
|
||||
✔ 标签已发送打印 → 正常(已交给 Windows 打印队列)
|
||||
⚠ 标签未打印:原因 → 红字 + 提示音,最近一行提示"请手工补打"
|
||||
不自动重打(铁律:不重复打印),失败一律人工补。
|
||||
· 没选打印机时只提醒一次(标签落成 data/last_label.prn),不会每件弹红字。
|
||||
@@ -1125,10 +1395,11 @@
|
||||
· 间距不是 2mm → 整张上移/下移,或者隔一张出现空白
|
||||
◆ 现在怎么排
|
||||
按实际宽高 × 分辨率反算字号、行距、二维码大小,任何尺寸都不溢出:
|
||||
· 字号从 32 往下挑,优先让所有字都单行;品名太长才折成两行;
|
||||
实在放不下才缩字号,最后才截断(缩了/截了会在预览里标红)
|
||||
· 二维码要放不下就整块不打,绝不打半个码
|
||||
· 超过 76mm(常见打印头宽度)自动夹到 76mm
|
||||
· 字号从 32 往下挑,优先让所有字都单行;品名太长往下折行;
|
||||
实在放不下就压行距,绝不截字(真排不下会在预览里标红提示加大标签)
|
||||
· 二维码按纸型动态取大小(1~10 点/模块),必须整块打印,不省略
|
||||
· 打印头宽度默认按 4 英寸(104mm);3 英寸机型在 config 的
|
||||
printer.max_width_mm 写 76,超过就按上限裁
|
||||
◆ 怎么改(唯一入口:设置 → 标签打印机 →「标签纸…」)
|
||||
① 点「自动读取尺寸」← 程序去 Windows 驱动里读这台打印机实际装的纸
|
||||
(宽、高、分辨率一次填好)。不用自己量、也不用拆纸。
|
||||
|
||||
Reference in New Issue
Block a user