refactor(agent, shipping): 简化代理模型并完善订单抽取业务
- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码 - 删除废弃的 AgentRuntimeBinding 模型及其依赖 - 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑 - 修复附件完整性检测、订单抽取状态映射问题 - 更新多语言错误文案与前端单元测试配置 - 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
1 parent
1f3ecb87b7
commit
61ac6403c4
159 files changed
+12883
-5099
No files matched your search
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/eml_parse.py
|
||||
|
||||
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、真实附件及各自文本)。
|
||||
用途:将 .eml 解析为结构化结果(邮件元数据、清洗正文、附件目录,按模式可选附件全文)。
|
||||
依赖:标准库 email/html、BeautifulSoup;Flask current_app(可选);notice_upload.extract_notice_text(叶附件抽取)。
|
||||
逻辑:由 notice_upload.extract_notice_text 在 file_type=eml 时调用;忽略内嵌图片/签名图;
|
||||
嵌套 message/rfc822 与附件型 multipart(disposition/filename)登记为独立附件;
|
||||
@@ -22,7 +22,7 @@ from email.message import Message
|
||||
from email.parser import BytesParser
|
||||
from email.utils import parsedate_to_datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, Literal
|
||||
|
||||
from bs4 import BeautifulSoup, Comment
|
||||
|
||||
@@ -545,8 +545,8 @@ def _register_and_expand_attached_multipart(
|
||||
"parse_status": "skipped",
|
||||
"extracted_text": "",
|
||||
"warnings": [],
|
||||
"_payload_bytes": raw or b"",
|
||||
}
|
||||
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
|
||||
|
||||
if size > state.limits.max_attachment_bytes:
|
||||
item["parse_status"] = "skipped"
|
||||
@@ -656,12 +656,15 @@ def _guess_suffix(filename: str, mime_type: str) -> str:
|
||||
|
||||
|
||||
ExtractTextFn = Callable[[Path], tuple[str, dict[str, Any]]]
|
||||
AttachmentExtractMode = Literal["deep", "preview"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ParseState:
|
||||
limits: EmlLimits
|
||||
extract_text: ExtractTextFn
|
||||
retain_payloads: bool = False
|
||||
attachment_mode: AttachmentExtractMode = "deep"
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
attachments: list[dict[str, Any]] = field(default_factory=list)
|
||||
nested_bodies: list[str] = field(default_factory=list) # 兼容保留;v3 起 rfc822 改走 attachments,不再写入
|
||||
@@ -678,6 +681,23 @@ def _next_attachment_key(state: _ParseState) -> str:
|
||||
return f"att-{state.attachment_seq:03d}"
|
||||
|
||||
|
||||
def _skip_inline_resource(state: _ParseState) -> None:
|
||||
"""跳过内嵌资源但保留 MIME 遍历序号,保证快览与深度解析附件键一致。"""
|
||||
state.skipped_inline += 1
|
||||
_next_attachment_key(state)
|
||||
|
||||
|
||||
def _remember_payload(
|
||||
item: dict[str, Any],
|
||||
payload: bytes,
|
||||
*,
|
||||
retain_payloads: bool,
|
||||
) -> None:
|
||||
"""仅在调用方显式要求时保留附件原始字节,避免预览链路持有大对象。"""
|
||||
if retain_payloads and payload:
|
||||
item["_payload_bytes"] = payload
|
||||
|
||||
|
||||
def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
|
||||
"""判定附件是否为可递归的 .eml / rfc822 载荷。"""
|
||||
suffix = Path(filename or "").suffix.lower()
|
||||
@@ -685,6 +705,101 @@ def _is_eml_payload(*, filename: str, mime_type: str) -> bool:
|
||||
return suffix == ".eml" or mime in {"message/rfc822", "application/eml"}
|
||||
|
||||
|
||||
_PREVIEW_READY_SUFFIXES = frozenset(
|
||||
{
|
||||
".pdf",
|
||||
".doc",
|
||||
".docx",
|
||||
".xls",
|
||||
".xlsx",
|
||||
".csv",
|
||||
".txt",
|
||||
".html",
|
||||
".htm",
|
||||
".xml",
|
||||
".json",
|
||||
".eml",
|
||||
".msg",
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".webp",
|
||||
".bmp",
|
||||
".tif",
|
||||
".tiff",
|
||||
}
|
||||
)
|
||||
_PREVIEW_ARCHIVE_SUFFIXES = frozenset(
|
||||
{".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz"}
|
||||
)
|
||||
_PREVIEW_EXECUTABLE_SUFFIXES = frozenset(
|
||||
{".exe", ".dll", ".bat", ".cmd", ".com", ".msi", ".vbs", ".js", ".jar", ".ps1", ".scr"}
|
||||
)
|
||||
_PREVIEW_MACRO_SUFFIXES = frozenset({".docm", ".xlsm", ".pptm", ".xlam", ".xltm"})
|
||||
_PREVIEW_READY_MIME_PREFIXES = ("text/", "image/")
|
||||
_PREVIEW_READY_MIMES = frozenset(
|
||||
{
|
||||
"application/pdf",
|
||||
"message/rfc822",
|
||||
"application/eml",
|
||||
"application/msword",
|
||||
"application/vnd.ms-excel",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
}
|
||||
)
|
||||
_PREVIEW_ARCHIVE_MIMES = frozenset(
|
||||
{
|
||||
"application/zip",
|
||||
"application/x-zip-compressed",
|
||||
"application/x-7z-compressed",
|
||||
"application/x-rar-compressed",
|
||||
"application/gzip",
|
||||
"application/x-tar",
|
||||
}
|
||||
)
|
||||
_PREVIEW_EXECUTABLE_MIMES = frozenset(
|
||||
{
|
||||
"application/x-msdownload",
|
||||
"application/x-msdos-program",
|
||||
"application/x-sh",
|
||||
"application/x-powershell",
|
||||
"application/java-archive",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _preview_catalog_reason(
|
||||
*,
|
||||
filename: str,
|
||||
mime_type: str,
|
||||
is_inline_resource: bool,
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
根据目录阶段可见事实判断附件是否可进入后续深度解析。
|
||||
|
||||
Returns:
|
||||
tuple[bool, str]: (是否可进入深度解析, 原因码)。
|
||||
"""
|
||||
suffix = Path(str(filename or "")).suffix.lower()
|
||||
mime = str(mime_type or "").lower()
|
||||
if is_inline_resource:
|
||||
if _looks_like_signature_or_logo(filename):
|
||||
return False, "signature_or_logo"
|
||||
return False, "inline_resource"
|
||||
if suffix in _PREVIEW_ARCHIVE_SUFFIXES or mime in _PREVIEW_ARCHIVE_MIMES:
|
||||
return False, "archive"
|
||||
if suffix in _PREVIEW_MACRO_SUFFIXES or "macroenabled" in mime:
|
||||
return False, "macro_enabled"
|
||||
if suffix in _PREVIEW_EXECUTABLE_SUFFIXES or mime in _PREVIEW_EXECUTABLE_MIMES:
|
||||
return False, "executable"
|
||||
if suffix in _PREVIEW_READY_SUFFIXES:
|
||||
return True, "ready_for_extraction"
|
||||
if mime in _PREVIEW_READY_MIMES or any(mime.startswith(prefix) for prefix in _PREVIEW_READY_MIME_PREFIXES):
|
||||
return True, "ready_for_extraction"
|
||||
return False, "unknown_binary"
|
||||
|
||||
|
||||
def _expand_eml_file_attachment(
|
||||
*,
|
||||
state: _ParseState,
|
||||
@@ -812,9 +927,9 @@ def _append_attachment(
|
||||
"parse_status": "skipped",
|
||||
"extracted_text": "",
|
||||
"warnings": [],
|
||||
# 仅内存保留供阶段二派生资产;写 structured_result / 对外 API 前必须剥离
|
||||
"_payload_bytes": payload or b"",
|
||||
}
|
||||
# 仅在显式深度链路保留原始字节;预览模式不再为后续派生资产持有 payload。
|
||||
_remember_payload(item, payload or b"", retain_payloads=state.retain_payloads)
|
||||
|
||||
# [STEP 2] 单附件 / 总大小上限
|
||||
# 计费规则:顶层真实附件(含 .eml 容器)计入总量;从已计费 .eml 展开的子内容不计。
|
||||
@@ -900,8 +1015,8 @@ def _register_and_expand_rfc822(
|
||||
"parse_status": "empty",
|
||||
"extracted_text": "",
|
||||
"warnings": [],
|
||||
"_payload_bytes": raw or b"",
|
||||
}
|
||||
_remember_payload(item, raw or b"", retain_payloads=state.retain_payloads)
|
||||
|
||||
if content_hash and content_hash in state.seen_hashes:
|
||||
item["parse_status"] = "duplicate"
|
||||
@@ -1000,6 +1115,182 @@ def _maybe_charge_rfc822_container(
|
||||
return True
|
||||
|
||||
|
||||
def _append_preview_attachment(
|
||||
state: _ParseState,
|
||||
*,
|
||||
filename: str,
|
||||
mime_type: str,
|
||||
payload: bytes,
|
||||
count_toward_total: bool = True,
|
||||
is_inline_resource: bool = False,
|
||||
forced_status: str | None = None,
|
||||
forced_warning: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
仅登记附件目录,不做正文抽取或递归展开。
|
||||
|
||||
核心逻辑:目录阶段只保留文件名、MIME、大小、哈希、内嵌标记和后续是否允许深度解析。
|
||||
forced_status/forced_warning 用于记录超深、不可读嵌套等目录不完整事实。
|
||||
"""
|
||||
state.discovered_attachment_count += 1
|
||||
if len(state.attachments) >= state.limits.max_attachments:
|
||||
_note_attachment_limit_exceeded(state)
|
||||
return
|
||||
|
||||
raw = payload or b""
|
||||
size = len(raw)
|
||||
content_hash = hashlib.sha256(raw).hexdigest().lower() if raw else ""
|
||||
ready_for_extraction, catalog_reason = _preview_catalog_reason(
|
||||
filename=filename,
|
||||
mime_type=mime_type,
|
||||
is_inline_resource=is_inline_resource,
|
||||
)
|
||||
key = _next_attachment_key(state)
|
||||
item: dict[str, Any] = {
|
||||
"attachment_key": key,
|
||||
"filename": filename,
|
||||
"mime_type": mime_type or "application/octet-stream",
|
||||
"size": size,
|
||||
"content_hash": content_hash,
|
||||
"parse_status": "ready_for_extraction" if ready_for_extraction else "directory_only",
|
||||
"extracted_text": "",
|
||||
"warnings": [],
|
||||
"ready_for_extraction": ready_for_extraction,
|
||||
"is_inline_resource": is_inline_resource,
|
||||
"catalog_reason": catalog_reason,
|
||||
}
|
||||
_remember_payload(item, raw, retain_payloads=state.retain_payloads)
|
||||
|
||||
if forced_warning:
|
||||
item["parse_status"] = forced_status or "skipped"
|
||||
item["ready_for_extraction"] = False
|
||||
item["warnings"].append(forced_warning)
|
||||
if forced_warning.startswith("eml_total_attachment_size_exceeded"):
|
||||
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
|
||||
state.warnings.append(forced_warning)
|
||||
elif forced_warning not in state.warnings:
|
||||
state.warnings.append(forced_warning)
|
||||
state.attachments.append(item)
|
||||
return
|
||||
|
||||
if size > state.limits.max_attachment_bytes:
|
||||
item["parse_status"] = "skipped"
|
||||
item["ready_for_extraction"] = False
|
||||
item["warnings"].append(f"eml_attachment_too_large:{size}")
|
||||
state.warnings.append(f"eml_attachment_too_large:{filename}:{size}")
|
||||
state.attachments.append(item)
|
||||
return
|
||||
if count_toward_total:
|
||||
if state.total_attachment_bytes + size > state.limits.max_total_attachment_bytes:
|
||||
item["parse_status"] = "skipped"
|
||||
item["ready_for_extraction"] = False
|
||||
item["warnings"].append("eml_total_attachment_size_exceeded")
|
||||
if not any(str(w).startswith("eml_total_attachment_size_exceeded") for w in state.warnings):
|
||||
state.warnings.append(
|
||||
f"eml_total_attachment_size_exceeded:{state.limits.max_total_attachment_bytes}"
|
||||
)
|
||||
state.attachments.append(item)
|
||||
return
|
||||
state.total_attachment_bytes += size
|
||||
if content_hash and content_hash in state.seen_hashes:
|
||||
item["parse_status"] = "duplicate"
|
||||
item["ready_for_extraction"] = False
|
||||
item["catalog_reason"] = "duplicate"
|
||||
item["warnings"].append(f"eml_attachment_duplicate:{state.seen_hashes[content_hash]}")
|
||||
state.warnings.append(f"eml_attachment_duplicate:{filename}")
|
||||
state.attachments.append(item)
|
||||
return
|
||||
if content_hash:
|
||||
state.seen_hashes[content_hash] = key
|
||||
state.attachments.append(item)
|
||||
|
||||
|
||||
def _walk_message_preview(
|
||||
msg: Message,
|
||||
state: _ParseState,
|
||||
*,
|
||||
depth: int,
|
||||
count_toward_total: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
遍历 MIME 树并仅登记附件目录。
|
||||
|
||||
核心逻辑:正文提取仍由根消息自身负责;目录阶段对 message/rfc822 和附件型 multipart
|
||||
只登记容器,不递归进入其内部附件,确保上传时延与附件正文/OCR/表格无关。
|
||||
"""
|
||||
if depth > state.limits.max_nesting_depth:
|
||||
state.warnings.append(f"eml_nesting_depth_exceeded:{state.limits.max_nesting_depth}")
|
||||
return
|
||||
|
||||
if not msg.is_multipart():
|
||||
is_inline = _is_inline_or_embedded_resource(msg)
|
||||
if is_inline:
|
||||
_skip_inline_resource(state)
|
||||
elif _is_real_attachment(msg):
|
||||
_append_preview_attachment(
|
||||
state,
|
||||
filename=_part_filename(msg),
|
||||
mime_type=str(msg.get_content_type() or "application/octet-stream"),
|
||||
payload=_read_part_payload(msg),
|
||||
count_toward_total=count_toward_total,
|
||||
)
|
||||
return
|
||||
|
||||
parts = list(msg.iter_parts()) if hasattr(msg, "iter_parts") else list(msg.get_payload() or [])
|
||||
for part in parts:
|
||||
if not isinstance(part, Message):
|
||||
continue
|
||||
ctype = str(part.get_content_type() or "").lower()
|
||||
|
||||
if ctype == "message/rfc822":
|
||||
_append_preview_attachment(
|
||||
state,
|
||||
filename=str(part.get_filename() or "").strip() or "forwarded-message.eml",
|
||||
mime_type="message/rfc822",
|
||||
payload=_rfc822_container_bytes(part),
|
||||
count_toward_total=count_toward_total,
|
||||
forced_status="skipped" if _unwrap_rfc822(part) is None else None,
|
||||
forced_warning="eml_nested_message_unreadable" if _unwrap_rfc822(part) is None else None,
|
||||
)
|
||||
continue
|
||||
if part.is_multipart():
|
||||
if _is_attached_multipart(part):
|
||||
try:
|
||||
raw = part.as_bytes()
|
||||
except Exception:
|
||||
raw = b""
|
||||
_append_preview_attachment(
|
||||
state,
|
||||
filename=_part_filename(part, fallback="bundle"),
|
||||
mime_type=str(part.get_content_type() or "multipart/mixed"),
|
||||
payload=raw,
|
||||
count_toward_total=count_toward_total,
|
||||
)
|
||||
continue
|
||||
_walk_message_preview(
|
||||
part,
|
||||
state,
|
||||
depth=depth,
|
||||
count_toward_total=count_toward_total,
|
||||
)
|
||||
continue
|
||||
is_inline = _is_inline_or_embedded_resource(part)
|
||||
if is_inline:
|
||||
# 内嵌签名图不是用户可识别的业务附件,不能占用附件数量或预算。
|
||||
_skip_inline_resource(state)
|
||||
continue
|
||||
if _is_body_text_part(part):
|
||||
continue
|
||||
if _is_real_attachment(part):
|
||||
_append_preview_attachment(
|
||||
state,
|
||||
filename=_part_filename(part),
|
||||
mime_type=str(part.get_content_type() or "application/octet-stream"),
|
||||
payload=_read_part_payload(part),
|
||||
count_toward_total=count_toward_total,
|
||||
)
|
||||
|
||||
|
||||
def _walk_message(
|
||||
msg: Message,
|
||||
state: _ParseState,
|
||||
@@ -1093,7 +1384,7 @@ def _walk_message(
|
||||
continue
|
||||
|
||||
if _is_inline_or_embedded_resource(part):
|
||||
state.skipped_inline += 1
|
||||
_skip_inline_resource(state)
|
||||
continue
|
||||
|
||||
if _is_body_text_part(part):
|
||||
@@ -1140,12 +1431,13 @@ def parse_eml_bytes(
|
||||
limits: EmlLimits | None = None,
|
||||
depth: int = 0,
|
||||
retain_payloads: bool = False,
|
||||
attachment_mode: AttachmentExtractMode = "deep",
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""
|
||||
结构化解析 EML 字节流。
|
||||
|
||||
核心逻辑:提取邮件头与清洗正文 → 区分真实附件与内嵌图片 → 对附件调用 extract_text;
|
||||
嵌套 rfc822 登记为独立附件并展开内层;不执行宏、脚本或嵌入对象。
|
||||
核心逻辑:提取邮件头与清洗正文;`deep` 模式递归抽取附件全文,
|
||||
`preview` 模式仅登记附件目录(名称、MIME、大小、哈希、是否内嵌、是否允许后续深度解析)。
|
||||
|
||||
Args:
|
||||
data: .eml 原始字节。
|
||||
@@ -1154,6 +1446,7 @@ def parse_eml_bytes(
|
||||
depth: 当前嵌套深度(供嵌套 .eml 附件复用)。
|
||||
retain_payloads: True 时在 attachments[*]._payload_bytes 保留二进制供派生资产;
|
||||
默认 False,返回前剥离,避免测试/JSON 路径泄漏。
|
||||
attachment_mode: `deep` 递归抽附件文本;`preview` 只生成附件目录。
|
||||
|
||||
Returns:
|
||||
tuple[str, dict]: (扁平拼接文本, meta含 email/attachments/attachment_count/warnings)。
|
||||
@@ -1178,8 +1471,16 @@ def parse_eml_bytes(
|
||||
body_text = _extract_body_text(msg)
|
||||
body_html_tables = _extract_body_html_tables(msg)
|
||||
|
||||
state = _ParseState(limits=limits, extract_text=extract_text)
|
||||
_walk_message(msg, state, depth=depth)
|
||||
state = _ParseState(
|
||||
limits=limits,
|
||||
extract_text=extract_text,
|
||||
retain_payloads=retain_payloads,
|
||||
attachment_mode=attachment_mode,
|
||||
)
|
||||
if attachment_mode == "preview":
|
||||
_walk_message_preview(msg, state, depth=depth)
|
||||
else:
|
||||
_walk_message(msg, state, depth=depth)
|
||||
|
||||
if state.skipped_inline:
|
||||
state.warnings.append(f"eml_inline_resources_skipped:{state.skipped_inline}")
|
||||
@@ -1199,10 +1500,11 @@ def parse_eml_bytes(
|
||||
flat = _compose_flat_text(
|
||||
subject=subject,
|
||||
body_text=combined_body,
|
||||
attachments=state.attachments,
|
||||
attachments=state.attachments if attachment_mode == "deep" else [],
|
||||
)
|
||||
meta: dict[str, Any] = {
|
||||
"file_type": "eml",
|
||||
"eml_attachment_mode": attachment_mode,
|
||||
"warnings": list(state.warnings),
|
||||
"email": email_meta,
|
||||
"attachments": list(state.attachments),
|
||||
|
||||
Reference in new issue
Block a user