feat(1.0.75): 同步秤端 v1.0.75 源码(UI 抖动修复 + 严格入库/分拣样本)

来自 入库分拣工作站_源代码_v1.0.75:点商品名抖动的中间帧修复、ui/osk/tablet 调整、严格入库校验、分拣场景样本(review_queue station=picking);版本/安装包/说明同步 1.0.75。注意:本版 confirm_before_submit 恒 True、submit_on_remove 恒 False,1.0.71 的 inbound_auto_submit 账号开关被移除;models/cls 与 data/ 未入库。EXE 由用户侧打包分发,本次只推源码。
This commit is contained in:
Ubuntu
2026-12-03 16:26:17 +08:00
parent 453d0b3478
commit 4966345424
21 changed files with 2966 additions and 2398 deletions
+36 -33
View File
@@ -1,33 +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
# 本地识别模型(YOLO-cls):由服务端分发/本地发布脚本写入 models/cls,约 10MB,不入库
models/cls/
# 排除配送系统文件夹
配送系统/
# 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/
+111
View File
@@ -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
View File
@@ -1,17 +1,17 @@
VSVersionInfo(
ffi=FixedFileInfo(filevers=(1, 0, 72, 0), prodvers=(1, 0, 72, 0),
mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1,
subtype=0x0, date=(0, 0)),
kids=[
StringFileInfo([StringTable('080404B0', [
StringStruct('CompanyName', '配送中心'),
StringStruct('FileDescription', '入库分拣工作站'),
StringStruct('FileVersion', '1.0.72.0'),
StringStruct('InternalName', 'WeighStation'),
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
StringStruct('ProductName', '入库分拣工作站'),
StringStruct('ProductVersion', '1.0.72.0'),
StringStruct('LegalCopyright', '内部使用')])]),
VarFileInfo([VarStruct('Translation', [2052, 1200])])
]
)
VSVersionInfo(
ffi=FixedFileInfo(filevers=(1, 0, 75, 0), prodvers=(1, 0, 75, 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.75.0'),
StringStruct('InternalName', 'WeighStation'),
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
StringStruct('ProductName', '入库分拣工作站'),
StringStruct('ProductVersion', '1.0.75.0'),
StringStruct('LegalCopyright', '内部使用')])]),
VarFileInfo([VarStruct('Translation', [2052, 1200])])
]
)
+2 -2
View File
@@ -20,7 +20,7 @@ import sys
ROOT = os.path.dirname(os.path.abspath(__file__))
APP_NAME = '入库分拣工作站'
APP_VERSION = '1.0.72'
APP_VERSION = '1.0.75'
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:
+111 -108
View File
@@ -1,108 +1,111 @@
{
"server": {
"base_url": "https://www.xdjchuanhui.com/api",
"mock": false
},
"account": {
"username": "13000000008",
"password": "",
"role": "picker"
},
"scale": {
"simulate": true,
"port": "COM3",
"baudrate": 1200,
"bytesize": 8,
"parity": "N",
"stopbits": 1.0,
"unit": "auto",
"pattern": "",
"poll_cmd": "",
"poll_ms": 500,
"protocol": "generic",
"min_weight_kg": 0.01,
"stable_count": 5,
"stable_tolerance_kg": 0.02,
"tare_cmd": "",
"zero_cmd": "",
"sim_loop_kg": 3.0,
"sim_loop_hold_s": 2.5,
"sim_loop_keep_s": 10.0,
"sim_loop_idle_s": 3.0,
"sim_loop_jitter_kg": 0.6
},
"camera": {
"simulate": true,
"index": 1,
"backend": "dshow",
"auto_pick": true,
"width": 1280,
"height": 720,
"usb_only": true,
"name": "BisonCam,NB Pro"
},
"vision": {
"provider": "doubao",
"api_key": "",
"base_url": "https://ark.cn-beijing.volces.com/api/v3",
"vision_model": "doubao-seed-2-1-pro-260915",
"text_model": "doubao-seed-2-1-pro-260915",
"disable_thinking": true,
"max_tokens": 32,
"timeout": 15,
"recognition_image_max_px": 1280,
"assist": {
"enabled": false,
"ask_cloud_below": 0.98,
"force_confirm": true,
"model": "models/cls/product_cls.onnx",
"classes": "models/cls/classes.json",
"imgsz": 320,
"topk": 3,
"journal_dir": "data/assist",
"auto_update": true,
"update_interval_sec": 21600,
"update_timeout": 180
}
},
"printer": {
"enabled": false,
"type": "tspl",
"printer_name": "HUAWEI CV81-WDMSE-0470",
"width_mm": 50,
"height_mm": 50,
"release_usb": false
},
"flow": {
"auto_submit": true,
"min_scale_kg": 0.01,
"stable_ms": 400,
"stable_delta_kg": 0.03,
"rescan_delta_kg": 0.04,
"unstable_fallback_ms": 2500,
"done_lift_off_kg": 0.2,
"recognize_timeout": 8,
"commit_timeout": 10,
"recognize_cooldown": 30,
"dedup_delta_kg": 0.005,
"frame_stale_ms": 5000,
"tolerance_policy": "block_auto",
"use_scale_stable": true,
"demo_recog": true
},
"capture_dir": "data/snapshots",
"record_file": "data/records_demo.csv",
"snapshot_keep_days": 30,
"ui": {
"mode": "window",
"width": 1440,
"height": 900,
"borderless": false,
"todo_thumb": false,
"todo_group": "customer",
"fit_screen": false
},
"devices": {
"auto_detect": true
}
}
{
"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
}
}
+25 -136
View File
@@ -189,12 +189,7 @@ class FlowEngine:
self.logged_in = False # UI 登录页成功后置 True
self.state = 'IDLE'
self.locked_msg = None # 未决提交锁
# 账号开关 profiles.inbound_auto_submit(2026-11-29):
# 关闭(默认)= 入库必须手动点「确认记账」;开启 = 保留旧行为(拿走货即自动提交)。
# 登录成功后由 FlowEngine.login() 用服务端下发值覆盖;本地 config 的
# flow.inbound_auto_submit 只用于演示/离线测试(默认 True,保持旧测试语义)。
self.inbound_auto_submit = bool(
(self.cfg.get('flow') or {}).get('inbound_auto_submit', True))
self._running = False
self._tick_started = False # tick 线程是否已起(防重复 start)
self._confirm_lock = threading.Lock() # 确认/提交互斥(防一笔提交两回)
@@ -329,8 +324,8 @@ class FlowEngine:
self._print_thread.start()
threading.Thread(target=self._photo_retry_loop, daemon=True).start()
# 入库照片送审:只登记/补传,真正的发送要等 submission journal 说成功
# (见 _review_stage / _review_retry_loop)。分拣工位不送审。
if self.station == 'inspection' and not getattr(self.api, 'mock', False):
# (见 _review_stage / _review_retry_loop)。
if not getattr(self.api, 'mock', False):
threading.Thread(target=self._review_retry_loop,
daemon=True).start()
# 模型自动更新:登录后会立刻查一次,这里负责「开着一整天」的定时复查
@@ -382,8 +377,7 @@ class FlowEngine:
self.api.account = acc
self.api.login()
# 入库自动提交:以服务端账号开关为准(读不到 ⇒ False ⇒ 手动确认)
self.set_inbound_auto_submit(
bool(getattr(self.api, 'inbound_auto_submit', False)))
self.emit('log', '手动确认:识别后请点确认记账')
self.logged_in = True
self.emit('log', '登录成功(%s / %s,role_type=%s)'
% (acc.get('username'), self.station, acc.get('role')))
@@ -1342,15 +1336,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:
@@ -1865,31 +1854,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):
@@ -2453,13 +2419,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
@@ -2496,10 +2457,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)
@@ -2895,13 +2854,13 @@ class FlowEngine:
返回 False = 本机连「记一笔」都做不到,这一笔不发(与「日志落盘失败,
本次未发送请求」同一口径:能追溯才允许动账)。
"""
if self.station != 'inspection' or getattr(self.api, 'mock', 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:
error = ReviewQueue().stage(self.api, op, row, source, path,
error = ReviewQueue().stage(self.api, op, row, source, path, station=self.station,
captured_at=captured_at)
except Exception as exc: # noqa: BLE001
self.journal.conclude(op, STATE_REJECTED, '送审队列写入失败')
@@ -3326,58 +3285,11 @@ class FlowEngine:
return bool(self.cfg.get('flow', {})
.get('allow_independent_inbound', False))
def set_inbound_auto_submit(self, enabled):
"""应用服务端账号开关(profiles.inbound_auto_submit)。
关闭(默认)= 入库必须手动点「确认记账」;开启 = 恢复旧行为(拿走货即自动提交)。
分拣工位不受影响(本来就要求点击「确认分拣」)。
"""
enabled = bool(enabled)
if enabled == self.inbound_auto_submit:
return
self.inbound_auto_submit = enabled
if self.station == 'picking':
return
self.emit('log', '入库提交模式:%s(账号开关)'
% ('自动提交(拿走货即记账)' if enabled
else '手动确认(必须点「确认记账」)'))
def _manual_confirm_required(self):
"""入库工位且账号未开启自动提交 ⇒ 必须人工点确认"""
# getattr 兜底:老测试桩(直接 __new__/Fake,不走 __init__)没有该属性 ⇒ 保持旧行为
return self.station != 'picking' and not getattr(
self, 'inbound_auto_submit', True)
def confirm_before_submit(self):
"""识别完先定位到商品行、等人确认,确认了才记账(v1.0.31 默认开)
为什么要这么改:AI 认错一次,账就错了,而且服务端没有冲正接口,
只能去后台手改(现场 11-04 夜里那几笔就是这么来的)。以前是「认出
就直接提交」,人根本没机会看;现在把「看」这一步塞回流程里 ——
认出哪一行就把界面跳过去高亮,看着不对点别的行就是改判。
关掉(flow.confirm_before_submit=false)回到旧行为:认出即提交。
"""
# v1.1.0 建议模式:本地和云端都只是「建议」,人必须点一下。
# 两个引擎都说苹果也不自动记账 —— 人是唯一基准(assist.force_confirm)。
_a = getattr(self, 'assist', None)
if _a is not None and _a.enabled and _a.force_confirm:
return True
# 2026-11-29:入库账号未开启「自动提交」⇒ 强制走确认页(必须点确认)
if self._manual_confirm_required():
return True
return bool(self.cfg.get('flow', {}).get('confirm_before_submit', True))
return True
def submit_on_remove(self):
"""非分拣工位可选「拿走货自动提交」;分拣始终等待人工确认。
选择行只确定记账对象;分拣标签在人工确认且提交成功后排队,
不受该配置影响。免称重行也沿用确认页流程。
"""
# 2026-11-29:入库账号未开启「自动提交」⇒ 拿走货不提交,必须点确认
if self._manual_confirm_required():
return False
return bool(self.cfg.get('flow', {}).get('submit_on_remove', True))
return False
def preselect(self, rid):
"""空秤时人工预选待办行(v1.0.40)
@@ -3588,6 +3500,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'] = ''
@@ -3630,8 +3544,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
@@ -4052,9 +3966,6 @@ class FlowEngine:
默认开。关掉就退回 v1.0.28 的行为:点按钮 → 抓拍 → 核对页 → 提交。
"""
# 2026-11-29:入库账号未开启「自动提交」⇒ 免称重也不自动记账,必须人工点确认
if self._manual_confirm_required():
return False
cfg = self.cfg.get('noweigh', {}) or {}
return bool(cfg.get('auto', True))
@@ -4454,32 +4365,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):
# 走到核对页就不再是「自动轮」了:后面的提交是人在点,按人工路径走
+11 -9
View File
@@ -59,7 +59,7 @@ def _iso(epoch_sec):
sign, off // 3600, (off % 3600) // 60)
def build_fields(api, op, row, source, captured_at):
def build_fields(api, op, row, source, captured_at, station="inspection"):
"""把一条入库行翻成 /mobile/recognition/samples 的字段(全部字符串)。
这里只描述事实:货单名原样送(「外地芹菜」就是「外地芹菜」),
@@ -70,7 +70,7 @@ def build_fields(api, op, row, source, captured_at):
fields = {
'sample_id': op,
'event_id': op,
'scene': 'stock_inbound',
'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],
@@ -81,7 +81,7 @@ def build_fields(api, op, row, source, captured_at):
# 整组入库:一张照片代表多行验收,单号不是唯一的那一个,
# 不瞎填(填错比空着更难查),只在样本上标明这是整组。
ids = row.get('inspection_ids')
if isinstance(ids, (list, tuple)) and len(ids) > 1:
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()
@@ -117,7 +117,7 @@ class ReviewQueue:
return []
# ------------------------------------------------ 登记
def stage(self, api, op, row, source, path, captured_at=None):
def stage(self, api, op, row, source, path, captured_at=None, station="inspection"):
"""入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。
写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理:
@@ -135,7 +135,7 @@ class ReviewQueue:
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)
error = self._write_stage(work, api, op, row, source, path, captured_at, station)
try:
os.rename(work, d)
except OSError:
@@ -145,7 +145,7 @@ class ReviewQueue:
return existing.get('error') or ''
return error
def _write_stage(self, d, api, op, row, source, path, captured_at):
def _write_stage(self, d, api, op, row, source, path, captured_at, station):
blob, error = b'', ''
try:
with open(path, 'rb') as f:
@@ -174,7 +174,7 @@ class ReviewQueue:
'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),
'fields': build_fields(api, op, row, source, captured_at, station),
'sha256': hashlib.sha256(blob).hexdigest() if blob else '',
'bytes': len(blob),
'error': error,
@@ -203,13 +203,15 @@ class ReviewQueue:
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)
self._say(log, '业务提交被拒绝,取消送审:%s' % op)
continue
if state != STATE_SUCCEEDED:
# 入库还没结论(在途/结果不明/待核实):下一轮再看,别抢跑。
@@ -248,7 +250,7 @@ class ReviewQueue:
continue
shutil.rmtree(self._dir(op), ignore_errors=True)
handled += 1
self._say(log, '入库照片已送审:%s(%s)'
self._say(log, '照片已送审:%s(%s)'
% (op, (meta.get('fields') or {}).get('label_name') or ''))
return handled
+3 -4
View File
@@ -24,7 +24,7 @@
| --- | --- |
| `core/submission/review_queue.py` | 待送审队列:登记、等结论、补传、转人工 |
| `core/flow.py` → `_review_stage()` | 两个入库入口(独立入库 / 有单验收)发请求前调用 |
| `core/flow.py` → `_review_retry_loop()` | 每 20 秒核对一次并补传(分拣工位不起这个线程) |
| `core/flow.py` → `_review_retry_loop()` | 每 20 秒核对一次并补传 |
| `core/api/client.py` → `upload_review_sample()` | multipart 打 `/mobile/recognition/samples` |
| `tools/_test_review_queue.py` | 离线回归(不需要秤/相机/网络) |
@@ -56,7 +56,6 @@ data/review_rejected.json 永久失败的那几条(含原因)
| `入库照片还没送出去 op-…:…` | 网络/服务端问题,退避重试中 | 网络恢复后自己会好 |
| `送审被拒绝,已转人工:op-…(…)` | 数据本身有问题(4xx) | 看 `data/review_rejected.json` 的原因 |
## 分拣工位不送审
## 分拣照片
分拣(picking)的照片已经走 `/mobile/picking/weigh-station/photo` 归档,
飞轮先只做入库。`_review_stage()` 第一行就按工位短路,不会误发。
分拣成功后,合格原图同时用于业务归档和识别样本审核。服务端审核通过后才能导出训练。模拟相机和回放不登记训练照片。结果未核实的提交保留队列,等待确认成功或作废。
@@ -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 -209
View File
@@ -1,209 +1,209 @@
; ============================================================
; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.72.exe
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
; ============================================================
#define AppName "入库分拣工作站"
#ifndef AppVersion
#define AppVersion "1.0.72"
#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.72.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: "{#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.75.exe
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
; ============================================================
#define AppName "入库分拣工作站"
#ifndef AppVersion
#define AppVersion "1.0.75"
#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.75.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;
+51
View File
@@ -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,子进程写字给父进程会崩。
+4 -1
View File
@@ -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={},
+74
View File
@@ -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'),
)
+2 -4
View File
@@ -31,10 +31,8 @@ from core.api.client import ApiClient # noqa: E402
from core.recognition.local_cls import LocalClassifier # noqa: E402
from core.recognition.model_sync import ModelSync # noqa: E402
ROOT = os.path.dirname(os.path.dirname(HERE)) # 项目根(…\嵌入式识别)
PY_TRAIN = os.path.join(ROOT, 'yolo-training')
REAL_ONNX = os.path.join(PY_TRAIN, 'runs', 'cls', 'product', 'weights', 'best.onnx')
REAL_CLASSES = os.path.join(PY_TRAIN, 'datasets', 'cls', 'classes.json')
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': {}}
+10 -38
View File
@@ -1,13 +1,5 @@
# -*- coding: utf-8 -*-
"""回归测试:入库「手动确认」账号开关(2026-11-29)。
服务端 profiles.inbound_auto_submit 默认 false ⇒ 入库必须点「确认记账」;
开启 ⇒ 恢复旧行为(拿走货即自动提交)。分拣工位不受影响。
**识别不受影响**:免称重(袋/包/桶)照旧自动抓拍识别,只是认出后
由 confirm_before_submit() 强制进确认页,点了才记账。
不需要秤/摄像头/网络:只验证闸门、登录取值与分页接口的接线。
"""
"""两种工位都自动识别,必须人工确认。"""
import sys
import io
import os
@@ -40,20 +32,14 @@ def check(name, cond, extra=''):
fail.append(name)
# 1) 默认(引擎构造、未登录)= 旧行为(本地 config 兜底 True),保证演示/旧测试不变
check('默认保持旧行为:submit_on_remove=True',
eng.submit_on_remove() is True)
check('默认保持旧行为:confirm_before_submit=True(config 默认)',
eng.confirm_before_submit() is True)
# 2) 账号关闭(服务端默认 false)⇒ 必须手动点确认
eng.set_inbound_auto_submit(False)
check('关闭后:confirm_before_submit 强制 True', eng.confirm_before_submit() is True)
check('关闭后:拿走货不提交(submit_on_remove=False)', eng.submit_on_remove() is False)
check('关闭后:免称重仍自动识别(auto_noweigh_on=True)',
eng.auto_noweigh_on() is True)
check('关闭后有模式日志', any('手动确认' in str(p) for ev, p in logs if ev == 'log'))
# 旧配置要求自动提交,也必须等人点确认。
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 = []
@@ -64,20 +50,6 @@ _one = {'id': 'x1', 'item_name': '土豆', 'unit': '袋',
eng._to_count_confirm('土豆', _one, [_one])
check('免称重认出后进确认页(不直接提交)', len(seen) == 1, )
# 3) 账号开启 ⇒ 恢复旧行为(拿走即提交)
eng.set_inbound_auto_submit(True)
check('开启后:submit_on_remove 恢复 True', eng.submit_on_remove() is True)
check('开启后:免称重自动识别仍为 True', eng.auto_noweigh_on() is True)
# 4) 分拣工位不受影响(本来就要求点击确认)
CFG_PICK = dict(CFG)
CFG_PICK['account'] = {'role': 'picking'}
eng_pick = FlowEngine(CFG_PICK, lambda ev, p=None: None)
eng_pick.refresh_pending = lambda initial=False: None
eng_pick.set_inbound_auto_submit(False)
check('分拣:submit_on_remove 不受开关影响(仍取 config=True)',
eng_pick.submit_on_remove() is True)
# 5) 登录按服务端下发值接线:api.login 写 False ⇒ 引擎变手动
CFG_LOGIN = dict(CFG)
CFG_LOGIN['account'] = {'role': 'inspection', 'username': 'u', 'password': 'p'}
@@ -87,7 +59,7 @@ eng2._sync_prompts = lambda force=False: None
def fake_login():
eng2.api.inbound_auto_submit = False # 服务端 profile 下发:默认关
eng2.api.inbound_auto_submit = True # 服务端 profile 下发:默认关
return {}
+11
View File
@@ -207,6 +207,17 @@ 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'])
shutil.rmtree(root, ignore_errors=True)
print()
if fails:
+1 -1
View File
@@ -222,7 +222,7 @@ check('available() 为假', lc.available() is False)
check('reason() 说得出原因', bool(lc.reason()))
check('predict 返回空 dict', lc.predict(img, ['苹果']) == {})
check('空路径直接返回空', lc.predict('', ['苹果']) == {})
a = Assist(cfg_of())
a = Assist(cfg_of({'model': 'no/such.onnx', 'classes': 'no/such.json'}))
check('建议模式里 local_suggest 同样返回 None',
a.local_suggest(img, ['苹果']) is None)
+329
View File
@@ -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)
+48 -18
View File
@@ -39,7 +39,7 @@ class _BoolVar:
self._sw.set(v)
APP_VERSION = '1.0.72'
APP_VERSION = '1.0.75'
# 待办卡外框粗细:所有卡统一这一个值,选中/确认只换颜色。
# Tk 的 highlight 环画在控件外侧,粗细一变控件尺寸就变,grid 会把整屏
@@ -2992,11 +2992,13 @@ class App:
mode = f.get('mode') or 'weigh'
# 引擎接管高亮:清掉「手动点过的那行 / 空秤预选」的琥珀框。
# 不然确认行(绿)会和之前点过的那张(琥珀)同时亮,看着像选了两张。
# v1.0.75:这里先只记账,真正的重画交给下面的 _reveal_row
# → _paint_focus 一次性做掉(撤琥珀 + 换确认行同一个 configure 批次)。
old_hl = [getattr(self, '_sel_rid', None),
getattr(self, '_pre_rid', None)]
self._sel_rid = None
self._pre_rid = None
self._repaint_cards(old_hl)
self._hl_pending = [x for x in old_hl if x]
self._show_focus_bar(True)
# v1.0.61:不再弹确认条 —— 结论压成状态卡下面那一行提示,
# 有警示语就整行变琥珀色且顶到最前面。
@@ -3034,7 +3036,6 @@ class App:
pass
# 跳过去 + 高亮(翻到那张卡所在的一页)
self._reveal_row(rid)
self._sync_big_confirm()
# 点「作废重拍」后若仍未识别出商品,弹出自定义美观提示窗
was_retry = bool(getattr(self, '_retry_pending', False))
self._retry_pending = False
@@ -3195,11 +3196,22 @@ class App:
v1.0.69:只改颜色(不碰粗细)—— 粗细一变几何就变,
grid 重排让整屏卡跟着跳。
v1.0.75:连**背景色也不改**(ui.focus_fill=true 才恢复粉底)。
实测(tools/probe:点一次卡,逐 1~16ms 采样 + 逐帧比像素):
· 卡片 x/y/宽 高全程一个像素都没动,没有重排、没有翻页;
· 屏幕上真正变化的只有三块:两张卡整块换色(190×121 ×2)、
左列「确认「X」」按钮上的白字、状态卡第二行提示。
也就是说「点一下界面抖」不是布局在动,是**两张卡整块粉底+红框
在同一帧里互换**——大面积色块跳位置,看着就是闪/抖。
现在高亮只留 4px 红边 + 数量数字变红(真正重绘面积从约 46000
像素降到约 2000),颜色没变就一个 configure 都不发。
"""
cache = getattr(self, '_paint_cache', None)
if cache is None:
cache = self._paint_cache = {}
cards = getattr(self, 'todo_cards', {})
fill = bool(self._get('ui.focus_fill', False))
for rid in rids:
if rid is None:
continue
@@ -3212,30 +3224,38 @@ class App:
continue # 没变,一个 configure 都不发
cache[rid] = color
is_focus = (color == CARD_FOCUS_BORDER)
bg = CARD_FOCUS_BG if is_focus else C.surface
bg = CARD_FOCUS_BG if (is_focus and fill) else C.surface
qty_fg = CARD_FOCUS_BORDER if is_focus else C.green
try:
# 粗细也一并写回固定值:万一别处动过它,下一次重画就纠正,
# 几何始终不变(写在 configure 里,值相同 Tk 不会引起重排)。
c.configure(bg=bg,
highlightbackground=color,
highlightcolor=color,
highlightthickness=CARD_HL)
# 粗细只在真不一致时写回(创建时已是 CARD_HL)。Tk 的 Frame
# 把 highlightthickness 算进请求尺寸,无谓地反复写它等于每
# 次点击都让 Tk 重算一遍几何。
if int(c.cget('highlightthickness')) != CARD_HL:
c.configure(highlightthickness=CARD_HL)
c.configure(highlightbackground=color, highlightcolor=color)
if str(c.cget('bg')) != bg:
c.configure(bg=bg)
for attr in ('_name_lbl', '_meta_lbl', '_qty_lbl',
'_thumb_label'):
w = getattr(c, attr, None)
if w is not None:
if attr == '_qty_lbl':
w.configure(bg=bg, fg=qty_fg)
else:
w.configure(bg=bg)
if w is None:
continue
if attr == '_qty_lbl' and str(w.cget('fg')) != qty_fg:
w.configure(fg=qty_fg)
if str(w.cget('bg')) != bg:
w.configure(bg=bg)
except Exception:
pass
def _paint_focus(self, rid):
old = getattr(self, '_focus_rid', None)
self._focus_rid = None if rid is None else str(rid)
self._repaint_cards([old, self._focus_rid])
# v1.0.75:_on_focus 先把「琥珀框要撤掉哪几张」记在这里,
# 和「旧确认行 / 新确认行」合成**一次** _repaint_cards —— 一次点击
# 只发一轮 configure,不会出现两张卡先各自闪一下再互换的过程。
extra = getattr(self, '_hl_pending', None) or []
self._hl_pending = None
self._repaint_cards(list(extra) + [old, self._focus_rid])
def _on_preselect(self, rid):
"""引擎回的「空秤预选」:只记录,不重画
@@ -4000,7 +4020,8 @@ class App:
# 先清掉上一轮留下的列宽约束,否则切列数/搜索筛完后
# 右边会残留一条空白,甚至出现横向滚动
for col in range(12):
self.todo_grid.columnconfigure(col, weight=0, minsize=0)
self.todo_grid.columnconfigure(col, weight=0, minsize=0,
uniform='')
card_w = (cw - gap * (ncols + 1)) // ncols
thumb = int(60 * self.S) if self._thumb_on() else 0
# v1.0.72(性能):列宽/缩略图变了,换行宽度跟着变 → 卡高会变,
@@ -4096,7 +4117,16 @@ class App:
obj.configure(width=card_w)
col += 1
for c in range(ncols):
self.todo_grid.columnconfigure(c, weight=1, minsize=card_w)
# v1.0.75:uniform —— 所有列必须一样宽。
# 不加这一句时:点一下卡(只改了 Frame 的 highlightbackground,
# 颜色而已)Tk 会把这张卡的请求宽度算成 198,grid 一算总宽超了
# 就把**别的列**从 190 压到 182,等下一次 idle 再排回 190:
# 实测 15ms 内整屏 8 张卡来回跳 64 次(190↔198、卡内 label
# 162↔154↔170),肉眼看就是「点一下界面抖一下」。
# 加了 uniform 后同样的操作 0 次几何跳变(tools/_ui_jitter_check.py
# 会盯着这条,别再删)。
self.todo_grid.columnconfigure(c, weight=1, minsize=card_w,
uniform='cf')
return page
# v1.0.70:摆完按**真实几何**兜底。卡高是靠 winfo_reqheight 估的,
+653 -653
View File
File diff suppressed because it is too large Load Diff
+1167 -1165
View File
File diff suppressed because it is too large Load Diff