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 handling of compound model suffixes in PDF table rendering
myhlolic61b2f06a4f3
diff --git a/mineru/model/flash/pdf/table_text_styles.py b/mineru/model/flash/pdf/table_text_styles.pyindex 5b3731c4..788415e0 100644--- a/mineru/model/flash/pdf/table_text_styles.py+++ b/mineru/model/flash/pdf/table_text_styles.py@@ -136,7 +136,7 @@ def _non_grid_fraction_rules(def _drop_shifted_word_prefixes(chars: list[dict[str, Any]], roles: list[ScriptRole]) -> None:- """拒绝普通字母词仅首字母偏移的弱候选,如 ``-SAT`` 中的 ``S``。"""+ """拒绝普通字母词仅首字母偏移的弱候选,完整同基线词由精炼层闭合。"""start = 0while start < len(chars):diff --git a/mineru/model/flash/pdf/text_styles.py b/mineru/model/flash/pdf/text_styles.pyindex e0aa8f78..1d4cb0b4 100644--- a/mineru/model/flash/pdf/text_styles.py+++ b/mineru/model/flash/pdf/text_styles.py@@ -133,6 +133,7 @@ _LIGATURE_REPLACEMENTS = {"st": "st",}_PDF_SCRIPT_TOKEN_CONNECTORS = frozenset({"^", "_", "ˆ", "~"})+_PDF_SCRIPT_COMPACT_JOINERS = frozenset({"-", "−", "–"})_PDF_SCRIPT_CITATION_BRACKETS = {"[": "]","[": "]",@@ -905,6 +906,58 @@ def _close_spaced_script_operators(roles[target] = role+def _close_compact_aligned_script_suffixes(+ chars: list[dict[str, Any]],+ raw_roles: list[ScriptRole],+ refined_roles: list[ScriptRole],+ tight_bboxes: dict[int, BBox],+ origins: dict[int, tuple[float, float]],+) -> None:+ """把已有可信角标 run 后同基线的紧凑连字符后缀整体闭合。"""+ for joiner_index in range(1, len(chars) - 1):+ if _script_char_text(chars[joiner_index]) not in _PDF_SCRIPT_COMPACT_JOINERS:+ continue+ left_seed = joiner_index - 1+ role = refined_roles[left_seed]+ if role == "body" or not _is_math_identifier_char(_script_char_text(chars[left_seed])):+ continue++ left_start = left_seed+ while (+ left_start > 0+ and refined_roles[left_start - 1] == role+ and _is_math_identifier_char(_script_char_text(chars[left_start - 1]))+ ):+ left_start -= 1+ if left_seed - left_start + 1 < 2:+ continue+ anchor_index = left_start - 1+ if (+ anchor_index < 0+ or refined_roles[anchor_index] != "body"+ or not _is_math_identifier_char(_script_char_text(chars[anchor_index]))+ ):+ continue++ suffix_start = joiner_index + 1+ suffix_end = suffix_start+ while suffix_end < len(chars) and _is_math_identifier_char(_script_char_text(chars[suffix_end])):+ suffix_end += 1+ if suffix_end - suffix_start < 2:+ continue+ restored_indices = range(joiner_index, suffix_end)+ if any(raw_roles[index] != role for index in restored_indices):+ continue+ if not _script_geometry_is_aligned(chars, left_seed, joiner_index, tight_bboxes, origins):+ continue+ if any(+ not _script_geometry_is_aligned(chars, left_seed, index, tight_bboxes, origins)+ for index in range(suffix_start, suffix_end)+ ):+ continue+ refined_roles[joiner_index:suffix_end] = [role] * (suffix_end - joiner_index)++def _protected_subscript_indices(chars: list[dict[str, Any]],roles: list[ScriptRole],@@ -1133,6 +1186,14 @@ def _refine_math_script_tokens():continuerefined[index] = "body"+ if not formula_region:+ _close_compact_aligned_script_suffixes(+ chars,+ roles,+ refined,+ tight_bboxes,+ origins,+ )return refineddiff --git a/tests/fixtures/native_pdf_table_script_truth.json b/tests/fixtures/native_pdf_table_script_truth.jsonindex 248d26ca..3a03442e 100644--- a/tests/fixtures/native_pdf_table_script_truth.json+++ b/tests/fixtures/native_pdf_table_script_truth.json@@ -498,7 +498,7 @@"row": 2,"col": 0,"cell_text": "TAPASBASE-SAT",- "text": "BASE",+ "text": "BASE-SAT","style": "subscript"},{@@ -508,7 +508,7 @@"row": 3,"col": 0,"cell_text": "TABLEFORMERBASE-SO",- "text": "BASE",+ "text": "BASE-SO","style": "subscript"},{@@ -933,6 +933,26 @@"text": "BASE","style": "subscript"},+ {+ "file": "demo3.pdf",+ "page_index": 6,+ "table_index": 1,+ "row": 2,+ "col": 0,+ "cell_text": "TAPASBASE-SAT",+ "text": "BASE-SAT",+ "style": "subscript"+ },+ {+ "file": "demo3.pdf",+ "page_index": 6,+ "table_index": 1,+ "row": 3,+ "col": 0,+ "cell_text": "TABLEFORMERBASE-SO",+ "text": "BASE-SO",+ "style": "subscript"+ },{"file": "demo3.pdf","page_index": 7,@@ -1034,24 +1054,7 @@"style": "superscript"}],- "forbidden_runs": [- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "cell_text": "TAPASBASE-SAT",- "text": "S",- "style": "subscript"- },- {- "file": "demo3.pdf",- "page_index": 6,- "table_index": 1,- "cell_text": "TABLEFORMERBASE-SO",- "text": "S",- "style": "subscript"- }- ],+ "forbidden_runs": [],"forbidden_plain_cells": ["最小值","最大值",diff --git a/tests/unittest/test_flash_pdf_scripts.py b/tests/unittest/test_flash_pdf_scripts.pyindex b6232a56..c576795a 100644--- a/tests/unittest/test_flash_pdf_scripts.py+++ b/tests/unittest/test_flash_pdf_scripts.py@@ -13,6 +13,7 @@ from mineru.model.flash import PdfModelfrom mineru.model.flash.pdf.document import PDFDocumentfrom mineru.model.flash.pdf.models import _AxisLine, _LineItemfrom mineru.model.flash.pdf.pipeline import _analyze_native_document+from mineru.model.flash.pdf.script_geometry import ScriptRolefrom mineru.model.flash.pdf.text_styles import (PDFTextLinkLine,PDFTextLinkRange,@@ -25,6 +26,7 @@ from mineru.model.flash.pdf.text_styles import (apply_pdf_text_styles,detect_pdf_text_script_lines,materialize_pdf_inline_spans,+ _refine_math_script_tokens,)from mineru.types import BBox@@ -81,9 +83,17 @@ _REVIEWED_SCRIPT_EXPECTATIONS = {(0, 11): (),(0, 14): (),},+ "mixed_elements_pages_11_15.pdf": {+ (0, 30): (("2", "subscript"),),+ },}_RUN_CLOSURE_EXPECTATIONS = {+ "demo3.pdf": {+ (6, 38): (("BASE-SAT", "subscript"),),+ (6, 102): (("BASE-SO", "subscript"),),+ (6, 114): (("BASE-SO", "subscript"),),+ },"demo2.pdf": {(2, 22): (("t-1", "subscript"),),(2, 25): (("t-1", "subscript"),),@@ -190,6 +200,68 @@ def _script_fixture()+def _compact_refinement_fixture(text: str) -> tuple[list[Char], dict[int, BBox], dict[int, tuple[float, float]]]:+ """构造同一 tight/origin 基线上的紧凑 token 精炼 fixture。"""+ chars: list[Char] = []+ tight_bboxes: dict[int, BBox] = {}+ origins: dict[int, tuple[float, float]] = {}+ for index, char_text in enumerate(text):+ left = 10.0 + index * 6.0+ bbox = (left, 40.0, left + 5.0, 46.0)+ chars.append(+ {+ "char": char_text,+ "char_idx": index,+ "bbox": Bbox(list(bbox)),+ "rotation": 0.0,+ "font": {},+ }+ )+ tight_bboxes[index] = bbox+ origins[index] = (left, 46.0)+ return chars, tight_bboxes, origins+++def test_flash_compact_aligned_script_suffix_closes_complete_run() -> None:+ """验证可信 BASE 下标会把同基线的 ``-SAT`` 整体闭合。"""+ chars, tight_bboxes, origins = _compact_refinement_fixture("XBASE-SAT")++ roles = _refine_math_script_tokens(+ chars,+ ["body", *(["sub"] * len("BASE-SAT"))],+ tight_bboxes,+ origins,+ formula_region=False,+ )++ assert roles == ["body", *(["sub"] * len("BASE-SAT"))]+++ ("text", "raw_roles"),+ [+ pytest.param("BASE-SAT", ["sub"] * len("BASE-SAT"), id="missing-body-anchor"),+ pytest.param("MODEL-SAT", ["body"] * len("MODEL-SAT"), id="plain-hyphenated-word"),+ ],+)+def test_flash_compact_script_suffix_requires_anchor_and_raw_geometry(+ text: str,+ raw_roles: list[ScriptRole],+) -> None:+ """验证无正文锚点或无原始角标证据时不会闭合连字符词。"""+ chars, tight_bboxes, origins = _compact_refinement_fixture(text)++ roles = _refine_math_script_tokens(+ chars,+ raw_roles,+ tight_bboxes,+ origins,+ formula_region=False,+ )++ assert roles == ["body"] * len(text)++@pytest.mark.parametrize("angle", [0, 90, 180, 270])def test_flash_script_geometry_uses_upright_coordinates(angle: int) -> None:"""验证四种页面方向下 loose/tight/origin 同步正向化后角色一致。"""@@ -604,7 +676,13 @@ def test_chinese_paper_page_12_recovers_numbered_formula_regions() -> None:),pytest.param("demo3.pdf",- (("i", "subscript"), ("BASE", "subscript"), ("LARGE", "subscript")),+ (+ ("i", "subscript"),+ ("BASE", "subscript"),+ ("LARGE", "subscript"),+ ("BASE-SAT", "subscript"),+ ("BASE-SO", "subscript"),+ ),id="model-subscripts",),pytest.param(diff --git a/tests/unittest/test_native_pdf_table_scripts.py b/tests/unittest/test_native_pdf_table_scripts.pyindex f3a3a578..f90310ae 100644--- a/tests/unittest/test_native_pdf_table_scripts.py+++ b/tests/unittest/test_native_pdf_table_scripts.py@@ -330,6 +330,26 @@ def _real_manifest_script_runs() -> tuple[set[tuple[object, ...]], set[str]]:return actual, styled_cell_texts+def test_demo3_compound_model_suffixes_are_complete_table_subscripts() -> None:+ """验证 demo3 表 5 的复合模型后缀整体进入同一个下标标签。"""+ manifest = json.loads((_PROJECT_ROOT / "tests/fixtures/native_pdf_table_demo_manifest.json").read_text(encoding="utf-8"))+ entry = next(+ item+ for item in manifest["tables"]+ if item["file"] == "demo3.pdf" and item["page_index"] == 6 and item["table_index"] == 1+ )+ with PDFDocument(str(_PROJECT_ROOT / "demo/pdfs/demo3.pdf")) as document:+ table_input, tight_bboxes, origins = _manifest_table_input(document, entry, cross_page_manifest=False)+ result = recover_native_pdf_table(table_input)+ assert result is not None++ styled = render_native_table_html_with_scripts(result, table_input, tight_bboxes, origins)+ cells = {cell.get_text(): cell for cell in BeautifulSoup(styled, "html.parser").find_all("td")}++ assert cells["TAPASBASE-SAT"].find("sub").get_text() == "BASE-SAT" # type: ignore[union-attr]+ assert cells["TABLEFORMERBASE-SO"].find("sub").get_text() == "BASE-SO" # type: ignore[union-attr]++def test_real_native_table_scripts_are_precision_gated() -> None:"""验证全部实际输出属于人工真值,必召回项存在且强制负例保持纯文本。"""