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 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 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 structured, float(structured.get("confidence") or 0.95), warnings 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: confidence = float(parsed.get("confidence") or 0.85) return parsed, confidence, warnings warnings.append("workflow_returned_no_structured_output") except Exception as exc: warnings.append(f"workflow_error:{exc}") return _heuristic_extract(raw_text), 0.5, warnings def _heuristic_extract(raw_text: str) -> dict[str, Any]: text = str(raw_text or "").strip() customer_name = "" m = re.search(r"客户[::]\s*(\S+)", text) if m: customer_name = m.group(1) lines: list[dict[str, Any]] = [] 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"}) return { "customer_name": customer_name, "customer_code": "", "ship_to": "", "required_date": "", "lines": lines, "confidence": 0.5 if lines else 0.3, }