Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance inline script merging by adding support for low overlap detached scripts and refining geometry rejection criteria
myhloli1adbc1b495f3
diff --git a/mineru/backend/flash/native_pdf/native_text.py b/mineru/backend/flash/native_pdf/native_text.pyindex 9bab5fb3..cb7db219 100644--- a/mineru/backend/flash/native_pdf/native_text.py+++ b/mineru/backend/flash/native_pdf/native_text.py@@ -234,6 +234,37 @@ def _fill_native_typography(line: _LineItem, page_size: tuple[float, float]) ->line.dominant_font_weight = None+def _is_detached_inline_script_candidate(+ small_bbox: BBox,+ base_bbox: BBox,+ base_height: float,+) -> bool:+ """仅依据紧凑宽度、边缘邻接和垂直偏移确认低重叠外置上下标。"""++ small_width = max(0.0, small_bbox[2] - small_bbox[0])+ edge_distance = min(+ abs(base_bbox[0] - small_bbox[2]),+ abs(small_bbox[0] - base_bbox[2]),+ )+ vertical_gap = max(+ 0.0,+ base_bbox[1] - small_bbox[3],+ small_bbox[1] - base_bbox[3],+ )+ center_offset = abs(_bbox_center_y(small_bbox) - _bbox_center_y(base_bbox))+ outside_offset = max(+ base_bbox[1] - small_bbox[1],+ small_bbox[3] - base_bbox[3],+ )+ return (+ small_width <= 0.75 * base_height+ and edge_distance <= max(1.0, 0.1 * base_height)+ and vertical_gap <= max(0.5, 0.15 * base_height)+ and center_offset >= max(0.5, 0.25 * base_height)+ and outside_offset >= max(0.5, 0.2 * base_height)+ )++def _merge_native_inline_scripts(lines: list[_LineItem],page_size: tuple[float, float],@@ -241,6 +272,7 @@ def _merge_native_inline_scripts("""以 mutual-nearest 规则把跨粗行的小字号前后置标记合入主体视觉行。"""candidates: list[tuple[float, int, int, Literal["prefix", "suffix"]]] = []+ detached_candidate_pairs: set[tuple[int, int, Literal["prefix", "suffix"]]] = set()for small_index, small in enumerate(lines):compact_text = "".join(char for char in small.text if not char.isspace())if not compact_text:@@ -263,7 +295,12 @@ def _merge_native_inline_scripts()small_height = max(0.1, small_local_bbox[3] - small_local_bbox[1])overlap_ratio = vertical_overlap / small_height- if overlap_ratio < 0.5:+ detached_candidate = overlap_ratio < 0.5 and _is_detached_inline_script_candidate(+ small_local_bbox,+ base_local_bbox,+ base.effective_height,+ )+ if overlap_ratio < 0.5 and not detached_candidate:continuecenter_offset = abs(_bbox_center_y(small_local_bbox) - _bbox_center_y(base_local_bbox))if center_offset < max(0.5, 0.12 * base.effective_height):@@ -291,6 +328,8 @@ def _merge_native_inline_scripts(continuemetric = abs(gap) + (1.0 - overlap_ratio) * base.effective_heightcandidates.append((metric, small_index, base_index, position))+ if detached_candidate:+ detached_candidate_pairs.add((small_index, base_index, position))best_base_for_small: dict[int, tuple[float, int, Literal["prefix", "suffix"]]] = {}best_small_for_base: dict[tuple[int, str], tuple[float, int]] = {}@@ -301,7 +340,7 @@ def _merge_native_inline_scripts(if base_key not in best_small_for_base or metric < best_small_for_base[base_key][0]:best_small_for_base[base_key] = (metric, small_index)- matches: dict[int, dict[str, int]] = {}+ matches: dict[int, dict[Literal["prefix", "suffix"], int]] = {}for small_index, (_metric, base_index, position) in best_base_for_small.items():if best_small_for_base.get((base_index, position), (math.inf, -1))[1] == small_index:matches.setdefault(base_index, {})[position] = small_index@@ -337,6 +376,12 @@ def _merge_native_inline_scripts(base.split_from_row = base.split_from_row or suffix.split_from_rowbase.bbox = merged_bboxbase.chars = merged_chars+ # 只有低重叠外置候选才需要按完整二维 bbox 计算后继行距;普通上下标保持原有基线行为。+ base.restored_inline_cluster = base.restored_inline_cluster or any(+ lines[child_index].restored_inline_cluster+ or (child_index, base_index, position) in detached_candidate_pairs+ for position, child_index in positions.items()+ )_fill_native_typography(base, page_size)visiting.remove(base_index)merged_base_indices.add(base_index)@@ -398,4 +443,3 @@ def _median_native_glyph_width(line: _LineItem, page_size: tuple[float, float])widths.append(max(0.1, local_bbox[2] - local_bbox[0]))line.median_glyph_width = statistics.median(widths) if widths else Nonereturn line.median_glyph_width-diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pyindex 1a8d79c9..c5361c0e 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -180,6 +180,9 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Nonpage3 = model_list[2]page3_contents = [block["content"] for block in page3]+ assert next(+ block for block in page3 if block["content"] == "B. Temporal cost aggregation"+ )["type"] == "paragraph_title"assert page3_contents[12] == "D. Iterative Disparity Refinement"assert all(block["bbox"][2] <= 0.5 for block in page3[:12])assert "O(ω2) to O(ω)" in page3_contents[0]@@ -337,7 +340,7 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:0,]assert [len(page) for page in model_list] == [- 24,+ 23,15,13,21,@@ -348,6 +351,7 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:17,18,]+ assert sum(len(page) for page in model_list) == 173page7_tables = [block for block in model_list[6] if block["type"] == "table"]page7_table4 = next(block for block in page7_tables if "Number of parameters" in block["content"]@@ -442,13 +446,13 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Nonpage1, page2 = _native_model_list("demo3.pdf")[:2]title = next(block for block in page1 if block["content"].startswith("TABLEFORMER:"))front_matter_contents = {- "∗","Aditya Gupta† Rahul Goel†",- "Jingfeng Yang Luheng He†",+ "Jingfeng Yang∗ Luheng He†","Shyam Upadhyay† Shachi Paul †","?Georgia Institute of Technology","†Google Assistant",+ "[email protected]",+ "[email protected]",}front_matter = [block for block in page1 if block["content"] in front_matter_contents@@ -473,6 +477,7 @@ def test_demo3_pages1_and2_fix_title_front_matter_and_embedding_formula() -> Nonassert title["type"] == "doc_title"assert len(front_matter) == len(front_matter_contents)assert all(block["type"] == "text" for block in front_matter)+ assert not [block for block in page1 if block["content"] == "∗"]assert next(block for block in page1 if block["content"] == "Abstract")["type"] == "paragraph_title"assert released_code["type"] == "page_footnote"assert aside["angle"] == 270diff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pyindex 3cb7ffff..f0c5ff58 100644--- a/tests/unittest/test_flash_pdf_text_blocks.py+++ b/tests/unittest/test_flash_pdf_text_blocks.py@@ -360,6 +360,7 @@ def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:merged_scripts = native_text._merge_native_inline_scripts(script_lines, (200.0, 100.0))assert [line.text for line in merged_scripts] == ["O(ω2", "Dip"]+ assert not any(line.restored_inline_cluster for line in merged_scripts)caption_prefix = _text_line("(4",@@ -406,6 +407,81 @@ def test_inline_scripts_and_touching_low_coverage_runs_are_recovered() -> None:)+def test_low_overlap_detached_script_preserves_following_row_gap() -> None:+ """验证低重叠外置字形按几何归入主体,且抬高的顶边不会拆断后继行。"""++ base = _text_line(+ "Alpha",+ (10.0, 10.0, 70.0, 20.8),+ 0,+ visual_row_id=0,+ effective_height=10.8,+ )+ detached_script = _text_line(+ "◇",+ (70.0, 3.6, 74.2, 11.1),+ 1,+ visual_row_id=1,+ effective_height=7.5,+ )+ following = _text_line(+ "Beta",+ (35.0, 22.0, 80.0, 34.0),+ 2,+ visual_row_id=2,+ effective_height=10.8,+ )++ merged = native_text._merge_native_inline_scripts(+ [base, detached_script, following],+ (120.0, 100.0),+ )++ assert [line.text for line in merged] == ["Alpha◇", "Beta"]+ assert merged[0].bbox == (10.0, 3.6, 74.2, 20.8)+ assert merged[0].restored_inline_cluster+ assert line_layout._effective_text_row_gap(+ (merged[0], merged[0].bbox),+ (following, following.bbox),+ ) == pytest.approx(1.2)+++ ("small_text", "small_bbox"),+ [+ pytest.param("wide", (50.0, 3.5, 62.0, 11.0), id="wide-token"),+ pytest.param("◇", (53.0, 3.5, 57.2, 11.0), id="horizontal-gap"),+ pytest.param("◇", (50.0, 0.0, 54.2, 7.5), id="vertical-gap"),+ pytest.param("◇", (50.0, 12.0, 54.2, 19.5), id="same-baseline-cell"),+ ],+)+def test_detached_script_geometry_rejects_ambiguous_small_runs(+ small_text: str,+ small_bbox: tuple[float, float, float, float],+) -> None:+ """验证宽文本、远距文本和同行小单元格不能仅凭小字号并入主体。"""++ base = _text_line(+ "Base",+ (0.0, 10.0, 50.0, 22.0),+ 0,+ visual_row_id=0,+ effective_height=12.0,+ )+ small = _text_line(+ small_text,+ small_bbox,+ 1,+ visual_row_id=1,+ effective_height=7.5,+ )++ merged = native_text._merge_native_inline_scripts([base, small], (120.0, 100.0))++ assert [line.text for line in merged] == ["Base", small_text]+ assert not any(line.restored_inline_cluster for line in merged)++def test_full_lane_large_height_mismatch_only_recovers_aligned_continuation() -> None:"""验证满栏混合字体 URL 可续接,而短公式与显式字体样式边界仍分离。"""