feat: 登录页可改服务器地址,支持无硬件回放测试
- 登录页页脚新增「修改服务器地址」,保存后立即生效并写回 config.json(server.base_url / history),不用重启程序 - camera.replay_dir:把真实商品图片回放当摄像头画面,识别仍走 真实模型,没摄像头也能验证识别准确率 - scale.sim_loop_kg 支持列表,模拟秤每轮换一个重量,便于对上待办 - 识别请求不再继承系统代理(与 ApiClient 一致),修复现场 ProxyError 导致 AI 一直认不出的问题 - 模拟/回放画面不再写入 data/learn;新增 tools/learn_clean_sim.py 清理已被污染(空白图当教材)的样本库 - 重量容差、严格写入开关这类服务端拒绝改成能照做的中文提示 - 版本号统一到 1.0.66,使用说明补对应章节
This commit is contained in:
@@ -1,16 +1,16 @@
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 65, 0), prodvers=(1, 0, 65, 0),
|
||||
ffi=FixedFileInfo(filevers=(1, 0, 66, 0), prodvers=(1, 0, 66, 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.65.0'),
|
||||
StringStruct('FileVersion', '1.0.66.0'),
|
||||
StringStruct('InternalName', 'WeighStation'),
|
||||
StringStruct('OriginalFilename', '入库分拣工作站.exe'),
|
||||
StringStruct('ProductName', '入库分拣工作站'),
|
||||
StringStruct('ProductVersion', '1.0.65.0'),
|
||||
StringStruct('ProductVersion', '1.0.66.0'),
|
||||
StringStruct('LegalCopyright', '内部使用')])]),
|
||||
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
||||
]
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
APP_NAME = '入库分拣工作站'
|
||||
APP_VERSION = '1.0.65'
|
||||
APP_VERSION = '1.0.66'
|
||||
ASSETS = os.path.join(ROOT, 'assets')
|
||||
DIST = os.path.join(ROOT, 'dist')
|
||||
OUT = os.path.join(DIST, APP_NAME)
|
||||
|
||||
+5
-1
@@ -411,8 +411,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 '',
|
||||
|
||||
+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:
|
||||
|
||||
+27
-1
@@ -119,6 +119,26 @@ 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))
|
||||
return ''
|
||||
|
||||
|
||||
class FlowEngine:
|
||||
def __init__(self, cfg, emit):
|
||||
self.cfg = cfg
|
||||
@@ -1809,6 +1829,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'
|
||||
@@ -2104,7 +2130,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;服务端若强制要重量,这里给出
|
||||
|
||||
@@ -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)
|
||||
|
||||
+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
|
||||
|
||||
|
||||
+3
-3
@@ -1,12 +1,12 @@
|
||||
; ============================================================
|
||||
; 入库分拣工作站 · 安装包脚本(Inno Setup 6)
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.64.exe
|
||||
; 编译:iscc installer.iss → dist\入库分拣工作站_安装程序_v1.0.66.exe
|
||||
; 说明:源目录为 build_exe.py 产出的 dist\入库分拣工作站(onedir)
|
||||
; ============================================================
|
||||
|
||||
#define AppName "入库分拣工作站"
|
||||
#ifndef AppVersion
|
||||
#define AppVersion "1.0.64"
|
||||
#define AppVersion "1.0.66"
|
||||
#endif
|
||||
#define AppExe "入库分拣工作站.exe"
|
||||
#define SrcDir "dist\入库分拣工作站"
|
||||
@@ -41,7 +41,7 @@ CloseApplications=yes
|
||||
RestartApplications=no
|
||||
AllowNoIcons=yes
|
||||
ShowLanguageDialog=no
|
||||
VersionInfoVersion=1.0.64.0
|
||||
VersionInfoVersion=1.0.66.0
|
||||
VersionInfoDescription={#AppName} 安装程序
|
||||
VersionInfoProductName={#AppName}
|
||||
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
# -*- 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
|
||||
|
||||
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))
|
||||
|
||||
root.destroy()
|
||||
print('\n结果:%d 项通过,%d 项失败' % (ok, fail))
|
||||
sys.exit(1 if fail else 0)
|
||||
@@ -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())
|
||||
@@ -505,15 +505,29 @@ class App:
|
||||
self.lbl_login_msg.pack(fill='x', pady=(px(10), px(4)))
|
||||
|
||||
# ---- 页脚 ----
|
||||
# 登录前就能换服务器:换机房/切备用机不用改 config.json 再重启。
|
||||
# 分两行:地址单独一行(长短不影响按钮),按钮放第二行,防止
|
||||
# 地址一长就把「修改」挤成半截字。
|
||||
foot = tk.Frame(form, bg=C.surface)
|
||||
foot.pack(fill='x', pady=(px(10), 0))
|
||||
srv = self.cfg.get('server', {}) or {}
|
||||
tag = '离线模拟' if srv.get('mock') else (srv.get('base_url') or '')
|
||||
tk.Label(foot, text='服务器:%s' % (tag or '未配置'), font=font(10),
|
||||
bg=C.surface, fg=C.ink3).pack(side='left')
|
||||
tk.Button(foot, text='退出程序', font=font(11), bd=0, bg=C.surface,
|
||||
foot.pack(fill='x', pady=(px(12), 0))
|
||||
self.lbl_login_srv = tk.Label(foot, text='', font=font(10),
|
||||
bg=C.surface, fg=C.ink3,
|
||||
anchor='w', justify='left',
|
||||
cursor='hand2')
|
||||
self.lbl_login_srv.pack(fill='x')
|
||||
self.lbl_login_srv.bind('<Button-1>', lambda e: self._edit_server())
|
||||
|
||||
frow = tk.Frame(foot, bg=C.surface)
|
||||
frow.pack(fill='x', pady=(px(8), 0))
|
||||
tk.Button(frow, text='修改服务器地址', font=font(10), bd=0,
|
||||
bg='#eef2f7', fg=C.brand, activebackground='#e3e9f2',
|
||||
activeforeground=C.brand, cursor='hand2',
|
||||
padx=px(12), pady=px(4),
|
||||
command=self._edit_server).pack(side='left')
|
||||
tk.Button(frow, text='退出程序', font=font(10), bd=0, bg=C.surface,
|
||||
fg=C.ink3, activebackground=C.surface,
|
||||
cursor='hand2', command=self._quit).pack(side='right')
|
||||
self._refresh_login_srv()
|
||||
|
||||
# 预填上次账号
|
||||
if acc.get('username'):
|
||||
@@ -537,6 +551,204 @@ class App:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------- 登录页改服务器地址
|
||||
def _refresh_login_srv(self):
|
||||
"""登录页页脚显示当前服务器(改完地址立即刷新,不用重启)
|
||||
|
||||
地址太长就中间打点:页脚是一行文字,撑出去会把第二行的按钮
|
||||
顶出可视区(现场就遇到过「修改」只剩半个字)。完整地址在
|
||||
修改窗口和 config.json 里都能看到。
|
||||
"""
|
||||
lbl = getattr(self, 'lbl_login_srv', None)
|
||||
if lbl is None:
|
||||
return
|
||||
srv = self.cfg.get('server', {}) or {}
|
||||
if srv.get('mock'):
|
||||
txt = '服务器:离线模拟(不连后端)'
|
||||
else:
|
||||
url = str(srv.get('base_url') or '未配置')
|
||||
if len(url) > 46:
|
||||
url = url[:20] + '…' + url[-22:]
|
||||
txt = '服务器:%s' % url
|
||||
try:
|
||||
lbl.configure(text=txt)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _edit_server(self):
|
||||
"""登录页直接改服务器地址。
|
||||
|
||||
现场换机房 / 切备用服务器不用退出程序、也不用手工编辑 config.json:
|
||||
保存后写回配置,并立刻作用到引擎的 ApiClient —— base_url 在
|
||||
__init__ 里就缓存了,只改 self.cfg 不会生效。
|
||||
"""
|
||||
if getattr(self, '_logging_in', False):
|
||||
return # 正在登录,别中途换地址
|
||||
px, font = self._px, self._font
|
||||
srv = self.cfg.setdefault('server', {})
|
||||
cur = '' if srv.get('mock') else str(srv.get('base_url') or '')
|
||||
d = self._dlg('服务器地址', px(560), px(392))
|
||||
body = tk.Frame(d, bg='#ffffff')
|
||||
body.pack(fill='both', expand=True, padx=px(24), pady=px(16))
|
||||
|
||||
tk.Label(body, text='服务器地址', font=font(15, 'bold'),
|
||||
bg='#ffffff', fg=C.ink).pack(anchor='w')
|
||||
tk.Label(body, text=('换机房 / 切备用服务器时在这里改。保存后立即生效,'
|
||||
'并写回程序目录的 config.json(server.base_url);'
|
||||
'原来是离线模拟的会一并关掉。'),
|
||||
font=font(11), bg='#ffffff', fg=C.ink2, justify='left',
|
||||
wraplength=px(500)).pack(anchor='w', pady=(px(2), px(10)))
|
||||
|
||||
card = Card(body, radius=px(12), pad=px(1), height=px(58),
|
||||
border='#dfe6ef')
|
||||
card.pack(fill='x')
|
||||
card.pack_propagate(False)
|
||||
ent = tk.Entry(card.body, font=font(14), bd=0, relief='flat',
|
||||
bg='#ffffff', fg=C.ink)
|
||||
ent.pack(fill='both', expand=True, padx=px(14), pady=px(6))
|
||||
if cur:
|
||||
ent.insert(0, cur)
|
||||
|
||||
msg = tk.Label(body, text='', font=font(11), bg='#ffffff', fg=C.ink2,
|
||||
anchor='w', justify='left', wraplength=px(500))
|
||||
msg.pack(fill='x', pady=(px(8), 0))
|
||||
|
||||
def say(text, color=C.ink2):
|
||||
try:
|
||||
msg.configure(text=text, fg=color)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 历史地址(用过的主备机):点一下填进输入框
|
||||
hist = [x for x in (srv.get('history') or [])
|
||||
if isinstance(x, str) and x and x != cur][:3]
|
||||
if hist:
|
||||
row = tk.Frame(body, bg='#ffffff')
|
||||
row.pack(fill='x', pady=(px(8), 0))
|
||||
tk.Label(row, text='用过:', font=font(10), bg='#ffffff',
|
||||
fg=C.ink3).pack(side='left')
|
||||
for u in hist:
|
||||
shown = u.replace('https://', '').replace('http://', '')
|
||||
if len(shown) > 32:
|
||||
shown = shown[:29] + '…'
|
||||
TouchButton(row, text=shown, fill='#eef2f7', fg=C.ink2,
|
||||
height=px(34), radius=px(17), font=font(10),
|
||||
surface='#ffffff',
|
||||
command=lambda x=u: (ent.delete(0, 'end'),
|
||||
ent.insert(0, x))).pack(
|
||||
side='left', padx=(px(6), 0))
|
||||
|
||||
def pick_url():
|
||||
raw = ent.get().strip()
|
||||
if not raw:
|
||||
say('请填写服务器地址,例如 https://www.xdjchuanhui.com/api',
|
||||
C.red)
|
||||
return ''
|
||||
low = raw.lower()
|
||||
if not (low.startswith('http://') or low.startswith('https://')):
|
||||
say('地址必须以 http:// 或 https:// 开头', C.red)
|
||||
return ''
|
||||
return raw.rstrip('/')
|
||||
|
||||
def do_test():
|
||||
url = pick_url()
|
||||
if not url:
|
||||
return
|
||||
say('正在测试 %s …' % url, C.ink2)
|
||||
res = {}
|
||||
|
||||
def work():
|
||||
try:
|
||||
import requests
|
||||
s = requests.Session()
|
||||
s.trust_env = False # 与正式客户端一致:直连
|
||||
r = s.get(url + '/mobile/picking/weigh-station/pending',
|
||||
timeout=(3, 5), allow_redirects=False)
|
||||
code = int(r.status_code)
|
||||
if code in (200, 401, 403):
|
||||
res['ok'] = True
|
||||
res['msg'] = ('连接正常(HTTP %d;未登录返回 401 是正常的)'
|
||||
% code)
|
||||
elif code == 404:
|
||||
res['msg'] = ('服务器有响应,但路径 404:地址多半少了'
|
||||
' /api,或指到了别的站点')
|
||||
else:
|
||||
res['msg'] = '服务器有响应,但返回 HTTP %d' % code
|
||||
except Exception as e: # noqa: BLE001
|
||||
res['msg'] = ('连不上:%s'
|
||||
% (getattr(e, 'message', None) or e))
|
||||
|
||||
threading.Thread(target=work, daemon=True).start()
|
||||
|
||||
def wait(n=0):
|
||||
if res:
|
||||
say(res.get('msg'), '#1a7f37' if res.get('ok') else C.red)
|
||||
elif n < 40:
|
||||
d.after(150, lambda: wait(n + 1))
|
||||
else:
|
||||
say('测试超时(网络不通或服务端没响应)', C.red)
|
||||
|
||||
d.after(150, wait)
|
||||
|
||||
def do_save():
|
||||
url = pick_url()
|
||||
if not url:
|
||||
return
|
||||
backup = {'base_url': srv.get('base_url'),
|
||||
'mock': srv.get('mock'),
|
||||
'history': srv.get('history')}
|
||||
srv['base_url'] = url
|
||||
srv['mock'] = False
|
||||
keep = [x for x in (srv.get('history') or [])
|
||||
if isinstance(x, str) and x and x != url]
|
||||
# 把「刚离开的地址」也存进历史:切到备用机之后要能一键切回来
|
||||
prev = cur.strip() if isinstance(cur, str) else ''
|
||||
if prev and prev != url and prev not in keep:
|
||||
keep.insert(0, prev)
|
||||
srv['history'] = ([url] + keep)[:5]
|
||||
try:
|
||||
save_config(self.cfg)
|
||||
except Exception as e: # noqa: BLE001
|
||||
# 写盘失败就把内存里的改动回滚,别让界面和文件不一致
|
||||
for k, v in backup.items():
|
||||
if v is None:
|
||||
srv.pop(k, None)
|
||||
else:
|
||||
srv[k] = v
|
||||
say('写入 config.json 失败:%s' % e, C.red)
|
||||
return
|
||||
# base_url 是 ApiClient.__init__ 里缓存的,只改 cfg 不会生效
|
||||
try:
|
||||
self.engine.api.base_url = url
|
||||
self.engine.api.mock = False
|
||||
# 旧服务器的 token 不能带给新服务器
|
||||
self.engine.api.token = ''
|
||||
except Exception:
|
||||
pass
|
||||
self._refresh_login_srv()
|
||||
try:
|
||||
d.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
self.log('服务器地址已改为 %s(已写入 config.json)' % url)
|
||||
self._login_msg('服务器已切换到 %s' % url, '#1a7f37')
|
||||
|
||||
btns = tk.Frame(body, bg='#ffffff')
|
||||
btns.pack(side='bottom', fill='x', pady=(px(12), 0))
|
||||
TouchButton(btns, text='取消', command=d.destroy, fill='#eef2f7',
|
||||
fg=C.ink2, height=px(56), width=px(120), radius=px(14),
|
||||
font=font(14), surface='#ffffff').pack(side='right')
|
||||
TouchButton(btns, text='保存并应用', command=do_save, fill=C.brand,
|
||||
fg='white', height=px(56), width=px(170), radius=px(14),
|
||||
font=font(14, 'bold'), surface='#ffffff').pack(
|
||||
side='right', padx=(0, px(10)))
|
||||
TouchButton(btns, text='测试连接', command=do_test, fill='#eef2f7',
|
||||
fg=C.ink2, height=px(56), width=px(120), radius=px(14),
|
||||
font=font(14), surface='#ffffff').pack(side='left')
|
||||
|
||||
ent.bind('<Return>', lambda e: (do_save(), 'break')[1])
|
||||
ent.focus_set()
|
||||
|
||||
|
||||
def _login_entry(self, parent, secret=False, label=''):
|
||||
e = tk.Entry(parent, font=self._font(17), bd=0, relief='flat',
|
||||
@@ -2824,8 +3036,10 @@ class App:
|
||||
if not p.get('row'):
|
||||
messagebox.showwarning(
|
||||
'还没选商品',
|
||||
'先在右边点一下这次要记账的那一行;'
|
||||
'数量按实际点数填。', parent=self.root)
|
||||
'先在右边点一下这次要记账的那一行。\n\n'
|
||||
'按斤/公斤称重的行:点完就按秤上读数记,不用填数量;\n'
|
||||
'按件/按桶/按袋的行:点完在「数量」里填实际点数。',
|
||||
parent=self.root)
|
||||
else:
|
||||
messagebox.showwarning(
|
||||
'数量不对', '数量要大于 0,请点「+」或直接输入。',
|
||||
@@ -3051,6 +3265,34 @@ class App:
|
||||
% len(show))
|
||||
self._paint_group_bar()
|
||||
|
||||
@staticmethod
|
||||
def _is_independent_inbound(r):
|
||||
"""仅用于待办卡片展示:判断是否为独立入库原材料。"""
|
||||
if not isinstance(r, dict):
|
||||
return False
|
||||
details = r.get('processing_details')
|
||||
value = (details.get('independent_inbound')
|
||||
if isinstance(details, dict) else None)
|
||||
if value is None:
|
||||
value = r.get('independent_inbound')
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in ('1', 'true', 'yes', 'y', '是')
|
||||
return bool(value)
|
||||
|
||||
def _paint_independent_badge(self, card, r):
|
||||
"""在商品名下方显示/隐藏独立入库提示,不参与业务数据。"""
|
||||
badge = getattr(card, '_independent_badge', None)
|
||||
if badge is None:
|
||||
return
|
||||
if self._is_independent_inbound(r):
|
||||
badge.configure(text='独立入库 · 加工原材料')
|
||||
if badge.winfo_manager() != 'pack':
|
||||
badge.pack(before=getattr(card, '_meta_lbl', None),
|
||||
side='top', anchor='w', padx=self._px(12),
|
||||
pady=(self._px(4), 0))
|
||||
elif badge.winfo_manager() == 'pack':
|
||||
badge.pack_forget()
|
||||
|
||||
def _update_card(self, r):
|
||||
"""就地刷新一张卡(数量/客户/规格变了但行没变)——只改文本不重建"""
|
||||
rid = str(r.get('id'))
|
||||
@@ -3063,6 +3305,7 @@ class App:
|
||||
meta = ' · '.join(x for x in [
|
||||
('规格 ' + str(r['spec'])) if r.get('spec') else '',
|
||||
str(who or '')] if x)
|
||||
self._paint_independent_badge(c, r)
|
||||
pairs = ((getattr(c, '_name_lbl', None), r.get('item_name') or '—'),
|
||||
(getattr(c, '_qty_lbl', None), '%g %s' % (q, unit)),
|
||||
(getattr(c, '_meta_lbl', None), meta))
|
||||
@@ -3095,6 +3338,11 @@ class App:
|
||||
wraplength=int(150 * self.S))
|
||||
lbl_name.pack(side='top', fill='x', padx=px(12), pady=(px(10), 0))
|
||||
c._name_lbl = lbl_name # _layout_cards 按列宽改 wraplength
|
||||
badge = tk.Label(c, text='独立入库 · 加工原材料',
|
||||
font=self._font(10, 'bold'), bg='#fff4d6',
|
||||
fg='#9a5b00', anchor='w', justify='left')
|
||||
c._independent_badge = badge
|
||||
self._paint_independent_badge(c, r)
|
||||
meta = ' · '.join(x for x in [
|
||||
('规格 ' + str(r['spec'])) if r.get('spec') else '',
|
||||
str(who or '')] if x)
|
||||
|
||||
@@ -25,7 +25,25 @@
|
||||
build_assets/ 打包素材(VC++ 运行库 vc_redist.x64.exe)
|
||||
打包.bat 双击打包
|
||||
dist/ 产物:dist\入库分拣工作站\(绿色版)
|
||||
dist\入库分拣工作站_安装程序_v1.0.64.exe(安装包)
|
||||
dist\入库分拣工作站_安装程序_v1.0.66.exe(安装包)
|
||||
|
||||
【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)】
|
||||
|
||||
@@ -46,6 +64,66 @@
|
||||
· 高级设置新增「标签二维码兜底字段」(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,现场当前已开启)】
|
||||
|
||||
◆ 现在这台机器的状态
|
||||
|
||||
Reference in New Issue
Block a user