Skip to content

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

feat: enhance PDF text normalization by adding Unicode space handling and refining control character sanitization

myhloli7fa1be689558
diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.py
index 68b6d134..9d7ddad3 100644
--- a/mineru/backend/flash/native_pdf/native_text.py
+++ b/mineru/backend/flash/native_pdf/native_text.py
@@ -29,7 +29,26 @@ from .geometry import (
)
-_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
+_PDF_CONTROL_CHAR_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
+_PDF_LINE_END_SOFT_HYPHEN_RE = re.compile(
+ r"(?<=[A-Za-z])[\x02\u00ad](?=[\t ]*(?:\n|$))"
+)
+# Unicode Zs 空格在 model_list 中只承担分词作用,统一成可互操作的 ASCII 空格。
+_PDF_SEPARATOR_SPACE_CHARS = (
+ "\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006"
+ "\u2007\u2008\u2009\u200a\u202f\u205f\u3000"
+)
+_PDF_UNICODE_TEXT_TRANSLATION = str.maketrans(
+ {
+ **dict.fromkeys(_PDF_SEPARATOR_SPACE_CHARS, " "),
+ "\u0085": "\n",
+ "\u2028": "\n",
+ "\u2029": "\n",
+ "\u200b": None,
+ "\u2060": None,
+ "\ufeff": None,
+ }
+)
_PDFTEXT_ROTATION_SPLIT_THRESHOLD_DEGREES = 44.9
_PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES = 0.1
_SUPPORTED_PDFTEXT_LINE_ANGLES = (0.0, 90.0, 270.0)
@@ -358,18 +377,18 @@ def _split_native_visual_runs(
def _normalize_native_run_text(text: str) -> str:
"""清理原生 run 文本,并把字母后的 PDF 软断词标记转换成 ASCII hyphen。"""
- normalized = text.replace("\r\n", "\n").replace("\r", "\n")
- normalized = re.sub(r"(?<=[A-Za-z])\x02(?=\s*$)", "-", normalized)
- normalized = _sanitize_pdf_control_text(normalized, preserve_newlines=False)
+ normalized = _sanitize_pdf_control_text(text, preserve_newlines=False)
normalized = re.sub(r"[\t\f\v ]+", " ", normalized)
return normalized.strip()
def _sanitize_pdf_control_text(text: str, *, preserve_newlines: bool) -> str:
- """删除 PDF 字体编码残留控制字符,并按调用场景决定是否保留物理换行。"""
+ """规范 PDF 排版空白与控制字符,并按调用场景决定是否保留物理换行。"""
normalized = str(text or "").replace("\r\n", "\n").replace("\r", "\n")
- normalized = re.sub(r"(?<=[A-Za-z])\x02(?=[\t ]*(?:\n|$))", "-", normalized)
+ normalized = normalized.translate(_PDF_UNICODE_TEXT_TRANSLATION)
+ normalized = _PDF_LINE_END_SOFT_HYPHEN_RE.sub("-", normalized)
+ normalized = normalized.replace("\u00ad", "")
normalized = normalized.replace("\t", " ")
if not preserve_newlines:
normalized = normalized.replace("\n", "")
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 427f2da0..7c57cb12 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -82,7 +82,7 @@ if __name__ == '__main__':
if __name__ == "__main__":
# pdf_path = "/Users/myhloli/pdf/截断合并/demo1-3.pdf"
# pdf_path = "/Users/myhloli/pdf/png/seal4.png" # shubiao.png
- pdf_path = "/Users/myhloli/pdf/基于Boosting、Bagging、Stacking与Voting四大集成学习模型的粉质砂土冻土抗剪强度预测研究.pdf"
+ pdf_path = "/Users/myhloli/projects/20240809magic_pdf/Magic-PDF/demo/pdfs/demo4.pdf"
pdf_bytes = read_fn(pdf_path)
model_list = doc_analyze(pdf_bytes, parse_mode="auto")
logger.info(f"model_list: {model_list}")
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
index d15cf657..f2d66ac5 100644
--- a/tests/unittest/test_flash_pdf_native_text.py
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -171,3 +171,84 @@ def test_only_supported_visual_line_directions_are_retained(
)
assert [item.angle for item in items] == ([] if expected_angle is None else [expected_angle])
+
+
+ "separator",
+ [
+ "\u00a0",
+ "\u1680",
+ "\u2000",
+ "\u2001",
+ "\u2002",
+ "\u2003",
+ "\u2004",
+ "\u2005",
+ "\u2006",
+ "\u2007",
+ "\u2008",
+ "\u2009",
+ "\u200a",
+ "\u202f",
+ "\u205f",
+ "\u3000",
+ ],
+)
+def test_pdf_unicode_separator_spaces_are_normalized_to_ascii(separator: str) -> None:
+ """验证所有 Unicode Zs 排版空格均转换为普通 ASCII 空格。"""
+
+ assert native_text._sanitize_pdf_control_text(
+ f"left{separator}right",
+ preserve_newlines=True,
+ ) == "left right"
+
+
+def test_pdf_unicode_line_separators_follow_newline_policy() -> None:
+ """验证 NEXT LINE、行分隔符和段分隔符统一遵循物理换行保留策略。"""
+
+ content = "first\u0085second\u2028third\u2029fourth"
+
+ assert native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=True,
+ ) == "first\nsecond\nthird\nfourth"
+ assert native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=False,
+ ) == "firstsecondthirdfourth"
+
+
+def test_pdf_safe_invisible_and_control_characters_are_removed_idempotently() -> None:
+ """验证无正文语义的零宽字符和 C0/C1 控制字符被稳定删除。"""
+
+ content = "A\u200bB\u2060C\ufeffD\x00E\x07F\x7fG\x80H\x9fI"
+ normalized = native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=True,
+ )
+
+ assert normalized == "ABCDEFGHI"
+ assert native_text._sanitize_pdf_control_text(
+ normalized,
+ preserve_newlines=True,
+ ) == normalized
+
+
+def test_pdf_soft_hyphens_keep_only_latin_line_end_breaks() -> None:
+ """验证两类 PDF 软断词仅在拉丁字母行末转成 ASCII hyphen。"""
+
+ assert native_text._normalize_native_run_text("inter\u00ad") == "inter-"
+ assert native_text._normalize_native_run_text("co\u00adoperate") == "cooperate"
+ assert native_text._normalize_native_run_text("word\x02") == "word-"
+ assert native_text._normalize_native_run_text("A\x02B") == "AB"
+
+
+def test_pdf_semantic_joiners_and_decode_markers_are_preserved() -> None:
+ """验证语言连接符、私用区字形和解码占位符不会被通用清理静默删除。"""
+
+ content = "a\u200cb\u200dc\uf8f1d\ufffde"
+
+ assert native_text._sanitize_pdf_control_text(
+ content,
+ preserve_newlines=True,
+ ) == content
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index 4b3d5457..8f0a3bca 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -302,6 +302,23 @@ def test_output_normalization_keeps_empty_equation_but_drops_empty_text() -> Non
assert text is None
+def test_output_normalization_applies_unicode_content_safety_net() -> None:
+ """验证最终 model_list 归一化会兜底清理排版空格和安全零宽字符。"""
+
+ block = pipeline._normalize_output_block(
+ {
+ "type": "text",
+ "bbox": (10.0, 20.0, 40.0, 50.0),
+ "angle": 0,
+ "content": "alpha\u00a0beta\u200bgamma",
+ },
+ (100.0, 100.0),
+ )
+
+ assert block is not None
+ assert block["content"] == "alpha betagamma"
+
+
def test_index_is_claimed_before_formula_anchor_growth() -> None:
"""验证目录右缘页码先形成完整 index,不再扩张为重叠公式。"""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index e83e39f2..873aff7c 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from collections import Counter
from pathlib import Path
from typing import Any
+import unicodedata
from mineru.backend.flash import pdf_extractor
@@ -83,6 +84,20 @@ def _normalized_content_probe(text: str) -> str:
return "".join(char.casefold() for char in text if char.isalnum())
+def _unsafe_flash_content_characters(text: str) -> list[str]:
+ """返回 Flash content 中不应跨接口保留的排版空白与控制字符。"""
+
+ return [
+ char
+ for char in text
+ if (
+ (unicodedata.category(char).startswith("Z") and char != " ")
+ or (unicodedata.category(char) == "Cc" and char != "\n")
+ or char in {"\u00ad", "\u200b", "\u2060", "\ufeff"}
+ )
+ ]
+
+
def _blocks_containing(
blocks: list[dict[str, Any]],
probe: str,
@@ -107,6 +122,7 @@ def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:
)
inventory: Counter[str] = Counter()
page_count = 0
+ unsafe_content: list[tuple[str, int, int, list[str]]] = []
for pdf_name in pdf_names:
model_list = _txt_model_list(pdf_name)
page_count += len(model_list)
@@ -115,10 +131,21 @@ def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:
for page in model_list
for block in page
)
+ unsafe_content.extend(
+ (pdf_name, page_index, block_index, unsafe_chars)
+ for page_index, page in enumerate(model_list)
+ for block_index, block in enumerate(page)
+ if (
+ unsafe_chars := _unsafe_flash_content_characters(
+ str(block.get("content", ""))
+ )
+ )
+ )
assert len(pdf_names) == 15
assert page_count == 218
assert sum(inventory.values()) == 2591
+ assert unsafe_content == []
assert inventory == Counter(
{
"text": 896,
@@ -899,6 +926,11 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
assert next(
block for block in page1 if block["content"] == "ORIGINAL ARTICLE"
)["type"] == "text"
+ author_line = _blocks_containing(page1, "Rucha Ronghe1")[0]
+ assert author_line["content"] == (
+ "Rucha Ronghe1 · Teresa Crespo Gonzalez2 · Catriona Wimberley3,4,5 "
+ "· Karla Suchacki3,6 · Adriana A. S. Tavares3,4"
+ )
assert _blocks_containing(page1, "contributed equally")[0]["type"] == "page_footnote"
assert _blocks_containing(page1, "University of Edinburgh")[0]["type"] == "page_footnote"
assert [
@@ -1087,6 +1119,8 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
assert "103389fimmu20231222129" in _normalized_content_probe(
str(reference48["content"])
)
+ assert "\u200b" not in str(reference48["content"])
+ assert "fimmu.2023.1222129" in str(reference48["content"])
def test_demo5_targeted_table_and_footer_regressions() -> None: