- 空运调价:无数量时单价留空,避免出单按「单价×计费重」再乘一遍(WO202611250038 金额被放大) - 报价模板:unit_price 只取单价字段,amount 仅作行合计,不再回退成单价 - 陆运一条线路多段时,同名费用行按段号/腿号补「起运 → 目的」展示名,后台与前端一致,不改金额与原名匹配 - 同义词扫描先剥掉补问清单示例行,避免示例车型/口岸覆盖销售实填值;车型正则补平板/高栏/厢车/冷藏等后缀 - 补空运计费重、报价行、陆运线路标签相关单测
1008 lines
37 KiB
Python
1008 lines
37 KiB
Python
"""
|
||
同义词配置:从主账 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
|
||
_last_fetch_ok = False
|
||
|
||
# 主账不可用时仍保证「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 _table_configured() -> bool:
|
||
"""是否配置了主账同义词表;内存后端/未配地址视为没有表。"""
|
||
if _override is not None:
|
||
return True
|
||
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 False
|
||
return bool(str(getattr(cfg, "biz_api_base_url", "") or "").strip())
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _ensure_loaded() -> None:
|
||
global _loaded_at, _rows, _index, _last_fetch_ok
|
||
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
|
||
configured = _table_configured()
|
||
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()
|
||
_last_fetch_ok = bool(configured)
|
||
logger.debug("synonym.loaded rows=%d file=%s", len(fresh), __file__)
|
||
elif not _rows:
|
||
_loaded_at = time.monotonic()
|
||
_last_fetch_ok = False
|
||
|
||
|
||
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 confirm_table_authoritative() -> bool:
|
||
"""
|
||
确认词是否由表说了算。
|
||
|
||
表已配置且成功加载 → True(停用即失效);
|
||
内存后端/未配地址/首次加载失败 → False(调用方用硬编码兜底)。
|
||
"""
|
||
if _disabled():
|
||
return False
|
||
if _override is not None:
|
||
return True
|
||
if not _table_configured():
|
||
return False
|
||
_ensure_loaded()
|
||
with _lock:
|
||
return bool(_last_fetch_ok)
|
||
|
||
|
||
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
|
||
|
||
|
||
# 城市/港口的三字码(SHA/SIN/KUL…)只认独立词,不能从英文单词里截出来匹配。
|
||
_PLACE_LOOKUP_FIELDS = frozenset(
|
||
{"城市", "港口", "起运港", "起运地", "目的港", "目的地"}
|
||
)
|
||
_ASCII_WORD_ONLY = re.compile(r"[A-Za-z]+")
|
||
_LATIN_WORD = re.compile(r"[A-Za-z]{2,}")
|
||
_ADDRESS_MARK = re.compile(r"[,,;;]|\d{3,}")
|
||
|
||
|
||
def _ascii_substring_hit(synonym: str, norm: str) -> bool:
|
||
"""
|
||
纯英文同义词在长值里只按整词命中。
|
||
|
||
运行证据:目的地「Kaushal Singh …」里的 KAUSHAL 含 SHA、SINGH 含 SIN,
|
||
被当成长值子串映射成上海/新加坡。中文同义词仍按普通子串。
|
||
"""
|
||
if not _ASCII_WORD_ONLY.fullmatch(synonym):
|
||
return True
|
||
return (
|
||
re.search(rf"(?<![A-Za-z]){re.escape(synonym)}(?![A-Za-z])", norm)
|
||
is not None
|
||
)
|
||
|
||
|
||
def _latin_street_address(text: str) -> bool:
|
||
"""
|
||
英文词 + 逗号/门牌邮编 = 街道地址,不整段折成城市。
|
||
|
||
「NEW DELHI - 110001, INDIA」里 DELHI 虽是表里的同义词,但整段是地址,
|
||
折成「德里」会丢掉收货地址。纯城市名(New York / SHA)没有逗号和门牌,照常归一。
|
||
中文地址保持原逻辑(只认中文同义词子串)。副作用:无。
|
||
"""
|
||
return bool(_LATIN_WORD.search(text) and _ADDRESS_MARK.search(text))
|
||
|
||
|
||
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 (
|
||
field in _PLACE_LOOKUP_FIELDS
|
||
and not _ascii_substring_hit(synonym, norm)
|
||
):
|
||
continue
|
||
if _negative_hit(row, text):
|
||
continue
|
||
if len(synonym) > best_len:
|
||
best = row
|
||
best_len = len(synonym)
|
||
return best
|
||
|
||
|
||
def display_value(field: str, value: Any, mode: str = "") -> str:
|
||
"""
|
||
内部值 → 表标准值(仅当标准值带括号说明时),供核对卡显示。
|
||
|
||
例:春疆 → 春疆(越南·谅山)、东莞 → 东莞(无机场,走 SZX)。
|
||
香港/HKG、广州/CAN 这类没有括号的标准值仍显示内部中文名,避免卡片变吵。
|
||
mode 用于区分:东莞只配 AIR,陆运/海运不显示机场说明。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return text
|
||
_ensure_loaded()
|
||
with _lock:
|
||
index = _build_index(_override) if _override is not None else _index
|
||
modes: list[str] = []
|
||
m = (mode or "").strip().upper()
|
||
if m:
|
||
modes.append(m)
|
||
modes.append("ALL")
|
||
for mm in modes:
|
||
bucket = index.get((field, mm))
|
||
if not bucket:
|
||
continue
|
||
for row in bucket.values():
|
||
if _row_internal(row) != text:
|
||
continue
|
||
std = _row_standard(row)
|
||
if std and ("(" in std or "(" in std):
|
||
return std
|
||
return text
|
||
|
||
|
||
def display_standard(field: str, value: Any, mode: str = "") -> str:
|
||
"""内部值 → 表标准值(不带括号限制);车型卡片显示「4.2米 厢车」。"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return text
|
||
_ensure_loaded()
|
||
with _lock:
|
||
index = _build_index(_override) if _override is not None else _index
|
||
modes: list[str] = []
|
||
m = (mode or "").strip().upper()
|
||
if m:
|
||
modes.append(m)
|
||
modes.append("ALL")
|
||
for mm in modes:
|
||
bucket = index.get((field, mm))
|
||
if not bucket:
|
||
continue
|
||
for row in bucket.values():
|
||
if _row_internal(row) != text:
|
||
continue
|
||
std = _row_standard(row)
|
||
if std:
|
||
return std
|
||
return text
|
||
|
||
|
||
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 is_confirm_message(text: str) -> bool:
|
||
"""
|
||
整句是否命中 inq_synonym 的「确认」INTENT 行(EXACT_MESSAGE)。
|
||
|
||
只认整句,不认长句里的子串;IT 加「收到/没问题」这类整句只改表。
|
||
"""
|
||
key = normalize_key(text)
|
||
if not key:
|
||
return False
|
||
for bucket in _buckets("确认", ""):
|
||
for row in bucket.values():
|
||
if (
|
||
str(row.get("synonymType") or row.get("synonym_type") or "").upper()
|
||
!= "INTENT"
|
||
):
|
||
continue
|
||
if str(row.get("enabled", 1)).lower() in {"0", "false"}:
|
||
continue
|
||
row_key = str(
|
||
row.get("_norm")
|
||
or row.get("synonymNorm")
|
||
or row.get("synonym_norm")
|
||
or normalize_key(row.get("synonym") or "")
|
||
)
|
||
if row_key == key:
|
||
return True
|
||
return False
|
||
|
||
|
||
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 == "货好时间":
|
||
try:
|
||
from agent.schema.field_validate import normalize_cargo_ready_value
|
||
|
||
out[key] = normalize_cargo_ready_value(val)
|
||
except Exception:
|
||
pass
|
||
continue
|
||
if field in {"毛重", "体积"}:
|
||
converted = normalize_unit_value(field, val)
|
||
if converted != val:
|
||
out[key] = converted
|
||
continue
|
||
if field == "车型/数量":
|
||
out[key] = _normalize_vehicle_qty(val, mode)
|
||
continue
|
||
# 英文街道地址不做城市归一:地址里出现 DELHI/HONG KONG 这类词也不能整段换成城市。
|
||
if field in _PLACE_LOOKUP_FIELDS and _latin_street_address(val):
|
||
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 and val != std:
|
||
out.setdefault("陆运业务类型", 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 _value_pairs(
|
||
field: str, mode: str = "", *, pack_fallback: bool = False
|
||
) -> list[tuple[str, str, dict[str, Any]]]:
|
||
"""字段同义词 (原始写法, internal, 行);只收 VALUE,长词优先。"""
|
||
pairs: list[tuple[str, str, dict[str, Any]]] = []
|
||
seen: set[str] = set()
|
||
for bucket in _buckets(field, mode):
|
||
for synonym, row in bucket.items():
|
||
if str(row.get("synonymType") or row.get("synonym_type") or "VALUE").upper() != "VALUE":
|
||
continue
|
||
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)
|
||
if pack_fallback:
|
||
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 _strip_prompt_examples(text: str) -> str:
|
||
"""
|
||
补问清单里的示例行((如:…))不是销售填的值,原话扫描前先剥掉。
|
||
|
||
运行证据:销售把补问清单整段复制回来、只在冒号后填值,示例行
|
||
「(如:9米6/1)」还在时,车型候选会把 18米平板 覆盖成 9.6高栏;
|
||
通关口岸同理,示例里的友谊关会被当成真实候选。只影响扫描副本。
|
||
"""
|
||
try:
|
||
from agent.schema.field_validate import _without_clarify_examples
|
||
|
||
return _without_clarify_examples(text)
|
||
except Exception:
|
||
return text
|
||
|
||
|
||
def _field_hits(
|
||
field: str,
|
||
text: str,
|
||
mode: str = "",
|
||
*,
|
||
pack_fallback: bool = False,
|
||
) -> list[tuple[int, str]]:
|
||
"""字段命中的 (结束位置, internal);长词优先,数据和负向词由表控制。"""
|
||
if _disabled():
|
||
return []
|
||
raw = _strip_prompt_examples(unicodedata.normalize("NFKC", str(text or "")))
|
||
if not raw:
|
||
return []
|
||
hits: list[tuple[int, str]] = []
|
||
pairs = _value_pairs(field, mode, pack_fallback=pack_fallback)
|
||
for syn, std, row in pairs:
|
||
if not syn:
|
||
continue
|
||
# 原话已 NFKC(全角括号→半角);同义词也要同口径,否则「4米2车(带尾板)」匹配不到。
|
||
syn = unicodedata.normalize("NFKC", str(syn))
|
||
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 single and raw[end:end + 1] in _BAD_AFTER:
|
||
continue
|
||
if not single and row and _negative_hit(row, raw):
|
||
continue
|
||
hits.append((end, std))
|
||
return hits
|
||
|
||
|
||
def harvest_field_value(
|
||
field: str,
|
||
text: str,
|
||
mode: str = "",
|
||
*,
|
||
unique: bool = True,
|
||
pack_fallback: bool = False,
|
||
) -> dict[str, str]:
|
||
"""
|
||
通用原话扫描:按 field_key 读 inq_synonym,返回 internal_value。
|
||
|
||
长词优先;requires_number / negative_words / VALUE 类型由数据表控制。
|
||
unique=True:同一句命中两个不同标准值时不猜,返回空。
|
||
unique=False:取最后一个(包装沿用“当前句最后出现的包装词”)。
|
||
"""
|
||
hits = _field_hits(field, text, mode, pack_fallback=pack_fallback)
|
||
if field == "贸易条款":
|
||
logger.debug(
|
||
"synonym.trade text=%r hits=%s",
|
||
str(text or "")[:60], [std for _, std in hits],
|
||
)
|
||
if not hits:
|
||
return {}
|
||
if unique:
|
||
distinct = {std for _, std in hits}
|
||
if len(distinct) > 1:
|
||
return {}
|
||
return {field: distinct.pop()}
|
||
return {field: max(hits, key=lambda x: x[0])[1]}
|
||
|
||
|
||
def harvest_field_standard(field: str, text: str, mode: str = "") -> str:
|
||
"""原话命中行的表标准值(陆运业务类型显示用)。"""
|
||
if _disabled():
|
||
return ""
|
||
hit = _lookup_with_aliases(field, str(text or ""), mode, substring=True)
|
||
if not hit:
|
||
return ""
|
||
if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE":
|
||
return ""
|
||
return _row_standard(hit)
|
||
|
||
|
||
def harvest_field_candidates(field: str, text: str, mode: str = "") -> list[str]:
|
||
"""同一句命中的所有不同 internal,按出现顺序;用于多口岸提示,不猜。"""
|
||
seen: list[str] = []
|
||
# 按原话出现顺序返回,卡片不能按同义词表顺序打乱车型。
|
||
for _, std in sorted(_field_hits(field, text, mode), key=lambda item: item[0]):
|
||
if std and std not in seen:
|
||
seen.append(std)
|
||
return seen
|
||
|
||
|
||
def harvest_port_group(text: str, mode: str = "LAND") -> str:
|
||
"""
|
||
斜杠组合口岸(如「友谊关/浦寨」)按一个组识别。
|
||
|
||
组行由 inq_synonym 维护:通关口岸 VALUE,synonym 含「/」,internal 为组值。
|
||
长词优先;整组命中后不再拆成两个单口岸。
|
||
"""
|
||
raw = _strip_prompt_examples(unicodedata.normalize("NFKC", str(text or "")))
|
||
if not raw:
|
||
return ""
|
||
best_syn = ""
|
||
best_std = ""
|
||
for bucket in _buckets("通关口岸", mode):
|
||
for synonym, row in bucket.items():
|
||
if str(row.get("synonymType") or row.get("synonym_type") or "VALUE").upper() != "VALUE":
|
||
continue
|
||
syn = str(row.get("synonym") or synonym).strip()
|
||
if not any(sep in syn for sep in ("/", "和", "、")):
|
||
continue
|
||
if syn and syn in raw and len(syn) > len(best_syn):
|
||
best_syn = syn
|
||
best_std = _row_internal(row) or syn
|
||
return best_std
|
||
|
||
|
||
def _fmt_number(value: float) -> str:
|
||
text = f"{value:.6f}".rstrip("0").rstrip(".")
|
||
return text or "0"
|
||
|
||
|
||
def normalize_unit_value(field: str, value: Any) -> str:
|
||
"""
|
||
把「1.5吨 / 500g / 2斤 / 2方」按 UNIT 行换算成 KG/CBM。
|
||
|
||
只认整串「数字+单位」,避免从地址、件数或长句里误抽;UNIT 行由 IT 维护。
|
||
"""
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return text
|
||
# 旧单/模型可能留下「大概4吨」:先去掉模糊词再认整串数字+单位。
|
||
try:
|
||
from agent.schema.field_validate import strip_quantity_filler
|
||
|
||
text = strip_quantity_filler(text)
|
||
except Exception:
|
||
pass
|
||
for bucket in _buckets(field, ""):
|
||
for synonym, row in bucket.items():
|
||
if str(row.get("synonymType") or row.get("synonym_type") or "").upper() != "UNIT":
|
||
continue
|
||
factor = row.get("unitFactor") if row.get("unitFactor") is not None else row.get("unit_factor")
|
||
if factor is None:
|
||
continue
|
||
# bucket 的 key 是 NFKC 归一后的词(m³ → M3);匹配要用行里的原始词。
|
||
unit_text = str(row.get("synonym") or synonym).strip()
|
||
match = re.fullmatch(
|
||
rf"\s*(\d+(?:\.\d+)?)\s*({re.escape(unit_text)})\s*",
|
||
text,
|
||
re.IGNORECASE,
|
||
)
|
||
if not match or _negative_hit(row, text):
|
||
continue
|
||
try:
|
||
number = float(match.group(1)) * float(factor)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if field == "体积":
|
||
return f"{_fmt_number(number)}CBM"
|
||
if field == "毛重":
|
||
return f"{_fmt_number(number)}KG"
|
||
return text
|
||
|
||
|
||
def harvest_unit_from_text(
|
||
field: str, text: str, facts: dict[str, str] | None = None, mode: str = ""
|
||
) -> dict[str, str]:
|
||
"""
|
||
从原话里扫「数字+单位」,单位列表和系数全部来自 inq_synonym 的 UNIT 行。
|
||
|
||
IT 新增单位(如市斤/ton)只加表;代码不再硬编码单位词。
|
||
只认数字紧邻单位;单位后紧跟负向词(吨后接车)跳过。
|
||
"""
|
||
merged = dict(facts or {})
|
||
raw = str(text or "")
|
||
if not raw:
|
||
return merged
|
||
candidates: list[tuple[int, str]] = []
|
||
for bucket in _buckets(field, mode):
|
||
for synonym, row in bucket.items():
|
||
if str(row.get("synonymType") or row.get("synonym_type") or "").upper() != "UNIT":
|
||
continue
|
||
factor = (
|
||
row.get("unitFactor")
|
||
if row.get("unitFactor") is not None
|
||
else row.get("unit_factor")
|
||
)
|
||
if factor is None:
|
||
continue
|
||
if not str(synonym).strip():
|
||
continue
|
||
# bucket 的 key 是归一后的词;匹配要用行里的原始词,保留 g/G 大小写。
|
||
syn_text = str(row.get("synonym") or synonym).strip()
|
||
# 大写 G 是常见网络制式(5G),不拿它当克;克只认小写 g 或“克”。
|
||
if field == "毛重" and syn_text == "G":
|
||
continue
|
||
flags = (
|
||
0
|
||
if len(syn_text) == 1 and syn_text.isascii() and syn_text.isalpha()
|
||
else re.IGNORECASE
|
||
)
|
||
tail = r"(?![A-Za-z0-9])"
|
||
if field == "毛重" and syn_text == "g":
|
||
# 3g网络/3g手机/3g设备:小写 g 后面接这些词也不是克。
|
||
tail = r"(?![A-Za-z0-9网手设信通套])"
|
||
pattern = re.compile(
|
||
rf"(?<![\d.])(\d+(?:\.\d+)?)\s*({re.escape(syn_text)}){tail}",
|
||
flags,
|
||
)
|
||
negatives = [
|
||
item.strip()
|
||
for item in str(row.get("negativeWords") or row.get("negative_words") or "")
|
||
.replace(",", ",")
|
||
.split(",")
|
||
if item.strip()
|
||
]
|
||
for match in pattern.finditer(raw):
|
||
after = raw[match.end() :]
|
||
if any(after.startswith(item) for item in negatives):
|
||
continue
|
||
try:
|
||
number = float(match.group(1)) * float(factor)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
unit = _row_internal(row) or ("KG" if field == "毛重" else "CBM")
|
||
candidates.append((match.end(), f"{_fmt_number(number)}{unit}"))
|
||
if candidates:
|
||
merged[field] = max(candidates, key=lambda item: item[0])[1]
|
||
return merged
|
||
|
||
|
||
_CARGO_READY_LABEL = re.compile(
|
||
r"(?:货好时间|备货时间|货好日期)\s*[::]\s*([^\n]*)", re.IGNORECASE
|
||
)
|
||
|
||
|
||
_CARGO_READY_QUOTE_LABELS = (
|
||
"报价日期", "询价日期", "走货日期", "发货日期", "提货日期", "装期",
|
||
)
|
||
|
||
|
||
def harvest_cargo_ready(text: str) -> dict[str, str]:
|
||
"""
|
||
货好时间最终口径:
|
||
|
||
- 具体日期(11月7日/11月7号/11-07/11/7/2026-11-07)→ yyyy-MM-dd;
|
||
- 状态词(货好/现货/随时/随时可提/客户随时可送货到仓/已备好/货已好)
|
||
→ 询价当日 yyyy-MM-dd;
|
||
- 本周/下周/月底 这类相对词暂不换算,保留原文;
|
||
- 带「报价日期/询价日期」等标签的日期不抢。
|
||
"""
|
||
raw = unicodedata.normalize("NFKC", str(text or ""))
|
||
if not raw:
|
||
return {}
|
||
try:
|
||
from agent.schema.field_validate import (
|
||
_harvest_quote_date,
|
||
normalize_cargo_ready_value,
|
||
)
|
||
except Exception:
|
||
return {}
|
||
labeled = _CARGO_READY_LABEL.search(raw)
|
||
if labeled:
|
||
value = (labeled.group(1) or "").strip()
|
||
if value:
|
||
date = _harvest_quote_date(value)
|
||
if date:
|
||
return {"货好时间": date}
|
||
state = harvest_field_value("货好时间", value, unique=False)
|
||
if state:
|
||
return {
|
||
"货好时间": normalize_cargo_ready_value(state["货好时间"])
|
||
}
|
||
normalized = normalize_cargo_ready_value(value)
|
||
if normalized != value:
|
||
return {"货好时间": normalized}
|
||
# 裸具体日期归货好时间;有报价日期标签时仍归报价日期。
|
||
if not any(label in raw for label in _CARGO_READY_QUOTE_LABELS):
|
||
date = _harvest_quote_date(raw)
|
||
if date:
|
||
return {"货好时间": date}
|
||
cleaned = _CARGO_READY_LABEL.sub(" ", raw)
|
||
# 状态词有重叠(随时 / 随时可提):取最长/最后,不用 unique 判歧义。
|
||
state = harvest_field_value("货好时间", cleaned, unique=False)
|
||
if state:
|
||
return {"货好时间": normalize_cargo_ready_value(state["货好时间"])}
|
||
return {}
|
||
|
||
|
||
def harvest_trade_term_word(text: str) -> dict[str, str]:
|
||
"""
|
||
从原话识别贸易条款:CY-CY / D2P / PORT TO DOOR / 港口到港口 / 门到门…
|
||
|
||
通用扫描器按 field_key=贸易条款 读表;多个不同条款时不猜。
|
||
"""
|
||
return harvest_field_value("贸易条款", text, "SEA", unique=True)
|
||
|
||
|
||
def harvest_packaging_word(text: str) -> dict[str, str]:
|
||
"""
|
||
裸包装词:不带数字也认(纸箱/木箱/CTN/PALLET/编织袋…)。
|
||
|
||
通用扫描器按 field_key=包装方式 读表;单字仍要求数字紧邻;多词取最后一个。
|
||
"""
|
||
return harvest_field_value(
|
||
"包装方式", text, unique=False, pack_fallback=True
|
||
)
|