Files
inquiry_robot/inquiry-agent/agent/schema/quote_recognition.py
T
linmianxun 04e00f0cfc checkpoint: 提交当前工作区代码(同义词配置初版 + 既有流程改动)
- 新增 inq_synonym 表、62组同义词种子与智能体只读接口
- Python 同义词加载/归一化与 1板/2箱 机读
- 同步当前分支既有协作、报价识别、陆运等改动
2026-11-24 16:26:49 +08:00

344 lines
13 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.
"""
报价识别分级:完整 / 部分 / 全无。
产品 2026-11-23 口径:
* 标准话术完整:解析字段入工单,原话进「原始报价参考」;
* 只识别到一部分:回「我识别内容为…,请确认是否正确」;
* 全无:回「我无法识别您的内容,请按格式重新报价」,原话仍留档。
本模块只判断识别程度、生成回执和格式样例;不写主账、不发企微。
"""
from __future__ import annotations
import re
from typing import Any, Optional
# 空运航线对:NKG-KUL / NKG/KUL / NKG—KUL。
_AIR_ROUTE = re.compile(r"\b([A-Za-z]{3})\s*[-–—/]\s*([A-Za-z]{3})\b")
# 空运标签写法:起运地NKG、目的港KUL。
_AIR_ROUTE_LABEL = re.compile(
r"(?:起运地|起运港|目的地|目的港)\s*([A-Za-z]{3})(?![A-Za-z])", re.I
)
# 陆运线路:东莞-春疆、深圳--香港、东莞到春疆。
_LAND_ROUTE = re.compile(
r"(?P<o>[一-鿿]{2,12})\s*(?:--|—|-|-|到|至)\s*(?P<d>[一-鿿]{2,12})"
)
# 陆运车型:10T、45HQ、7.6米、40GP、45尺柜。
_LAND_VEHICLE = re.compile(r"\d+(?:\.\d+)?\s*(?:尺柜|T|吨|HQ|GP|尺|米)", re.I)
def business_line_of(business_line: str = "", transport_mode: str = "") -> str:
"""统一成 AIR / LAND / SEA;认不出返回空串。"""
line = (business_line or "").strip().upper()
if line in {"AIR", "LAND", "SEA"}:
return line
mode = (transport_mode or "").strip()
if mode in {"空运", "AIR", "air"}:
return "AIR"
if mode in {"陆运", "LAND", "land"}:
return "LAND"
if mode in {"海运", "SEA", "sea"}:
return "SEA"
return ""
def quote_format_hint(business_line: str = "", transport_mode: str = "") -> str:
"""
该业务线要求产品按什么格式重报。
空运/陆运用产品 2026-11-23 定的样例;海运暂无标准话术,
用「费用名+金额+币种」兜底,后续定了再换。
"""
line = business_line_of(business_line, transport_mode)
if line == "AIR":
return "工单号,USD11/kg、TH、NKG-KUL、11月2日"
if line == "LAND":
return "东莞-春疆,危险品,45HQ,CNY18500;都是含0点税"
return "费用名+金额+币种,例如“码头操作费100CNY,报关费300CNY”"
def _has_price(quote: dict[str, Any]) -> bool:
"""报价里有没有可入账的金额(费用行/车型价/分档价/合计)。"""
if not quote:
return False
if quote.get("vehicleRates") or quote.get("vehicle_rates"):
return True
if quote.get("weightPrices") or quote.get("weight_prices"):
return True
for row in quote.get("fee_rows") or quote.get("fee_lines") or []:
if isinstance(row, dict) and str(row.get("amount") or "").strip():
return True
return str(quote.get("total") or "").strip() not in {"", "-", "—", "-"}
def _air_price_line(quote: dict[str, Any]) -> str:
"""空运回执的价格行:空运费:USD11/kg。"""
ccy = str(quote.get("currency") or "").strip()
for row in quote.get("fee_rows") or []:
if not isinstance(row, dict):
continue
name = str(row.get("name") or "空运费").strip() or "空运费"
amount = str(row.get("unit_price") or row.get("amount") or "").strip()
unit = str(row.get("unit") or "").strip()
if not amount:
continue
if unit.upper() in {"KG", "KGS"}:
return f"{name}:{ccy}{amount}/{unit.lower()}"
return f"{name}:{ccy}{amount}"
total = str(quote.get("total") or "").strip()
return f"空运费:{ccy}{total}" if total else ""
def _land_price_lines(quote: dict[str, Any]) -> list[str]:
"""陆运回执的价格行:车型价逐档,或普通费用行逐项。"""
out: list[str] = []
ccy = str(quote.get("currency") or "").strip()
rates = quote.get("vehicleRates") or quote.get("vehicle_rates")
if isinstance(rates, dict) and rates:
for model, amount in rates.items():
model_text = str(model or "").strip()
amount_text = str(amount or "").strip()
if not model_text or not amount_text:
continue
out.append(f"车型/数量:{model_text}")
out.append(f"运输费:{ccy}{amount_text}")
return out
for row in quote.get("fee_rows") or []:
if not isinstance(row, dict):
continue
name = str(row.get("name") or "").strip()
amount = str(row.get("amount") or "").strip()
row_ccy = str(row.get("currency") or ccy).strip()
unit = str(row.get("unit") or "").strip()
if name and amount:
out.append(f"{name}:{row_ccy}{amount}{('/' + unit) if unit else ''}")
return out
def _land_route_in_text(text: str) -> tuple[str, str]:
"""从原话里认「起运地-目的地」。认不出返回空串,不去猜。"""
for hit in _LAND_ROUTE.finditer(text or ""):
origin = (hit.group("o") or "").strip()
dest = (hit.group("d") or "").strip()
if not origin or not dest:
continue
# 排除「2026-11-23」这类被中文包住的时间片段(虽然正则已要求中文)。
if any(x in origin for x in ("月", "日", "点", "税", "价")):
continue
if any(x in dest for x in ("月", "日", "点", "税", "价")):
continue
return origin, dest
return "", ""
def _fact(facts: dict[str, Any], *keys: str) -> str:
for key in keys:
val = str(facts.get(key) or "").strip()
if val:
return val
return ""
# 其它字段的展示名:从原话里能认到的都列进回执(产品 2026-11-24:尽可能识别)。
_EXTRA_LABELS = {
"件数": "件数",
"毛重": "毛重",
"重量": "毛重",
"体积": "体积",
"包装方式": "包装类型",
"包装类型": "包装类型",
"品名": "品名",
"是否为危险品": "是否为危险品",
"是否含电": "是否含电",
"是否含磁": "是否含磁",
"是否含油": "是否含油",
"货好时间": "货好时间",
"HS编码": "HS编码",
"商品海关编码": "HS编码",
"贸易条款": "贸易条款",
"货值": "货值",
"车型/数量": "车型/数量",
"计费重": "计费重",
}
def inspect_quote_recognition(
text: str,
quote: Optional[dict[str, Any]] = None,
*,
business_line: str = "",
transport_mode: str = "",
facts: Optional[dict[str, Any]] = None,
extra_facts: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""
判断这句话的报价识别程度。
参数:
text:产品原话(已剥 @ 机器人的)。
quote:extract_product_quote 的结果;可以传空,用来识别「只有字段没价格」。
facts:工单询价字段,用于把话术没写、但工单已有的线路/车型/日期标成「按工单」。
返回:
{"status": "full"|"partial"|"none",
"recognized": [回执行], "missing": [缺项名], "hint": 格式样例}
「部分」以**话术本身**为准:线路/车型/日期没写在原话里,即使工单已有,
也算部分识别,回执里标「按工单」,请产品确认。
"""
raw = (text or "").strip()
src = dict(quote or {})
facts = dict(facts or {})
line = business_line_of(business_line, transport_mode)
recognized: list[str] = []
missing: list[str] = []
in_text = 0
if line == "AIR":
from agent.policy.air_group_ops import _harvest_air_manual_airline
from agent.schema.field_validate import _harvest_quote_date
price = _has_price(src)
airline = (
str(src.get("airlineCode") or src.get("airline") or "").strip()
or _harvest_air_manual_airline(raw)
)
origin = dest = ""
labels = _AIR_ROUTE_LABEL.findall(raw)
pair = _AIR_ROUTE.search(raw)
if pair:
origin, dest = pair.group(1).upper(), pair.group(2).upper()
if len(labels) >= 2:
origin, dest = labels[0].upper(), labels[1].upper()
date = _harvest_quote_date(raw)
if price:
in_text += 1
price_line = _air_price_line(src)
if price_line:
recognized.append(price_line)
else:
missing.append("单价")
# 比例 / 重量等级 / 增值服务也是产品原话里识别到的内容,回执要列全。
from agent.schema.added_services import harvest_added_services
from agent.schema.field_validate import _harvest_air_ratio
ratio = _harvest_air_ratio(raw)
weight_break = str(src.get("weight_break") or "").strip()
if not weight_break:
try:
from agent.llm.extract_text import _harvest_air_weight_break
weight_break = _harvest_air_weight_break(raw)
except Exception:
weight_break = ""
added = harvest_added_services(raw)
if ratio:
in_text += 1
recognized.append(f"比例:{ratio}")
if weight_break:
in_text += 1
recognized.append(f"重量等级:{weight_break}")
if added:
in_text += 1
recognized.append("增值服务:" + "/".join(added))
if airline:
in_text += 1
recognized.append(f"航司:{airline}")
else:
missing.append("航司")
if origin and dest:
in_text += 1
recognized.append(f"线路:{origin}-{dest}")
else:
origin_fact = _fact(facts, "起运港", "起运地", "始发站")
dest_fact = _fact(facts, "目的港", "目的地", "收货地址", "送货地址")
if origin_fact and dest_fact:
recognized.append(f"线路:{origin_fact}-{dest_fact}")
else:
missing.append("线路")
if date:
in_text += 1
recognized.append(f"航线日期:{date}")
else:
date_fact = _fact(facts, "报价日期")
if date_fact:
recognized.append(f"航线日期:{date_fact}")
else:
missing.append("报价日期")
full = price and bool(airline) and bool(origin and dest) and bool(date)
status = "full" if full else ("partial" if in_text > 0 else "none")
elif line == "LAND":
price = _has_price(src)
origin, dest = _land_route_in_text(raw)
vehicle_hit = _LAND_VEHICLE.search(raw)
vehicle_in_text = bool(vehicle_hit) or "车型" in raw
if origin and dest:
in_text += 1
recognized.append(f"起运地:{origin}")
recognized.append(f"目的地:{dest}")
else:
origin_fact = _fact(facts, "起运港", "始发站", "起运地", "提货地址")
dest_fact = _fact(facts, "目的港", "目的地", "收货地址", "送货地址")
if origin_fact and dest_fact:
recognized.append(f"起运地/目的地:{origin_fact}-{dest_fact}")
else:
missing.append("线路")
if vehicle_in_text:
in_text += 1
label = (vehicle_hit.group(0) if vehicle_hit else "车型").strip()
recognized.insert(0, f"车型/数量:{label}")
else:
vehicle_fact = _fact(facts, "车型/数量", "车型", "车型数量")
if vehicle_fact:
recognized.append(f"车型/数量:{vehicle_fact}")
else:
missing.append("车型/数量")
if price:
in_text += 1
recognized.extend(_land_price_lines(src))
else:
missing.append("价格")
tax = str(src.get("tax_rate") or src.get("taxRate") or "").strip()
if tax:
recognized.append(f"税率:{tax}")
remark = str(src.get("remark") or "").strip()
if remark:
recognized.append(f"备注:{remark}")
full = price and bool(origin and dest) and bool(vehicle_in_text)
status = "full" if full else ("partial" if in_text > 0 else "none")
else:
# 海运暂无标准话术:有价就算完整,没价且没字段就是全无。
price = _has_price(src)
if price:
recognized.extend(_land_price_lines(src))
else:
missing.append("价格")
status = "full" if price else "none"
# 其它从原话里识别到的字段(件数/毛重/体积/包装/品名/危险品/含电含磁/计费重…)。
for key, val in (extra_facts or {}).items():
text_val = str(val or "").strip().strip(",,;;。")
if not text_val or text_val in {"-", "—", "-"}:
continue
label = _EXTRA_LABELS.get(str(key))
if not label:
continue
recognized.append(f"{label}:{text_val}")
in_text += 1
# 车型行可能同时来自「车型在话术里」和车型价明细,去重后回执才不重复。
deduped = list(dict.fromkeys(x for x in recognized if x))
return {
"status": status,
"recognized": deduped,
"missing": list(dict.fromkeys(x for x in missing if x)),
"hint": quote_format_hint(line),
}