264 lines
10 KiB
Python
264 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""回归测试:终端识别提示词改为「服务端下发模板 + 本地渲染」(v1.0.33)
|
||
|
||
背景:原来提示词硬编码在 core/recognition/cloud.py,现场想改一句话就得重
|
||
打 86MB 安装包。现在模板存服务端 ai_prompt_templates(后台可改/可发布/可
|
||
按分公司覆盖),端上登录后拉原文、自己塞待办名单、直连豆包。
|
||
|
||
验证:
|
||
① 占位符渲染:{{scene}}/{{item_list}} 正常替换,未知占位符原样保留
|
||
② 空值段落剔除:手写板没有候选词时,那段「候选词」引导句整段去掉
|
||
③ 坏模板拦截:服务端模板缺 {{item_list}} → 整条回退内置默认(不给名单
|
||
会让模型自由发挥,是最坏的错账来源)
|
||
④ 同步成功 → 写磁盘缓存,重启后断网仍用缓存(source=cache)
|
||
⑤ 同步失败 → 不影响识别,继续用缓存 / 内置默认,只留错误原因
|
||
⑥ 识别器真的把名单拼进了提示词(拦截 _chat 看 prompt 原文)
|
||
⑦ 登录后 FlowEngine 会同步提示词并发出 prompt 事件,且不堵塞主循环
|
||
|
||
不需要秤/摄像头/真实网络。
|
||
"""
|
||
import sys
|
||
import io
|
||
import os
|
||
import json
|
||
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.recognition import prompts as P
|
||
from core.recognition.cloud import CloudRecognizer, RecognitionError
|
||
from core.flow import FlowEngine
|
||
|
||
OK = []
|
||
FAIL = []
|
||
|
||
|
||
def check(name, cond, detail=''):
|
||
(OK if cond else FAIL).append(name)
|
||
print('%s %s%s' % ('[ok]' if cond else '[!!]', name,
|
||
(' ' + str(detail)) if detail and not cond else ''))
|
||
|
||
|
||
def tmpdir():
|
||
d = tempfile.mkdtemp(prefix='prompt_')
|
||
return d
|
||
|
||
|
||
# ---------------------------------------------------------------- ① 渲染
|
||
tpl = P.BUILTIN['weigh.recognize.pick_list']
|
||
out = P.render(tpl, {'scene': '待拣分拣', 'item_list': '- 土豆\n- 圆萝卜',
|
||
'confusable': ''})
|
||
check('① 场景与名单都渲染进去',
|
||
'待拣分拣' in out and '- 土豆' in out and '- 圆萝卜' in out)
|
||
check('① 占位符不漏出', '{{' not in out)
|
||
check('① 未知占位符原样保留',
|
||
'{{unknown}}' in P.render('abc {{unknown}} def', {'x': 1}))
|
||
|
||
# ---------------------------------------------------------------- ② 空段剔除
|
||
hw = P.BUILTIN['weigh.recognize.handwrite']
|
||
with_hints = P.render(hw, {'hints': '土豆、圆萝卜'})
|
||
no_hints = P.render(hw, {'hints': ''})
|
||
check('② 有候选词时带候选词', '土豆、圆萝卜' in with_hints)
|
||
check('② 没候选词时整段去掉', '内容很可能出自' not in no_hints,
|
||
no_hints[-40:])
|
||
check('② 没候选词仍保留主指令', '只输出文字本身' in no_hints)
|
||
|
||
# ---------------------------------------------------------------- ③ 坏模板
|
||
cfg = {'vision': {'prompt_source': 'server', 'prompt_ttl_min': 30}}
|
||
d = tmpdir()
|
||
st = P.PromptStore(cfg, path=os.path.join(d, 'c.json'))
|
||
|
||
|
||
class FakeApi:
|
||
def __init__(self, items=None, err=None):
|
||
self.items = items or []
|
||
self.err = err
|
||
|
||
def get_prompts(self, keys):
|
||
if self.err:
|
||
raise RuntimeError(self.err)
|
||
return {'items': self.items, 'branch_code': 'BR002'}
|
||
|
||
|
||
bad = [{'feature_key': 'weigh.recognize.pick_list',
|
||
'system_template': '你是一个识别助手,请从图里认出商品名称并告诉我。',
|
||
'version': 9, 'source': 'published'}]
|
||
st.sync(FakeApi(bad), force=True)
|
||
src_tpl, meta = st.template('weigh.recognize.pick_list')
|
||
check('③ 缺 {{item_list}} 的模板被拦下', meta['source'] == 'builtin',
|
||
meta)
|
||
check('③ 回退后仍是内置全文', '{{item_list}}' in src_tpl)
|
||
|
||
# ---------------------------------------------------------------- ④ 缓存
|
||
d2 = tmpdir()
|
||
cache_path = os.path.join(d2, 'prompt_cache.json')
|
||
good = [{'feature_key': 'weigh.recognize.pick_list',
|
||
'system_template': ('服务端版本:当前场景 {{scene}}。\n\n'
|
||
'只从下面名单里挑一个最像的:\n{{item_list}}\n\n'
|
||
'只输出一行 JSON,不要解释、不要代码块。'),
|
||
'version': 4, 'source': 'published'},
|
||
{'feature_key': 'weigh.recognize.synonym',
|
||
'system_template': ('仓库AI识别出货品名称为"{{detected}}"。候选名单:\n'
|
||
'{{candidates}}\n'
|
||
'判断是否存在同一商品不同叫法的条目,只输出 JSON。'),
|
||
'version': 2, 'source': 'published'}]
|
||
s1 = P.PromptStore(cfg, path=cache_path)
|
||
changed = s1.sync(FakeApi(good), force=True)
|
||
check('④ 同步报告有更新', changed is True, changed)
|
||
check('④ 缓存文件落盘', os.path.exists(cache_path))
|
||
t1, m1 = s1.template('weigh.recognize.pick_list')
|
||
check('④ 取到服务端模板', '服务端版本' in t1 and m1['version'] == 4, m1)
|
||
|
||
# 模拟重启 + 断网:新实例读盘
|
||
s2 = P.PromptStore(cfg, path=cache_path)
|
||
t2, m2 = s2.template('weigh.recognize.pick_list')
|
||
check('④ 重启后仍用缓存模板', '服务端版本' in t2 and m2['source'] == 'cache',
|
||
m2)
|
||
failed = s2.sync(FakeApi(err='connection refused'), force=True)
|
||
t3, m3 = s2.template('weigh.recognize.pick_list')
|
||
check('⑤ 断网同步失败不抛', failed is False)
|
||
check('⑤ 断网继续用缓存', '服务端版本' in t3 and m3['source'] == 'cache')
|
||
check('⑤ 记录了失败原因', 'connection refused' in s2.last_error,
|
||
s2.last_error)
|
||
|
||
# ---------------------------------------------------------------- ⑤b 无缓存
|
||
d3 = tmpdir()
|
||
s3 = P.PromptStore(cfg, path=os.path.join(d3, 'none.json'))
|
||
s3.sync(FakeApi(err='no route'), force=True)
|
||
t4, m4 = s3.template('weigh.recognize.pick_list')
|
||
check('⑤b 无缓存无网络 → 内置默认',
|
||
m4['source'] == 'builtin' and '{{item_list}}' in t4, m4)
|
||
check('⑤b 展示口径正确', s3.origin_label().startswith('内置默认'),
|
||
s3.origin_label())
|
||
|
||
# 关闭服务端提示词
|
||
off = P.PromptStore({'vision': {'prompt_source': 'local'}},
|
||
path=os.path.join(d3, 'off.json'))
|
||
check('⑤c prompt_source=local 时不同步',
|
||
off.enabled is False and off.sync(FakeApi(good), force=True) is False)
|
||
|
||
|
||
# 服务端还是旧版(接口 404):算「没升级」,不当故障,10 分钟后再试
|
||
class _E(Exception):
|
||
code = 404
|
||
message = '业务拒绝 404'
|
||
|
||
|
||
class Api404:
|
||
def get_prompts(self, keys):
|
||
raise _E()
|
||
|
||
|
||
s5 = P.PromptStore(cfg, path=os.path.join(d3, 'v404.json'))
|
||
s5.sync(Api404(), force=True)
|
||
check('⑤d 404 归为「服务端未升级」',
|
||
'还没升级' in s5.last_error, s5.last_error)
|
||
check('⑤d 404 时照样能认货',
|
||
s5.template('weigh.recognize.pick_list')[1]['source'] == 'builtin')
|
||
|
||
# ---------------------------------------------------------------- ⑥ 真实拼装
|
||
d4 = tmpdir()
|
||
cache4 = os.path.join(d4, 'c.json')
|
||
s4 = P.PromptStore(cfg, path=cache4)
|
||
s4.sync(FakeApi(good), force=True)
|
||
P.reset_store()
|
||
P._STORE = s4 # 让 CloudRecognizer 用这份缓存
|
||
|
||
img = os.path.join(d4, 'f.jpg')
|
||
with open(img, 'wb') as f:
|
||
f.write(b'\xff\xd8\xff\xd9')
|
||
|
||
seen = {}
|
||
|
||
|
||
class Rec(CloudRecognizer):
|
||
def _chat(self, messages, model, timeout, max_tokens=None):
|
||
seen['prompt'] = messages[0]['content'][0]['text']
|
||
return ('{"name":"圆萝卜","conf":88,"alt":"白萝卜","alt_conf":40}')
|
||
|
||
|
||
r = Rec({'vision': {'api_key': 'k', 'provider': 'doubao'},
|
||
'account': {'role': 'picker'}})
|
||
info = r.identify_ex(img, ['圆萝卜', '白萝卜', '土豆'])
|
||
check('⑥ 名单拼进提示词',
|
||
'- 圆萝卜' in seen.get('prompt', '')
|
||
and '- 白萝卜' in seen.get('prompt', ''), seen.get('prompt', '')[:80])
|
||
check('⑥ 场景词按工位注入(分拣)', '待拣分拣' in seen.get('prompt', ''))
|
||
check('⑥ 解析结果正确',
|
||
info['name'] == '圆萝卜' and info['conf'] == 88
|
||
and info['alt'] == '白萝卜')
|
||
check('⑥ 带回提示词版本标记', info.get('prompt_tag') == 'v4',
|
||
info.get('prompt_tag'))
|
||
check('⑥ 来源标记为服务端', info.get('prompt_source') == 'server',
|
||
info.get('prompt_source'))
|
||
|
||
# 内置兜底时 tag 是「本地」
|
||
P.reset_store()
|
||
P._STORE = P.PromptStore(cfg, path=os.path.join(d4, 'empty.json'))
|
||
r2 = Rec({'vision': {'api_key': 'k'},
|
||
'account': {'role': 'inspector'}})
|
||
i2 = r2.identify_ex(img, ['土豆'])
|
||
check('⑥ 内置默认时 tag=本地', i2.get('prompt_tag') == '本地',
|
||
i2.get('prompt_tag'))
|
||
check('⑥ 入库工位场景词', '待验入库' in seen.get('prompt', ''))
|
||
|
||
# NOT_IN_LIST
|
||
class RecNot(Rec):
|
||
def _chat(self, *a, **k):
|
||
return '{"name":"NOT_IN_LIST","conf":10,"alt":"","alt_conf":0}'
|
||
|
||
|
||
check('⑥ NOT_IN_LIST 归为未识别',
|
||
RecNot({'vision': {'api_key': 'k'}, 'account': {'role': 'picker'}}
|
||
).identify_ex(img, ['土豆']).get('name') is None)
|
||
|
||
# ---------------------------------------------------------------- ⑦ 流程接线
|
||
d5 = tmpdir()
|
||
P.reset_store()
|
||
P._STORE = P.PromptStore(cfg, path=os.path.join(d5, 'c.json'))
|
||
|
||
CFG = {
|
||
'flow': {'min_scale_kg': 0.05, 'stable_ms': 400, 'settle_ms': 650,
|
||
'stable_delta_kg': 0.03, 'done_timeout_s': 12,
|
||
'done_lift_off_kg': 0.2, 'confirm_before_submit': True,
|
||
'auto_submit': True},
|
||
'scale': {'simulate': True},
|
||
'camera': {'simulate': True},
|
||
'vision': {'min_confidence': 60, 'prompt_source': 'server'},
|
||
'server': {'mock': True},
|
||
}
|
||
EVENTS = []
|
||
eng = FlowEngine(CFG, lambda ev, p=None: EVENTS.append((ev, p)))
|
||
eng.refresh_pending = lambda initial=False: None
|
||
eng.login('smoke', 'x', 'picking')
|
||
deadline = time.time() + 5
|
||
while time.time() < deadline:
|
||
if any(e == 'prompt' for e, _ in EVENTS):
|
||
break
|
||
time.sleep(0.05)
|
||
prom = [p for e, p in EVENTS if e == 'prompt']
|
||
check('⑦ 登录后同步并发出 prompt 事件', bool(prom), [e for e, _ in EVENTS])
|
||
if prom:
|
||
check('⑦ 事件里带摘要', bool(prom[-1].get('summary')),
|
||
prom[-1])
|
||
logs = [p for e, p in EVENTS if e == 'log']
|
||
check('⑦ 日志说明提示词来源',
|
||
any('识别提示词' in str(x) for x in logs), logs[-3:])
|
||
|
||
# 主循环不被网络拖住:sync 用后台线程,_tick 立刻返回
|
||
t0 = time.time()
|
||
for _ in range(5):
|
||
eng._tick()
|
||
check('⑦ 主循环不被同步拖住(5 次 tick < 1s)', time.time() - t0 < 1.0,
|
||
'%.3fs' % (time.time() - t0))
|
||
eng.stop()
|
||
|
||
# ---------------------------------------------------------------- 汇总
|
||
print('\n通过 %d,失败 %d' % (len(OK), len(FAIL)))
|
||
if FAIL:
|
||
for f in FAIL:
|
||
print(' - ' + f)
|
||
sys.exit(1)
|