Files
syops/backend/app/services/shipping_notice/extract.py
T
hugo 2d7bdecc43 feat(shipping-notice): 新增货代发货通知全流程业务功能
- 新增后端完整业务支持:数据库模型、API接口、核心服务与RPA对接逻辑
- 新增前端工作台页面、路由适配与多语言国际化
- 新增Dify自定义工具OpenAPI规范、Agent配置脚本与部署文档
- 新增发货Excel模板生成脚本与默认模板
- 修复测试配置文件中的环境变量命名错误
- 更新本地开发环境变量配置
2026-06-01 21:22:22 +08:00

82 lines
2.7 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.
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,
}