449 lines
17 KiB
Python
449 lines
17 KiB
Python
"""
|
|
backend/app/services/shipping_notice/field_adjudication.py
|
|
|
|
用途:把后端表格解析与 Dify LLM 输出转换为不可变字段 Observation,并生成规范订单行裁决结果。
|
|
依赖:ShippingOrderDocument、notice_lines、标准库 hashlib/json/re。
|
|
逻辑:后台 Run 结果持久化在 Candidate 校验前调用;原始 Observation 只追加不互相覆盖,裁决结果另行投影。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
from decimal import Decimal, InvalidOperation
|
|
from typing import Any
|
|
|
|
from app.models import ShippingOrderDocument
|
|
from app.services.shipping_notice.notice_lines import normalize_notice_line, parse_notice_table_text
|
|
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
|
|
|
ADJUDICATION_SCHEMA_VERSION = "shipping-field-adjudication-v1"
|
|
ADJUDICATED_LINE_FIELDS = (
|
|
"part_number",
|
|
"customer_part_number",
|
|
"aws_part_number",
|
|
"reservation_id",
|
|
"qty",
|
|
)
|
|
_TRUSTED_SCORE = 70
|
|
_CREDIBLE_SCORE = 50
|
|
_DECISION_MARGIN = 20
|
|
|
|
|
|
def _json_value(value: Any) -> Any:
|
|
"""将 Observation 值转换为稳定、可 JSON 序列化的标量。"""
|
|
if isinstance(value, Decimal):
|
|
return float(value)
|
|
return value
|
|
|
|
|
|
def _normalized_value(field: str, value: Any) -> str:
|
|
"""按字段语义生成比较键;数量使用 Decimal 避免 10 与 10.0 被误判冲突。"""
|
|
if value in (None, ""):
|
|
return ""
|
|
if field == "qty":
|
|
try:
|
|
return format(Decimal(str(value).replace(",", "").strip()).normalize(), "f")
|
|
except (InvalidOperation, ValueError):
|
|
return ""
|
|
return str(value).strip().upper()
|
|
|
|
|
|
def _observation_id(payload: dict[str, Any]) -> str:
|
|
"""基于不可变 Observation 内容生成稳定标识。"""
|
|
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)
|
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
|
|
|
|
|
|
def _quote_supports_value(field: str, value: Any, quote: str) -> bool:
|
|
"""确认 quote 不仅存在于原文,还实际包含被声明字段值。"""
|
|
normalized = _normalized_value(field, value)
|
|
if not normalized:
|
|
return False
|
|
if field != "qty":
|
|
return normalized in str(quote or "").upper()
|
|
numbers = re.findall(r"[-+]?\d[\d,]*(?:\.\d+)?", str(quote or ""))
|
|
return any(_normalized_value("qty", item) == normalized for item in numbers)
|
|
|
|
|
|
def _evidence_for_field(
|
|
*,
|
|
evidence_items: list[dict[str, Any]],
|
|
documents_by_id: dict[int, ShippingOrderDocument],
|
|
line_index: int,
|
|
field: str,
|
|
value: Any,
|
|
) -> tuple[list[dict[str, Any]], bool]:
|
|
"""验证 Dify 字段证据的路径、Document 归属、逐字 quote 和值包含关系。"""
|
|
expected = f"lines[{line_index}].{field}".lower()
|
|
verified: list[dict[str, Any]] = []
|
|
for item in evidence_items:
|
|
if str(item.get("field") or "").strip().lower() != expected:
|
|
continue
|
|
document_id = item.get("document_id")
|
|
document = documents_by_id.get(int(document_id)) if str(document_id or "").isdigit() else None
|
|
quote = str(item.get("quote") or "").strip()
|
|
text = str(document.extracted_text or "") if document is not None else ""
|
|
if not quote or quote not in text or not _quote_supports_value(field, value, quote):
|
|
continue
|
|
verified.append({
|
|
"field": expected,
|
|
"quote": quote,
|
|
"document_id": int(document.id),
|
|
"verified": True,
|
|
})
|
|
return verified, bool(verified)
|
|
|
|
|
|
def _make_observation(
|
|
*,
|
|
source: str,
|
|
line_index: int,
|
|
field: str,
|
|
value: Any,
|
|
raw_value: Any = None,
|
|
document_id: int | None = None,
|
|
evidence: list[dict[str, Any]] | None = None,
|
|
evidence_verified: bool,
|
|
source_confidence: float,
|
|
score: int,
|
|
reasons: list[str],
|
|
) -> dict[str, Any]:
|
|
"""构造只包含事实与评分依据的不可变 Observation 字典。"""
|
|
payload = {
|
|
"source": source,
|
|
"line_index": line_index,
|
|
"field": field,
|
|
"value": _json_value(value),
|
|
"raw_value": _json_value(raw_value if raw_value is not None else value),
|
|
"normalized_value": _normalized_value(field, value),
|
|
"document_id": document_id,
|
|
"evidence": list(evidence or []),
|
|
"evidence_verified": evidence_verified,
|
|
"source_confidence": round(max(0.0, min(float(source_confidence), 1.0)), 4),
|
|
"score": max(0, min(int(score), 100)),
|
|
"score_reasons": list(reasons),
|
|
}
|
|
return {"observation_id": _observation_id(payload), **payload}
|
|
|
|
|
|
def _backend_rows(
|
|
documents: list[ShippingOrderDocument], *, schema_definition: dict[str, Any],
|
|
) -> list[dict[str, Any]]:
|
|
"""从每个锁定 Document 的保留列边界文本生成后端表格 Observation 原料。"""
|
|
contract = compile_table_header_contract(schema_definition)
|
|
rows: list[dict[str, Any]] = []
|
|
for document in documents:
|
|
for row in parse_notice_table_text(str(document.extracted_text or ""), contract=contract):
|
|
if isinstance(row, dict):
|
|
rows.append({**row, "_document_id": int(document.id)})
|
|
return rows
|
|
|
|
|
|
def _line_matches_backend(raw_line: dict[str, Any], backend_row: dict[str, Any]) -> bool:
|
|
"""使用稳定标识优先、唯一数量兜底前的单行关联判断。"""
|
|
for field in ("reservation_id", "part_number", "customer_part_number", "aws_part_number"):
|
|
left = _normalized_value(field, raw_line.get(field))
|
|
right = _normalized_value(field, backend_row.get(field))
|
|
if left and right and left == right:
|
|
return True
|
|
return False
|
|
|
|
|
|
def _associated_backend_rows(
|
|
raw_line: dict[str, Any],
|
|
backend_rows: list[dict[str, Any]],
|
|
) -> list[dict[str, Any]]:
|
|
"""关联后端行;无稳定字段命中时,仅允许 Qty 唯一命中兜底。"""
|
|
matched = [row for row in backend_rows if _line_matches_backend(raw_line, row)]
|
|
if matched:
|
|
return matched
|
|
qty = _normalized_value("qty", raw_line.get("qty"))
|
|
qty_matches = [row for row in backend_rows if qty and _normalized_value("qty", row.get("qty")) == qty]
|
|
return qty_matches if len(qty_matches) == 1 else []
|
|
|
|
|
|
def _dify_observations(
|
|
*,
|
|
raw_line: dict[str, Any],
|
|
normalized_line: dict[str, Any],
|
|
line_index: int,
|
|
evidence_items: list[dict[str, Any]],
|
|
documents_by_id: dict[int, ShippingOrderDocument],
|
|
field_confidence: dict[str, Any],
|
|
) -> list[dict[str, Any]]:
|
|
"""将 Dify 行转换为 Observation;自报 confidence 只贡献最多 10 分。"""
|
|
observations: list[dict[str, Any]] = []
|
|
for field in ADJUDICATED_LINE_FIELDS:
|
|
value = normalized_line.get(field)
|
|
if value in (None, ""):
|
|
continue
|
|
evidence, verified = _evidence_for_field(
|
|
evidence_items=evidence_items,
|
|
documents_by_id=documents_by_id,
|
|
line_index=line_index,
|
|
field=field,
|
|
value=value,
|
|
)
|
|
confidence = field_confidence.get(field)
|
|
if confidence is None and field in {"customer_part_number", "aws_part_number", "reservation_id"}:
|
|
confidence = field_confidence.get("part_number")
|
|
try:
|
|
confidence_value = max(0.0, min(float(confidence), 1.0))
|
|
except (TypeError, ValueError):
|
|
confidence_value = 0.0
|
|
score = 35 + (35 if verified else 0) + round(confidence_value * 10)
|
|
raw_value = raw_line.get(field)
|
|
if raw_value in (None, "") and field == "customer_part_number":
|
|
raw_value = raw_line.get("part_number")
|
|
observations.append(_make_observation(
|
|
source="dify_llm",
|
|
line_index=line_index,
|
|
field=field,
|
|
value=value,
|
|
raw_value=raw_value,
|
|
evidence=evidence,
|
|
evidence_verified=verified,
|
|
source_confidence=confidence_value,
|
|
score=score,
|
|
reasons=["dify_candidate", "verified_quote" if verified else "unverified_quote", "self_confidence_weak_weight"],
|
|
))
|
|
return observations
|
|
|
|
|
|
def _backend_observations(
|
|
*,
|
|
rows: list[dict[str, Any]],
|
|
line_index: int,
|
|
) -> list[dict[str, Any]]:
|
|
"""将列边界明确的后端表格值转换为高可信 Observation。"""
|
|
observations: list[dict[str, Any]] = []
|
|
for row in rows:
|
|
document_id = int(row.get("_document_id"))
|
|
for field in ADJUDICATED_LINE_FIELDS:
|
|
value = row.get(field)
|
|
if value in (None, ""):
|
|
continue
|
|
evidence = [{
|
|
"document_id": document_id,
|
|
"parser": "backend_table",
|
|
"column_boundary_verified": True,
|
|
}]
|
|
observations.append(_make_observation(
|
|
source="backend_table",
|
|
line_index=line_index,
|
|
field=field,
|
|
value=value,
|
|
document_id=document_id,
|
|
evidence=evidence,
|
|
evidence_verified=True,
|
|
source_confidence=0.9,
|
|
score=85,
|
|
reasons=["backend_parser", "column_boundary_verified", "format_valid"],
|
|
))
|
|
return observations
|
|
|
|
|
|
def _decide_field(
|
|
*,
|
|
field: str,
|
|
line_index: int,
|
|
observations: list[dict[str, Any]],
|
|
) -> tuple[dict[str, Any], dict[str, Any] | None]:
|
|
"""按可信阈值和分差选择字段值;双方高可信不同或分差不足时返回阻断冲突。"""
|
|
grouped: dict[str, list[dict[str, Any]]] = {}
|
|
for observation in observations:
|
|
normalized = str(observation.get("normalized_value") or "")
|
|
if normalized:
|
|
grouped.setdefault(normalized, []).append(observation)
|
|
ranked = sorted(
|
|
grouped.items(),
|
|
key=lambda item: (-max(int(obs["score"]) for obs in item[1]), item[0]),
|
|
)
|
|
if not ranked:
|
|
return {
|
|
"line_index": line_index,
|
|
"field": field,
|
|
"status": "unresolved",
|
|
"value": None,
|
|
"score": 0,
|
|
"observation_ids": [],
|
|
}, None
|
|
|
|
top_key, top_observations = ranked[0]
|
|
top_score = max(int(item["score"]) for item in top_observations)
|
|
top_value = max(top_observations, key=lambda item: int(item["score"]))["value"]
|
|
source_set = {str(item["source"]) for item in top_observations}
|
|
if len(ranked) == 1:
|
|
status = "consensus" if len(source_set) > 1 else "selected"
|
|
return {
|
|
"line_index": line_index,
|
|
"field": field,
|
|
"status": status,
|
|
"value": top_value,
|
|
"score": top_score,
|
|
"observation_ids": [item["observation_id"] for item in top_observations],
|
|
}, None
|
|
|
|
second_key, second_observations = ranked[1]
|
|
second_score = max(int(item["score"]) for item in second_observations)
|
|
trusted_values = [key for key, items in ranked if max(int(item["score"]) for item in items) >= _TRUSTED_SCORE]
|
|
insufficient_margin = top_score - second_score < _DECISION_MARGIN
|
|
if len(trusted_values) > 1 or (second_score >= _CREDIBLE_SCORE and insufficient_margin):
|
|
conflict = {
|
|
"field": field,
|
|
"line_index": line_index,
|
|
"severity": "blocking",
|
|
"reason": "cross_source_conflict" if len(trusted_values) > 1 else "insufficient_score_margin",
|
|
"values": [top_key, second_key],
|
|
"observation_ids": [
|
|
item["observation_id"]
|
|
for _, items in ranked
|
|
for item in items
|
|
],
|
|
}
|
|
return {
|
|
"line_index": line_index,
|
|
"field": field,
|
|
"status": "conflicted",
|
|
"value": top_value,
|
|
"score": top_score,
|
|
"observation_ids": conflict["observation_ids"],
|
|
}, conflict
|
|
|
|
return {
|
|
"line_index": line_index,
|
|
"field": field,
|
|
"status": "selected",
|
|
"value": top_value,
|
|
"score": top_score,
|
|
"observation_ids": [item["observation_id"] for item in top_observations],
|
|
}, None
|
|
|
|
|
|
def adjudicate_order_fields(
|
|
summary: dict[str, Any],
|
|
*,
|
|
raw_order: dict[str, Any],
|
|
documents: list[ShippingOrderDocument],
|
|
schema_definition: dict[str, Any],
|
|
field_confidence: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""
|
|
对单个 Dify 订单和当前 Intake 的后端解析结果执行字段级交叉裁决。
|
|
|
|
核心逻辑:逐行生成两侧 Observation,按稳定字段/唯一 Qty 关联后端行,再按字段评分;
|
|
仅一侧可信时采用、双方一致时 consensus、双方可信不同或分差不足时生成 blocking conflict。
|
|
Args:
|
|
summary: 已去除抽取元数据的 Dify 业务摘要。
|
|
raw_order: Dify 原始订单对象,保留 evidence 与原始复合值。
|
|
documents: 当前 Intake 的锁定 Document 集合。
|
|
schema_definition: 与本次输入一同冻结的完整订单 Schema 定义。
|
|
field_confidence: Dify 自报字段置信度,仅作弱权重。
|
|
Returns:
|
|
包含 canonical summary、不可变 observations、decisions 和 conflicts 的裁决结果。
|
|
"""
|
|
raw_lines = summary.get("lines") if isinstance(summary.get("lines"), list) else []
|
|
backend_rows = _backend_rows(documents, schema_definition=schema_definition)
|
|
documents_by_id = {int(item.id): item for item in documents}
|
|
evidence_items = [item for item in (raw_order.get("evidence") or []) if isinstance(item, dict)]
|
|
confidence = dict(field_confidence or {})
|
|
canonical_lines: list[dict[str, Any]] = []
|
|
observations: list[dict[str, Any]] = []
|
|
decisions: list[dict[str, Any]] = []
|
|
conflicts: list[dict[str, Any]] = []
|
|
|
|
line_count = len(raw_lines) if raw_lines else len(backend_rows)
|
|
for line_index in range(line_count):
|
|
raw_line = dict(raw_lines[line_index]) if line_index < len(raw_lines) and isinstance(raw_lines[line_index], dict) else {}
|
|
normalized_line = normalize_notice_line(raw_line) or {
|
|
key: value for key, value in raw_line.items() if value not in (None, "")
|
|
}
|
|
associated = _associated_backend_rows(raw_line, backend_rows)
|
|
if not raw_line and line_index < len(backend_rows):
|
|
associated = [backend_rows[line_index]]
|
|
line_observations = _dify_observations(
|
|
raw_line=raw_line,
|
|
normalized_line=normalized_line,
|
|
line_index=line_index,
|
|
evidence_items=evidence_items,
|
|
documents_by_id=documents_by_id,
|
|
field_confidence=confidence,
|
|
)
|
|
line_observations.extend(_backend_observations(rows=associated, line_index=line_index))
|
|
observations.extend(line_observations)
|
|
|
|
canonical = dict(normalized_line)
|
|
for field in ADJUDICATED_LINE_FIELDS:
|
|
field_observations = [item for item in line_observations if item["field"] == field]
|
|
decision, conflict = _decide_field(
|
|
field=field,
|
|
line_index=line_index,
|
|
observations=field_observations,
|
|
)
|
|
decisions.append(decision)
|
|
if decision.get("value") not in (None, ""):
|
|
canonical[field] = decision["value"]
|
|
if conflict:
|
|
conflicts.append(conflict)
|
|
normalized_canonical = normalize_notice_line(canonical)
|
|
canonical_lines.append(normalized_canonical or canonical)
|
|
|
|
canonical_summary = dict(summary)
|
|
canonical_summary["lines"] = canonical_lines
|
|
return {
|
|
"schema_version": ADJUDICATION_SCHEMA_VERSION,
|
|
"summary": canonical_summary,
|
|
"observations": observations,
|
|
"decisions": decisions,
|
|
"conflicts": conflicts,
|
|
}
|
|
|
|
|
|
def merge_observation_history(
|
|
previous: list[dict[str, Any]] | None,
|
|
current: list[dict[str, Any]] | None,
|
|
) -> list[dict[str, Any]]:
|
|
"""
|
|
按 Observation ID 追加不可变审计历史。
|
|
|
|
核心逻辑:已有 Observation 原样保留,新 Observation 仅在 ID 未出现时追加;禁止以当前值覆盖历史内容。
|
|
Args:
|
|
previous: Candidate 已持久化的历史 Observation。
|
|
current: 本次锁定快照生成的 Observation。
|
|
Returns:
|
|
保持首次出现顺序的累积 Observation 列表。
|
|
"""
|
|
merged: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
for item in [*(previous or []), *(current or [])]:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
observation_id = str(item.get("observation_id") or "").strip()
|
|
if not observation_id or observation_id in seen:
|
|
continue
|
|
seen.add(observation_id)
|
|
merged.append(dict(item))
|
|
return merged
|
|
|
|
|
|
def trusted_required_fields(adjudication: dict[str, Any]) -> bool:
|
|
"""确认每条规范行的 part_number 与 qty 都有可信且未冲突的裁决决定。"""
|
|
decisions = [item for item in (adjudication.get("decisions") or []) if isinstance(item, dict)]
|
|
lines = (adjudication.get("summary") or {}).get("lines") or []
|
|
for line_index, _line in enumerate(lines):
|
|
for field in ("part_number", "qty"):
|
|
decision = next(
|
|
(
|
|
item for item in decisions
|
|
if item.get("line_index") == line_index and item.get("field") == field
|
|
),
|
|
None,
|
|
)
|
|
if not decision or decision.get("status") in {"unresolved", "conflicted"}:
|
|
return False
|
|
if int(decision.get("score") or 0) < _TRUSTED_SCORE:
|
|
return False
|
|
return bool(lines)
|