Files
syops/backend/app/services/shipping_notice/notice_upload.py
T

181 lines
6.2 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.
"""
services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow。
"""
from __future__ import annotations
import base64
import re
from email import policy
from email.parser import BytesParser
from pathlib import Path
from typing import Any
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
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 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 _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 _eml_to_text(data: bytes) -> str:
msg = BytesParser(policy=policy.default).parsebytes(data)
parts: list[str] = []
subject = str(msg.get("subject") or "").strip()
if subject:
parts.append(f"Subject: {subject}")
if msg.is_multipart():
for part in msg.walk():
if part.is_multipart():
continue
ctype = str(part.get_content_type() or "")
payload = part.get_payload(decode=True) or b""
if ctype == "text/plain":
parts.append(_decode_text(payload).strip())
elif ctype == "text/html":
parts.append(_html_to_text(_decode_text(payload)).strip())
else:
payload = msg.get_payload(decode=True) or b""
ctype = str(msg.get_content_type() or "")
if ctype == "text/html":
parts.append(_html_to_text(_decode_text(payload)).strip())
else:
parts.append(_decode_text(payload).strip())
return "\n\n".join(x for x in parts if x)
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) -> tuple[str, dict[str, Any]]:
"""
从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。
Returns:
tuple[str, dict]: (抽取文本, meta 含 warnings 与 file_type)。
"""
path = Path(file_path)
ext = path.suffix.lower().lstrip(".")
ctx = Context(file_type=ext)
warnings: list[str] = []
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"}:
return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext}
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