from __future__ import annotations import json import os import re from typing import Any from app.services.dify import DifyService from app.services.shipping_notice.po_number import enrich_notice_with_po_number from app.services.shipping_notice.reservation_id import find_reservation_id_in_document from app.services.shipping_notice.agent_resolver import resolve_extract_agent from app.services.shipping_notice.notice_lines import ( enrich_notice_with_document_currency, enrich_notice_with_document_required_date, enrich_notice_with_document_reservation, 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, raw_text: str = "", ) -> tuple[dict[str, Any], float, list[str]]: lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else []) parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text) parsed = enrich_notice_with_document_required_date(parsed) parsed = enrich_notice_with_document_currency(parsed) parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text) lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else [] 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 _resolve_workflow_file_input_key(agent) -> str | None: forced = str(os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_FILE_INPUT_KEY") or "").strip() if forced: return forced params = DifyService.get_app_parameters(agent) or {} def _walk(v: Any) -> str | None: if isinstance(v, dict): var = str(v.get("variable") or v.get("name") or "").strip() t = str(v.get("type") or v.get("value_type") or v.get("valueType") or "").strip().lower() has_file_cfg = isinstance(v.get("file"), dict) or isinstance(v.get("file_upload"), dict) or isinstance(v.get("fileUpload"), dict) if var and (has_file_cfg or t in {"file", "files", "file_array", "filearray", "file-list", "file_list"}): return var for vv in v.values(): hit = _walk(vv) if hit: return hit elif isinstance(v, list): for item in v: hit = _walk(item) if hit: return hit return None return _walk(params) def extract_notice_fields( *, raw_text: str, source_type: str = "manual", structured: dict[str, Any] | None = None, notice_files: list[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), raw_text=str(structured.get("raw_text") or ""), ) agent = resolve_extract_agent() if agent and (raw_text.strip() or notice_files): try: inputs: dict[str, Any] = {"raw_text": raw_text, "source_type": source_type} if notice_files: key = _resolve_workflow_file_input_key(agent) if key: inputs[key] = notice_files else: warnings.append("workflow_file_input_key_missing") result = DifyService.run_workflow_streaming( agent=agent, inputs=inputs, 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), raw_text=raw_text, ) 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, raw_text=raw_text) 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: doc_rid = find_reservation_id_in_document(text) if doc_rid: for line in lines: if not line.get("reservation_id"): line["reservation_id"] = doc_rid 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, )