from __future__ import annotations import json import re from typing import Any from app.services.dify import DifyService from app.services.shipping_notice.agent_resolver import resolve_extract_agent from app.services.shipping_notice.notice_lines import ( normalize_notice_lines, parse_notice_table_text, validate_notice_lines, ) def _parse_workflow_outputs(result: dict[str, Any]) -> dict[str, Any] | None: outputs = result.get("outputs") if isinstance(result, dict) else None if not isinstance(outputs, dict): data = result.get("data") if isinstance(result, dict) else None outputs = data.get("outputs") if isinstance(data, dict) else None if not isinstance(outputs, dict): return None for key in ("result", "text", "json", "structured", "output"): val = outputs.get(key) if isinstance(val, dict): return val if isinstance(val, str) and val.strip(): try: parsed = json.loads(val) if isinstance(parsed, dict): return parsed except json.JSONDecodeError: continue return outputs if outputs else None def _finalize_notice_parse(parsed: dict[str, Any], *, base_confidence: float) -> tuple[dict[str, Any], float, list[str]]: lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else []) parsed = {**parsed, "lines": lines} warnings = validate_notice_lines(lines) from app.services.shipping_notice.notice_lines import notice_parse_completeness completeness = notice_parse_completeness(lines) confidence = min(base_confidence, 0.95) * (0.5 + 0.5 * completeness) if lines else base_confidence * 0.5 return parsed, round(confidence, 4), warnings def extract_notice_fields( *, raw_text: str, source_type: str = "manual", structured: dict[str, Any] | None = None, ) -> tuple[dict[str, Any], float, list[str]]: warnings: list[str] = [] if structured and isinstance(structured, dict): return _finalize_notice_parse(structured, base_confidence=float(structured.get("confidence") or 0.95)) agent = resolve_extract_agent() if agent and raw_text.strip(): try: result = DifyService.run_workflow_streaming( agent=agent, inputs={"raw_text": raw_text, "source_type": source_type}, user="shipping_notice_tool", ) parsed = _parse_workflow_outputs(result) if parsed: finalized, confidence, line_warnings = _finalize_notice_parse( parsed, base_confidence=float(parsed.get("confidence") or 0.85), ) warnings.extend(line_warnings) return finalized, confidence, warnings warnings.append("workflow_returned_no_structured_output") except Exception as exc: warnings.append(f"workflow_error:{exc}") heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text) warnings.extend(heuristic_warnings) return _finalize_notice_parse(heuristic, base_confidence=confidence) def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]: text = str(raw_text or "").strip() warnings: list[str] = [] customer_name = "" m = re.search(r"客户[::]\s*(\S+)", text) if m: customer_name = m.group(1) lines = parse_notice_table_text(text) if lines: return ( { "customer_name": customer_name, "customer_code": "", "ship_to": "", "required_date": "", "lines": lines, "confidence": 0.72, }, 0.72, warnings, ) lines = [] for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text): lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"}) # 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2) if not lines: for m in re.finditer( r"(?P\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)", text, ): lines.append( { "reservation_id": m.group("resv"), "sku": m.group(2), "qty": float(m.group(3)), "uom": "EA", } ) if not lines: warnings.append("heuristic_no_lines_detected") confidence = 0.5 if lines else 0.3 return ( { "customer_name": customer_name, "customer_code": "", "ship_to": "", "required_date": "", "lines": lines, "confidence": confidence, }, confidence, warnings, )