Files
inquiry_robot/inquiry-agent/agent/policy/synonym.py
T
linmianxun ceee650b23 同义词分批落地:包装全量识别 + 柜型/贸易条款/单一口岸
- 包装按表合并:纸箱→散货、木箱→托盘;新增 DB 驱动裸词扫描
- 同义词表改四列:standard/internal/tms/tms_code
- 批次 3:40GP/40HQ/45HQ、D2P/P2D/P2P、浦寨/霍尔果斯/友谊关/磨憨
- 更新种子生成器与同义词测试
2026-11-24 17:32:17 +08:00

509 lines
18 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.
"""
同义词配置:从主账 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箱」能识别,避免上线前行为倒退。
# 口径与 Excel 表一致:纸箱/箱/CTN 归散货,木箱/WOODEN BOX 归托盘。
_DEFAULT_PACK = (
("托盘", ("托盘", "托", "板", "卡板", "栈板", "托盘货", "打托", "带托",
"托盘包装", "PALLET", "PALLETS", "PLT", "PLTS", "SKID", "SKIDS",
"木箱", "木箱包装", "WOODEN BOX", "WOODEN CASE", "WOODEN CRATE")),
("散货", ("散货", "散件", "散箱", "散装", "散杂", "LOOSE", "LOOSE CARGO",
"BULK", "LCL CARGO", "纸箱", "箱", "纸箱包装", "外箱", "CARTON",
"CARTONS", "CTN", "CTNS", "CBOX", "袋", "编织袋", "吨袋", "太空袋",
"麻袋", "BAG", "SACK", "JUMBO BAG", "FIBC", "桶", "铁桶", "塑料桶",
"IBC", "DRUM", "BARREL", "TANK", "卷", "卷材", "布卷", "卷筒",
"ROLL", "ROLLS", "COIL")),
)
# 单字包装后面接这些字不算包装:箱型箱量、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 _row_standard(row: dict[str, Any]) -> str:
"""表标准值:工单/核对卡显示。"""
return str(row.get("standardValue") or row.get("standard_value") or "").strip()
def _row_internal(row: dict[str, Any]) -> str:
"""系统内部值:流程/TMS 判断;老数据没有 internal_value 时回退 standard。"""
internal = str(row.get("internalValue") or row.get("internal_value") or "").strip()
return internal or _row_standard(row)
def _row_tms_code(row: dict[str, Any]) -> str:
"""TMS 代码/三字码/模板表头;兼容旧 target_code。"""
return str(
row.get("tmsCode")
or row.get("tms_code")
or row.get("targetCode")
or row.get("target_code")
or ""
).strip()
def _fallback_pack_standard(value: str) -> str:
"""主账无配置时,按内置表把完整包装值折成散货/托盘(只做整串匹配)。"""
norm = normalize_key(value)
for std, syns in _DEFAULT_PACK:
for syn in syns:
if normalize_key(syn) == norm:
return std
return ""
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:
# 主账无配置/未命中时,包装仍按内置表归一(纸箱→散货、木箱→托盘)。
if field == "包装方式":
fb = _fallback_pack_standard(val)
if fb and fb != val:
out[key] = fb
continue
if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE":
continue
std = _row_internal(hit)
if std and std != val:
out[key] = std
# 陆运:事实写内部值,另存表标准值给卡片显示。
if field in {"运输类型", "线路类别"}:
display = _row_standard(hit)
if display:
out["陆运业务类型"] = display
# 「中亚零担」「东南亚整车」这类一个说法同时决定运输类型+线路类别;
# 销售只写了其中一个字段时,把另一个补出来。
if "运输类型" in src and not str(out.get("线路类别") or "").strip():
hit = lookup("线路类别", src["运输类型"], mode)
if hit is not None and _is_value(hit):
std = _row_internal(hit)
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 = _row_internal(hit)
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 = _row_internal(hit)
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 _row_tms_code(hit).upper()
def _packaging_pairs() -> list[tuple[str, str, dict[str, Any]]]:
"""包装同义词 (原始写法, 标准值, 行);长词优先,主账无配置时用内置兜底。"""
pairs: list[tuple[str, str, dict[str, Any]]] = []
seen: set[str] = set()
for bucket in _buckets("包装方式", ""):
for synonym, row in bucket.items():
std = _row_internal(row)
if not std or synonym in seen:
continue
# 原始写法优先;匹配键只用于去重。
syn = str(row.get("synonym") or "").strip() or synonym
pairs.append((syn, std, row))
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)
pairs.sort(key=lambda x: len(x[0]), reverse=True)
return pairs
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 = _packaging_pairs()
if not pairs:
return {}
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"(?<![\d.])(\d+(?:\.\d+)?)\s*({branches})(?![A-Za-z0-9])",
re.IGNORECASE,
)
last = None
for match in pattern.finditer(raw):
unit = match.group(2)
after = raw[match.end():match.end() + 1]
if after in _BAD_AFTER:
continue
std = std_by_norm.get(normalize_key(unit))
if not std:
continue
last = (match.group(1), unit, std)
if last is None:
return {}
num, unit, std = last
return {"件数": f"{num}{unit}", "包装方式": std}
def harvest_packaging_word(text: str) -> dict[str, str]:
"""
裸包装词:不带数字也认(纸箱/木箱/CTN/PALLET/编织袋…)。
用主账 inq_synonym 的 61 条包装同义词动态扫描,长词优先、取最后一个。
单字 托/板/箱/袋/桶/卷 仍必须数字紧邻,避免「委托/托运/箱型箱量」误伤。
件数由 harvest_package_count 另算;本函数只给包装方式标准值。
"""
if _disabled():
return {}
raw = unicodedata.normalize("NFKC", str(text or ""))
if not raw:
return {}
last_std = ""
last_end = -1
for syn, std, row in _packaging_pairs():
if not syn:
continue
single = len(syn) == 1
req = int(row.get("requiresNumber") or row.get("requires_number") or 0) if row else int(single)
if req:
# 单字只认数字紧邻:1板 / 2箱;1板车、1箱型后面跟车/型不算。
pattern = re.compile(
rf"(?<![\d.])\d+(?:\.\d+)?\s*({re.escape(syn)})(?![A-Za-z0-9])",
re.IGNORECASE,
)
elif syn.isascii():
# 英文裸词加边界,避免 BAG 命中 BAGGAGE、PLT 命中 PLTS。
pattern = re.compile(
rf"(?<![A-Za-z0-9])({re.escape(syn)})(?![A-Za-z0-9])",
re.IGNORECASE,
)
else:
pattern = re.compile(re.escape(syn), re.IGNORECASE)
for match in pattern.finditer(raw):
end = match.end()
if end <= last_end:
continue
if single and raw[end:end + 1] in _BAD_AFTER:
continue
if not single and row and _negative_hit(row, raw):
continue
last_std = std
last_end = end
return {"包装方式": last_std} if last_std else {}