Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Delegate PDF text normalization to DocGale after content assembly

myhloli033a3a2544a8
diff --git a/mineru/backend/analysis/pdf/normalization.py b/mineru/backend/analysis/pdf/normalization.py
index fac77a89..ec6c5c56 100644
--- a/mineru/backend/analysis/pdf/normalization.py
+++ b/mineru/backend/analysis/pdf/normalization.py
@@ -13,7 +13,7 @@ from docgale.content.spans import inline_span_plain_text
from docgale.content.spans import strip_span_dicts
from ....types import BBox, BlockType, RAW_ALGORITHM, RAW_PHONETIC
from docgale.foundation.geometry import calculate_overlap_area_2_minbox_area_ratio
-from docgale.foundation.text import full_to_half_exclude_marks
+from docgale.content import normalize_pdf_model_text
from .constants import (
LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD,
@@ -97,40 +97,6 @@ def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
return True
-def _normalize_natural_language_fragment(content: str) -> str:
- """规范自然语言片段中的全角字符,同时原样保留行内公式片段。"""
-
- normalized_parts: list[str] = []
- cursor = 0
- formula_markers = (("\\(", "\\)"),)
-
- while cursor < len(content):
- formula_starts = [
- (start, opening, closing) for opening, closing in formula_markers if (start := content.find(opening, cursor)) >= 0
- ]
- if not formula_starts:
- normalized_parts.append(full_to_half_exclude_marks(content[cursor:]))
- break
-
- formula_start, opening, closing = min(formula_starts, key=lambda item: item[0])
- normalized_parts.append(full_to_half_exclude_marks(content[cursor:formula_start]))
- formula_end = content.find(closing, formula_start + len(opening))
- if formula_end < 0:
- normalized_parts.append(content[formula_start:])
- break
-
- formula_end += len(closing)
- normalized_parts.append(content[formula_start:formula_end])
- cursor = formula_end
-
- return "".join(normalized_parts)
-
-
-def _normalize_natural_language_content(content: str) -> str:
- """规范尚未 Span 化的自然语言可见文本。"""
- return _normalize_natural_language_fragment(content)
-
-
def _natural_language_spans(content: str) -> list[dict[str, Any]]:
"""把 PDF 自然语言字符串及圆括号公式定界符直接转换为 Span。"""
pattern = re.compile(r"\\\((?P<round>.*?)\\\)", re.DOTALL)
@@ -144,19 +110,6 @@ def _natural_language_spans(content: str) -> list[dict[str, Any]]:
return strip_span_dicts(spans)
-def _normalize_existing_span_text(spans: list[Any]) -> None:
- """只规范已有 Span 中的 TextSpan 文字,保留公式、代码和链接目标原文。"""
- for span in spans:
- if not isinstance(span, dict):
- continue
- span_type = span.get("type")
- span_content = span.get("content")
- if span_type == "text" and isinstance(span_content, str):
- span["content"] = _normalize_natural_language_fragment(span_content)
- elif span_type == "hyperlink" and isinstance(span_content, list):
- _normalize_existing_span_text(span_content)
-
-
def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
"""清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""
for page_idx, page_model_list in enumerate(model_list):
@@ -179,13 +132,10 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
block.pop("merge_prev", None)
content = block.get("content")
if isinstance(content, list):
- if block.get("type") in {*NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES, RAW_ALGORITHM}:
- _normalize_existing_span_text(content)
continue
if not isinstance(content, str):
continue
if block.get("type") in NATURAL_LANGUAGE_CONTENT_BLOCK_TYPES:
- content = _normalize_natural_language_content(content)
block["content"] = _natural_language_spans(content)
elif block.get("type") == BlockType.CODE:
spans = _natural_language_spans(content)
@@ -199,3 +149,5 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
for block in page_model_list
if block.get("type") not in LINE_METADATA_BLOCK_TYPES or _is_valid_pdf_text_block(block)
]
+ # 统一在回填、Span 构造及宿主元数据清理完成后调用共享实现。
+ normalize_pdf_model_text(model_list)
diff --git a/tests/unittest/test_docgale_routing.py b/tests/unittest/test_docgale_routing.py
index 5dd49e08..f9b3c174 100644
--- a/tests/unittest/test_docgale_routing.py
+++ b/tests/unittest/test_docgale_routing.py
@@ -48,7 +48,12 @@ def test_flash_routes_classification_and_native_analysis_explicitly(
def process(_data: bytes, _document: Document, **options: object) -> list[list[dict[str, object]]]:
"""记录实际传给处理窗口的路由决定。"""
observed.append(options)
- return [[]]
+ return [
+ [
+ {"type": "text", "content": "A1", "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}]},
+ {"type": "table", "content": "<table><tr><td>B2</td></tr></table>"},
+ ]
+ ]
monkeypatch.setattr(pipeline, "PDFDocument", Document)
monkeypatch.setattr(pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=get_model))
@@ -61,3 +66,38 @@ def test_flash_routes_classification_and_native_analysis_explicitly(
assert observed[0]["parse_mode"] == ("txt" if native else "ocr")
assert result.parse_mode == ("txt" if native else "ocr")
assert calls[-1] == "close"
+ assert result.model_list[0][0]["content"] == [{"type": "text", "content": "A1"}]
+ assert result.model_list[0][1]["content"] == "<table><tr><td>B2</td></tr></table>"
+
+
[email protected]("effort", ["medium", "high", "xhigh"])
[email protected]("parse_mode", ["txt", "ocr"])
+def test_hybrid_and_vlm_pdf_outputs_share_docgale_text_cleanup(
+ monkeypatch: pytest.MonkeyPatch,
+ effort: str,
+ parse_mode: str,
+) -> None:
+ """推理和原生回填的编排留在宿主,所有非 Flash PDF 出口都使用相同文字清洗。"""
+ # 只隔离模型推理,真实执行 PDF 管线的公共出口与协议规范化。
+ monkeypatch.setattr(pipeline, "PDFDocument", lambda _data: SimpleNamespace(close=lambda: None))
+ monkeypatch.setattr(
+ pipeline, "HybridLocalModelContextSingleton", lambda: SimpleNamespace(get_model=lambda: SimpleNamespace(device="cpu"))
+ )
+ monkeypatch.setattr(pipeline, "get_vlm_predictor", lambda _config: (object(), "test"))
+ monkeypatch.setattr(pipeline, "clean_memory", lambda _device: None)
+
+ def process(_data: bytes, _document: object, **options: object) -> list[list[dict[str, object]]]:
+ """模拟文字回填后的页,确认非原生路由不会被本次清洗切换。"""
+ assert options["flash_txt_mode"] is False
+ return [
+ [
+ {"type": "text", "content": "A1", "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}]},
+ {"type": "table", "content": "<table><tr><td>B2<eq>C3</eq></td></tr></table>"},
+ ]
+ ]
+
+ monkeypatch.setattr(pipeline, "process_pdf_windows", process)
+ result = pipeline.analyze_pdf(b"pdf", effort=effort, parse_mode=parse_mode)
+ assert result.effort == effort and result.parse_mode == parse_mode
+ assert result.model_list[0][0]["content"] == [{"type": "text", "content": "A1"}]
+ assert result.model_list[0][1]["content"] == "<table><tr><td>B2<eq>C3</eq></td></tr></table>"
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index abac518e..1aff4156 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -606,139 +606,6 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
assert all("angle" not in block and "score" not in block for page_model_list in model_list for block in page_model_list)
- "block_type",
- [
- BlockType.TEXT,
- BlockType.DOC_TITLE,
- BlockType.PARAGRAPH_TITLE,
- BlockType.ASIDE_TEXT,
- BlockType.HEADER,
- BlockType.FOOTER,
- BlockType.PAGE_NUMBER,
- BlockType.PAGE_FOOTNOTE,
- BlockType.REF_TEXT,
- BlockType.LIST,
- BlockType.INDEX,
- RAW_CAPTION,
- RAW_FOOTNOTE,
- RAW_PHONETIC,
- ],
-)
-def test_normalize_pdf_model_list_converts_full_width_alphanumeric_for_textual_blocks(
- block_type: str,
-) -> None:
- """验证 PDF 自然语言块统一转换全角字母和数字,同时保留全角标点。"""
- model_list = [
- [
- {
- "type": block_type,
- "content": "Az0,。!?()",
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ]
- ]
-
- normalization._normalize_pdf_model_list(model_list)
-
- assert inline_text(model_list[0][0]["content"]) == "Az0,。!?()"
- expected_type = BlockType.TEXT if block_type == RAW_PHONETIC else block_type
- assert model_list[0][0]["type"] == expected_type
-
-
-def test_normalize_pdf_model_list_preserves_inline_formulas_and_tag_literals_during_full_width_cleanup() -> None:
- """验证圆括号公式不参与全角转换,标签外观原文仍作为普通 TextSpan 清洗。"""
- model_list = [
- [
- {
- "type": BlockType.TEXT,
- "content": "前A1 \\(F2+x\\) 中B3 <eq>C4+y</eq> 后D5",
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ]
- ]
-
- normalization._normalize_pdf_model_list(model_list)
-
- content = model_list[0][0]["content"]
- assert inline_text(content) == "前A1 F2+x 中B3 <eq>C4+y</eq> 后D5"
- assert [span["content"] for span in content if span.get("type") == "equation_inline"] == ["F2+x"]
-
-
-def test_normalize_pdf_model_list_preserves_hyperlink_url_payload() -> None:
- """验证已有 HyperlinkSpan 的可见文字正常清洗,而 URL 与公式内容保持原样。"""
-
- model_list = [
- [
- {
- "type": BlockType.TEXT,
- "content": [
- *inline("前A "),
- hyperlink("https://example.test/A\\(x\\)?q=1&amp;y=2", "标B"),
- *inline(" 后C "),
- equation("D"),
- ],
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ]
- ]
-
- normalization._normalize_pdf_model_list(model_list)
-
- content = model_list[0][0]["content"]
- assert inline_text(content) == "前A 标B 后C D"
- assert inline_urls(content) == ["https://example.test/A\\(x\\)?q=1&amp;y=2"]
- assert next(span for span in inline_items(content) if span.get("type") == "equation_inline")["content"] == "D"
-
-
- ("content", "expected"),
- [
- ("前A1 \\(F2 后B3", "前A1 \\(F2 后B3"),
- ("前A1 <eq>F2 后B3", "前A1 <eq>F2 后B3"),
- ],
-)
-def test_normalize_pdf_model_list_preserves_content_after_unclosed_inline_formula(
- content: str,
- expected: str,
-) -> None:
- """验证未闭合公式从起始符到文本末尾均保持原样,避免误清洗公式内容。"""
- model_list = [
- [
- {
- "type": BlockType.TEXT,
- "content": content,
- "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
- }
- ]
- ]
-
- normalization._normalize_pdf_model_list(model_list)
-
- assert inline_text(model_list[0][0]["content"]) == expected
-
-
- "block_type",
- [
- BlockType.TABLE,
- BlockType.CODE,
- RAW_ALGORITHM,
- BlockType.EQUATION,
- BlockType.IMAGE,
- BlockType.CHART,
- "unknown",
- ],
-)
-def test_normalize_pdf_model_list_skips_non_natural_language_content(block_type: str) -> None:
- """验证表格、代码、公式、视觉主体和未知类型不执行自然语言全角清洗。"""
- model_list = [[{"type": block_type, "content": "Az0,。!?()"}]]
-
- normalization._normalize_pdf_model_list(model_list)
-
- assert model_list[0][0]["content"] == "Az0,。!?()"
-
-
def test_normalize_pdf_model_list_converts_phonetic_and_cleans_equation() -> None:
"""验证 phonetic 转公开类型,同时 equation 保持类型并清理展示分隔符。"""
model_list = [
@@ -1941,3 +1808,32 @@ def test_doc_analyze_flash_returns_complete_model_json_and_typed_middle_json(mon
"document_close",
]
assert not hasattr(analyze, "append_pages")
+
+
+def test_pdf_output_delegates_text_cleanup_after_span_and_metadata_processing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """宿主只负责协议清理和 Span 构造,可见英数统一交给 DocGale。"""
+ original = normalization.normalize_pdf_model_text
+ calls = []
+
+ def normalize(pages: list[list[dict[str, object]]]) -> None:
+ """在实际委托边界核对原始全角文字尚在、元数据已清理且公式已成为 Span。"""
+ calls.append(pages)
+ assert pages[0][0]["type"] == BlockType.TEXT
+ assert "angle" not in pages[0][0]
+ assert [span["type"] for span in pages[0][0]["content"]] == ["text", "equation_inline"]
+ assert pages[0][0]["content"][0]["content"] == "A1 "
+ original(pages)
+
+ monkeypatch.setattr(normalization, "normalize_pdf_model_text", normalize)
+ pages = [
+ [
+ {"type": RAW_PHONETIC, "content": r"A1 \(B2\)", "angle": 90, "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}]},
+ {"type": BlockType.TABLE, "content": "<table><tr><td>C3<eq>D4</eq></td></tr></table>"},
+ {"type": RAW_ALGORITHM, "content": [{"type": "text", "content": "E5"}]},
+ ]
+ ]
+ normalization._normalize_pdf_model_list(pages)
+ assert len(calls) == 1 and calls[0] is pages
+ assert inline_text(pages[0][0]["content"]) == "A1 B2"
+ assert pages[0][1]["content"] == "<table><tr><td>C3<eq>D4</eq></td></tr></table>"
+ assert pages[0][2]["content"] == [{"type": "text", "content": "E5"}]