Files
Ubuntu edaa057d68 feat(1.0.72): 本地模型自动更新 + 入库照片送审(数据飞轮)
基于 1.0.71 合入:model_sync/local_cls/assist 本地模型自动更新(版本比对/下载/sha+加载校验/替换失败回滚);review_queue 入库照先落队列、成功才送审、回执 image_sha256 核对;build_exe/installer 有 models/cls 就打包;版本 1.0.72;补工具脚本、文档与 config.sanitized.json。
2026-12-02 15:58:27 +08:00

284 lines
13 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""本地模型自动更新:服务器上有新版本就换,换不动就不换。
为什么需要它:模型不是「装一次就完」的东西 —— 每攒一批审核图就重训一版,
而现场十来台秤分散在几个库房。人工拷 U 盘的结果是「三台新、两台旧,
谁也说不出哪台是哪版」。这里把「哪一版」变成一个可比对的版本号。
三条底线(代码照这个写):
1. **先验后用**:下载完先算 sha256、再用端上那份 `local_cls.py` 真加载一遍;
过不了就整批丢弃 —— 宁可继续用旧版,也不能让某台秤明天开局「本地没意见」。
2. **原子替换 + 失败回滚**:两个文件先落 `models/cls/.incoming/`,验过才
`os.replace` 到正式路径,`model.json` 最后写;换到一半失败(第二个文件换不动、
清单没写成)就按 `.incoming/.backup` 把已换的文件还原,磁盘回到旧版完整状态。
中途断电最坏是版本号对不上、下次重装一遍。
3. **绝不挡流程**:任何异常都吞掉、只返回一句话。登录、称重、提交一步都不等它。
配置(config.json → vision.assist,都有默认值):
auto_update 默认 true;关掉就只用手工放进 models/cls 的文件
update_interval_sec 默认 21600(6 小时);登录时先查一次
update_timeout 下载超时秒,默认 180
返回的 status:
current 服务器版本与本地一致,什么都没做
updated 换了新版本(附新 manifest,调用方要重建 LocalClassifier)
skipped 没开自动更新 / mock 模式 / 服务器还没发布模型
failed 取版本、下载、校验任一步失败 —— 本地文件保持原样
"""
import hashlib
import json
import os
import shutil
import time
from core.recognition.local_cls import LocalClassifier
DEFAULTS = {
'auto_update': True,
'update_interval_sec': 21600,
'update_timeout': 180,
}
# 与后台 `server/src/services/clsModelService.ts` 的白名单一致;新增文件三处一起改
MODEL_FILES = ('product_cls.onnx', 'classes.json')
def _sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
while True:
b = f.read(1 << 20)
if not b:
break
h.update(b)
return h.hexdigest()
def _read_json(path):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def _iso_now():
t = time.localtime()
off = -(time.altzone if t.tm_isdst > 0 else time.timezone)
sign = '+' if off >= 0 else '-'
off = abs(int(off))
return '%s%s%02d:%02d' % (time.strftime('%Y-%m-%dT%H:%M:%S', t), sign,
off // 3600, (off % 3600) // 60)
class ModelSync:
"""模型拉取/校验/替换。构造不碰网络,也不碰磁盘。"""
def __init__(self, cfg=None):
v = (cfg or {}).get('vision') if isinstance(cfg, dict) else {}
if not isinstance(v, dict):
v = {}
raw = v.get('assist')
self.cfg = dict(DEFAULTS)
if isinstance(raw, dict):
self.cfg.update(raw)
self.enabled = bool(self.cfg.get('auto_update', True))
try:
self.interval = max(60, int(self.cfg.get('update_interval_sec')
or 21600))
except (TypeError, ValueError):
self.interval = 21600
try:
self.timeout = max(10, int(self.cfg.get('update_timeout') or 180))
except (TypeError, ValueError):
self.timeout = 180
self.model_path = str(self.cfg.get('model')
or 'models/cls/product_cls.onnx')
self.classes_path = str(self.cfg.get('classes')
or 'models/cls/classes.json')
self.dir = os.path.dirname(self.model_path) or 'models/cls'
self.manifest_path = os.path.join(self.dir, 'model.json')
self._next_at = 0.0 # 下次允许检查的时刻
# ------------------------------------------------------------ 状态
def due(self):
return time.time() >= self._next_at
def local_manifest(self):
"""本机 model.json(发布/自动更新写的那份);没有就返回 {}。"""
return _read_json(self.manifest_path)
def local_version(self):
return str(self.local_manifest().get('version') or '')
def _files_present(self):
for name in MODEL_FILES:
if not os.path.isfile(os.path.join(self.dir, name)):
return False
return True
# ------------------------------------------------------------ 主流程
def run(self, api, force=False):
"""比对 + 下载 + 替换。**不抛异常**,返回 {'status': ..., ...}。"""
if not self.enabled:
self._next_at = time.time() + self.interval
return {'status': 'skipped', 'reason': 'auto_update 已关闭'}
if getattr(api, 'mock', False):
self._next_at = time.time() + self.interval
return {'status': 'skipped', 'reason': 'mock 模式不拉模型'}
if not force and not self.due():
return {'status': 'skipped', 'reason': '还没到检查时间'}
self._next_at = time.time() + self.interval
try:
remote = api.cls_model_manifest()
except Exception as e: # noqa: BLE001
return {'status': 'failed', 'reason': '取版本失败:%s' % e}
if not remote:
return {'status': 'skipped', 'reason': '服务器未发布模型'}
version = str(remote.get('version') or '').strip()
want = self._remote_files(remote)
if not version or not want:
return {'status': 'failed', 'reason': '服务器版本清单不完整'}
if str(self.local_manifest().get('version') or '') == version:
if self._files_present():
return {'status': 'current', 'version': version}
# 清单写着这版、文件却没了(被人删了 / 上次拷了一半)→ 当成没装,重下一遍
return self._install(api, remote, version, want)
def _install(self, api, remote, version, want):
"""下载 → 校验 → 试加载 → 换文件 → 写清单;任一步失败都回到旧版。
「换文件」不是一个原子动作:product_cls.onnx 和 classes.json 是两个
`os.replace`。只把第一个换成功、第二个失败(被杀毒软件占住、磁盘满、
断电)就会留下「新 onnx + 旧 classes + 旧 manifest」——端上加载得了,
却用两份对不上的资产推理,还不报错。所以替换前先备份旧文件,替换/写
清单任一步抛异常就回滚已替换的那几个(见 `_rollback`)。
"""
incoming = os.path.join(self.dir, '.incoming')
backup_dir = os.path.join(incoming, '.backup')
replaced = [] # 已换到正式路径的文件名(回滚按逆序还原)
backups = {} # name -> 备份路径;None = 替换前本来没有
try:
shutil.rmtree(incoming, ignore_errors=True)
os.makedirs(incoming, exist_ok=True)
for name in MODEL_FILES:
api.download_cls_model_file(
name, os.path.join(incoming, name),
sha256=want[name]['sha256'], size=want[name]['size'],
timeout=self.timeout)
# 落盘后再自己算一遍:客户端那边验过,这是「换上去之前」的总闸
for name in MODEL_FILES:
got = _sha256(os.path.join(incoming, name))
if got != want[name]['sha256']:
raise RuntimeError('%s 校验不一致(%s…)' % (name, got[:12]))
# 试加载:端上读不了就不换 —— 换模型是为了更好用,不是换一个加载不了的
probe_cfg = dict(self.cfg)
probe_cfg['model'] = os.path.join(incoming, 'product_cls.onnx')
probe_cfg['classes'] = os.path.join(incoming, 'classes.json')
probe = LocalClassifier({'assist': probe_cfg})
if not probe.available():
raise RuntimeError('端上读不了这版模型:%s' % probe.reason())
# 结果字段先算好:等文件换上去之后再抛异常,就没人能还原了
class_count = int(remote.get('class_count') or 0)
notes = str(remote.get('notes') or '')
# 动正式目录之前,先把旧的一对文件留一份(没有就记 None)
os.makedirs(backup_dir, exist_ok=True)
for name in MODEL_FILES:
dst = os.path.join(self.dir, name)
if os.path.isfile(dst):
bak = os.path.join(backup_dir, name)
shutil.copy2(dst, bak)
backups[name] = bak
else:
backups[name] = None
# 两个文件依次换;任一失败(或下面写清单失败)都回滚
for name in MODEL_FILES:
os.replace(os.path.join(incoming, name),
os.path.join(self.dir, name))
replaced.append(name)
self._write_manifest(version, remote, want)
return {'status': 'updated',
'version': version,
'class_count': class_count,
'notes': notes}
except Exception as e: # noqa: BLE001
self._rollback(replaced, backups)
return {'status': 'failed', 'reason': '%s' % e}
finally:
shutil.rmtree(incoming, ignore_errors=True)
def _rollback(self, replaced, backups):
"""把已经换上去的文件还原成替换前的样子(尽力而为,绝不抛异常)。
调用点只有 `_install` 的 except:走到那里说明「两个文件换到一半」或
「文件换完了但清单没写成」。有备份的 copy2 回去;替换前本来没有的,
就把刚落下的新文件删掉。回滚自己失败也只能放过 —— 返回给调用方的仍是
failed,秤端下次检查会按清单版本重新装一遍。
"""
for name in reversed(list(replaced)):
dst = os.path.join(self.dir, name)
bak = backups.get(name)
try:
if bak and os.path.isfile(bak):
shutil.copy2(bak, dst)
elif os.path.isfile(dst):
os.remove(dst)
except OSError:
pass
# 清单写失败可能留下半个 model.json.tmp,顺手清掉(旧 model.json 没动)
try:
tmp = self.manifest_path + '.tmp'
if os.path.isfile(tmp):
os.remove(tmp)
except OSError:
pass
# ------------------------------------------------------------ 内部
def _remote_files(self, remote):
"""服务端清单 → {name: {sha256, size}};缺一个就整单作废。"""
listed = remote.get('files')
rows = listed if isinstance(listed, list) else []
out = {}
for row in rows:
if not isinstance(row, dict):
continue
name = str(row.get('name') or '')
sha = str(row.get('sha256') or '').strip().lower()
try:
size = int(row.get('size') or 0)
except (TypeError, ValueError):
size = 0
if name in MODEL_FILES and len(sha) == 64 and size > 0:
out[name] = {'sha256': sha, 'size': size}
return out if len(out) == len(MODEL_FILES) else {}
def _write_manifest(self, version, remote, files):
data = {
'schema': 1,
'version': version,
'created_at': str(remote.get('created_at') or ''),
'installed_at': _iso_now(),
'imgsz': int(remote.get('imgsz') or 0),
'class_count': int(remote.get('class_count') or 0),
'notes': str(remote.get('notes') or ''),
'source': 'server',
'files': {k: {'sha256': v['sha256'], 'size': v['size']}
for k, v in files.items()},
}
tmp = self.manifest_path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write('\n')
f.flush()
os.fsync(f.fileno())
os.replace(tmp, self.manifest_path)