来自 入库分拣工作站_源代码_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 由用户侧打包分发,本次只推源码。
352 lines
13 KiB
Python
352 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""入库分拣工作站入口(按 docs/design/20261102-win10-inbound-sorting-station.md 实现)
|
||
|
||
打包成 exe 后有两件额外的事要做:
|
||
① 工作目录钉在程序所在目录 —— config.json / data/ 全是相对路径,
|
||
从快捷方式或其它目录启动时不能跑偏;
|
||
② 摄像头探测/取帧子进程原本用 ``python -m core.evidence._cam_child``,
|
||
打包后没有 python 解释器,改成用本 exe 自己分发(--wb-child <模块>),
|
||
并在分发时补回 sys.stdout(无控制台模式下它是 None,管道通信会崩)。
|
||
"""
|
||
import os
|
||
import shutil
|
||
import tempfile
|
||
import sys
|
||
|
||
|
||
def _app_dir():
|
||
"""程序所在目录:打包后 = exe 所在目录;开发时 = 项目根目录"""
|
||
if getattr(sys, 'frozen', False):
|
||
return os.path.dirname(os.path.abspath(sys.executable))
|
||
return os.path.dirname(os.path.abspath(__file__))
|
||
|
||
|
||
APP_DIR = _app_dir()
|
||
try:
|
||
os.chdir(APP_DIR) # 相对路径统一以程序目录为准
|
||
except Exception:
|
||
pass
|
||
sys.path.insert(0, APP_DIR)
|
||
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,子进程写字给父进程会崩。
|
||
|
||
父进程 Popen 时传了 PIPE,fd 1 依然有效,按文本流重新包一层即可。
|
||
必须是 TextIOWrapper —— _probe_child 用 print,_cam_child 用
|
||
sys.stdout.buffer(只有文本流才有 .buffer),两种写法都得兼容。
|
||
"""
|
||
for name, fd in (('stdout', 1), ('stderr', 2)):
|
||
if getattr(sys, name) is not None:
|
||
continue
|
||
try:
|
||
setattr(sys, name, open(fd, 'w', encoding='utf-8',
|
||
errors='replace', buffering=1,
|
||
closefd=False))
|
||
except Exception:
|
||
setattr(sys, name, open(os.devnull, 'w', encoding='utf-8'))
|
||
|
||
|
||
def _run_child(module, argv):
|
||
"""子进程分发:本 exe --wb-child core.evidence._probe_child 0,2 1280 720"""
|
||
import runpy
|
||
_restore_stdio()
|
||
sys.argv = [module] + list(argv)
|
||
runpy.run_module(module, run_name='__main__', alter_sys=True)
|
||
|
||
|
||
def _report_crash(exc):
|
||
"""打包后没有控制台,出问题必须留下痕迹(日志 + 弹窗),不能静默退出"""
|
||
import traceback
|
||
import datetime
|
||
|
||
tb = traceback.format_exc()
|
||
try:
|
||
os.makedirs('data', exist_ok=True)
|
||
with open(os.path.join('data', 'crash.log'), 'a',
|
||
encoding='utf-8') as f:
|
||
f.write('\n==== %s ====\n%s\n'
|
||
% (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
||
tb))
|
||
except Exception:
|
||
pass
|
||
try:
|
||
import ctypes
|
||
ctypes.windll.user32.MessageBoxW(
|
||
None,
|
||
'程序启动失败,无法继续运行。\n\n%s: %s\n\n'
|
||
'详细信息已写入 data\\crash.log,请把该文件发给维护人员。'
|
||
% (type(exc).__name__, exc),
|
||
'入库分拣工作站', 0x10)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
_MUTEX = None # 命名互斥量句柄,进程存活期间必须一直持有
|
||
|
||
|
||
def _single_instance():
|
||
"""只允许一个实例:双开必然抢同一个摄像头,第二个窗口一帧都看不到。
|
||
|
||
用命名互斥量而不是锁文件:进程被强杀时系统自动释放,不会留下死锁;
|
||
卸载程序也按这个名字(installer.iss 的 AppMutex)判断程序是否在跑。
|
||
"""
|
||
global _MUTEX
|
||
try:
|
||
import ctypes
|
||
k32 = ctypes.windll.kernel32
|
||
h = k32.CreateMutexW(None, False, 'InboundSortingStation')
|
||
if not h:
|
||
return True
|
||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||
return False
|
||
_MUTEX = h # 保持引用,GC 掉就释放了
|
||
except Exception:
|
||
pass # 判不了就别拦着用户
|
||
return True
|
||
|
||
|
||
def _activate_existing():
|
||
"""把已经开着的窗口叫到前台(双击第二次时不让用户以为「没反应」)"""
|
||
try:
|
||
import ctypes
|
||
u = ctypes.windll.user32
|
||
h = (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)
|
||
u.SetForegroundWindow(h)
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _selftest():
|
||
"""依赖自检(打包后用 exe --selftest 跑):结果写 data/selftest.txt
|
||
|
||
现场反馈「打不开/摄像头没画面/打印机不出纸」时,先让对方跑这一条,
|
||
能立刻分清是环境问题还是程序问题。
|
||
"""
|
||
lines = []
|
||
|
||
def check(label, fn):
|
||
try:
|
||
lines.append('[OK] %-14s %s' % (label, fn()))
|
||
except Exception as e: # noqa: BLE001
|
||
lines.append('[FAIL] %-14s %s: %s' % (label, type(e).__name__, e))
|
||
|
||
lines.append('时间: %s' % __import__('datetime').datetime.now()
|
||
.strftime('%Y-%m-%d %H:%M:%S'))
|
||
lines.append('程序: %s' % sys.executable)
|
||
lines.append('目录: %s' % APP_DIR)
|
||
lines.append('打包: %s' % bool(getattr(sys, 'frozen', False)))
|
||
lines.append('-' * 56)
|
||
|
||
def _cv2():
|
||
import cv2
|
||
return 'opencv %s' % cv2.__version__
|
||
|
||
def _pil():
|
||
import PIL
|
||
return 'Pillow %s' % PIL.__version__
|
||
|
||
def _serial():
|
||
import serial
|
||
from core.scale.reader import list_serial_ports
|
||
ports = list_serial_ports()
|
||
return 'pyserial %s, 串口 %s' % (
|
||
serial.__version__,
|
||
', '.join('%s(%s)' % (p.get('device'), p.get('desc', ''))
|
||
for p in ports) or '无')
|
||
|
||
def _printers():
|
||
from core.printing.label import list_printers
|
||
ps = list_printers()
|
||
return '%d 台: %s' % (len(ps), ' / '.join(ps) if ps else '无')
|
||
|
||
def _cameras():
|
||
from core.evidence import frames
|
||
devs = frames.discover_devices(conf_idx=0, want_w=1280, want_h=720,
|
||
timeout=20.0)
|
||
return '%d 台: %s' % (len(devs),
|
||
', '.join('idx%s' % d.get('index')
|
||
for d in devs) or '无')
|
||
|
||
def _cam_names():
|
||
# 走 pygrabber + comtypes(打包后最容易失效的一环)
|
||
from core.evidence import usbcam
|
||
info = usbcam.enumerate_cameras(force=True)
|
||
names = [d.get('name', '') for d in info.get('usb', [])]
|
||
return 'USB %d 台: %s(模式 %s)' % (
|
||
len(names), ' / '.join(names) or '无', info.get('mode', ''))
|
||
|
||
def _api():
|
||
import json
|
||
from core.api.client import ApiClient
|
||
with open(os.path.join(APP_DIR, 'config.json'), encoding='utf-8') as f:
|
||
cfg = json.load(f)
|
||
c = ApiClient(cfg)
|
||
return '服务端 %s' % (getattr(c, 'base_url', '') or '已加载')
|
||
|
||
def _autodetect():
|
||
"""三台设备自动识别的实际结果(现场判断"程序认不认得我的设备"用)"""
|
||
import json
|
||
from core import devices as dv
|
||
with open(os.path.join(APP_DIR, 'config.json'), encoding='utf-8') as f:
|
||
cfg = json.load(f)
|
||
res = dv.detect_all(cfg)
|
||
return dv.summary_text(res)
|
||
|
||
def _win32():
|
||
import win32print
|
||
return 'pywin32 ok, 默认打印机 %s' % (
|
||
win32print.GetDefaultPrinter())
|
||
|
||
def _tk():
|
||
import tkinter as tk
|
||
r = tk.Tk()
|
||
r.withdraw()
|
||
r.update()
|
||
r.destroy()
|
||
return 'Tk %s' % tk.TkVersion
|
||
|
||
def _vision():
|
||
"""识别链路:只发一句话,验证 key + 模型名 + 网络(不发图,省流量)。"""
|
||
import json
|
||
import time
|
||
from core.recognition.cloud import CloudRecognizer
|
||
with open(os.path.join(APP_DIR, 'config.json'), encoding='utf-8') as f:
|
||
cfg = json.load(f)
|
||
v = cfg.get('vision', {}) or {}
|
||
if not v.get('api_key'):
|
||
raise RuntimeError('未配置 vision.api_key')
|
||
r = CloudRecognizer(cfg)
|
||
t = time.time()
|
||
txt = r._chat([{'role': 'user', 'content': '只回答两个字:正常'}],
|
||
r.cfg.get('text_model'), 10)
|
||
return '%s · %s %.1fs → %s' % (
|
||
v.get('provider') or '-', r.cfg.get('text_model'),
|
||
time.time() - t, str(txt or '').strip()[:12])
|
||
|
||
check('opencv', _cv2)
|
||
check('Pillow', _pil)
|
||
check('串口', _serial)
|
||
check('打印机', _printers)
|
||
check('win32', _win32)
|
||
check('摄像头', _cameras)
|
||
check('摄像头名称', _cam_names)
|
||
check('自动识别', _autodetect)
|
||
check('接口', _api)
|
||
check('界面库', _tk)
|
||
# 识别要联网:失败只算 WARN,别让现场误以为设备有问题
|
||
try:
|
||
lines.append('[OK] %-14s %s' % ('识别API', _vision()))
|
||
except Exception as e: # noqa: BLE001
|
||
lines.append('[WARN] %-14s %s(离线或 key 失效,不影响称重/打印)'
|
||
% ('识别API', str(e)[:90]))
|
||
|
||
lines.append('-' * 56)
|
||
bad = sum(1 for ln in lines if ln.startswith('[FAIL]'))
|
||
lines.append('结果: %s' % ('全部通过' if bad == 0 else '%d 项失败' % bad))
|
||
try:
|
||
os.makedirs('data', exist_ok=True)
|
||
with open(os.path.join('data', 'selftest.txt'), 'w',
|
||
encoding='utf-8') as f:
|
||
f.write('\n'.join(lines) + '\n')
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
if __name__ == '__main__':
|
||
# 子进程模式(摄像头探测 / 取帧)——必须在建界面之前分流
|
||
if len(sys.argv) >= 3 and sys.argv[1] == '--wb-child':
|
||
_run_child(sys.argv[2], sys.argv[3:])
|
||
raise SystemExit(0)
|
||
|
||
# 依赖自检:exe --selftest → data/selftest.txt
|
||
if '--selftest' in sys.argv:
|
||
_selftest()
|
||
raise SystemExit(0)
|
||
|
||
# 单实例:两个窗口会抢同一个摄像头/串口,第二个必然「没画面」
|
||
if not _single_instance():
|
||
# 先把已开的窗口叫到前台;叫不出来才弹窗解释
|
||
if not _activate_existing():
|
||
try:
|
||
import ctypes
|
||
ctypes.windll.user32.MessageBoxW(
|
||
None,
|
||
'入库分拣工作站已经在运行了。\n\n'
|
||
'同一台电脑开两个会抢同一个摄像头,第二个窗口看不到画面。\n'
|
||
'请用任务栏上已经打开的那个窗口;如果找不到,'
|
||
'先在任务管理器结束「入库分拣工作站」再重新打开。',
|
||
'程序已在运行', 0x40)
|
||
except Exception:
|
||
pass
|
||
raise SystemExit(0)
|
||
|
||
try:
|
||
from ui.app import run # noqa: E402
|
||
run()
|
||
except SystemExit:
|
||
raise
|
||
except BaseException as e: # noqa: BLE001
|
||
_report_crash(e)
|
||
raise
|