""" 同义词配置:从主账 inq_synonym 读取,做值归一化与“数量+包装”机读。 本文件职责: * 60 秒短缓存 GET /inquiry/agent/synonym/listEnabled; * 按 field_key + transport_mode 精确/最长子串匹配,把卡板→托盘、40尺高柜→40HQ; * 从「1板 / 2箱 / 3托」同时写件数与包装方式; * 空运三字码优先查表,查不到再回退代码内 _AIRPORTS。 禁止: * 全文字符串 replace;单字同义词必须数字紧邻; * 用同义词覆盖带数量的车型字段(9米6/1 必须保留 /1); * 主账失败时清空旧缓存;失败保留旧值,从未加载成功则回退代码默认。 线程:进程内锁刷新;与 bot_reply 一致,不同工单共享一份缓存。 """ from __future__ import annotations import logging import os import re import threading import time import unicodedata from typing import Any, Optional logger = logging.getLogger(__name__) # 后台改词后最多这么久生效;不当 checkpoint。 _TTL_SECONDS = 60.0 _lock = threading.Lock() _loaded_at = 0.0 _rows: list[dict[str, Any]] = [] _index: dict[tuple[str, str], dict[str, dict[str, Any]]] = {} _override: Optional[list[dict[str, Any]]] = None # 主账不可用时仍保证「1板/2箱」能识别,避免上线前行为倒退。 _DEFAULT_PACK = ( ("托盘", ("托盘", "托", "板", "卡板", "栈板", "PALLET", "PALLETS", "PLT", "PLTS", "SKID")), ("纸箱", ("纸箱", "箱", "CARTON", "CARTONS", "CTN", "CTNS", "CBOX")), ("木箱", ("木箱", "WOODEN BOX", "WOODEN CASE", "WOODEN CRATE")), ("散货", ("散货", "散件", "散装", "散杂", "LOOSE", "BULK")), ) # 单字包装后面接这些字不算包装:箱型箱量、1板车。 _BAD_AFTER = ("型", "量", "体", "码", "规", "单", "柜", "车") def override_catalog(rows: Optional[list[dict[str, Any]]]) -> None: """单测注入同义词行;传 None 清掉注入并重新走主账。""" global _override, _loaded_at, _rows with _lock: _override = [dict(r) for r in rows] if rows is not None else None _loaded_at = 0.0 if rows is None: _rows = [] def normalize_key(value: Any) -> str: """匹配键:全半角统一、去空白、去引号、转大写。""" text = unicodedata.normalize("NFKC", str(value or "")) for ch in ("'", '"', "’", "‘", "“", "”", "`"): text = text.replace(ch, "") text = "".join(text.split()) return text.upper() def _unwrap_rows(data: Any) -> list[Any]: """解开 Jeecg Result 列表。""" if isinstance(data, list): return data if not isinstance(data, dict): return [] inner = data.get("result") if isinstance(inner, list): return inner if isinstance(inner, dict): rec = inner.get("records") if isinstance(rec, list): return rec rec = data.get("records") or data.get("data") if isinstance(rec, list): return rec return [] def _fetch() -> Optional[list[dict[str, Any]]]: """ GET /inquiry/agent/synonym/listEnabled。 未配主账地址/内存后端返回空列表,避免每次空打;失败返回 None 保留旧缓存。 """ try: from agent.config import get_settings cfg = get_settings() backend = str( os.environ.get("LEDGER_BACKEND") or getattr(cfg, "ledger_backend", "") or "" ).strip().lower() if backend in {"memory", "mem", "stub"}: return [] if not str(getattr(cfg, "biz_api_base_url", "") or "").strip(): return [] from agent.ledger import LedgerClient from agent.ledger.api_shell import LedgerApiShell client = LedgerClient.from_settings() client.timeout_seconds = min(float(client.timeout_seconds or 10), 3.0) resp = LedgerApiShell(client=client).list_synonyms() if not resp.ok: logger.warning("synonym listEnabled fail status=%s err=%s", resp.status_code, resp.error) return None out: list[dict[str, Any]] = [] for row in _unwrap_rows(resp.data): if isinstance(row, dict): out.append(row) return out except Exception: logger.warning("synonym listEnabled 异常,保留旧缓存", exc_info=True) return None def _build_index(rows: list[dict[str, Any]]) -> dict[tuple[str, str], dict[str, dict[str, Any]]]: """(field, mode) → norm → row;同键保留 priority 大的。""" index: dict[tuple[str, str], dict[str, dict[str, Any]]] = {} for raw in rows: if not isinstance(raw, dict): continue if int(raw.get("enabled") if raw.get("enabled") is not None else 1) != 1: continue field = str(raw.get("fieldKey") or raw.get("field_key") or "").strip() mode = str(raw.get("transportMode") or raw.get("transport_mode") or "ALL").strip().upper() syn = str(raw.get("synonym") or "").strip() if not field or not syn: continue key = str(raw.get("synonymNorm") or raw.get("synonym_norm") or "").strip() or normalize_key(syn) row = dict(raw) row["_field"] = field row["_mode"] = mode row["_norm"] = key row["_priority"] = int(raw.get("priority") or 100) bucket = index.setdefault((field, mode), {}) old = bucket.get(key) if old is None or row["_priority"] >= int(old.get("_priority") or 0): bucket[key] = row return index def _disabled() -> bool: """紧急回滚开关:INQUIRY_SYNONYM_DISABLED=1 时完全不走同义词。""" return str(os.environ.get("INQUIRY_SYNONYM_DISABLED") or "").strip().lower() in { "1", "true", "yes", "on", } def _ensure_loaded() -> None: global _loaded_at, _rows, _index if _disabled(): return now = time.monotonic() with _lock: if _override is not None: return if _loaded_at > 0 and (now - _loaded_at) < _TTL_SECONDS: return fresh = _fetch() with _lock: if _override is not None: return if fresh is not None: _rows = fresh _index = _build_index(fresh) _loaded_at = time.monotonic() elif not _rows: _loaded_at = time.monotonic() def _buckets(field: str, mode: str) -> list[dict[str, dict[str, Any]]]: if _disabled(): return [] _ensure_loaded() mode = (mode or "").strip().upper() with _lock: if _override is not None: index = _build_index(_override) else: index = _index out = [] for m in (mode, "ALL"): if not m: continue bucket = index.get((field, m)) if bucket and all(bucket is not seen for seen in out): out.append(bucket) return out def _negative_hit(row: dict[str, Any], text: str) -> bool: """negative_words 命中任一就不映射。""" raw = str(row.get("negativeWords") or row.get("negative_words") or "").strip() if not raw: return False for word in re.split(r"[,,、]", raw): word = word.strip() if word and word in text: return True return False def lookup(field: str, value: Any, mode: str = "", *, substring: bool = True) -> Optional[dict[str, Any]]: """ 按字段取值对应的同义词行。 先精确,再最长子串(只认长度≥2、非单字)。单字 requires_number 不在值里直接命中, 由 harvest_package_count 按「数字+包装」处理。 substring=False 用于箱型箱量:2个40尺高柜 / 40HQ*2 必须留给 TMS 解析器拆箱量, 不能被「40HQ」整串替换掉数量。 """ text = str(value or "").strip() if not text: return None norm = normalize_key(text) buckets = _buckets(field, mode) for bucket in buckets: hit = bucket.get(norm) if hit is not None and not _negative_hit(hit, text): return hit if not substring: return None # 最长子串:避免「包装纸箱」漏掉;单字不参与。 best: Optional[dict[str, Any]] = None best_len = 1 for bucket in buckets: for synonym, row in bucket.items(): if int(row.get("requiresNumber") or row.get("requires_number") or 0) == 1: continue if len(synonym) < 2 or synonym not in norm: continue if _negative_hit(row, text): continue if len(synonym) > best_len: best = row best_len = len(synonym) return best def _lookup_with_aliases( field: str, value: Any, mode: str = "", *, substring: bool = True ) -> Optional[dict[str, Any]]: """起运港/目的港先查自身字段,再查城市(空运/陆运)或港口(海运)。""" hit = lookup(field, value, mode, substring=substring) if hit is not None: return hit if field in {"起运港", "起运地", "目的港", "目的地"}: return ( lookup("城市", value, mode, substring=substring) or lookup("港口", value, mode, substring=substring) ) return None # 内部键 → 配置字段键;包装类型与包装方式共用一套。 _FIELD_ALIASES = { "包装类型": "包装方式", "起运地": "起运港", "目的地": "目的港", "车型数量": "车型/数量", "货物数量": "货量", } def apply_value_synonyms( facts: dict[str, Any] | None, business_line: str = "", ) -> dict[str, Any]: """ 把事实里的值折成标准值。只改 VALUE 类型;UNIT/LABEL/INTENT/RULE 不动。 只处理字符串值;added_services / containerItems 这类列表或数字原样保留。 车型/数量 特殊处理:只归一车型部分,保留 /1 这类台数。 返回新 dict,不改入参。 """ src = {str(k): v for k, v in dict(facts or {}).items() if v is not None} out = dict(src) mode = (business_line or "").strip().upper() for key, raw_val in src.items(): if not isinstance(raw_val, str): continue val = raw_val.strip() if not val: continue field = _FIELD_ALIASES.get(key, key) if field == "车型/数量": out[key] = _normalize_vehicle_qty(val, mode) continue hit = _lookup_with_aliases( field, val, mode, substring=field not in {"箱型箱量"} ) if hit is None: continue if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE": continue std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip() if std and std != val: out[key] = std # 「中亚零担」「东南亚整车」这类一个说法同时决定运输类型+线路类别; # 销售只写了其中一个字段时,把另一个补出来。 if "运输类型" in src and not str(out.get("线路类别") or "").strip(): hit = lookup("线路类别", src["运输类型"], mode) if hit is not None and _is_value(hit): std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip() if std: out["线路类别"] = std if "线路类别" in src and not str(out.get("运输类型") or "").strip(): hit = lookup("运输类型", src["线路类别"], mode) if hit is not None and _is_value(hit): std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip() if std: out["运输类型"] = std return out def _is_value(hit: dict[str, Any]) -> bool: return str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() == "VALUE" def _normalize_vehicle_qty(value: str, mode: str) -> str: """9米6/1 → 9.6高栏/1;拆不出台数就只归一车型。""" text = (value or "").strip() if not text: return text parts = re.split(r"\s*[/xX×**]\s*", text, maxsplit=1) vehicle = parts[0].strip() hit = lookup("车型/数量", vehicle, mode or "LAND") if hit is None: return text if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE": return text std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip() if not std: return text if len(parts) == 2 and parts[1].strip(): return f"{std}/{parts[1].strip()}" return std def airport_code(value: Any) -> str: """地名 → 空运三字码;查不到返回空串,调用方回退 _AIRPORTS。""" hit = lookup("城市", value, "AIR") if hit is None: return "" return str(hit.get("targetCode") or hit.get("target_code") or "").strip().upper() def harvest_package_count(text: str) -> dict[str, str]: """ 从「1板 / 2箱 / 3托」取件数与包装方式。 件数保留销售原文(1板);包装写标准值(托盘)。单字后面接 型/量/体/码/规/单/柜/车 不算包装。主账无配置时用内置兜底。 """ if _disabled(): return {} raw = unicodedata.normalize("NFKC", str(text or "")) if not raw: return {} pairs: list[tuple[str, str]] = [] seen: set[str] = set() for bucket in _buckets("包装方式", ""): for synonym, row in bucket.items(): std = str(row.get("standardValue") or row.get("standard_value") or "").strip() if not std or synonym in seen: continue # 原始写法优先;匹配键只用于去重。 syn = str(row.get("synonym") or "").strip() or synonym pairs.append((syn, std)) seen.add(synonym) for std, syns in _DEFAULT_PACK: for syn in syns: key = normalize_key(syn) if key in seen: continue pairs.append((syn, std)) seen.add(key) if not pairs: return {} # 长词优先,避免「托盘」被「托」抢先。 pairs.sort(key=lambda x: len(x[0]), reverse=True) branches = "|".join(re.escape(s) for s, _ in pairs) std_by_norm = {normalize_key(s): std for s, std in pairs} # 数字紧邻;后面接 型/量/体/码/规/单/柜/车 时不算。 pattern = re.compile( rf"(?