feat(loader_pdf): 提取 XFA 数据集并更新上下文信息

- 添加 XFA 数据集提取功能
- 更新上下文以包含提取的 XFA 文本
- 增加相关测试以验证 XFA 数据集的提取
This commit is contained in:
hugo committed 2026-06-29 14:46:22 +08:00
1 parent 1fc9976ca3
commit f434402530
2 files changed
+122

No files matched your search

+104
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
import base64
import io
from pathlib import Path
import re
import xml.etree.ElementTree as ET
from edkb_system.contracts import Block, Context
@@ -13,6 +15,19 @@ _DEFAULT_PAGE_TEXT_LIMIT = 120
_MIN_SCAN_IMAGE_BYTES = 4 * 1024
_MIN_DEFAULT_IMAGE_BYTES = 16 * 1024
_MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024
_XFA_ROW_CONTAINER_TAGS = {"DATA"}
_XFA_SKIP_TAGS = {
"config",
"connectionSet",
"dataDescription",
"desc",
"extras",
"form",
"localeSet",
"manifest",
"occur",
"template",
}
def _is_scanned(text_chars: int, pages: int) -> bool:
@@ -44,6 +59,80 @@ def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
return f"data:{content_type};base64,{b64}"
def _local_name(tag: str) -> str:
return str(tag or "").rsplit("}", 1)[-1]
def _normalize_xfa_text(text: str) -> str:
return re.sub(r"[ \t\r\f\v]+", " ", str(text or "")).strip()
def _iter_xfa_roots(reader) -> list[ET.Element]:
try:
xfa_obj = getattr(reader, "xfa", None)
xfa = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, "xfa", None)
except Exception:
xfa = None
if not xfa:
return []
roots: list[ET.Element] = []
items = xfa.items() if isinstance(xfa, dict) else xfa
for _name, payload in items:
if isinstance(payload, str):
raw = payload.encode("utf-8", errors="ignore")
else:
raw = bytes(payload or b"")
if not raw.strip():
continue
try:
roots.append(ET.fromstring(raw))
except Exception:
continue
return roots
def _render_xfa_leaf_rows(node: ET.Element, prefix: tuple[str, ...] = ()) -> list[str]:
tag = _local_name(node.tag)
if tag in _XFA_SKIP_TAGS:
return []
children = [child for child in list(node) if isinstance(child.tag, str)]
text = _normalize_xfa_text(" ".join(node.itertext()))
if not children:
return [f"{'/'.join((*prefix, tag))}: {text}"] if text else []
leaf_children = [
child
for child in children
if not [grand for grand in list(child) if isinstance(grand.tag, str)]
and _normalize_xfa_text(" ".join(child.itertext()))
]
if tag in _XFA_ROW_CONTAINER_TAGS and leaf_children:
cells = [
f"{_local_name(child.tag)}={_normalize_xfa_text(' '.join(child.itertext()))}"
for child in leaf_children
]
return [f"{'/'.join((*prefix, tag))}: " + " | ".join(cells)]
rows: list[str] = []
for child in children:
rows.extend(_render_xfa_leaf_rows(child, (*prefix, tag)))
return rows
def _extract_xfa_text(reader) -> str:
rows: list[str] = []
seen: set[str] = set()
for root in _iter_xfa_roots(reader):
for row in _render_xfa_leaf_rows(root):
if row in seen:
continue
seen.add(row)
rows.append(row)
return "\n".join(rows).strip()
def _normalize_box(
bounds: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
@@ -224,6 +313,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
reader = PdfReader(str(file_path))
context.pages = len(reader.pages)
xfa_text = _extract_xfa_text(reader)
text_chars = 0
page_payloads: list[dict] = []
for page_idx, p in enumerate(reader.pages, start=1):
@@ -367,6 +457,20 @@ def run(input_data: dict, context: Context) -> list[Block]:
)
context.images += 1
if xfa_text:
blocks.append(
Block(
id="pdf-xfa",
page=1,
type="paragraph",
text=xfa_text,
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={"source": "pdf_xfa"},
)
)
context.extras["pdf_xfa_text"] = True
context.warnings.append("pdf xfa datasets extracted")
if scan_likely:
context.warnings.append("pdf likely scanned; OCR recommended")
context.extras["scan_likely"] = True
@@ -13,6 +13,24 @@ from app.services.shipping_notice.reservation_id import (
)
def test_extract_notice_text_reads_xfa_pdf_datasets():
"""XFA 表单型 PO 的订单字段应进入 raw_text,避免只抽页面文本漏明细。"""
from pathlib import Path
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
assert "pdf xfa datasets extracted" in meta["warnings"]
assert "HEADER/EBELN: 4510038672" in text
assert "HEADER/SHIPMENT_TEXT: 1000144510" in text
assert "TEMP-S000218922" in text
assert "MPN:D4-A08AR12000001" in text
assert "EINDT=2026-06-23" in text
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"