/** * 称重识图:本地视觉 Top-K(onnxruntime-node 常驻进程内推理)。 * 设计:docs/design/20260901-weigh-local-topk-then-llm.md * docs/design/20260908-onnx-direct-recognize.md * * 改造说明(20260908): * - 原方案每次识别 spawn Python 进程,启动+加载模型 ~1.3s/次 * - 新方案用 onnxruntime-node 在 Node 进程内常驻模型,首次 ~1s,后续 ~0.2s * - prototypes.npz 预转换为 prototypes.json,Node 启动时加载 */ import { createRequire } from 'node:module'; import fs from 'node:fs'; import path from 'node:path'; import sharp from 'sharp'; /** 本地未装 onnxruntime-node 时不得拖垮整个 API(登录/财务等)。识图调用时再加载,失败则回退 LLM。 */ type OrtModule = { InferenceSession: { create: (modelPath: string, options?: Record) => Promise }; Tensor: new (type: string, data: Float32Array, dims: number[]) => unknown; }; const nodeRequire = createRequire(__filename); let _ort: OrtModule | null | undefined; function getOrt(): OrtModule | null { if (_ort !== undefined) return _ort; try { _ort = nodeRequire('onnxruntime-node') as OrtModule; return _ort; } catch (err) { console.warn( '[weigh-local-vision] onnxruntime-node unavailable, skip local ONNX:', (err as Error).message ); _ort = null; return null; } } export type WeighCatalogRow = { sku_code: string | null; item_name: string | null }; /** server/src/services 或 server/dist/services → server/ */ const SERVER_ROOT = path.resolve(__dirname, '../..'); // ─── 配置 ───────────────────────────────────────────── /** 与 tools/vision-dataset 中 safe_product_name 对齐 */ export function safeVisionProductName(name: string): string { return String(name || '') .trim() .replace(/[<>:"/\\|?*\x00-\x1f]/g, '_') .replace(/[. ]+$/g, '') .replace(/\s+/g, ' ') .slice(0, 80); } export function weighLocalVisionIndexReady(): boolean { const dir = weighLocalVisionIndexDir(); try { return ( fs.existsSync(path.join(dir, 'backbone.onnx')) && (fs.existsSync(path.join(dir, 'prototypes.json')) || fs.existsSync(path.join(dir, 'prototypes.npz'))) ); } catch { return false; } } export function isWeighLocalVisionEnabled(): boolean { const raw = String(process.env.WEIGH_LOCAL_VISION ?? '').trim().toLowerCase(); if (raw === '0' || raw === 'false' || raw === 'no' || raw === 'off') return false; if (raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on') return true; // 默认关闭:需显式 WEIGH_LOCAL_VISION=1(避免索引在场时自动开 ONNX) return false; } export function weighLocalVisionTopK(): number { const n = Number(process.env.WEIGH_LOCAL_VISION_TOPK); if (!Number.isFinite(n) || n <= 0) return 12; return Math.min(50, Math.floor(n)); } export function weighLocalVisionMinScore(): number { const n = Number(process.env.WEIGH_LOCAL_VISION_MIN_SCORE); if (!Number.isFinite(n)) return 0.15; return n; } /** ONNX 直返阈值:top-1 score ≥ 此值时跳过 LLM,直接返回结果 */ export function weighOnnxDirectThreshold(): number { const n = Number(process.env.WEIGH_ONNX_DIRECT_THRESHOLD); if (!Number.isFinite(n)) return 0.75; return Math.min(1, Math.max(0, n)); } export function weighLocalVisionTimeoutMs(): number { const n = Number(process.env.WEIGH_LOCAL_VISION_TIMEOUT_MS); if (!Number.isFinite(n) || n < 500) return 4000; return Math.min(20000, Math.floor(n)); } export function weighLocalVisionIndexDir(): string { const fromEnv = String(process.env.WEIGH_LOCAL_VISION_INDEX_DIR || '').trim(); if (fromEnv) return path.resolve(fromEnv); return path.join(SERVER_ROOT, 'data/weigh-vision'); } export function localVisionIndexReady(indexDir = weighLocalVisionIndexDir()): boolean { return ( fs.existsSync(path.join(indexDir, 'backbone.onnx')) && (fs.existsSync(path.join(indexDir, 'prototypes.json')) || fs.existsSync(path.join(indexDir, 'prototypes.npz'))) ); } // ─── 模型常驻(懒加载) ──────────────────────────────── let _session: any | null = null; let _names: string[] | null = null; let _vectors: Float32Array | null = null; let _dim = 0; let _loadedIndexDir: string | null = null; // ─── 自动学习状态 ───────────────────────────────────── let _learnCounts = new Map(); // 商品名 → 已学习次数 const LEARN_MAX_PER_PRODUCT = 20; // 每个商品最多学习 20 次 let _pendingWrites = 0; // 待持久化计数(防抖) let _writeTimer: NodeJS.Timeout | null = null; function isAutoLearnEnabled(): boolean { const raw = String(process.env.WEIGH_ONNX_AUTO_LEARN ?? '1').trim().toLowerCase(); return raw !== '0' && raw !== 'false' && raw !== 'no' && raw !== 'off'; } function learnThreshold(): number { const n = Number(process.env.WEIGH_ONNX_LEARN_THRESHOLD); if (!Number.isFinite(n)) return 0.85; return Math.min(1, Math.max(0.5, n)); } const IMAGENET_MEAN = [0.485, 0.456, 0.406]; const IMAGENET_STD = [0.229, 0.224, 0.225]; /** 懒加载 ONNX 模型和 prototypes(首次调用时加载,之后常驻内存) */ async function ensureModelLoaded(indexDir: string): Promise { if (_loadedIndexDir === indexDir && _session && _names && _vectors) return; const onnxPath = path.join(indexDir, 'backbone.onnx'); const jsonPath = path.join(indexDir, 'prototypes.json'); if (!fs.existsSync(onnxPath)) throw new Error(`backbone.onnx not found: ${onnxPath}`); if (!fs.existsSync(jsonPath)) throw new Error(`prototypes.json not found: ${jsonPath}`); const ort = getOrt(); if (!ort) throw new Error('onnxruntime-node not installed'); const t0 = Date.now(); // 加载 ONNX 模型 _session = await ort.InferenceSession.create(onnxPath, { executionProviders: ['cpu'], }); // 加载 prototypes const raw = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); _names = raw.names.map((n: string) => safeVisionProductName(n)); const flat: number[] = raw.vectors.flat(); _dim = raw.dim; _vectors = new Float32Array(flat); // L2 normalize prototype vectors const count = _names!.length; for (let i = 0; i < count; i++) { let norm = 0; for (let j = 0; j < _dim; j++) norm += _vectors[i * _dim + j] * _vectors[i * _dim + j]; norm = Math.sqrt(norm) + 1e-8; for (let j = 0; j < _dim; j++) _vectors[i * _dim + j] /= norm; } _loadedIndexDir = indexDir; console.info(`[weigh-local-vision] model loaded: ${count} prototypes, dim=${_dim}, ${Date.now() - t0}ms`); } // ─── 图像预处理 ────────────────────────────────────── /** * 解码 base64 JPEG → resize(min=224) → center crop 224×224 → normalize → CHW float32 * 复刻 Python infer_topk.py 的 preprocess 逻辑 */ async function preprocessImage(imageBuffer: Buffer): Promise { // 用 sharp 解码并获取原始像素 const img = sharp(imageBuffer); const meta = await img.metadata(); const h = meta.height || 0; const w = meta.width || 0; if (!h || !w) throw new Error('bad image dimensions'); // resize: short side = 224 (like Python: scale = 224.0 / min(h, w)) const scale = 224.0 / Math.min(h, w); let nh = Math.max(224, Math.round(h * scale)); let nw = Math.max(224, Math.round(w * scale)); const resized = await sharp(imageBuffer) .resize(nw, nh, { fit: 'fill' }) .raw() .toBuffer(); // center crop 224×224 const y0 = Math.floor((nh - 224) / 2); const x0 = Math.floor((nw - 224) / 2); // 提取 224×224 RGB 像素,归一化,转 CHW const chw = new Float32Array(3 * 224 * 224); for (let c = 0; c < 3; c++) { for (let y = 0; y < 224; y++) { for (let x = 0; x < 224; x++) { const srcIdx = ((y0 + y) * nw + (x0 + x)) * 3 + c; const pixel = resized[srcIdx] / 255.0; chw[c * 224 * 224 + y * 224 + x] = (pixel - IMAGENET_MEAN[c]) / IMAGENET_STD[c]; } } } return chw; } // ─── 推理 ───────────────────────────────────────────── /** 运行 ONNX 推理,返回 L2 归一化后的 embedding */ async function embedImage(imageBuffer: Buffer): Promise { const ort = getOrt(); if (!ort) throw new Error('onnxruntime-node not installed'); const input = await preprocessImage(imageBuffer); const tensor = new ort.Tensor('float32', input, [1, 3, 224, 224]); const inputName = _session.inputNames[0]; // "input" const outputName = _session.outputNames[0]; const results = await _session.run({ [inputName]: tensor }); const out = results[outputName] as any; // out.data 是 Float32Array 或 typed array, shape [1, dim] const rawData = out.data as Float32Array; const dim = rawData.length; const v = new Float32Array(dim); let norm = 0; for (let i = 0; i < dim; i++) { v[i] = rawData[i]; norm += rawData[i] * rawData[i]; } norm = Math.sqrt(norm) + 1e-8; for (let i = 0; i < dim; i++) v[i] /= norm; return v; } // ─── 自动学习 ───────────────────────────────────────── /** 持久化 prototypes 到 JSON(防抖:积累 5 次后写一次) */ function schedulePersistPrototypes(): void { _pendingWrites++; if (_writeTimer) clearTimeout(_writeTimer); _writeTimer = setTimeout(() => { _writeTimer = null; _pendingWrites = 0; persistPrototypesNow(); }, 2000); // 2 秒内无新更新则写入 } /** 立即写入 prototypes.json */ function persistPrototypesNow(): void { if (!_loadedIndexDir || !_names || !_vectors) return; try { const jsonPath = path.join(_loadedIndexDir, 'prototypes.json'); const vectorsArr: number[][] = []; for (let i = 0; i < _names!.length; i++) { const row: number[] = []; for (let j = 0; j < _dim; j++) row.push(_vectors![i * _dim + j]); vectorsArr.push(row); } const data = { names: _names, vectors: vectorsArr, dim: _dim, count: _names.length, }; fs.writeFileSync(jsonPath, JSON.stringify(data), 'utf8'); console.info(`[weigh-local-vision] prototypes persisted: ${_names!.length} items`); } catch (err) { console.warn('[weigh-local-vision] persist failed:', err); } } /** * 自动学习:用当前图片更新指定商品的 prototype。 * - 已有 prototype:加权平均(旧 0.8 + 新 0.2),L2 重新归一化 * - 新商品:直接作为新 prototype * - 每个商品最多学习 LEARN_MAX_PER_PRODUCT 次 * - 异步持久化,不阻塞识别响应 */ export async function learnPrototype(imageBase64: string, productName: string): Promise { if (!isAutoLearnEnabled()) return; if (!_session || !_names || !_vectors || !_loadedIndexDir) return; const safeName = safeVisionProductName(productName); if (!safeName) return; const count = _learnCounts.get(safeName) || 0; if (count >= LEARN_MAX_PER_PRODUCT) return; try { const b64 = stripImageBase64(imageBase64); const imageBuffer = Buffer.from(b64, 'base64'); const embedding = await embedImage(imageBuffer); const existingIdx = _names.indexOf(safeName); if (existingIdx >= 0) { // 加权平均:旧 0.8 + 新 0.2 const oldWeight = 0.8; const newWeight = 0.2; for (let j = 0; j < _dim; j++) { const oldVal = _vectors[existingIdx * _dim + j]; const newVal = embedding[j]; let blended = oldVal * oldWeight + newVal * newWeight; _vectors[existingIdx * _dim + j] = blended; } // L2 重新归一化 let norm = 0; for (let j = 0; j < _dim; j++) norm += _vectors[existingIdx * _dim + j] * _vectors[existingIdx * _dim + j]; norm = Math.sqrt(norm) + 1e-8; for (let j = 0; j < _dim; j++) _vectors[existingIdx * _dim + j] /= norm; console.info(`[weigh-local-vision] learned: ${safeName} (update #${count + 1})`); } else { // 新商品:追加到 prototypes const newIdx = _names.length; const newVectors = new Float32Array((_names.length + 1) * _dim); newVectors.set(_vectors); newVectors.set(embedding, newIdx * _dim); _vectors = newVectors; _names.push(safeName); console.info(`[weigh-local-vision] learned: ${safeName} (new prototype #${newIdx + 1})`); } _learnCounts.set(safeName, count + 1); schedulePersistPrototypes(); } catch (err) { console.warn('[weigh-local-vision] learn failed:', err); } } // ─── 工具函数 ───────────────────────────────────────── function stripImageBase64(raw: string): string { const trimmed = String(raw || '').trim(); const m = /^data:[^;]+;base64,(.+)$/i.exec(trimmed); return m ? m[1] : trimmed; } /** 按 Top 品名顺序过滤 catalog;同名多 SKU 均保留。 */ export function filterCatalogByTopNames( catalog: WeighCatalogRow[], topNames: string[] ): WeighCatalogRow[] { const order = new Map(); topNames.forEach((n, i) => { const key = safeVisionProductName(n); if (key && !order.has(key)) order.set(key, i); }); if (!order.size) return []; const matched = catalog.filter((row) => order.has(safeVisionProductName(String(row.item_name || ''))) ); matched.sort((a, b) => { const ia = order.get(safeVisionProductName(String(a.item_name || ''))) ?? 9999; const ib = order.get(safeVisionProductName(String(b.item_name || ''))) ?? 9999; if (ia !== ib) return ia - ib; return String(a.sku_code || '').localeCompare(String(b.sku_code || '')); }); return matched; } // ─── 主接口 ─────────────────────────────────────────── /** * 用本地视觉在 catalog 品名内取 Top-K;失败或需回退时返回 null(调用方用全量)。 * 现在用 onnxruntime-node 进程内推理,不再 spawn Python。 */ export async function narrowCatalogWithLocalVision(input: { imageBase64: string; catalog: WeighCatalogRow[]; topK?: number; minScore?: number; }): Promise<{ catalog: WeighCatalogRow[]; top: Array<{ name: string; score: number }> } | null> { if (!isWeighLocalVisionEnabled()) return null; const indexDir = weighLocalVisionIndexDir(); if (!localVisionIndexReady(indexDir)) { console.warn('[weigh-local-vision] index not ready, skip:', indexDir); return null; } const catalog = Array.isArray(input.catalog) ? input.catalog : []; const candidates = [ ...new Set( catalog .map((r) => safeVisionProductName(String(r.item_name || ''))) .filter(Boolean) ), ]; if (candidates.length <= 1) return null; const b64 = stripImageBase64(input.imageBase64); if (!b64) return null; try { // 加载模型(首次调用时加载,之后常驻) await ensureModelLoaded(indexDir); const imageBuffer = Buffer.from(b64, 'base64'); const t0 = Date.now(); // 推理 const q = await embedImage(imageBuffer); const inferMs = Date.now() - t0; // 比对 prototypes(cosine similarity = dot product,因为都 L2 归一化了) const nameToIdx = new Map(); _names!.forEach((n, i) => nameToIdx.set(n, i)); const k = Math.min(input.topK ?? weighLocalVisionTopK(), 50); const minScore = input.minScore ?? weighLocalVisionMinScore(); const scored: Array<{ name: string; score: number }> = []; const seen = new Set(); for (const name of candidates) { if (seen.has(name)) continue; seen.add(name); const idx = nameToIdx.get(name); if (idx === undefined) continue; let score = 0; for (let j = 0; j < _dim; j++) score += q[j] * _vectors![idx * _dim + j]; scored.push({ name, score }); } if (scored.length < 2) { console.info(`[weigh-local-vision] too few indexed candidates: ${scored.length}, infer=${inferMs}ms`); return null; } scored.sort((a, b) => b.score - a.score); if (scored[0].score < minScore) { console.info(`[weigh-local-vision] low score: ${scored[0].score.toFixed(3)} < ${minScore}, infer=${inferMs}ms`); return null; } const top = scored.slice(0, k); const narrowed = filterCatalogByTopNames( catalog, top.map((t) => t.name) ); if (!narrowed.length) return null; console.info( `[weigh-local-vision] infer=${inferMs}ms top1=${top[0].name}:${top[0].score.toFixed(3)}` ); return { catalog: narrowed, top }; } catch (err) { console.warn('[weigh-local-vision] error:', err); return null; } }