Skip to content

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

feat(pdf): implement code span spacing protection and update tight spacing logic

myhlolif712c9fd7b42
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 4fb1ca6b..570c6172 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -181,6 +181,23 @@ def _get_page_table_regions(
return regions
+def _protect_code_span_spacing(spans: list[_AnalyzeSpan], blocks: list[dict[str, Any]], page_size: tuple[float, float]) -> None:
+ """在整页虚拟文本块回填之前保留实际代码区域,避免新增词界改写代码。"""
+ regions = [
+ region
+ for block in blocks
+ if block.get("type") in CODE_CONTENT_BLOCK_TYPES
+ and (region := _sidecar_bbox_to_page_bbox(block.get("bbox"), page_size, 1.0)) is not None
+ ]
+ if not regions:
+ return
+ for span in spans:
+ cx = (span.bbox[0] + span.bbox[2]) / 2
+ cy = (span.bbox[1] + span.bbox[3]) / 2
+ if any(x0 <= cx <= x1 and y0 <= cy <= y1 for x0, y0, x1, y1 in regions):
+ span.metadata["_native_tight_spacing"] = False
+
+
def _fill_native_pdf_text_spans(
pdf_page: PDFPage,
page_spans: list[_AnalyzeSpan],
@@ -422,6 +439,7 @@ def _fill_window_block_content_and_lines(
)
evidence = PDFTextEvidence(page_size)
if parse_mode == "txt":
+ _protect_code_span_spacing(page_spans, page_model_list, page_size)
native_text_owner = None
page_text_geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
try:
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 9a7b13d6..ed763ed9 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -13,6 +13,7 @@ from typing import Any, Callable, cast
import cv2
import numpy as np
from docvortex.analyzers.pdf import PDF_NATIVE_SCRIPT_MARKUP_KEY, ScriptRole, classify_char_script_roles
+from docvortex.analyzers.pdf import join_tight_text, needs_tight_space
from docvortex.assets import calculate_contrast
from docvortex.document.pdf import Char, PDFPage, get_lines_from_chars
from docvortex.geometry import calculate_overlap_area_in_bbox1_area_ratio
@@ -149,6 +150,8 @@ def txt_spans_extract(
if block[7] in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.EQUATION]:
continue
if calculate_overlap_area_in_bbox1_area_ratio(span.bbox, block[0:4]) > 0.5:
+ # 新增几何词界只服务普通文字,不改变代码内容。
+ span.metadata.setdefault("_native_tight_spacing", block[7] not in {BlockType.CODE, "algorithm"})
if (
span.metadata["height"] > median_span_height * 2.3
and span.metadata["height"] > span.metadata["width"] * 2.3
@@ -166,8 +169,12 @@ def txt_spans_extract(
for pdf_line in pdf_lines:
for span in vertical_spans:
if calculate_overlap_area_in_bbox1_area_ratio(pdf_line["bbox"].bbox, span.bbox) > 0.5:
- for pdf_span in pdf_line["spans"]:
- span.content += pdf_span["text"]
+ line_chars = [char for part in pdf_line["spans"] for char in part.get("chars", [])]
+ if line_chars and span.metadata.get("_native_tight_spacing", True):
+ span.content += join_tight_text(line_chars, tight_bboxes=tight_bboxes, origins=origins)
+ else:
+ for pdf_span in pdf_line["spans"]:
+ span.content += pdf_span["text"]
break
for span in vertical_spans:
@@ -558,6 +565,7 @@ def _owned_span_texts(owner: Any, spans: list[_AnalyzeSpan], median_height: floa
if detect_scripts or not callable(getattr(owner, "prepare_span_texts", None)):
return None
functions = (
+ needs_tight_space,
chars_to_content,
__replace_unicode,
__replace_ligatures,
@@ -598,6 +606,7 @@ def _owned_span_texts(owner: Any, spans: list[_AnalyzeSpan], median_height: floa
_SPACING_DIACRITIC_TO_COMBINING,
threshold,
(PRIVATE_USE_AREA_START, PRIVATE_USE_AREA_END),
+ [span.metadata.get("_native_tight_spacing", True) for span in spans],
)
@@ -1087,7 +1096,14 @@ def chars_to_content(
role_text_parts.append((role1, char1["char"]))
if (
char2
- and char2["bbox"][0] - char1["bbox"][2] > median_width * 0.25
+ and (
+ char2["bbox"][0] - char1["bbox"][2] > median_width * 0.25
+ or (
+ span.metadata.get("_native_tight_spacing", True)
+ and role1 == role2 == "body"
+ and needs_tight_space(char1, char2, tight_bboxes=tight_bboxes, origins=origins)
+ )
+ )
and char1["char"] != " "
and char2["char"] != " "
):
@@ -1106,6 +1122,7 @@ def chars_to_content(
# 仅原有内置规则启用整段原生化,替换后的函数保留参考调用及异常语义。
_STANDARD_CONTENT_FUNCTIONS = (
+ needs_tight_space,
chars_to_content,
__replace_unicode,
__replace_ligatures,
diff --git a/pyproject.toml b/pyproject.toml
index 4876e97d..bb63c8a6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,7 +39,7 @@ classifiers = [
"Programming Language :: Python :: 3.14",
]
dependencies = [
- "docvortex>=0.5.2,<1",
+ "docvortex>=0.5.3,<1",
"gradio>=6.8,<7",
"mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'",
"mineru-vl-utils>=2.0.5,<3",
diff --git a/tests/unittest/test_pdf_tight_spacing.py b/tests/unittest/test_pdf_tight_spacing.py
new file mode 100644
index 00000000..a4b9d5f3
--- /dev/null
+++ b/tests/unittest/test_pdf_tight_spacing.py
@@ -0,0 +1,144 @@
+"""验证普通、旋转及 Rust 原生回填共用非 CJK 墨迹词界规则。"""
+
+from copy import deepcopy
+from pathlib import Path
+from typing import Any
+
+import pytest
+from docvortex.document.pdf import PDFDocument
+from docvortex.document.pdf.text._contracts import Bbox
+from mineru.backend.analysis.pdf.text import native
+from mineru.backend.analysis.pdf.text.models import _AnalyzeSpan
+from mineru.types import ContentType
+
+
+def _char(text: str, index: int, x: float) -> dict[str, Any]:
+ """构造短英文或 CJK 字符,故意使 loose 框覆盖真实留白。"""
+ return {
+ "char": text,
+ "char_idx": index,
+ "bbox": Bbox([x, 0, x + 10, 10]),
+ "tight_bbox": (x, 1, x + 4, 9),
+ "origin": (x, 10),
+ "writing_angle": 0.0,
+ "rotation": 0.0,
+ "font": {"name": "Fixture", "size": 10.0, "flags": 0, "weight": 400},
+ }
+
+
[email protected]("text, expected", [("AIML", "AI ML"), ("中文", "中文"), ("中A", "中A"), ("A文", "A文")])
+def test_short_span_needs_no_reference_samples(text: str, expected: str) -> None:
+ """无需同行参考样本即可补短英文,CJK 边界保持旧输出。"""
+ positions = [0, 5, 13, 18] if len(text) == 4 else [0, 8]
+ chars = [_char(char, index, positions[index]) for index, char in enumerate(text)]
+ span = _AnalyzeSpan(ContentType.TEXT, (0, 0, 40, 10), metadata={"chars": chars})
+ native.chars_to_content(span, detect_scripts=False)
+ assert span.content == expected
+
+
+def test_code_span_keeps_old_content() -> None:
+ """被代码块认领的 span 不启用新增墨迹词界。"""
+ span = _AnalyzeSpan(
+ ContentType.TEXT,
+ (0, 0, 30, 10),
+ metadata={"chars": [_char("A", 0, 0), _char("B", 1, 8)], "_native_tight_spacing": False},
+ )
+ native.chars_to_content(span, detect_scripts=False)
+ assert span.content == "AB"
+
+
+def test_virtual_page_fill_keeps_actual_code_region() -> None:
+ """实际页面代码区域的禁用标记不会被虚拟整页文本框覆盖。"""
+ from mineru.backend.analysis.pdf.text.content import _protect_code_span_spacing
+ from mineru.types import BlockType
+ from unittest.mock import Mock
+
+ chars = [_char("A", 0, 0), _char("B", 1, 8)]
+ span = _AnalyzeSpan(ContentType.TEXT, (0, 0, 30, 10))
+ _protect_code_span_spacing([span], [{"type": BlockType.CODE, "bbox": (0, 0, 0.5, 0.5)}], (100, 100))
+ page = Mock()
+ page.get_char_count.return_value = 2
+ native.txt_spans_extract(
+ page,
+ [span],
+ None,
+ 1.0,
+ [(0, 0, 100, 100, None, None, None, BlockType.TEXT)],
+ [],
+ page_chars=chars,
+ detect_scripts=False,
+ )
+ assert span.content == "AB"
+ assert span.metadata["_native_tight_spacing"] is False
+
+
+def test_vertical_line_fill_uses_tight_spacing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """强制命中竖向 line/span 回填分支,验证没有绕过共享词界规则。"""
+ import math
+ from unittest.mock import Mock
+ from PIL import Image
+ from mineru.types import BlockType
+
+ chars = [_char("A", 0, 0), _char("B", 1, 8)]
+ for char, y in zip(chars, [0, 8]):
+ char.update(
+ bbox=Bbox([40, y, 50, y + 10]),
+ tight_bbox=(41, y, 49, y + 4),
+ origin=(40, y),
+ rotation=math.pi / 2,
+ writing_angle=math.pi / 2,
+ )
+ line = {"rotation": math.pi / 2, "bbox": Bbox([40, 0, 50, 30]), "spans": [{"text": "AB", "chars": chars}]}
+ monkeypatch.setattr(native, "get_lines_from_chars", Mock(return_value=[line]))
+ page = Mock()
+ page.get_char_count.return_value = 2
+ target = _AnalyzeSpan(ContentType.TEXT, (40, 0, 50, 30))
+ spans = [target, _AnalyzeSpan(ContentType.TEXT, (60, 60, 80, 68)), _AnalyzeSpan(ContentType.TEXT, (60, 80, 80, 88))]
+ with Image.new("RGB", (100, 100), "white") as image:
+ native.txt_spans_extract(
+ page,
+ spans,
+ image,
+ 1.0,
+ [(0, 0, 100, 100, None, None, None, BlockType.TEXT)],
+ [],
+ page_chars=chars,
+ detect_scripts=False,
+ )
+ assert target.content == "A B"
+
+
[email protected]("enabled", [True, False])
+def test_real_snapshot_content_matches_python(enabled: bool) -> None:
+ """真实论文逐字符验证 Rust 物化与 Python 回退一致,且确实执行 Rust 内容快路径。"""
+ from docvortex._compute_backend import get_native
+
+ extension = get_native()
+ if extension is None:
+ pytest.skip("requires native extension")
+ path = Path(__file__).resolve().parents[3] / "docvortex/demo/pdfs/中文论文2.pdf"
+ with PDFDocument(path.read_bytes()) as document:
+ owner = document[0].get_text_snapshot()
+ width, height = document[0].size
+ geometry = owner.materialize_geometry()
+ results = []
+ before = extension.text_snapshot_stats()[2]
+ for current_owner in (None, owner):
+ span = _AnalyzeSpan(
+ ContentType.TEXT,
+ (0.0, 0.0, width, height),
+ metadata={"chars": [], "height": height, "width": width, "_native_tight_spacing": enabled},
+ )
+ native.fill_char_in_spans(
+ [span],
+ deepcopy(geometry.chars),
+ 10.0,
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ detect_scripts=False,
+ _native_text=current_owner,
+ )
+ results.append(span.content)
+ assert extension.text_snapshot_stats()[2] == before + 1
+ assert results[0] == results[1]
+ assert ("Large Language Models" in results[0]) is enabled