Files
SupplierSystem/server/data/weigh-vision/infer_topk.py
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

166 lines
5.4 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.
#!/usr/bin/env python3
"""待验品名集合内 Top-K(ONNX MobileNet 原型余弦)。
stdin JSON: {image_path|image_base64, candidates[], k, min_score, index_dir}
stdout JSON: {ok, fallback, top:[{name,score}], error?}
设计:docs/design/20260901-weigh-local-topk-then-llm.md
"""
from __future__ import annotations
import base64
import json
import re
import sys
from pathlib import Path
import cv2
import numpy as np
_ILLEGAL = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
IMAGENET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMAGENET_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
_SESSION = None
_NAMES: list[str] | None = None
_VECTORS: np.ndarray | None = None
_INDEX_DIR: str | None = None
def safe_product_name(name: str) -> str:
s = _ILLEGAL.sub("_", (name or "").strip())
s = re.sub(r"[. ]+$", "", s)
s = re.sub(r"\s+", " ", s)
return s[:80]
def imread_path(path: Path) -> np.ndarray | None:
try:
data = np.fromfile(str(path), dtype=np.uint8)
if data.size == 0:
return None
return cv2.imdecode(data, cv2.IMREAD_COLOR)
except OSError:
return None
def center_crop_224_bgr(img: np.ndarray) -> np.ndarray:
h, w = img.shape[:2]
scale = 224.0 / float(min(h, w))
nh, nw = max(224, int(round(h * scale))), max(224, int(round(w * scale)))
resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR)
y0 = (nh - 224) // 2
x0 = (nw - 224) // 2
return resized[y0 : y0 + 224, x0 : x0 + 224]
def preprocess(img: np.ndarray) -> np.ndarray:
crop = center_crop_224_bgr(img)
rgb = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
rgb = (rgb - IMAGENET_MEAN) / IMAGENET_STD
chw = np.transpose(rgb, (2, 0, 1))[None, ...].astype(np.float32)
return chw
def load_index(index_dir: Path) -> None:
global _SESSION, _NAMES, _VECTORS, _INDEX_DIR
key = str(index_dir.resolve())
if _INDEX_DIR == key and _SESSION is not None and _NAMES is not None and _VECTORS is not None:
return
import onnxruntime as ort
onnx_path = index_dir / "backbone.onnx"
npz_path = index_dir / "prototypes.npz"
if not onnx_path.is_file() or not npz_path.is_file():
raise FileNotFoundError(f"missing index under {index_dir}")
_SESSION = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
data = np.load(str(npz_path), allow_pickle=True)
_NAMES = [safe_product_name(str(x)) for x in data["names"].tolist()]
_VECTORS = data["vectors"].astype(np.float32)
# L2 normalize rows
norms = np.linalg.norm(_VECTORS, axis=1, keepdims=True) + 1e-8
_VECTORS = _VECTORS / norms
_INDEX_DIR = key
def embed(img: np.ndarray) -> np.ndarray:
assert _SESSION is not None
inp = preprocess(img)
out = _SESSION.run(None, {"input": inp})[0]
v = out[0].astype(np.float32)
v = v / (np.linalg.norm(v) + 1e-8)
return v
def run(payload: dict) -> dict:
index_dir = Path(payload.get("index_dir") or "server/data/weigh-vision")
load_index(index_dir)
assert _NAMES is not None and _VECTORS is not None
img = None
image_path = payload.get("image_path")
if image_path:
img = imread_path(Path(str(image_path)))
if img is None and payload.get("image_base64"):
raw = str(payload["image_base64"])
if "," in raw and raw.strip().lower().startswith("data:"):
raw = raw.split(",", 1)[1]
buf = np.frombuffer(base64.b64decode(raw), dtype=np.uint8)
img = cv2.imdecode(buf, cv2.IMREAD_COLOR)
if img is None:
return {"ok": False, "fallback": True, "error": "bad_image", "top": []}
q = embed(img)
name_to_idx = {n: i for i, n in enumerate(_NAMES)}
candidates = [safe_product_name(str(x)) for x in (payload.get("candidates") or [])]
candidates = [c for c in candidates if c]
k = int(payload.get("k") or 12)
k = max(1, min(k, 50))
min_score = float(payload.get("min_score") if payload.get("min_score") is not None else 0.15)
scored: list[tuple[str, float]] = []
seen: set[str] = set()
for name in candidates:
if name in seen:
continue
seen.add(name)
idx = name_to_idx.get(name)
if idx is None:
continue
score = float(np.dot(q, _VECTORS[idx]))
scored.append((name, score))
if len(scored) < 2:
return {"ok": True, "fallback": True, "reason": "too_few_indexed_candidates", "top": []}
scored.sort(key=lambda x: x[1], reverse=True)
if scored[0][1] < min_score:
return {
"ok": True,
"fallback": True,
"reason": "low_score",
"max_score": scored[0][1],
"top": [{"name": n, "score": s} for n, s in scored[:k]],
}
top = [{"name": n, "score": s} for n, s in scored[:k]]
return {"ok": True, "fallback": False, "top": top}
def main() -> None:
try:
payload = json.load(sys.stdin)
except Exception as exc: # noqa: BLE001
json.dump({"ok": False, "fallback": True, "error": f"bad_json:{exc}", "top": []}, sys.stdout, ensure_ascii=False)
return
try:
result = run(payload)
except Exception as exc: # noqa: BLE001
result = {"ok": False, "fallback": True, "error": str(exc), "top": []}
json.dump(result, sys.stdout, ensure_ascii=False)
sys.stdout.write("\n")
if __name__ == "__main__":
main()