Files
windows-fenjian/core/recognition/cloud.py
T

357 lines
16 KiB
Python
Raw 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 -*-
"""云端识别(快速模式)+ 限名单绑定 + 同物异名核查。
铁律 3:识别只在名单内——云端/大模型返回的名称必须绑回本轮待办行,
绑不上就丢弃并提示,绝不补位。
提示词不在这里写死了:模板从服务端 ai_prompt_templates 来(后台「AI 提示词」
可改、可发布、可按分公司覆盖),本地渲染、断网用缓存/内置默认。详见
core/recognition/prompts.py。
"""
import re
import json
import time
import requests
from core.matching import engine as M # noqa: F401 (预筛扩展用)
from core.recognition.prompts import get_store
# 工位 -> 提示词里的 {{scene}} 用词(与服务端 defaults.ts 的变量说明一致)
_SCENE_CN = {'picking': '待拣分拣', 'inspection': '待验入库'}
_PRESETS = {
'qwen': {'base_url': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
'vision_model': 'qwen-vl-flash', 'text_model': 'qwen-turbo'},
'glm': {'base_url': 'https://open.bigmodel.cn/api/paas/v4',
'vision_model': 'glm-4v-flash', 'text_model': 'glm-4-flash'},
# 豆包(火山方舟):v1.0.45 起用 2.1 pro——现场 lite 档把南充菜认成
# 小葱(82% 把握,2026-11-05 17:45),地域名蔬菜辨识是 lite 短板。
# 注意 doubao-1.5-vision-lite / doubao-seed-1-6-vision 已下线,
# 现网账号里能用的是 seed-2.x 系列(seed 系列统一多模态,直接吃图)。
'doubao': {'base_url': 'https://ark.cn-beijing.volces.com/api/v3',
'vision_model': 'doubao-seed-2-1-pro-260915',
'text_model': 'doubao-seed-2-1-pro-260915'},
}
class RecognitionError(Exception):
pass
def _prompt_tag(meta):
"""提示词短标记:本地 / v3(写日志用;没有版本号就写「默认」)。"""
meta = meta or {}
if meta.get('source') == 'builtin':
return '本地'
ver = meta.get('version')
return 'v%s' % (ver if ver is not None else '默认')
def _confusable_text(names):
"""本轮名单里命中的易混组规则;dataset 模块缺失也不影响识别。"""
try:
from core.recognition.dataset import confusable_text
return confusable_text(names)
except Exception: # noqa: BLE001
return ''
def _example_b64(path, max_px=640):
"""样例图缩到 640 长边再发:样例只要看清形态,不需要原图那份像素。
注意这里**不裁不增强**——样例要呈现货在车间的真实样子,裁剪反而会
把「这货平时是怎么摆的」这个信息弄丢。
"""
try:
import base64
import cv2
from core.recognition import prep
img = prep.read_image(path)
if img is None:
return ''
h, w = img.shape[:2]
if max(h, w) > max_px:
r = max_px / float(max(h, w))
img = cv2.resize(img, (max(1, int(w * r)), max(1, int(h * r))),
interpolation=cv2.INTER_AREA)
buf = prep.encode_jpeg(img, 80)
return base64.b64encode(buf).decode() if buf else ''
except Exception: # noqa: BLE001
return ''
class CloudRecognizer:
def __init__(self, cfg):
self.cfg = cfg.get('vision', {})
if self.cfg.get('provider') and self.cfg['provider'] != 'custom':
p = _PRESETS[self.cfg['provider']]
self.cfg['base_url'] = p['base_url']
self.cfg['vision_model'] = p['vision_model']
self.cfg['text_model'] = p['text_model']
self._session = requests.Session()
self._last_fail_at = 0.0
# 提示词仓库:与手写板、主流程共用同一个单例(同一份磁盘缓存)
self.prompts = get_store(cfg)
role = str((cfg.get('account') or {}).get('role') or 'picker').lower()
station = {'picker': 'picking', 'inspector': 'inspection'}.get(role, role)
self.scene = _SCENE_CN.get(station, _SCENE_CN['picking'])
# ------------------------------------------------ 底层请求(快速模式)
def _chat(self, messages, model, timeout, max_tokens=None):
url = self.cfg['base_url'].rstrip('/') + '/chat/completions'
body = {
'model': model,
'messages': messages,
'temperature': 0,
'max_tokens': int(max_tokens or self.cfg.get('max_tokens', 32)),
}
if self.cfg.get('disable_thinking', True):
# 各家的"关思考"开关名字不一样,传错了会 400
prov = str(self.cfg.get('provider') or '').lower()
if prov == 'doubao':
body['thinking'] = {'type': 'disabled'}
elif prov in ('', 'qwen', 'glm', 'custom'):
body['enable_thinking'] = False
r = self._session.post(
url, json=body,
headers={'Authorization': 'Bearer ' + self.cfg.get('api_key', '')},
timeout=(2, timeout))
r.raise_for_status()
return r.json()['choices'][0]['message']['content']
def _cooldown_ok(self):
return time.monotonic() - self._last_fail_at > \
float(self.cfg.get('recognize_cooldown', 30))
def _mark_fail(self):
self._last_fail_at = time.monotonic()
# ------------------------------------------------ 视觉识别
def identify(self, image_path, pending_names, timeout=8.0):
"""识别帧 -> 名单内的商品名称;不在名单返回 None。
pending_names: 本轮待办行的商品名清单(限名单识别的核心)
"""
return self.identify_ex(image_path, pending_names, timeout).get('name')
def identify_ex(self, image_path, pending_names, timeout=8.0, crop=None):
"""识别帧 -> {'name', 'conf', 'alt', 'alt_conf'}
crop: 覆盖 vision.recog_crop。称重台是固定俯拍、货在秤盘正中,可以
放心裁四周;免称重是操作员手动抓拍、整袋货可能占满画面,那边要
传个更保守的值(见 flow._run_count_recognition),别把货切掉。
为什么要 conf / alt:原来只让模型吐一个名字,它就一定吐一个名字。
现场 19:21 同一袋 4.11kg 土豆,第一次答「去皮小土豆」,货没取走、
第二次答「冰糖橙」——两次都是"很有把握"地胡说,程序却照单全收。
现在让它同时报「把握程度」和第二像的候选,把握不足或者两个候选
落在不同行时转人工,而不是拿一个 50% 的猜测去写库存。
解析失败(模型不听话、吐了纯名字)不算错:conf 给 None,
退回原来的行为,不让识别整个挂掉。
"""
if not self.cfg.get('api_key'):
raise RecognitionError('未配置识别 API Key')
if not self._cooldown_ok():
raise RecognitionError('识别失败冷却中,请稍候或手选')
b64, prep_meta = self._image_b64(image_path, crop)
listing = '\n'.join('- %s' % n for n in pending_names[:60])
prompt, pmeta = self.prompts.render_one(
'weigh.recognize.pick_list',
{'scene': self.scene, 'item_list': listing,
# 本轮名单里同时出现易混组(白芹/西芹、小葱/大葱…)时
# 才注入这一组的区分口径,全品类时为空、不占篇幅
'confusable': _confusable_text(pending_names)})
content = [{'type': 'text', 'text': prompt}]
# 本地样本库反哺:把车间确认过的实拍图当 few-shot 样例附上
few = self._few_shot(pending_names)
for name, p in few:
eb = _example_b64(p)
if not eb:
continue
content.append({'type': 'text', 'text': '样例(%s):' % name})
content.append({'type': 'image_url',
'image_url': {'url': 'data:image/jpeg;base64,' + eb}})
if few:
content.append({'type': 'text',
'text': '以上是车间实拍样例,按同样的形态标准判断。'
'现在识别这一张:'})
content.append(
{'type': 'image_url',
'image_url': {'url': 'data:image/jpeg;base64,' + b64}})
try:
text = self._chat([{'role': 'user', 'content': content}],
self.cfg.get('vision_model'), timeout,
max_tokens=int(self.cfg.get('json_max_tokens',
120)))
except Exception as e:
self._mark_fail()
raise RecognitionError('识别失败: %s' % e)
info = self._parse_identify(text, pending_names)
# 哪一版提示词认出来的:现场再出「莫名其妙认成别的」时,先看这个
info['prompt_tag'] = _prompt_tag(pmeta)
info['prompt_source'] = pmeta.get('source')
info['prep'] = prep_meta
info['few'] = [n for n, _ in few]
return info
def _few_shot(self, pending_names):
"""本轮该附哪几张样例。默认最多 2 张,且只在易混组命中时才附。
多图的代价是实打实的:每张 640 长边的图约 1k tokens、弱机上还要
多几百毫秒编码。全场都附,收益远不如只在「小葱/大葱」这类真会
混的场景附。
"""
try:
maxn = int(self.cfg.get('few_shot_max', 2) or 0)
except (TypeError, ValueError):
maxn = 2
if maxn <= 0:
return []
try:
limit_names = int(self.cfg.get('few_shot_max_names', 30) or 30)
except (TypeError, ValueError):
limit_names = 30
if len(pending_names or []) > limit_names:
return []
try:
from core.recognition.dataset import pick_few
return pick_few(pending_names, maxn)
except Exception: # noqa: BLE001
return []
def _image_b64(self, image_path, crop=None):
"""读识别帧 -> (base64, 前处理元信息)。
发给模型的是**处理过的副本**:裁掉画面四周、按需提亮锐化,见
core/recognition/prep.py。原文件不动——records.csv 里那列、上传
服务端的凭证图必须还是相机原帧。
任何一步出问题(图坏了、cv2 抽风)就退回原文件,绝不让"美化"
把识别整条堵死。
"""
import base64
vcfg = self.cfg
if crop is not None:
vcfg = dict(self.cfg)
vcfg['recog_crop'] = crop
if vcfg.get('recog_prep', True):
try:
from core.recognition import prep
img = prep.read_image(image_path)
if img is not None:
out, meta = prep.for_ai(
img, vcfg,
max_px=vcfg.get('recognition_image_max_px', 1280))
buf = prep.encode_jpeg(
out, int(vcfg.get('recog_quality', 88) or 88))
if buf:
return base64.b64encode(buf).decode(), meta
meta = {'error': '读图失败'}
except Exception as e: # noqa: BLE001
meta = {'error': str(e)[:60]}
else:
meta = {'off': True}
with open(image_path, 'rb') as f:
return base64.b64encode(f.read()).decode(), meta
@staticmethod
def _parse_identify(text, pending_names):
raw = (text or '').strip()
out = {'name': None, 'conf': None, 'alt': '', 'raw': raw}
data = None
m = re.search(r'\{.*\}', raw, re.S)
if m:
try:
data = json.loads(m.group())
except ValueError:
data = None
if isinstance(data, dict):
name = str(data.get('name') or '').strip()
alt = str(data.get('alt') or '').strip()
try:
conf = float(data.get('conf'))
except (TypeError, ValueError):
conf = None
if conf is not None:
conf = max(0.0, min(100.0, conf))
try:
alt_conf = float(data.get('alt_conf'))
except (TypeError, ValueError):
alt_conf = None
if alt_conf is not None:
alt_conf = max(0.0, min(100.0, alt_conf))
names = {str(n) for n in pending_names}
out['conf'] = conf
out['alt'] = alt if alt in names else ''
# alt_conf 只在 alt 有效时才有意义:模型常把 alt 填了却给 0
out['alt_conf'] = alt_conf if out['alt'] else None
out['name'] = None if (not name or
name.upper().startswith('NOT_IN_LIST')) \
else name
return out
# 模型没按 JSON 来:当作纯名字,置信度未知
name = raw.strip().strip('。.,,"\'「」《》 ')
if not name or name.upper().startswith('NOT_IN_LIST'):
return out
out['name'] = name
return out
# ------------------------------------------------ 手写/截图读字
def read_text(self, image_path, hints=None, timeout=6.0):
"""读图里的文字(内置手写板用)。返回模型原始字符串。
hints: 可能的词(如当前待办的商品名),给了能显著提高手写命中率;
只作参考,模型判断与图上不符时按实际输出。
"""
if not self.cfg.get('api_key'):
raise RecognitionError('未配置识别 API Key')
import base64
with open(image_path, 'rb') as f:
b64 = base64.b64encode(f.read()).decode()
prompt, _ = self.prompts.render_one(
'weigh.recognize.handwrite',
{'hints': '、'.join(str(h) for h in (hints or [])[:40])})
content = [
{'type': 'text', 'text': prompt},
{'type': 'image_url',
'image_url': {'url': 'data:image/png;base64,' + b64}},
]
try:
return self._chat([{'role': 'user', 'content': content}],
self.cfg.get('vision_model'), timeout).strip()
except Exception as e:
raise RecognitionError('手写识别失败: %s' % e)
# ------------------------------------------------ 同物异名核查
def synonym_match(self, detected, candidates, timeout=4.0):
"""大模型核查"同物异名",命中必须仍在候选(=名单)内。
candidates: 待办行名称(已预筛,≤30 条)
返回 (命中的名单原名 or None, 理由)
"""
if not candidates:
return None, '候选为空'
listing = '\n'.join('%d. %s' % (i + 1, n)
for i, n in enumerate(candidates))
prompt, _ = self.prompts.render_one(
'weigh.recognize.synonym',
{'detected': detected, 'candidates': listing})
try:
text = self._chat([{'role': 'user', 'content': prompt}],
self.cfg.get('text_model'), timeout)
except Exception as e:
return None, '核查失败: %s' % e
m = re.search(r'\{.*\}', text, re.S)
if not m:
return None, '返回无法解析'
try:
data = json.loads(m.group())
except ValueError:
return None, 'JSON 解析失败'
match, reason = data.get('match'), data.get('reason', '')
if match and match in candidates:
return match, reason
return None, reason or '无匹配'