Files
windows-fenjian/tools/_test_review_queue.py
Ubuntu 5d4f2d1ba3 feat(1.0.76): 识别记录留档(本地 YOLO + 云端)
来自 秤端源码-v1.0.76:flow 生成 recognition_audit(本地候选/耗时 + 云端结果)并随 review_queue 送审;assist/local_cls 记录本地推理;审核后台可查;版本/安装包 1.0.76。保留 1.0.71-1.0.75 既有修复与文档;config.json/data/models 未入库。
2026-12-03 17:05:19 +08:00

241 lines
9.0 KiB
Python

# -*- coding: utf-8 -*-
"""回归测试:入库照片送审队列(不需要秤/相机/网络)。
盯的是三件事,每一件都是「现场会真的发生」的:
1. 入库没成功 → 一张都不许送(否则训练图会挂在不存在的账上);
2. 入库成功但当场断电/断网 → 重启后照样送,且只送一次;
3. 数据本身有问题(4xx)→ 转人工,别无限刷日志。
"""
from concurrent.futures import Future
import json
import io
import os
import shutil
import sys
import tempfile
import time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.storage import atomic
from core.submission import journal as J
from core.submission import review_queue as R
class FakeApiError(Exception):
"""与 core.api.client.ApiError 同形(只用到 .code/.message)。
这里不 import 真客户端:那个模块要 requests,本机 python 未必装了,
而这条队列本身跟网络库无关 —— 测试要能在任何一台机器上跑。
"""
def __init__(self, code, message):
super().__init__(message)
self.code = code
self.message = message
class FakeApi:
"""只实现队列用到的那几样。ack 按服务端真实回执的形状复刻。"""
mock = False
token = 'tok'
user_id = 'u-1'
base_url = 'http://127.0.0.1:3000/api'
review_branch = 'B01'
def __init__(self):
self.sent = []
self.fail = None # None / FakeApiError / 'ack_bad'
def upload_review_sample(self, fields, image):
if self.fail is not None and self.fail != 'ack_bad':
raise self.fail
import hashlib
ack = dict(fields)
ack['image_sha256'] = hashlib.sha256(image).hexdigest()
ack['branch_code'] = 'B01'
if self.fail == 'ack_bad':
ack['order_code'] = 'NOT-THE-SAME'
self.sent.append((dict(fields), image))
return ack
logs = []
def say(msg):
logs.append(msg)
def fresh_env():
root = tempfile.mkdtemp(prefix='review_q_')
R.PENDING_DIR = os.path.join(root, 'pending')
R.REJECTED_FILE = os.path.join(root, 'rejected.json')
# 队列模块在 import 时就把 JOURNAL_DIR 绑进了自己的命名空间,两个都要改
J.JOURNAL_DIR = os.path.join(root, 'journal')
R.JOURNAL_DIR = J.JOURNAL_DIR
os.makedirs(R.PENDING_DIR, exist_ok=True)
os.makedirs(J.JOURNAL_DIR, exist_ok=True)
return root
def photo(root, name='shot.jpg', blob=b'\xff\xd8\xff\xe0PHOTO'):
p = os.path.join(root, name)
with open(p, 'wb') as f:
f.write(blob)
return p
def journal(op, state):
atomic.write_json(os.path.join(J.JOURNAL_DIR, op + '.json'),
{'operationId': op, 'state': state})
def ops():
return R.ReviewQueue().pending_ops()
ROW = {'id': 'item-1', 'item_name': '外地芹菜', 'sku_code': 'SKU-1',
'order_code': 'O-1', 'order_item_id': 'not-a-uuid'}
fails = []
def check(name, cond, detail=''):
print((' ok ' if cond else ' [x] ') + name
+ ('' if cond else ' ' + detail))
if not cond:
fails.append(name)
print('1) 字段翻译:货单名原样送,训练名不在这里改')
f = R.build_fields(FakeApi(), 'op-1', ROW, 'AI识别', time.time())
check('label_name 是货单名', f['label_name'] == '外地芹菜', f.get('label_name'))
check('带单号', f['order_code'] == 'O-1')
check('非 UUID 的 order_item_id 不送', 'order_item_id' not in f, str(f))
check('captured_at 是 ISO', 'T' in f['captured_at'] and ':' in f['captured_at'],
f.get('captured_at'))
group = dict(ROW, inspection_ids=['i-1', 'i-2', 'i-3'])
g = R.build_fields(FakeApi(), 'op-2', group, 'AI识别', time.time())
check('整组入库标成 group 且不瞎填单号',
g['scene'] == 'stock_inbound_group' and not g.get('order_code'), str(g))
manual = R.build_fields(FakeApi(), 'op-3', ROW, '人工选中+拿走自动提交', time.time())
check('人工选的名字另存 employee_label_name',
manual.get('employee_label_name') == '外地芹菜')
print('2) 入库没结论 → 一张都不送')
root = fresh_env()
api = FakeApi()
qp = R.ReviewQueue()
err = qp.stage(api, 'op-a', ROW, 'AI识别', photo(root))
check('登记成功', err == '', err)
check('磁盘上有原图', os.path.isfile(qp._photo('op-a')))
qp.drain(api, say)
check('没送', not api.sent)
check('还在队列里', ops() == ['op-a'], str(ops()))
print('3) 入库成功 → 送一次,回执核对通过后出队;再跑不重发')
journal('op-a', J.STATE_SUCCEEDED)
qp.drain(api, say)
check('送了一张', len(api.sent) == 1, str(len(api.sent)))
check('出队了', ops() == [], str(ops()))
qp.drain(api, say)
check('再跑不重发', len(api.sent) == 1, str(len(api.sent)))
print('4) 断电重启:新进程照样能接着送')
qp.stage(api, 'op-b', ROW, 'AI识别', photo(root, 'b.jpg'))
journal('op-b', J.STATE_SUCCEEDED)
R.ReviewQueue().drain(api, say) # 模拟重启后的新实例
check('重启后补上', any(s[0].get('sample_id') == 'op-b' for s in api.sent))
print('5) 入库被拒绝 → 取消送审,不留垃圾')
qp.stage(api, 'op-c', ROW, 'AI识别', photo(root, 'c.jpg'))
journal('op-c', J.STATE_REJECTED)
before = len(api.sent)
qp.drain(api, say)
check('没送', len(api.sent) == before)
check('队列清干净', 'op-c' not in ops(), str(ops()))
print('6) 断网 → 留在队列里等下次')
qp.stage(api, 'op-d', ROW, 'AI识别', photo(root, 'd.jpg'))
journal('op-d', J.STATE_SUCCEEDED)
api.fail = FakeApiError(-1, '连接未建立')
qp.drain(api, say)
check('还在队列', 'op-d' in ops(), str(ops()))
meta = atomic.read_json(qp._meta('op-d'))
check('记了错因并退避', bool(meta.get('error')) and meta.get('retry_at') > time.time(),
str(meta.get('retry_at')))
api.fail = None
print('7) 回执对不上 → 先重试,连错 5 次才转人工')
api.fail = 'ack_bad'
for _ in range(R.MAX_TRIES):
if 'op-d' not in ops():
break
meta = atomic.read_json(qp._meta('op-d'))
atomic.write_json(qp._meta('op-d'), dict(meta, retry_at=0))
qp.drain(api, say)
check('转人工清单里有它',
any(x.get('op') == 'op-d'
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
check('队列里没有了', 'op-d' not in ops())
api.fail = None
print('8) 数据被服务端明确拒绝(400)→ 直接转人工')
qp.stage(api, 'op-e', ROW, 'AI识别', photo(root, 'e.jpg'))
journal('op-e', J.STATE_SUCCEEDED)
api.fail = FakeApiError(400, '业务拒绝 400: invalid_captured_at')
qp.drain(api, say)
check('没无限重试', 'op-e' not in ops(), str(ops()))
check('人工清单里能查到原因',
any('invalid_captured_at' in str(x.get('reason'))
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
api.fail = None
print('9) 原图丢了 → 入库照常,但这一笔转人工(不静默丢)')
qp.stage(api, 'op-f', ROW, 'AI识别', os.path.join(root, 'no-such.jpg'))
journal('op-f', J.STATE_SUCCEEDED)
qp.drain(api, say)
check('转人工', any(x.get('op') == 'op-f'
for x in (atomic.read_json(R.REJECTED_FILE) or [])))
check('一条都没发', not any(s[0].get('sample_id') == 'op-f' for s in api.sent))
print('10) 换账号:别人的队列不碰')
qp.stage(api, 'op-g', ROW, 'AI识别', photo(root, 'g.jpg'))
journal('op-g', J.STATE_SUCCEEDED)
other = FakeApi()
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'])
pending = Future()
audit = {'local': pending, 'cloud': {'status': 'recognized', 'name': '芹菜'}}
qp.stage(api, 'op-audit', ROW, '人工', photo(root, 'audit.jpg'), audit=audit)
journal('op-audit', J.STATE_SUCCEEDED)
qp.drain(api, say)
check('记账成功时本地还在算,只让后台队列等', 'op-audit' in ops())
pending.set_result({'status': 'recognized', 'name': '小葱'})
qp.drain(api, say)
reports = [json.loads(f['recognition_audit']) for f, _ in api.sent if f['event_id'] == 'op-audit']
check('同一笔上传两边的结果', len(reports) == 1 and reports[0]['local']['name'] == '小葱'
and reports[0]['cloud']['name'] == '芹菜')
shutil.rmtree(root, ignore_errors=True)
print()
if fails:
print('[x] %d 项没过:%s' % (len(fails), '、'.join(fails)))
sys.exit(1)
print('全部通过(%d 条日志)' % len(logs))