来自 秤端源码-v1.0.76:flow 生成 recognition_audit(本地候选/耗时 + 云端结果)并随 review_queue 送审;assist/local_cls 记录本地推理;审核后台可查;版本/安装包 1.0.76。保留 1.0.71-1.0.75 既有修复与文档;config.json/data/models 未入库。
363 lines
17 KiB
Python
363 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""入库照片送审队列(数据飞轮第二步:秤 → 后台「识别样本」待审核)。
|
||
|
||
为什么不是「入库成功后顺手发一张」:
|
||
|
||
入库刚成功、秤就断电/断网,那一次发送就永远没了 —— 而这一笔货是真实入账的,
|
||
照片却再也进不了训练库。反过来,入库还没结论就先送审,可能出现「训练库里
|
||
挂着一张不属于任何账的图」。
|
||
|
||
所以顺序固定为三步:
|
||
|
||
1. 提交入库请求**之前**:把「哪次操作、哪张原图、哪条货单」写进本机队列,
|
||
原图复制一份进来(data/snapshots 会被滚动清理,只记路径靠不住);
|
||
2. 提交日志(core/submission/journal.py)给出 succeeded 才真的发;
|
||
3. 入库被拒绝(rejected)→ 队列里这条直接删;断网/重启/断电 → 队列还在盘上,
|
||
后台线程每 20 秒接着查、接着传。
|
||
|
||
幂等靠操作号:它同时当 sample_id 和 event_id,服务端 event_id 同图重复提交
|
||
只会返回 duplicate,不会产生第二行。回执还要核对照片 sha256、单号、货单,
|
||
对不上就当没送到(留队列重试,不删)。
|
||
|
||
目录(一个操作一个目录,方便人眼看、也方便整条丢弃):
|
||
data/review_pending/<操作号>/meta.json
|
||
data/review_pending/<操作号>/photo.jpg
|
||
data/review_rejected.json 永久失败(数据本身有问题)的清单,交人工
|
||
"""
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import re
|
||
import tempfile
|
||
import uuid
|
||
import shutil
|
||
import time
|
||
|
||
from core.storage import atomic
|
||
from core.submission.journal import (JOURNAL_DIR, STATE_REJECTED,
|
||
STATE_SUCCEEDED)
|
||
|
||
PENDING_DIR = 'data/review_pending'
|
||
REJECTED_FILE = 'data/review_rejected.json'
|
||
RETRY_SECONDS = 20 # 后台线程多久回来看一次「这笔入库结了吗」
|
||
BACKOFF_SECONDS = 120 # 上传失败的退避
|
||
MAX_BACKOFF_SECONDS = 900
|
||
MAX_TRIES = 5 # 回执连续对不上这么多次就转人工,别无限重试
|
||
# 明确「数据有问题」的状态码:重传也一样会被拒,留着只会无限刷日志
|
||
PERMANENT_HTTP = (400, 409, 413, 422)
|
||
_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}'
|
||
r'-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)
|
||
_SAFE = re.compile(r'[^A-Za-z0-9._:-]')
|
||
|
||
|
||
def _iso(epoch_sec):
|
||
"""本地时区的 ISO 时间(服务端 new Date() 直接能解析)。"""
|
||
t = time.localtime(epoch_sec)
|
||
off = -(time.altzone if t.tm_isdst > 0 else time.timezone)
|
||
sign = '+' if off >= 0 else '-'
|
||
off = abs(int(off))
|
||
return '%s%s%02d:%02d' % (time.strftime('%Y-%m-%dT%H:%M:%S', t),
|
||
sign, off // 3600, (off % 3600) // 60)
|
||
|
||
|
||
def build_fields(api, op, row, source, captured_at, station="inspection"):
|
||
"""把一条入库行翻成 /mobile/recognition/samples 的字段(全部字符串)。
|
||
|
||
这里只描述事实:货单名原样送(「外地芹菜」就是「外地芹菜」),
|
||
训练用名的翻译在后台审核页做,不动订单、SKU、台账。
|
||
"""
|
||
row = row or {}
|
||
item = str(row.get('item_name') or '').strip()
|
||
fields = {
|
||
'sample_id': op,
|
||
'event_id': op,
|
||
'scene': 'picking' if station == 'picking' else 'stock_inbound',
|
||
'trigger_reason': str(source or '')[:40],
|
||
'label_name': item[:200],
|
||
'sku_code': str(row.get('sku_code') or '').strip()[:50],
|
||
'business_item_id': str(row.get('id') or '').strip()[:100],
|
||
'order_code': str(row.get('order_code') or '').strip()[:50],
|
||
'captured_at': _iso(captured_at) if captured_at else '',
|
||
}
|
||
# 整组入库:一张照片代表多行验收,单号不是唯一的那一个,
|
||
# 不瞎填(填错比空着更难查),只在样本上标明这是整组。
|
||
ids = row.get('inspection_ids')
|
||
if station != "picking" and isinstance(ids, (list, tuple)) and len(ids) > 1:
|
||
fields['scene'] = 'stock_inbound_group'
|
||
fields['order_code'] = ''
|
||
order_item = str(row.get('order_item_id') or '').strip()
|
||
if _UUID.match(order_item):
|
||
fields['order_item_id'] = order_item # 服务端只认 UUID,别送别的
|
||
if '人工' in str(source or ''):
|
||
# 员工现场选的名字(不是模型认的):审核页要知道「这是人选的」
|
||
fields['employee_label_name'] = item[:200]
|
||
return {k: v for k, v in fields.items() if v not in ('', None)}
|
||
|
||
|
||
class ReviewQueue:
|
||
"""本机待送审队列(一个操作一个目录,原图复制一份进去)。"""
|
||
|
||
def __init__(self, root=None):
|
||
# root 显式传才生效;默认值在调用时取模块常量(测试里能改指向临时目录)
|
||
self.root = PENDING_DIR if root is None else root
|
||
|
||
# ------------------------------------------------ 路径
|
||
def _dir(self, op):
|
||
return os.path.join(self.root, _SAFE.sub('_', str(op))[:80])
|
||
|
||
def _meta(self, op):
|
||
return os.path.join(self._dir(op), 'meta.json')
|
||
|
||
def _photo(self, op):
|
||
return os.path.join(self._dir(op), 'photo.jpg')
|
||
|
||
def pending_ops(self):
|
||
try:
|
||
return sorted(op for op in os.listdir(self.root) if not op.startswith('.stage-'))
|
||
except OSError:
|
||
return []
|
||
|
||
# ------------------------------------------------ 登记
|
||
def stage(self, api, op, row, source, path, captured_at=None, station="inspection", audit=None):
|
||
"""入库请求发出前调用。返回 '' = 已登记;否则是本笔缺图的原因。
|
||
|
||
写不进去(磁盘满/权限)会抛异常 —— 调用方按「日志落盘失败」处理:
|
||
宁可这笔不发,也不发一笔事后无法追溯的入库。
|
||
"""
|
||
d = self._dir(op)
|
||
existing = atomic.read_json(self._meta(op))
|
||
if existing:
|
||
return existing.get('error') or ''
|
||
if os.path.isdir(d):
|
||
# 旧版本(原子改名之前)断电留下的半截目录:同名目录占着这个操作号,
|
||
# 新的改名永远进不来。挪到人工区留档,别让它一直卡在这儿。
|
||
self._reject(op, {'op': op, 'fields': {}}, '旧版本留下的半截送审记录')
|
||
os.makedirs(self.root, exist_ok=True)
|
||
with tempfile.TemporaryDirectory(prefix='.stage-', dir=self.root) as temp:
|
||
work = os.path.join(temp, 'record')
|
||
os.mkdir(work)
|
||
error = self._write_stage(work, api, op, row, source, path, captured_at, station, audit)
|
||
try:
|
||
os.rename(work, d)
|
||
except OSError:
|
||
existing = atomic.read_json(self._meta(op))
|
||
if not existing:
|
||
raise
|
||
return existing.get('error') or ''
|
||
if audit:
|
||
audit['local'].add_done_callback(
|
||
lambda future: self._save_local_audit(d, future))
|
||
return error
|
||
|
||
@staticmethod
|
||
def _save_local_audit(directory, future):
|
||
# 写结果落在现有队列目录中。若上传或作废已删除目录,不再创建。
|
||
try:
|
||
with tempfile.NamedTemporaryFile(dir=directory, delete=False, mode='w',
|
||
encoding='utf-8') as f:
|
||
temp_path = f.name
|
||
try:
|
||
json.dump(future.result(), f, ensure_ascii=False, allow_nan=False)
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
finally:
|
||
f.close()
|
||
os.replace(temp_path, os.path.join(directory, 'local_result.json'))
|
||
except Exception:
|
||
if 'temp_path' in locals():
|
||
try:
|
||
os.unlink(temp_path)
|
||
except OSError:
|
||
pass
|
||
|
||
def _write_stage(self, d, api, op, row, source, path, captured_at, station, audit):
|
||
blob, error = b'', ''
|
||
try:
|
||
with open(path, 'rb') as f:
|
||
blob = f.read()
|
||
if not blob:
|
||
error = '原图是空文件'
|
||
elif len(blob) > 5 * 1024 * 1024:
|
||
# 服务端上限 5MB;塞进去只会被 413 拒,不如当场记清楚
|
||
error = '原图 %d 字节,超过服务端 5MB 上限' % len(blob)
|
||
except (TypeError, OSError) as exc:
|
||
error = '读不到原图:%s' % exc
|
||
if blob:
|
||
tmp = os.path.join(d, 'photo.tmp')
|
||
with open(tmp, 'wb') as f:
|
||
f.write(blob)
|
||
f.flush()
|
||
os.fsync(f.fileno())
|
||
os.replace(tmp, os.path.join(d, 'photo.jpg'))
|
||
if not captured_at:
|
||
try:
|
||
captured_at = os.path.getmtime(path)
|
||
except (TypeError, OSError):
|
||
captured_at = None
|
||
meta = {
|
||
'op': op,
|
||
'account': str(getattr(api, 'user_id', '') or ''),
|
||
'server': str(getattr(api, 'base_url', '') or ''),
|
||
'branch': str(getattr(api, 'review_branch', '') or ''),
|
||
'fields': build_fields(api, op, row, source, captured_at, station),
|
||
'sha256': hashlib.sha256(blob).hexdigest() if blob else '',
|
||
'bytes': len(blob),
|
||
'error': error,
|
||
'retry_at': 0,
|
||
'tries': 0,
|
||
'staged_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||
}
|
||
if audit:
|
||
meta['audit'] = {'cloud': audit['cloud'], 'deadline': time.time() + 25}
|
||
if not atomic.write_json(os.path.join(d, 'meta.json'), meta):
|
||
shutil.rmtree(d, ignore_errors=True)
|
||
raise OSError('送审队列写入失败:%s' % d)
|
||
return error
|
||
|
||
# ------------------------------------------------ 后台核对/补传
|
||
def drain(self, api, log=None):
|
||
"""检查入库结论 + 补传。返回本次处理掉的条数(成功或作废)。"""
|
||
if not api or getattr(api, 'mock', False) or not getattr(api, 'token', ''):
|
||
return 0
|
||
now = time.time()
|
||
handled = 0
|
||
for op in self.pending_ops():
|
||
meta = atomic.read_json(self._meta(op))
|
||
if not meta:
|
||
self._say(log, '待审记录不完整,原件已保留:%s' % op)
|
||
continue
|
||
# 换账号/换服务器:这条不属于当前会话,原样留着等原账号登录
|
||
if (meta.get('account'), meta.get('server')) != (
|
||
getattr(api, 'user_id', ''), getattr(api, 'base_url', '')):
|
||
continue
|
||
if meta.get('branch') and meta['branch'] != getattr(api, 'review_branch', ''):
|
||
continue
|
||
if float(meta.get('retry_at') or 0) > now:
|
||
continue
|
||
state = self._journal_state(op)
|
||
if state == STATE_REJECTED:
|
||
shutil.rmtree(self._dir(op), ignore_errors=True)
|
||
handled += 1
|
||
self._say(log, '业务提交被拒绝,取消送审:%s' % op)
|
||
continue
|
||
if state != STATE_SUCCEEDED:
|
||
# 入库还没结论(在途/结果不明/待核实):下一轮再看,别抢跑。
|
||
# 不写盘:这个分支每 20 秒会走一次,写盘只会磨损 SD 卡。
|
||
continue
|
||
if float(meta.get('retry_at') or 0) > now:
|
||
continue # 上次上传失败,退避中
|
||
if meta.get('bytes', 0) > 5 * 1024 * 1024:
|
||
self._reject(op, meta, '照片超过后台 5MB 上限')
|
||
handled += 1
|
||
self._say(log, '超大原图已转人工:%s' % op)
|
||
continue
|
||
try:
|
||
with open(self._photo(op), 'rb') as f:
|
||
photo = f.read()
|
||
except OSError:
|
||
photo = b''
|
||
if not photo:
|
||
self._reject(op, meta, meta.get('error') or '原图已不在本机')
|
||
handled += 1
|
||
self._say(log, '本笔没有可送审的原图,已转人工:%s' % op)
|
||
continue
|
||
try:
|
||
fields = dict(meta.get('fields') or {})
|
||
audit = meta.get('audit')
|
||
if audit:
|
||
local = atomic.read_json(os.path.join(self._dir(op), 'local_result.json'))
|
||
if not local and now < float(audit['deadline']):
|
||
continue
|
||
fields['recognition_audit'] = json.dumps({
|
||
'local': local or {'status': 'unfinished'},
|
||
'cloud': audit.get('cloud') or {'status': 'unavailable'},
|
||
}, ensure_ascii=False, allow_nan=False)
|
||
ack = api.upload_review_sample(fields, photo)
|
||
problem = self._ack_problem(meta, ack)
|
||
if problem:
|
||
raise ValueError(problem)
|
||
except Exception as exc: # noqa: BLE001
|
||
if getattr(exc, 'code', None) in PERMANENT_HTTP:
|
||
self._reject(op, meta, str(exc))
|
||
handled += 1
|
||
self._say(log, '送审被拒绝,已转人工:%s(%s)' % (op, exc))
|
||
else:
|
||
self._backoff(op, meta, exc, log)
|
||
continue
|
||
shutil.rmtree(self._dir(op), ignore_errors=True)
|
||
handled += 1
|
||
self._say(log, '照片已送审:%s(%s)'
|
||
% (op, (meta.get('fields') or {}).get('label_name') or ''))
|
||
return handled
|
||
|
||
# ------------------------------------------------ 内部
|
||
def _journal_state(self, op):
|
||
rec = atomic.read_json(os.path.join(
|
||
JOURNAL_DIR, _SAFE.sub('_', str(op)) + '.json'))
|
||
return str((rec or {}).get('state') or '')
|
||
|
||
def _save(self, op, meta, **fields):
|
||
meta.update(fields)
|
||
atomic.write_json(self._meta(op), meta)
|
||
|
||
def _ack_problem(self, meta, ack):
|
||
"""回执核对:样本号、照片字节、这一笔的关联资料,全对上才算送到。"""
|
||
if not isinstance(ack, dict):
|
||
return '回执不是 JSON 对象'
|
||
fields = meta.get('fields') or {}
|
||
if str(ack.get('sample_id') or '') != str(meta.get('op') or ''):
|
||
return '回执样本号不一致'
|
||
sha = str(ack.get('image_sha256') or '')
|
||
if not sha or sha != meta.get('sha256'):
|
||
return '回执照片内容不一致'
|
||
branch = str(meta.get('branch') or '')
|
||
if branch and str(ack.get('branch_code') or '') != branch:
|
||
return '回执分公司不一致'
|
||
for key in ('event_id', 'order_code', 'business_item_id',
|
||
'label_name', 'sku_code'):
|
||
want = str(fields.get(key) or '')
|
||
got = str(ack.get(key) or '')
|
||
if want and want != got:
|
||
return '回执资料不一致:%s(送 %s / 回 %s)' % (key, want, got)
|
||
return ''
|
||
|
||
def _backoff(self, op, meta, exc, log):
|
||
tries = int(meta.get('tries') or 0) + 1
|
||
msg = str(exc)[:300]
|
||
if isinstance(exc, ValueError) and tries >= MAX_TRIES:
|
||
# 回执一直对不上:不是网络问题,是数据/接口不对,交人工
|
||
self._reject(op, meta, msg)
|
||
self._say(log, '送审连续 %d 次对不上,已转人工:%s(%s)'
|
||
% (tries, op, msg))
|
||
return
|
||
wait = min(MAX_BACKOFF_SECONDS, BACKOFF_SECONDS * (2 ** (tries - 1)))
|
||
self._save(op, meta, tries=tries, error=msg,
|
||
retry_at=time.time() + wait)
|
||
self._say(log, '入库照片还没送出去 %s:%s' % (op, msg))
|
||
|
||
def _reject(self, op, meta, reason):
|
||
"""按操作号保留失败原因、关联资料和原图,供人工重新处理。"""
|
||
archive = os.path.join(os.path.dirname(self.root), 'review_manual')
|
||
os.makedirs(archive, exist_ok=True)
|
||
target = os.path.join(archive, os.path.basename(self._dir(op)))
|
||
if os.path.exists(target):
|
||
target += '-' + uuid.uuid4().hex
|
||
meta = dict(meta, reason=reason, failed_at=time.strftime('%Y-%m-%d %H:%M:%S'))
|
||
if not atomic.write_json(self._meta(op), meta):
|
||
raise OSError('人工归档写入失败,保留待传记录:' + op)
|
||
os.rename(self._dir(op), target)
|
||
# 兼容以前的最近失败列表;完整记录和原图保存在上面的独立目录。
|
||
recent = atomic.read_json(REJECTED_FILE) or []
|
||
if isinstance(recent, list):
|
||
recent.append(dict(op=op, reason=reason, fields=meta['fields'],
|
||
at=meta['failed_at'], archive=target))
|
||
atomic.write_json(REJECTED_FILE, recent[-200:])
|
||
|
||
@staticmethod
|
||
def _say(log, msg):
|
||
if log:
|
||
try:
|
||
log(msg)
|
||
except Exception:
|
||
pass
|