- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
516 lines
18 KiB
Python
516 lines
18 KiB
Python
"""
|
||
services/shipping_notice/notice_upload.py
|
||
|
||
用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。
|
||
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、eml_parse、export._storage_root、Flask current_app 配置。
|
||
逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads
|
||
收敛抽取与失败分流;.eml 走结构化解析(正文/内嵌资源/真实附件);下游只消费 NoticeIntakeResult。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import re
|
||
import shutil
|
||
from dataclasses import dataclass, field
|
||
from pathlib import Path
|
||
from typing import Any, Literal, Sequence
|
||
|
||
from flask import current_app
|
||
|
||
from edkb_system.contracts import Block, Context
|
||
from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr
|
||
from app.services.shipping_notice.export import _storage_root
|
||
from app.services.shipping_notice.eml_parse import parse_eml_bytes
|
||
|
||
|
||
def task_notice_upload_path(task_no: str, filename: str) -> Path:
|
||
"""生成任务级发货通知附件落盘路径(notice_uploads/{task_no}/{filename})。"""
|
||
safe_task = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||
name = str(filename or "").strip() or "notice"
|
||
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
|
||
return _storage_root() / "notice_uploads" / safe_task / safe_name
|
||
|
||
|
||
def temp_notice_upload_dir(request_id: str) -> Path:
|
||
"""
|
||
返回批量上传预检使用的请求级临时目录。
|
||
核心逻辑:将同一请求下的临时文件收敛到 `_tmp/{request_id}`,便于 finally 阶段整目录清理。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
Returns:
|
||
Path: 临时目录路径。
|
||
"""
|
||
safe_request = re.sub(r"[^\w\-]+", "_", str(request_id or "").strip()) or "unknown"
|
||
return _storage_root() / "notice_uploads" / "_tmp" / safe_request
|
||
|
||
|
||
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
|
||
"""保存发货通知附件字节流并返回落盘路径。"""
|
||
path = task_notice_upload_path(task_no, filename)
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_bytes(data)
|
||
return path
|
||
|
||
|
||
def save_temp_notice_upload(request_id: str, index: int, filename: str, data: bytes) -> Path:
|
||
"""
|
||
保存批量上传预检阶段的临时附件。
|
||
核心逻辑:以请求 ID 作为一级目录、文件序号作为二级目录,避免同请求内同名文件互相覆盖。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
index: 当前文件在请求内的顺序号。
|
||
filename: 原始文件名。
|
||
data: 文件字节流。
|
||
Returns:
|
||
Path: 临时落盘路径。
|
||
"""
|
||
name = str(filename or "").strip() or "notice"
|
||
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
|
||
safe_index = max(int(index or 0), 1)
|
||
path = temp_notice_upload_dir(request_id) / str(safe_index) / safe_name
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_bytes(data)
|
||
return path
|
||
|
||
|
||
def cleanup_temp_notice_uploads(request_id: str) -> None:
|
||
"""
|
||
清理指定请求的临时上传目录。
|
||
【AI 触发时机】:仅在批量上传预检完成后调用;正式任务附件目录禁止使用本函数清理。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
"""
|
||
path = temp_notice_upload_dir(request_id)
|
||
if path.exists():
|
||
shutil.rmtree(path, ignore_errors=True)
|
||
parent = path.parent
|
||
if parent.exists() and not any(parent.iterdir()):
|
||
parent.rmdir()
|
||
|
||
|
||
def _decode_text(data: bytes) -> str:
|
||
if not data:
|
||
return ""
|
||
for enc in ("utf-8", "utf-8-sig", "gb18030", "gbk"):
|
||
try:
|
||
return data.decode(enc)
|
||
except Exception:
|
||
continue
|
||
return data.decode("utf-8", errors="ignore")
|
||
|
||
|
||
def _html_to_text(html: str) -> str:
|
||
s = re.sub(r"(?is)<(script|style).*?>.*?</\\1>", "", html or "")
|
||
s = re.sub(r"(?is)<br\\s*/?>", "\n", s)
|
||
s = re.sub(r"(?is)</p\\s*>", "\n", s)
|
||
s = re.sub(r"(?is)<[^>]+>", " ", s)
|
||
s = re.sub(r"[ \t]+", " ", s)
|
||
s = re.sub(r"\\n\\s*\\n+", "\n\n", s)
|
||
return s.strip()
|
||
|
||
|
||
def _image_bytes_to_blocks(raw: bytes) -> list[Block]:
|
||
if not raw:
|
||
return []
|
||
data_uri = "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
|
||
return [
|
||
Block(
|
||
id="img-1",
|
||
page=1,
|
||
type="image",
|
||
text="",
|
||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||
meta={"data_uri": data_uri},
|
||
)
|
||
]
|
||
|
||
|
||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||
lines: list[str] = []
|
||
for b in blocks:
|
||
if b.type not in {"paragraph", "ocr_text"}:
|
||
continue
|
||
txt = str(b.text or "").strip()
|
||
if not txt:
|
||
continue
|
||
if b.type == "ocr_text":
|
||
if txt.startswith("OCR_TEXT:"):
|
||
txt = txt[len("OCR_TEXT:") :].strip()
|
||
txt = re.sub(r"(?m)^\s*-\s*", "", txt).strip()
|
||
lines.append(txt)
|
||
text = "\n\n".join(lines)
|
||
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
||
return text
|
||
|
||
|
||
def extract_notice_text(
|
||
file_path: Path,
|
||
*,
|
||
retain_payloads: bool = False,
|
||
eml_attachment_mode: Literal["deep", "preview"] = "deep",
|
||
preview_only: bool = False,
|
||
) -> tuple[str, dict[str, Any]]:
|
||
"""
|
||
从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。
|
||
|
||
核心逻辑:普通文件走 edkb loaders;.eml 委托 eml_parse 做结构化解析。
|
||
`deep` 模式递归抽取附件文本,`preview` 模式仅保留邮件头/正文/附件目录。
|
||
非 EML 的 `preview_only` 只返回文件元信息,避免上传阶段触发 Loader 或 OCR。
|
||
|
||
Args:
|
||
file_path: 已落盘的通知文件路径。
|
||
retain_payloads: 仅 EML;True 时保留 attachments[*]._payload_bytes 供 Intake 派生资产。
|
||
eml_attachment_mode: `preview` 仅生成附件目录;`deep` 递归抽取附件文本。
|
||
preview_only: True 时普通文件不执行文本/OCR 抽取,留待发送后的深度识别阶段。
|
||
|
||
Returns:
|
||
tuple[str, dict]: (抽取文本, meta 含 warnings、file_type;eml 另含 email/attachments/attachment_count)。
|
||
"""
|
||
path = Path(file_path)
|
||
ext = path.suffix.lower().lstrip(".")
|
||
ctx = Context(file_type=ext)
|
||
warnings: list[str] = []
|
||
|
||
if preview_only and ext != "eml":
|
||
return "", {
|
||
"warnings": warnings,
|
||
"file_type": ext,
|
||
"content_mode": "preview",
|
||
}
|
||
|
||
if ext in {"txt", "md", "log"}:
|
||
return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext}
|
||
if ext in {"html", "htm"}:
|
||
return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext}
|
||
if ext in {"eml"}:
|
||
# 叶附件递归抽取时复用本函数;eml_parse 通过嵌套深度上限防止 bom 炸弹式嵌套
|
||
return parse_eml_bytes(
|
||
path.read_bytes(),
|
||
extract_text=extract_notice_text,
|
||
retain_payloads=retain_payloads,
|
||
attachment_mode=eml_attachment_mode,
|
||
)
|
||
|
||
blocks: list[Block] = []
|
||
if ext in {"pdf"}:
|
||
blocks = loader_pdf.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"docx"}:
|
||
blocks = loader_docx.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"csv"}:
|
||
blocks = loader_csv.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"png", "jpg", "jpeg", "webp"}:
|
||
blocks = _image_bytes_to_blocks(path.read_bytes())
|
||
else:
|
||
warnings.append(f"unsupported_file_type:{ext}")
|
||
|
||
if blocks:
|
||
has_images = any(b.type == "image" for b in blocks)
|
||
if has_images:
|
||
blocks = ocr.run(blocks, ctx)
|
||
text = _blocks_to_text(blocks)
|
||
return text.strip(), {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||
|
||
return "", {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||
|
||
|
||
def guess_source_type(filename: str) -> str:
|
||
"""按扩展名推断 source_type(pdf / email / manual)。"""
|
||
ext = str(Path(filename or "").suffix or "").lower().lstrip(".")
|
||
if ext in {"pdf"}:
|
||
return "pdf"
|
||
if ext in {"eml"}:
|
||
return "email"
|
||
return "manual"
|
||
|
||
|
||
def max_notice_chars() -> int:
|
||
"""发货通知正文最大字符数(SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS,默认 200000)。"""
|
||
raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip()
|
||
try:
|
||
value = int(raw) if raw else 0
|
||
except Exception:
|
||
value = 0
|
||
return value if value > 0 else 200000
|
||
|
||
|
||
EMPTY_TEXT_REJECT_MESSAGE = "notice text is empty after extraction"
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class NoticeIntakeResult:
|
||
"""
|
||
发货通知附件统一接入结果。
|
||
|
||
三条工作台入口(单票建单 / 批量建单 / 重新上传)共用本模型,避免抽取、截断与失败分流行为漂移。
|
||
"""
|
||
|
||
filename: str
|
||
source_type: str
|
||
source_file_type: str | None
|
||
text: str
|
||
warnings: list[str] = field(default_factory=list)
|
||
meta: dict[str, Any] = field(default_factory=dict)
|
||
content_hash: str = ""
|
||
file_size: int = 0
|
||
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
|
||
saved_path: Path | None = None
|
||
|
||
@property
|
||
def accepted(self) -> bool:
|
||
"""抽取成功且正文非空。"""
|
||
return self.status == "accepted"
|
||
|
||
def to_notice_item(self) -> dict[str, Any]:
|
||
"""批量建单 notice_items 载荷项。"""
|
||
return {
|
||
"source_type": self.source_type,
|
||
"source_file_name": self.filename,
|
||
"source_file_type": self.source_file_type,
|
||
"source_content_hash": self.content_hash,
|
||
"file_size": self.file_size,
|
||
"raw_text": self.text,
|
||
"warnings": list(self.warnings),
|
||
}
|
||
|
||
def to_accepted_file_summary(self) -> dict[str, Any]:
|
||
"""批量预检 accepted_files 摘要项。"""
|
||
return {
|
||
"filename": self.filename,
|
||
"source_type": self.source_type,
|
||
"source_file_type": self.source_file_type,
|
||
"text_length": len(self.text),
|
||
"content_hash": self.content_hash,
|
||
"file_size": self.file_size,
|
||
"warnings": list(self.warnings),
|
||
}
|
||
|
||
def to_rejected_file_summary(self) -> dict[str, Any]:
|
||
"""批量预检 rejected_files 摘要项。"""
|
||
return {
|
||
"filename": self.filename,
|
||
"source_type": self.source_type,
|
||
"source_file_type": self.source_file_type,
|
||
"reason": "empty_text",
|
||
"message": EMPTY_TEXT_REJECT_MESSAGE,
|
||
"warnings": list(self.warnings),
|
||
}
|
||
|
||
def to_notice_upload_meta(self) -> dict[str, Any]:
|
||
"""API data.notice_upload 响应字段。"""
|
||
payload = dict(self.meta) if isinstance(self.meta, dict) else {}
|
||
payload["filename"] = self.filename
|
||
payload["warnings"] = list(self.warnings)
|
||
return payload
|
||
|
||
|
||
def notice_source_file_type(upload: Any) -> str | None:
|
||
"""从 Flask/Werkzeug 上传对象提取 MIME type;为空时返回 None。"""
|
||
return str(getattr(upload, "mimetype", "") or "").strip() or None
|
||
|
||
|
||
def truncate_notice_text(text: str, warnings: list[str] | None = None) -> tuple[str, list[str]]:
|
||
"""
|
||
按配置上限截断发货通知正文,并追加统一 warning 标记。
|
||
|
||
Args:
|
||
text: 抽取后的原始正文。
|
||
warnings: 已有 warnings,截断时会追加 notice_text_truncated 项。
|
||
|
||
Returns:
|
||
tuple[str, list[str]]: (截断后正文, 更新后的 warnings)。
|
||
"""
|
||
ws = list(warnings or [])
|
||
limit = max_notice_chars()
|
||
if len(text) > limit:
|
||
text = text[:limit]
|
||
ws.append(f"notice_text_truncated:{limit}")
|
||
return text, ws
|
||
|
||
|
||
def intake_notice_attachment(
|
||
*,
|
||
filename: str,
|
||
raw: bytes,
|
||
source_file_type: str | None = None,
|
||
storage: Literal["task", "temp"] = "task",
|
||
task_no: str | None = None,
|
||
temp_request_id: str | None = None,
|
||
temp_index: int = 1,
|
||
eml_attachment_mode: Literal["deep", "preview"] = "preview",
|
||
) -> NoticeIntakeResult:
|
||
"""
|
||
单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。
|
||
|
||
核心逻辑:三条工作台入口均调用本函数,保证 empty_text / extract_failed 与 warnings 语义一致。
|
||
|
||
Args:
|
||
filename: 原始文件名。
|
||
raw: 文件字节流。
|
||
source_file_type: MIME type,可为空。
|
||
storage: task 为任务级持久化目录;temp 为批量预检临时目录。
|
||
task_no: storage=task 时必填。
|
||
temp_request_id: storage=temp 时必填。
|
||
temp_index: storage=temp 时文件序号,避免同名覆盖。
|
||
eml_attachment_mode: EML 上传模式;`preview` 仅保留附件目录,适合输入栏快览。
|
||
|
||
Returns:
|
||
NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。
|
||
"""
|
||
name = str(filename or "").strip() or "notice"
|
||
source_type = guess_source_type(name)
|
||
raw_bytes = raw or b""
|
||
content_hash = hashlib.sha256(raw_bytes).hexdigest().lower()
|
||
file_size = len(raw_bytes)
|
||
saved_path: Path | None = None
|
||
text = ""
|
||
meta: dict[str, Any] = {}
|
||
warnings: list[str] = []
|
||
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
|
||
|
||
try:
|
||
if storage == "task":
|
||
if not task_no:
|
||
raise ValueError("task_no is required for task storage")
|
||
saved_path = save_task_notice_upload(task_no, name, raw_bytes)
|
||
else:
|
||
if not temp_request_id:
|
||
raise ValueError("temp_request_id is required for temp storage")
|
||
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw_bytes)
|
||
text, meta = extract_notice_text(saved_path, eml_attachment_mode=eml_attachment_mode)
|
||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||
except Exception as exc:
|
||
warnings = [f"notice_extract_failed:{exc}"]
|
||
status = "extract_failed"
|
||
return NoticeIntakeResult(
|
||
filename=name,
|
||
source_type=source_type,
|
||
source_file_type=source_file_type,
|
||
text="",
|
||
warnings=warnings,
|
||
meta=meta if isinstance(meta, dict) else {},
|
||
content_hash=content_hash,
|
||
file_size=file_size,
|
||
status=status,
|
||
saved_path=saved_path,
|
||
)
|
||
|
||
preview_accept_without_text = (
|
||
isinstance(meta, dict)
|
||
and str(meta.get("file_type") or "").lower() == "eml"
|
||
and str(meta.get("eml_attachment_mode") or "").lower() == "preview"
|
||
and (
|
||
bool(meta.get("attachment_count"))
|
||
or bool(meta.get("attachments"))
|
||
or bool(meta.get("email"))
|
||
)
|
||
)
|
||
if not str(text or "").strip() and not preview_accept_without_text:
|
||
return NoticeIntakeResult(
|
||
filename=name,
|
||
source_type=source_type,
|
||
source_file_type=source_file_type,
|
||
text="",
|
||
warnings=warnings,
|
||
meta=meta if isinstance(meta, dict) else {},
|
||
content_hash=content_hash,
|
||
file_size=file_size,
|
||
status="empty_text",
|
||
saved_path=saved_path,
|
||
)
|
||
|
||
text, warnings = truncate_notice_text(text, warnings)
|
||
return NoticeIntakeResult(
|
||
filename=name,
|
||
source_type=source_type,
|
||
source_file_type=source_file_type,
|
||
text=text,
|
||
warnings=warnings,
|
||
meta=meta if isinstance(meta, dict) else {},
|
||
content_hash=content_hash,
|
||
file_size=file_size,
|
||
status="accepted",
|
||
saved_path=saved_path,
|
||
)
|
||
|
||
|
||
def intake_temp_notice_uploads(
|
||
temp_request_id: str,
|
||
uploads: Sequence[Any],
|
||
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult], list[dict[str, Any]]]:
|
||
"""
|
||
批量建单入口:逐份附件接入、同请求内按内容哈希去重,并在 finally 外由调用方清理临时目录。
|
||
|
||
Args:
|
||
temp_request_id: 请求级临时目录 ID。
|
||
uploads: Flask request.files 中的上传对象序列。
|
||
|
||
Returns:
|
||
tuple: (accepted 结果列表, rejected 结果列表, duplicate_files 摘要列表)。
|
||
"""
|
||
accepted: list[NoticeIntakeResult] = []
|
||
rejected: list[NoticeIntakeResult] = []
|
||
duplicate_files: list[dict[str, Any]] = []
|
||
seen_hashes: dict[str, str] = {}
|
||
for index, upload in enumerate(uploads, start=1):
|
||
raw = upload.read() or b""
|
||
content_hash = hashlib.sha256(raw).hexdigest().lower()
|
||
filename = str(upload.filename or "notice").strip() or "notice"
|
||
if content_hash in seen_hashes:
|
||
duplicate_files.append(
|
||
{
|
||
"filename": filename,
|
||
"duplicate_of": seen_hashes[content_hash],
|
||
"content_hash": content_hash,
|
||
}
|
||
)
|
||
continue
|
||
seen_hashes[content_hash] = filename
|
||
result = intake_notice_attachment(
|
||
filename=filename,
|
||
raw=raw,
|
||
source_file_type=notice_source_file_type(upload),
|
||
storage="temp",
|
||
temp_request_id=temp_request_id,
|
||
temp_index=index,
|
||
)
|
||
if result.accepted:
|
||
accepted.append(result)
|
||
else:
|
||
rejected.append(result)
|
||
return accepted, rejected, duplicate_files
|
||
|
||
|
||
def build_notice_file_summary(
|
||
*,
|
||
total_files: int,
|
||
accepted: Sequence[NoticeIntakeResult],
|
||
rejected: Sequence[NoticeIntakeResult],
|
||
duplicate_files: Sequence[dict[str, Any]] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
构建批量上传预检摘要,供前端回显与测试断言。
|
||
|
||
Args:
|
||
total_files: 请求内附件总数。
|
||
accepted: 接入成功的结果列表。
|
||
rejected: 接入失败的结果列表。
|
||
duplicate_files: 同请求内内容重复、已跳过的文件摘要。
|
||
|
||
Returns:
|
||
dict: total/accepted/rejected/duplicate 计数与文件明细。
|
||
"""
|
||
accepted_files = [item.to_accepted_file_summary() for item in accepted]
|
||
rejected_files = [item.to_rejected_file_summary() for item in rejected]
|
||
duplicates = [dict(item) for item in (duplicate_files or [])]
|
||
return {
|
||
"total_files": total_files,
|
||
"accepted_count": len(accepted_files),
|
||
"rejected_count": len(rejected_files),
|
||
"duplicate_count": len(duplicates),
|
||
"accepted_files": accepted_files,
|
||
"rejected_files": rejected_files,
|
||
"duplicate_files": duplicates,
|
||
}
|