Skip to content

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

perf: consume native span assignments in shared PDF text filling

myhloli646f53508c95
diff --git a/.github/workflows/docvortex-boundary.yml b/.github/workflows/docvortex-boundary.yml
index 13b7ea3f..6f88d2d2 100644
--- a/.github/workflows/docvortex-boundary.yml
+++ b/.github/workflows/docvortex-boundary.yml
@@ -167,7 +167,7 @@ jobs:
assert any(path.is_relative_to(root) for root in site_roots), (name, path, site_roots)
info = backend_info()
assert info["backend"] == "rust", info
- assert native.PROTOCOL_VERSION >= 12 and info["protocol"] == native.PROTOCOL_VERSION, info
+ assert native.PROTOCOL_VERSION >= 13 and info["protocol"] == native.PROTOCOL_VERSION, info
assert info["extension_sha256"] == hashlib.sha256(origins["native"].read_bytes()).hexdigest(), info
artifact = json.loads(Path(".boundary/engine-artifact.json").read_text(encoding="utf-8"))
distribution = importlib.metadata.distribution("docvortex")
@@ -257,6 +257,7 @@ jobs:
tests/unittest/test_pdf_memory_lifecycle.py \
tests/unittest/test_pdf_render_session_integration.py \
tests/unittest/test_pdf_window_snapshots.py \
+ tests/unittest/test_native_span_assignment.py \
tests/unittest/test_flash_pdf_render_scheduling.py \
tests/unittest/test_process_heap_memory.py
- name: Retain exact wheel and installation evidence
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 175c2ed1..4fb1ca6b 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -190,6 +190,7 @@ def _fill_native_pdf_text_spans(
*,
page_text_geometry: PDFPageTextGeometry | None = None,
detect_scripts: bool = True,
+ _native_text: Any = None,
) -> list[_AnalyzeSpan]:
"""复用原生 PDF 字符回填逻辑,并允许共享同页删除线检测读取的字符。"""
page_width, page_height = page_size
@@ -205,6 +206,7 @@ def _fill_native_pdf_text_spans(
tight_bboxes=page_text_geometry.tight_bboxes if page_text_geometry is not None else None,
origins=page_text_geometry.origins if page_text_geometry is not None else None,
detect_scripts=detect_scripts,
+ **({"_native_text": _native_text} if _native_text is not None else {}),
)
@@ -420,6 +422,7 @@ def _fill_window_block_content_and_lines(
)
evidence = PDFTextEvidence(page_size)
if parse_mode == "txt":
+ native_text_owner = None
page_text_geometry = page_text_geometries[page_idx] if page_text_geometries is not None else None
try:
page_char_count = pdf_page.get_char_count()
@@ -439,6 +442,10 @@ def _fill_window_block_content_and_lines(
vector_geometry=vector_geometry,
)
if snapshot_entry is not None:
+ if callable(getattr(snapshot_entry.text_owner, "assign_spans", None)) and callable(
+ getattr(snapshot_entry.text_owner, "supports_span_matching", None)
+ ):
+ native_text_owner = snapshot_entry.text_owner
evidence = prepare_text_evidence(
pdf_page,
snapshot=snapshot_entry.get_full_snapshot(pdf_page),
@@ -464,6 +471,7 @@ def _fill_window_block_content_and_lines(
page_size,
page_text_geometry=page_text_geometry,
detect_scripts=not use_shared_script_sidecar,
+ **({"_native_text": native_text_owner} if native_text_owner is not None else {}),
)
# 后续只消费已物化证据;逐页释放 Rust owner,避免与窗口 Python 几何长期双份驻留。
if page_snapshots is not None:
diff --git a/mineru/backend/analysis/pdf/text/native.py b/mineru/backend/analysis/pdf/text/native.py
index 429ac55b..0134a0c2 100644
--- a/mineru/backend/analysis/pdf/text/native.py
+++ b/mineru/backend/analysis/pdf/text/native.py
@@ -81,6 +81,7 @@ def txt_spans_extract(
tight_bboxes: dict[int, BBox] | None = None,
origins: dict[int, tuple[float, float]] | None = None,
detect_scripts: bool = True,
+ _native_text: Any = None,
) -> list[_AnalyzeSpan]:
"""从 PDF 原生字符中提取文本 Span,并允许复用调用方已读取的页面字符。"""
page_char_count = None
@@ -110,10 +111,20 @@ def txt_spans_extract(
base_lines = get_lines_from_chars(page_chars)
return base_lines
- page_all_chars = _get_chars_for_span_fill(
- page_chars,
- line_provider=get_page_lines if type(page_chars) is list else None,
- )
+ # 仅窗口内部刚从同一快照得到的 geometry 可走该通道;显式外部几何不提供 owner。
+ if (
+ _native_text is not None
+ and type(page_chars) is list
+ and len(page_chars) == _native_text.info()[0]
+ and _native_text.supports_span_matching()
+ ):
+ page_all_chars = page_chars
+ else:
+ _native_text = None
+ page_all_chars = _get_chars_for_span_fill(
+ page_chars,
+ line_provider=get_page_lines if type(page_chars) is list else None,
+ )
# 计算所有span的高度的中位数
span_height_list = []
@@ -178,6 +189,7 @@ def txt_spans_extract(
tight_bboxes=tight_bboxes,
origins=origins,
detect_scripts=detect_scripts,
+ **({"_native_text": _native_text} if _native_text is not None else {}),
)
return _prepare_post_ocr_spans(need_ocr_spans, spans, pil_img, scale)
@@ -504,6 +516,32 @@ def _bridge_unassigned_punctuation(
assigned_span_indices[char_position] = previous_owner
+def _owned_span_assignments(owner: Any, spans: list[_AnalyzeSpan], median_height: float):
+ """内部同源快照直接匹配字符;特殊可执行值和替换后的规则保留原 Python 语义。"""
+ if owner is None or calculate_char_in_span is not _STANDARD_CHAR_IN_SPAN:
+ return None
+ defaults = calculate_char_in_span.__defaults__
+ if type(defaults) is not tuple or len(defaults) != 1:
+ return None
+ ratio = defaults[0]
+ values = [median_height, ratio]
+ boxes = []
+ for span in spans:
+ box = span.bbox
+ if type(box) not in (tuple, list) or len(box) != 4:
+ return None
+ boxes.append(box)
+ values.extend(box)
+ if any(type(value) not in (int, float) or not -(2**52) <= value <= 2**52 or not math.isfinite(value) for value in values):
+ return None
+ if any(
+ type(flags) not in (tuple, list) or any(type(flag) is not str for flag in flags)
+ for flags in (LINE_STOP_FLAG, LINE_START_FLAG)
+ ):
+ return None
+ return owner.assign_spans(boxes, median_height, LINE_STOP_FLAG, LINE_START_FLAG, ratio)
+
+
def fill_char_in_spans(
spans: list[_AnalyzeSpan],
all_chars: list[Char],
@@ -512,102 +550,107 @@ def fill_char_in_spans(
tight_bboxes: dict[int, BBox] | None = None,
origins: dict[int, tuple[float, float]] | None = None,
detect_scripts: bool = True,
+ _native_text: Any = None,
) -> list[_AnalyzeSpan]:
"""以 tight-first、loose-fallback 将字符分配到 Span,并返回待 OCR Span。"""
spans = sorted(spans, key=lambda x: x.bbox[1])
tight_bboxes = tight_bboxes or {}
origins = origins or {}
- grid_size = max(1, median_span_height)
- grid = collections.defaultdict(list)
- span_bboxes = []
- for span_index, span in enumerate(spans):
- span_bbox = span.bbox
- span_bboxes.append(span_bbox)
- start_cell = int(span_bbox[1] / grid_size)
- end_cell = int(span_bbox[3] / grid_size)
- for cell_idx in range(start_cell, end_cell + 1):
- grid[cell_idx].append(span_index)
-
- assigned_span_indices: list[int | None] = [None] * len(all_chars)
- for char_position, char in enumerate(all_chars):
- char_idx = _char_geometry_key(char)
- tight_bbox = _coerce_finite_bbox(tight_bboxes.get(char_idx)) if char_idx is not None else None
- loose_bbox = _coerce_finite_bbox(char.get("bbox"))
- char_text = str(char.get("char", ""))
- if char_text.isspace():
- continue
- for candidate_bbox in (tight_bbox, loose_bbox):
- if candidate_bbox is None:
+ assigned_span_indices = _owned_span_assignments(_native_text, spans, median_span_height)
+ if assigned_span_indices is not None and len(assigned_span_indices) != len(all_chars):
+ raise RuntimeError("Native span assignments do not match the owned character sequence")
+ if assigned_span_indices is None:
+ grid_size = max(1, median_span_height)
+ grid = collections.defaultdict(list)
+ span_bboxes = []
+ for span_index, span in enumerate(spans):
+ span_bbox = span.bbox
+ span_bboxes.append(span_bbox)
+ start_cell = int(span_bbox[1] / grid_size)
+ end_cell = int(span_bbox[3] / grid_size)
+ for cell_idx in range(start_cell, end_cell + 1):
+ grid[cell_idx].append(span_index)
+
+ assigned_span_indices: list[int | None] = [None] * len(all_chars)
+ for char_position, char in enumerate(all_chars):
+ char_idx = _char_geometry_key(char)
+ tight_bbox = _coerce_finite_bbox(tight_bboxes.get(char_idx)) if char_idx is not None else None
+ loose_bbox = _coerce_finite_bbox(char.get("bbox"))
+ char_text = str(char.get("char", ""))
+ if char_text.isspace():
continue
- assigned_span_indices[char_position] = _match_char_bbox_to_span(
- candidate_bbox,
- char_text,
- span_bboxes,
- grid,
- grid_size,
- )
- if assigned_span_indices[char_position] is not None:
- break
+ for candidate_bbox in (tight_bbox, loose_bbox):
+ if candidate_bbox is None:
+ continue
+ assigned_span_indices[char_position] = _match_char_bbox_to_span(
+ candidate_bbox,
+ char_text,
+ span_bboxes,
+ grid,
+ grid_size,
+ )
+ if assigned_span_indices[char_position] is not None:
+ break
- previous_visible_owners: list[int | None] = [None] * len(all_chars)
- previous_owner = None
- for char_position, char in enumerate(all_chars):
- char_text = str(char.get("char", ""))
- if char_text in CONTROL_LINE_BREAK_CHARS:
- previous_owner = None
- continue
- previous_visible_owners[char_position] = previous_owner
- if not char_text.isspace() and assigned_span_indices[char_position] is not None:
- previous_owner = assigned_span_indices[char_position]
-
- next_visible_owners: list[int | None] = [None] * len(all_chars)
- next_owner = None
- for char_position in range(len(all_chars) - 1, -1, -1):
- char_text = str(all_chars[char_position].get("char", ""))
- if char_text in CONTROL_LINE_BREAK_CHARS:
- next_owner = None
- continue
- next_visible_owners[char_position] = next_owner
- if not char_text.isspace() and assigned_span_indices[char_position] is not None:
- next_owner = assigned_span_indices[char_position]
-
- _bridge_unassigned_punctuation(
- assigned_span_indices,
- all_chars,
- previous_visible_owners,
- next_visible_owners,
- span_bboxes,
- tight_bboxes,
- )
+ previous_visible_owners: list[int | None] = [None] * len(all_chars)
+ previous_owner = None
+ for char_position, char in enumerate(all_chars):
+ char_text = str(char.get("char", ""))
+ if char_text in CONTROL_LINE_BREAK_CHARS:
+ previous_owner = None
+ continue
+ previous_visible_owners[char_position] = previous_owner
+ if not char_text.isspace() and assigned_span_indices[char_position] is not None:
+ previous_owner = assigned_span_indices[char_position]
+
+ next_visible_owners: list[int | None] = [None] * len(all_chars)
+ next_owner = None
+ for char_position in range(len(all_chars) - 1, -1, -1):
+ char_text = str(all_chars[char_position].get("char", ""))
+ if char_text in CONTROL_LINE_BREAK_CHARS:
+ next_owner = None
+ continue
+ next_visible_owners[char_position] = next_owner
+ if not char_text.isspace() and assigned_span_indices[char_position] is not None:
+ next_owner = assigned_span_indices[char_position]
+
+ _bridge_unassigned_punctuation(
+ assigned_span_indices,
+ all_chars,
+ previous_visible_owners,
+ next_visible_owners,
+ span_bboxes,
+ tight_bboxes,
+ )
- for char_position, char in enumerate(all_chars):
- char_text = str(char.get("char", ""))
- if not char_text.isspace():
- continue
- loose_bbox = _coerce_finite_whitespace_bbox(char.get("bbox"))
- if loose_bbox is None:
- continue
- previous_owner = previous_visible_owners[char_position]
- next_owner = next_visible_owners[char_position]
- same_neighbor_owner = previous_owner is not None and previous_owner == next_owner
- neighbor_owner = previous_owner if same_neighbor_owner else None
- if neighbor_owner is None:
- neighbor_owner = previous_owner if next_owner is None else next_owner if previous_owner is None else None
- if (
- char_text not in CONTROL_LINE_BREAK_CHARS
- and neighbor_owner is not None
- and (same_neighbor_owner or calculate_char_in_span(loose_bbox, span_bboxes[neighbor_owner], char_text))
- ):
- assigned_span_indices[char_position] = neighbor_owner
- else:
- assigned_span_indices[char_position] = _match_whitespace_bbox_to_first_span(
- loose_bbox,
- char_text,
- span_bboxes,
- grid,
- grid_size,
- )
+ for char_position, char in enumerate(all_chars):
+ char_text = str(char.get("char", ""))
+ if not char_text.isspace():
+ continue
+ loose_bbox = _coerce_finite_whitespace_bbox(char.get("bbox"))
+ if loose_bbox is None:
+ continue
+ previous_owner = previous_visible_owners[char_position]
+ next_owner = next_visible_owners[char_position]
+ same_neighbor_owner = previous_owner is not None and previous_owner == next_owner
+ neighbor_owner = previous_owner if same_neighbor_owner else None
+ if neighbor_owner is None:
+ neighbor_owner = previous_owner if next_owner is None else next_owner if previous_owner is None else None
+ if (
+ char_text not in CONTROL_LINE_BREAK_CHARS
+ and neighbor_owner is not None
+ and (same_neighbor_owner or calculate_char_in_span(loose_bbox, span_bboxes[neighbor_owner], char_text))
+ ):
+ assigned_span_indices[char_position] = neighbor_owner
+ else:
+ assigned_span_indices[char_position] = _match_whitespace_bbox_to_first_span(
+ loose_bbox,
+ char_text,
+ span_bboxes,
+ grid,
+ grid_size,
+ )
for char, span_index in zip(all_chars, assigned_span_indices):
if span_index is not None:
@@ -792,6 +835,10 @@ def calculate_char_in_span(
return False
+# 原规则身份用于显式选择参考路径,不把自定义计算规则静默替换为原生规则。
+_STANDARD_CHAR_IN_SPAN = calculate_char_in_span
+
+
def _get_char_bbox_metrics(char: Char) -> dict[str, float]:
"""提取字符 bbox 的宽高和中心点,统一兼容 list 与 DocVortex Bbox 对象。"""
bbox = char["bbox"]
diff --git a/tests/unittest/test_native_span_assignment.py b/tests/unittest/test_native_span_assignment.py
new file mode 100644
index 00000000..f72e03e2
--- /dev/null
+++ b/tests/unittest/test_native_span_assignment.py
@@ -0,0 +1,97 @@
+"""真实字符快照的 Rust 归属与原 Python 规则逐字符差分。"""
+
+from copy import deepcopy
+from dataclasses import asdict
+from io import BytesIO
+import random
+
+import pytest
+from reportlab.pdfgen.canvas import Canvas
+
+from docvortex.document.pdf import PDFDocument
+from mineru.backend.analysis.pdf.text import native
+from mineru.backend.analysis.pdf.text.models import _AnalyzeSpan
+from mineru.types import ContentType
+
+
+def owned_text():
+ """生成包含边界标点、空白及多行的 PDF,关闭原文档后再验证归属。"""
+ stream = BytesIO()
+ canvas = Canvas(stream, pagesize=(320, 100))
+ for y, text in [(80, "(A B), C! [D]"), (50, "E F? G: H;"), (20, "I J. K-L / M")]:
+ canvas.drawString(10, y, text)
+ canvas.save()
+ with PDFDocument(stream.getvalue()) as document:
+ owner = document[0].get_text_snapshot()
+ if owner is None or not hasattr(owner, "assign_spans"):
+ pytest.skip("Native span assignment unavailable")
+ assert owner.supports_span_matching()
+ return owner
+
+
[email protected]("seed", range(24))
+def test_owned_assignments_match_python_for_overlapping_spans(owned_text, monkeypatch, seed):
+ """在随机重叠框、负坐标与相同框中比对原始 char_idx 归属、文本及后置 OCR 判定。"""
+ randomizer = random.Random(seed)
+ boxes = [(0.0, 0.0, 100.0, 100.0), (0.0, 0.0, 100.0, 100.0)]
+ for _ in range(14):
+ x, y = randomizer.uniform(-15, 100), randomizer.uniform(-10, 95)
+ boxes.append((x, y, x + randomizer.uniform(2, 90), y + randomizer.uniform(2, 30)))
+ original = native.chars_to_content
+ observed = []
+
+ def capture(span, **kwargs):
+ """在原内容组装删除临时字符前记录归属,不替换实际规则。"""
+ observed.append((span.bbox, [char["char_idx"] for char in span.metadata["chars"]]))
+ original(span, **kwargs)
+
+ monkeypatch.setattr(native, "chars_to_content", capture)
+ results = []
+ assignments = []
+ for owner in [None, owned_text]:
+ geometry = owned_text.materialize_geometry()
+ spans = [
+ _AnalyzeSpan(ContentType.TEXT, box, metadata={"chars": [], "height": box[3] - box[1], "width": box[2] - box[0]})
+ for box in boxes
+ ]
+ observed.clear()
+ pending = native.fill_char_in_spans(
+ spans,
+ geometry.chars,
+ 12.0,
+ tight_bboxes=geometry.tight_bboxes,
+ origins=geometry.origins,
+ detect_scripts=False,
+ **({"_native_text": owner} if owner else {}),
+ )
+ assignments.append(deepcopy(observed))
+ results.append(([asdict(span) for span in spans], [spans.index(span) for span in pending]))
+ assert assignments[0] == assignments[1]
+ assert results[0] == results[1]
+
+
+def test_owned_assignment_keeps_replaced_rules_on_reference_path(owned_text, monkeypatch):
+ """调用方替换归属规则时不偷偷使用原生版本,保持参考计算能力。"""
+
+ def reject(*args):
+ """让所有字符失配,验证规则替换确实被执行。"""
+ return False
+
+ monkeypatch.setattr(native, "calculate_char_in_span", reject)
+ assert native._owned_span_assignments(owned_text, [_AnalyzeSpan(ContentType.TEXT, (0.0, 0.0, 100.0, 100.0))], 12.0) is None
+
+
+def test_rotated_snapshot_explicitly_retains_reference_selection():
+ """整行倾斜水印仍由原有组行规则裁决,不能把未迁移角度当成可忽略字符。"""
+ stream = BytesIO()
+ canvas = Canvas(stream, pagesize=(120, 120))
+ canvas.rotate(20)
+ canvas.drawString(20, 50, "WATERMARK")
+ canvas.save()
+ with PDFDocument(stream.getvalue()) as document:
+ owner = document[0].get_text_snapshot()
+ if owner is None or not hasattr(owner, "assign_spans"):
+ pytest.skip("Native span assignment unavailable")
+ assert not owner.supports_span_matching()
+ assert owner.assign_spans([(0.0, 0.0, 120.0, 120.0)], 10.0, native.LINE_STOP_FLAG, native.LINE_START_FLAG, 0.33) is None