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
fix: update text_sha256 values in PDF table manifests and improve cell glyph handling
myhloli0899e76b8c80
diff --git a/mineru/backend/analysis/pdf/tables.py b/mineru/backend/analysis/pdf/tables.pyindex 8023d034..3ac66643 100644--- a/mineru/backend/analysis/pdf/tables.py+++ b/mineru/backend/analysis/pdf/tables.py@@ -246,11 +246,7 @@ def _apply_native_txt_table_priority({"table_block": block,"table_bbox": table_bbox,- "complex_reasons": (- {"rotated_table"}- if _normalize_visual_block_angle(block.get("angle", 0)) != 0- else set()- ),+ "complex_reasons": set(),})diff --git a/mineru/model/flash/pdf/table_recovery/text.py b/mineru/model/flash/pdf/table_recovery/text.pyindex ffcb7aae..b4d69de3 100644--- a/mineru/model/flash/pdf/table_recovery/text.py+++ b/mineru/model/flash/pdf/table_recovery/text.py@@ -4,11 +4,13 @@from __future__ import annotationsimport statistics+import unicodedatafrom dataclasses import dataclassfrom pdftext.schema import Charfrom .....types import BBox+from .....utils.text import resolve_text_line_boundaryfrom ..spatial_text import _normalize_table_textfrom .contracts import (@@ -196,6 +198,70 @@ def _join_glyph_line(return "".join(text for text, _source_index in _glyph_line_parts(glyphs, median_height))+def _nearest_alphabetic_char(text: str, *, reverse: bool) -> str:+ """从物理行边界向内查找最近的 Unicode 字母。"""++ normalized = text.rstrip() if reverse else text.lstrip()+ characters = reversed(normalized) if reverse else iter(normalized)+ return next((char for char in characters if char.isalpha()), "")+++def _is_latin_letter(char: str) -> bool:+ """判断单个 Unicode 字符规范化后是否只由 Latin 字母组成。"""++ if len(char) != 1:+ return False+ normalized = unicodedata.normalize("NFKC", char)+ return bool(normalized) and all(item.isalpha() and unicodedata.name(item, "").startswith("LATIN ") for item in normalized)+++def _looks_like_compact_unit_or_identifier(+ previous_line: str,+ next_line: str,+) -> bool:+ """识别不应因视觉换行插入空格的紧凑单位或标识符片段。"""++ combined = previous_line.strip() + next_line.strip()+ if not combined or any(char.isspace() for char in combined):+ return False+ return any(char.isdigit() or char in "/_^%°µμ" for char in combined)+++def _starts_with_url(text: str) -> bool:+ """判断下一物理行是否自身以完整 URL 前缀开始。"""++ normalized = text.lstrip().casefold()+ return normalized.startswith(("http://", "https://", "ftp://", "www."))+++def _cell_row_separator(+ accumulated_content: str,+ previous_line: str,+ next_line: str,+) -> str:+ """按相邻行边界词元返回安全分隔符,非 Latin 边界保持直连。"""++ previous_letter = _nearest_alphabetic_char(previous_line, reverse=True)+ next_letter = _nearest_alphabetic_char(next_line, reverse=False)+ if not (_is_latin_letter(previous_letter) and _is_latin_letter(next_letter)):+ return ""++ _processed_previous, separator = resolve_text_line_boundary(+ accumulated_content,+ block_language="en",+ next_content=next_line,+ )+ if separator != " ":+ # 表格 HTML 保留原始连字符,只复用正文规则的 URL/连字符直连判定。+ return separator+ if not _starts_with_url(next_line) and _looks_like_compact_unit_or_identifier(+ previous_line,+ next_line,+ ):+ return ""+ return separator++def _glyph_line_parts(glyphs: list[NativeTableGlyph] | list[_PendingGlyph],median_height: float,@@ -323,8 +389,23 @@ def build_cell_text_parts(for glyph in glyphs:grouped.setdefault(glyph.visual_row, []).append(glyph)parts: list[tuple[str, int | None]] = []+ previous_line = ""for row_index in sorted(grouped):- parts.extend(_glyph_line_parts(grouped[row_index], median_height))+ row_parts = _glyph_line_parts(grouped[row_index], median_height)+ row_text = "".join(text for text, _source_index in row_parts)+ if not row_text:+ continue+ if parts:+ accumulated_content = "".join(text for text, _source_index in parts)+ separator = _cell_row_separator(+ accumulated_content,+ previous_line,+ row_text,+ )+ if separator and not accumulated_content.endswith(" ") and not row_text.startswith(" "):+ parts.append((separator, None))+ parts.extend(row_parts)+ previous_line = row_textreturn partsdiff --git a/tests/fixtures/native_pdf_table_cross_page_manifest.json b/tests/fixtures/native_pdf_table_cross_page_manifest.jsonindex 0412bbe4..0aac0335 100644--- a/tests/fixtures/native_pdf_table_cross_page_manifest.json+++ b/tests/fixtures/native_pdf_table_cross_page_manifest.json@@ -58,7 +58,7 @@1]],- "text_sha256": "8b887f3be58a4bceac993857ec28c45f9639fa1d509d7391b9badd5576994ac7"+ "text_sha256": "810d555fabe290304673013dc4356a7f2e3992250ac81ef4a65a745564769a8d"},{"file": "conference_schedule_tables.pdf",@@ -82,7 +82,7 @@1]],- "text_sha256": "e58fe41773b2f27073b3677aedd9a27e5eab6736a37ad83d5fa3a295ecd123b8"+ "text_sha256": "764463f5dfcec4ab72f5db2dfa6baf5074612bb1c73cd997c683e0eaf2055b5f"},{"file": "conference_schedule_tables.pdf",@@ -118,7 +118,7 @@1]],- "text_sha256": "c78c7fa48096ffa6de29e492e2944bdfb06662a231e6c14f8bcb4ac348c73665"+ "text_sha256": "2506fd5ea02ab1abcce4d86c6010c213e5ed0f64c5d0ab1f6821905c3ebcd536"},{"file": "conference_schedule_tables.pdf",@@ -135,7 +135,7 @@"rows": 6,"cols": 3,"span_signature": [],- "text_sha256": "2f9f38231f92a729661344f5cfa7ef43f6c3a406920a2d8297e53d5b9b922f32"+ "text_sha256": "a6e63e3f226220e813730c30a044aa34c9beb3d4bc16052470d5af2884154085"},{"file": "conference_schedule_tables.pdf",@@ -183,7 +183,7 @@1]],- "text_sha256": "41a3d96e4d4740039d93989d015c413e766f0fe3933a770c4e2f7977bd4d3daa"+ "text_sha256": "0d00c0749caa6c177a3a59406e99970c08f000c2306574455a85b339de26277f"},{"file": "conference_schedule_tables.pdf",@@ -207,7 +207,7 @@1]],- "text_sha256": "bf13feeccd3514cfe4ec76f4f5b7ba962f301906b6252290795bf7ab0646f8d9"+ "text_sha256": "47c55c2a4920d713875d7e88895a28844dc56b82be90e001a1cad9b0b076e744"},{"file": "conference_schedule_tables.pdf",@@ -237,7 +237,7 @@1]],- "text_sha256": "c898bbdc23b8a7aee415515c0e38241146b3df36757d6577c7c0eac6790a6f0d"+ "text_sha256": "fc13188f8e07725e1ff6acc094e22cfb266fe1ff8a88931d8a04eae2dfdbcc6e"},{"file": "conference_schedule_tables.pdf",@@ -261,7 +261,7 @@1]],- "text_sha256": "5024e9352d3e89138773621157357488c4480919f465ef0858454f9696b523cc"+ "text_sha256": "704d7793284eaa624d29d545ae9fb17a519ae17ad13915bffc3f7556624ee8ee"},{"file": "conference_schedule_tables.pdf",@@ -285,7 +285,7 @@1]],- "text_sha256": "e69c3d0532acbdcfc2d359de1e847222482fe228126cf5d5d2192faa17501412"+ "text_sha256": "8864dca4ca86743515fb3545106829b3c966849f88d8f0560795fa1b486d5c29"},{"file": "conference_schedule_tables.pdf",@@ -309,7 +309,7 @@1]],- "text_sha256": "c7850b320840870b9ab233498cc42cfbfe10681428ea2b9795e1ea6405772e91"+ "text_sha256": "23d2a97190151ed201b5911536a56d57dde00128513efcf2f08e3986b6588718"},{"file": "manufacturing_facilities_cross_page_table.pdf",@@ -590,7 +590,7 @@"rows": 2,"cols": 5,"span_signature": [],- "text_sha256": "56201500eae3689cb69053ba3eb7439df814d6143f91dd40f98bff47221bf376"+ "text_sha256": "e03fb9e7ae02cfe3a8435dc2c97fda32b9070211d56f4749511081968c6ceef8"},{"file": "procurement_document_blank_page_tables.pdf",@@ -607,7 +607,7 @@"rows": 2,"cols": 3,"span_signature": [],- "text_sha256": "2c50430ff8e62a80a91343f0ef299f69cf9bd84b0831351a931f645b090989a6"+ "text_sha256": "0167a7b5e8ab8907367eb22dee475ca1d46a9a4ffb6a71d739b340f2431eb7c7"},{"file": "procurement_document_blank_page_tables.pdf",@@ -6807,7 +6807,7 @@"rows": 5,"cols": 6,"span_signature": [],- "text_sha256": "f751d0f566056aa4e8b7bad15e215a5966ddc9cf996de249cc18ec69f86a0aec"+ "text_sha256": "e7db8dc5f8ac2c65c386a19cd1d416ee0d4b674b01309274d85345ea962c7897"},{"file": "pollutant_discharge_tables.pdf",@@ -6906,7 +6906,7 @@"rows": 2,"cols": 6,"span_signature": [],- "text_sha256": "afc9d366a18c2ea698366a986f6a0e7edc916e0868030cf17241d7b736fbbc85"+ "text_sha256": "cbe5984248be83176d2cbb8c287552bfa009fa02cc563a9bb0a29e9bc4c3417c"},{"file": "pollutant_discharge_tables.pdf",@@ -7626,7 +7626,7 @@6]],- "text_sha256": "03920f1c17f81c79754c045187daccba62c5e29249e5a6d44cdfa5869104af2f"+ "text_sha256": "ad5104dbf481f378d0293464db320e2effd71478abed326904ccc38ac3ee41d4"},{"file": "engineering_process_restrictions_table.pdf",diff --git a/tests/fixtures/native_pdf_table_demo_manifest.json b/tests/fixtures/native_pdf_table_demo_manifest.jsonindex fb161b64..ab6ef832 100644--- a/tests/fixtures/native_pdf_table_demo_manifest.json+++ b/tests/fixtures/native_pdf_table_demo_manifest.json@@ -5073,7 +5073,7 @@"angle": 0,"expected_output": "html","review_status": "target_verified",- "content_sha256": "0489b58206469821c2c7ce4aac25d2fdb2c6cffb670d09010d77d1dbef2124fa",+ "content_sha256": "35f94188ba7298ba29beaf056e3c20ed40bc6f272f3dfd0826b752110636dc00","expected_source": "sparse_multiline","rows": 6,"cols": 2,@@ -5112,7 +5112,7 @@"col": 0,"rowspan": 1,"colspan": 1,- "text": "小鹏汽车-W(9868 HK)"+ "text": "小鹏汽车-W (9868 HK)"},{"row": 2,@@ -5133,7 +5133,7 @@"col": 1,"rowspan": 1,"colspan": 1,- "text": "23Q4创季度营收新高,24Q1创季度归母净利新高公司发布23年年报及24Q1季报,23年营收46.25亿元(yoy+36.68%),归母净利6.09亿元(yoy+35.26%),其中Q4营收14.31亿元(yoy+48.56%,qoq+16.13%),归母净利1.54亿元(yoy+73.39%,qoq-14.44%)。24Q1营收14.17亿元(yoy +55.22%,qoq -1.00%),归母净利2.19亿元(yoy+ 66.24%,qoq +42.47%)。考虑后续行业竞争加剧,我们预计公司24~26年归母净利分别为8.52/11.68/15.00亿元(前值24~25年10.39/13.97亿元)。可比公司24年iFind一致预期PE均值为33.0倍,考虑公司产品升级明显,且国际化拓展具备优势,给予公司20%的可比估值溢价,24年39.6倍PE目标,目标价83.44元(前值67.86元),维持\"买入\"评级。风险提示:下游整车行业产销不及预期;新项目开拓速度不及预期。报告发布日期:2024年04月20日点击下载全文:科博达(603786 CH,买入): 营收业绩再创新高,展现强劲动能"+ "text": "23Q4创季度营收新高,24Q1创季度归母净利新高公司发布23年年报及24Q1季报,23年营收46.25亿元(yoy+36.68%),归母净利6.09亿元(yoy+35.26%),其中Q4营收14.31亿元(yoy+48.56%, qoq+16.13%),归母净利1.54亿元(yoy+73.39%,qoq-14.44%)。24Q1营收14.17亿元(yoy +55.22%,qoq -1.00%),归母净利2.19亿元(yoy + 66.24%,qoq +42.47%)。考虑后续行业竞争加剧,我们预计公司24~26年归母净利分别为8.52/11.68/15.00亿元(前值24~25年10.39/13.97亿元)。可比公司24年iFind一致预期PE均值为33.0倍,考虑公司产品升级明显,且国际化拓展具备优势,给予公司20%的可比估值溢价,24年39.6倍PE目标,目标价83.44元(前值67.86元),维持\"买入\"评级。风险提示:下游整车行业产销不及预期;新项目开拓速度不及预期。报告发布日期:2024年04月20日点击下载全文:科博达(603786 CH,买入): 营收业绩再创新高,展现强劲动能"},{"row": 4,@@ -16752,7 +16752,7 @@"angle": 270,"expected_output": "html","review_status": "target_verified",- "content_sha256": "d6273b35bc26223b61fd7900ab7d48bc00292b256d6724586a0fc483a5d20ee8",+ "content_sha256": "412113029f464ab3d6c03d1ef843d614fe77470c1981b97bddd42663e39941c5","expected_source": "sparse_multiline","rows": 11,"cols": 11,@@ -16784,42 +16784,42 @@"col": 3,"rowspan": 1,"colspan": 1,- "text": "% Areaplanted"+ "text": "% Area planted"},{"row": 0,"col": 4,"rowspan": 1,"colspan": 1,- "text": "Meanannualrainfall(mm)"+ "text": "Mean annual rainfall (mm)"},{"row": 0,"col": 5,"rowspan": 1,"colspan": 1,- "text": "*Raindistrib."+ "text": "*Rain distrib."},{"row": 0,"col": 6,"rowspan": 1,"colspan": 1,- "text": "Pre-treat-ment(years)"+ "text": "Pre-treat-ment (years)"},{"row": 0,"col": 7,"rowspan": 1,"colspan": 1,- "text": "Forest age(years)"+ "text": "Forest age (years)"},{"row": 0,"col": 8,"rowspan": 1,"colspan": 1,- "text": "Mean soildepth (m)"+ "text": "Mean soil depth (m)"},{"row": 0,@@ -17141,7 +17141,7 @@"col": 10,"rowspan": 1,"colspan": 1,- "text": "Nandakumar andMein, 1 993"+ "text": "Nandakumar and Mein, 1 993"},{"row": 5,@@ -20284,7 +20284,7 @@"angle": 0,"expected_output": "html","review_status": "target_verified",- "content_sha256": "989d9e4a1dcc90eb8c78165ebc9c086209fc55ca0a907ec8a5a46af0f41d4a19",+ "content_sha256": "a52e2efd31f2c51402ab62e618e2442d872c34c8318abcaf149af2352256b664","expected_source": "sparse_multiline","rows": 10,"cols": 7,@@ -20353,14 +20353,14 @@"col": 3,"rowspan": 2,"colspan": 1,- "text": "Total flowreduction (%)"+ "text": "Total flow reduction (%)"},{"row": 0,"col": 4,"rowspan": 2,"colspan": 1,- "text": "Low flowreduction (%)"+ "text": "Low flow reduction (%)"},{"row": 0,@@ -20374,14 +20374,14 @@"col": 5,"rowspan": 1,"colspan": 1,- "text": "Total flowreduction (%)b"+ "text": "Total flow reduction (%)b"},{"row": 1,"col": 6,"rowspan": 1,"colspan": 1,- "text": "Low flowreduction (%)c"+ "text": "Low flow reduction (%)c"},{"row": 2,@@ -23301,7 +23301,7 @@"angle": 0,"expected_output": "html","review_status": "target_verified",- "content_sha256": "dd085ccd303c047fe52d2a9e01a3a3fc9afec41170fc6a4905e7b91ce26b5b0c",+ "content_sha256": "bb234ea8e74105d4cccde9e040b08089dc42b2ecb74d78a7e060ad7f737b1334","expected_source": "sparse_multiline","rows": 5,"cols": 5,@@ -24735,7 +24735,7 @@"angle": 0,"expected_output": "html","review_status": "existing_verified",- "content_sha256": "110e749698e1ccdad658112b45f6b5924cbc4a6b6d6728ead0becfe07917b4cb",+ "content_sha256": "f85576a1b0a52c3b1fca65763cc2880e8e099772b4086181c73b1e3d25b86b53","expected_source": "vector_grid","rows": 11,"cols": 4,@@ -24760,14 +24760,14 @@"col": 2,"rowspan": 1,"colspan": 1,- "text": "Position ofdead code"+ "text": "Position of dead code"},{"row": 0,"col": 3,"rowspan": 1,"colspan": 1,- "text": "Types ofdead code"+ "text": "Types of dead code"},{"row": 1,@@ -25064,7 +25064,7 @@"angle": 0,"expected_output": "html","review_status": "existing_verified",- "content_sha256": "cf6e545fb4f6bad3ee63ec6b17dfdc6ec5d2a33e2772772367d3cdc927f1a600",+ "content_sha256": "46f3d31b3d4e2aa725491b7dfafe9a5fc5bf3debd1eab2906adbacad7a384f4c","expected_source": "vector_grid","rows": 6,"cols": 3,@@ -25082,14 +25082,14 @@"col": 1,"rowspan": 1,"colspan": 1,- "text": "Number of deadcode lines detected"+ "text": "Number of dead code lines detected"},{"row": 0,"col": 2,"rowspan": 1,"colspan": 1,- "text": "Percentagedetected"+ "text": "Percentage detected"},{"row": 1,@@ -25211,7 +25211,7 @@"angle": 0,"expected_output": "html","review_status": "target_verified",- "content_sha256": "9470c6774f0ed9f16f63b07a7c8f55ca5e6f2cde08038a0ad4dccb93e54d64c6",+ "content_sha256": "7d525b88a5b6481bef729f75e57bfdd160276c57d9e4c0e1f168a53620cef88d","expected_source": "sparse_multiline","rows": 7,"cols": 5,@@ -25229,7 +25229,7 @@"col": 1,"rowspan": 1,"colspan": 1,- "text": "Lesion Lengthmm"+ "text": "Lesion Length mm"},{"row": 0,@@ -25243,7 +25243,7 @@"col": 3,"rowspan": 1,"colspan": 1,- "text": "Pepsin Activitymg tyrosine/mL/10 min"+ "text": "Pepsin Activity mg tyrosine/mL/10 min"},{"row": 0,diff --git a/tests/unittest/test_native_pdf_table.py b/tests/unittest/test_native_pdf_table.pyindex e0673402..5662db5b 100644--- a/tests/unittest/test_native_pdf_table.py+++ b/tests/unittest/test_native_pdf_table.py@@ -19,13 +19,17 @@ from mineru.model.flash.pdf.table_recovery import (recover_native_pdf_table,)from mineru.model.flash.pdf.table_recovery.candidate import GridCellSpec, build_candidate-from mineru.model.flash.pdf.table_recovery.contracts import NativeTableCandidate+from mineru.model.flash.pdf.table_recovery.contracts import NativeTableCandidate, NativeTableGlyphfrom mineru.model.flash.pdf.table_recovery.engine import (_remove_undercounted_vector_candidates,_select_candidate,diagnose_native_pdf_table,)-from mineru.model.flash.pdf.table_recovery.text import build_native_table_text+from mineru.model.flash.pdf.table_recovery.text import (+ build_cell_text,+ build_cell_text_parts,+ build_native_table_text,+)from mineru.model.flash.pdf.table_recovery.vector import (MAX_PRIMITIVES_PER_TABLE,build_vector_candidates,@@ -58,6 +62,35 @@ def _char_items(return tuple(rebuilt)+def _cell_glyph_rows(rows: list[str]) -> list[NativeTableGlyph]:+ """把多条物理行构造成保留显式词间空格的 cell 字形。"""++ glyphs: list[NativeTableGlyph] = []+ source_index = 0+ for row_index, text in enumerate(rows):+ x = 0.0+ pending_space = False+ for char in text:+ if char.isspace():+ pending_space = True+ x += 2.0+ continue+ glyphs.append(+ NativeTableGlyph(+ glyph_id=len(glyphs),+ source_index=source_index,+ text=char,+ bbox=(x, row_index * 12.0, x + 4.0, row_index * 12.0 + 8.0),+ visual_row=row_index,+ explicit_space_before=pending_space,+ )+ )+ source_index += 1+ pending_space = False+ x += 4.0+ return glyphs++def _grid_rules(*,width: float = 100.0,@@ -1530,8 +1563,8 @@ def test_vector_grid_rejects_non_rectangular_merge_component() -> None:assert build_vector_candidates(table_input, text) == []-def test_vector_cell_concatenates_multiple_visual_lines() -> None:- """验证同一逻辑单元格中的多行文本直接拼接且不写入 HTML 换行。"""+def test_vector_cell_joins_latin_visual_lines_with_space() -> None:+ """验证同一逻辑单元格中的 Latin 多行补空格但不写入 HTML 换行。"""table_input = NativeTableInput(table_bbox=(0.0, 0.0, 100.0, 60.0),@@ -1552,10 +1585,46 @@ def test_vector_cell_concatenates_multiple_visual_lines() -> None:result = recover_native_pdf_table(table_input)assert result is not None- assert "<td>AB</td>" in result.html+ assert "<td>A B</td>" in result.htmlassert "<br>" not in result.html+ ("rows", "expected"),+ [+ (["Latin line", "continues"], "Latin line continues"),+ (["中文", "继续"], "中文继续"),+ (["标题 neural", "networks"], "标题 neural networks"),+ (["Neural Networks:", "Unlocking"], "Neural Networks: Unlocking"),+ (["RF-", "based"], "RF-based"),+ (["https://example.test/path", "/next"], "https://example.test/path/next"),+ (["https://example.test/one", "https://example.test/two"], "https://example.test/one https://example.test/two"),+ (["40.5000", "00"], "40.500000"),+ (["1.0mg/N", "m3"], "1.0mg/Nm3"),+ (["RFC3986", "URL"], "RFC3986URL"),+ (["Привет", "мир"], "Приветмир"),+ ],+)+def test_cell_visual_line_join_is_language_aware(+ rows: list[str],+ expected: str,+) -> None:+ """验证 Latin、CJK、URL、连字符、数字和紧凑标识符的边界策略。"""++ glyphs = _cell_glyph_rows(rows)++ assert build_cell_text(glyphs, 8.0) == expected+++def test_cell_visual_line_separator_has_no_source_index() -> None:+ """验证新增行间空格不伪造 PDF 字符来源索引。"""++ parts = build_cell_text_parts(_cell_glyph_rows(["Latin", "text"]), 8.0)++ assert (" ", None) in parts+ assert "".join(text for text, _source_index in parts) == "Latin text"++@pytest.mark.parametrize("angle", [0, 90, 180, 270])def test_text_grid_supports_standard_table_rotations(angle: int) -> None:"""验证三列无线表在四个标准方向下恢复相同结构。"""@@ -1991,7 +2060,7 @@ def test_sparse_multiline_recovers_keyed_long_records() -> None:assert result is not Noneassert result.source == "sparse_multiline"assert (result.rows, result.cols) == (4, 2)- assert "<td>Alpha(A1)</td><td>Title Abody a1body a2body a3</td>" in result.html+ assert "<td>Alpha(A1)</td><td>Title A body a1 body a2 body a3</td>" in result.htmldef test_sparse_multiline_recovers_filled_record_continuations() -> None:diff --git a/tests/unittest/test_native_pdf_table_pipeline.py b/tests/unittest/test_native_pdf_table_pipeline.pyindex 44d395b2..04ffc3ab 100644--- a/tests/unittest/test_native_pdf_table_pipeline.py+++ b/tests/unittest/test_native_pdf_table_pipeline.py@@ -3,7 +3,10 @@from __future__ import annotations+import json+from pathlib import Pathfrom types import SimpleNamespace+from typing import Literalfrom unittest.mock import MagicMockimport numpy as np@@ -16,10 +19,13 @@ from mineru.backend.analysis.pdf import tables as pdf_tablesfrom mineru.backend.analysis.pdf import window as pdf_windowfrom mineru.model.flash.pdf import models as flash_modelsfrom mineru.model.flash.pdf import tables as flash_tables-from mineru.model.flash.pdf.document import PDFPageTextGeometry+from mineru.model.flash.pdf.document import PDFDocument, PDFPageTextGeometryfrom mineru.types import RAW_FORMULA_NUMBER, BlockType+_PROJECT_ROOT = Path(__file__).parents[2]++def _build_native_pdf_page(*, width: float = 100.0, height: float = 100.0) -> MagicMock:"""构造带完整原生表格页面接口的测试替身。"""@@ -272,17 +278,22 @@ def test_high_native_table_priority_ignores_layout_formula_and_removes_duplicaterecover.assert_called_once()-def test_hybrid_native_table_priority_falls_back_for_rotated_table([email protected]("effort", ["medium", "high"])[email protected]("angle", [90, 180, 270])+def test_hybrid_native_table_priority_attempts_rotated_table(monkeypatch: pytest.MonkeyPatch,+ effort: Literal["medium", "high"],+ angle: int,) -> None:- """验证真实字符源顺序未覆盖的旋转表继续使用现有模型。"""+ """验证 Medium/High 会把标准旋转角传入原生表格恢复器。"""- recover = MagicMock()+ html = "<table><tbody><tr><td>rotated</td></tr></tbody></table>"+ recover = MagicMock(return_value=SimpleNamespace(html=html, source="vector_grid", confidence=1.0))monkeypatch.setattr(pdf_tables, "recover_native_pdf_table", recover)table_block = {"type": BlockType.TABLE,"bbox": [0.1, 0.1, 0.9, 0.9],- "angle": 270,+ "angle": angle,}image = Image.new("RGB", (100, 100), "white")try:@@ -291,17 +302,55 @@ def test_hybrid_native_table_priority_falls_back_for_rotated_table([[]],[_build_native_pdf_page()],[{"img_pil": image, "scale": 1.0}],- effort="medium",+ effort=effort,)finally:image.close()- assert "content" not in table_block+ assert table_block["content"] == htmlassert summary == pdf_tables._NativeTablePrioritySummary(total=1,- complex_fallbacks=1,+ accepted=1,)- recover.assert_not_called()+ recover.assert_called_once()+ assert recover.call_args.args[0].angle == angle++[email protected]("effort", ["medium", "high"])+def test_hybrid_native_table_priority_accepts_real_rotated_table(+ effort: Literal["medium", "high"],+) -> None:+ """验证真实 270 度表格在 Medium/High 中都能直接生成原生 HTML。"""++ manifest = json.loads((_PROJECT_ROOT / "tests" / "fixtures" / "native_pdf_table_demo_manifest.json").read_text())+ target = next(+ item+ for item in manifest["tables"]+ if item["file"] == "demo1.pdf" and item["page_index"] == 4 and item["table_index"] == 0+ )+ pdf_path = _PROJECT_ROOT / manifest["source_root"] / target["file"]+ with PDFDocument(pdf_path.read_bytes()) as document:+ page = document[target["page_index"]]+ image = Image.new("RGB", (round(page.size[0]), round(page.size[1])), "white")+ table_block = {+ "type": BlockType.TABLE,+ "bbox": target["bbox"],+ "angle": target["angle"],+ }+ try:+ summary = pdf_tables._apply_native_txt_table_priority(+ [[table_block]],+ [[]],+ [page],+ [{"img_pil": image, "scale": 1.0}],+ effort=effort,+ )+ finally:+ image.close()++ assert summary == pdf_tables._NativeTablePrioritySummary(total=1, accepted=1)+ assert table_block["content"].count("<tr>") == target["rows"]+ assert table_block["content"].startswith("<table><tbody>")def test_hybrid_native_table_priority_keeps_none_and_exception_fallbacks(@@ -312,8 +361,8 @@ def test_hybrid_native_table_priority_keeps_none_and_exception_fallbacks(recover = MagicMock(side_effect=[None, RuntimeError("broken")])monkeypatch.setattr(pdf_tables, "recover_native_pdf_table", recover)tables = [- {"type": BlockType.TABLE, "bbox": [0.05, 0.1, 0.45, 0.9], "angle": 0},- {"type": BlockType.TABLE, "bbox": [0.55, 0.1, 0.95, 0.9], "angle": 0},+ {"type": BlockType.TABLE, "bbox": [0.05, 0.1, 0.45, 0.9], "angle": 270},+ {"type": BlockType.TABLE, "bbox": [0.55, 0.1, 0.95, 0.9], "angle": 90},]equation_block = {"type": BlockType.EQUATION, "bbox": [0.1, 0.2, 0.3, 0.4]}page_blocks = [tables[0], equation_block, tables[1]]@@ -340,6 +389,7 @@ def test_hybrid_native_table_priority_keeps_none_and_exception_fallbacks(errors=1,)assert recover.call_count == 2+ assert [call.args[0].angle for call in recover.call_args_list] == [270, 90]page.get_chars_with_geometry.assert_called_once_with()diff --git a/tests/unittest/test_native_pdf_table_scripts.py b/tests/unittest/test_native_pdf_table_scripts.pyindex f90310ae..1ecc3e0c 100644--- a/tests/unittest/test_native_pdf_table_scripts.py+++ b/tests/unittest/test_native_pdf_table_scripts.py@@ -11,6 +11,7 @@ from bs4 import BeautifulSoupfrom pdftext.schema import Bbox, Charimport pytest+from mineru.model.flash.pdf import table_text_styles as pdf_table_text_stylesfrom mineru.model.flash.pdf.geometry import _rotate_bbox_from_uprightfrom mineru.model.flash.pdf.document import PDFDocumentfrom mineru.model.flash.pdf.table_recovery import (@@ -148,6 +149,49 @@ def test_table_script_serialization_escapes_text_and_marks_superscript() -> Noneassert BeautifulSoup(styled, "html.parser").get_text() == "<A2"+def test_table_script_serialization_preserves_latin_row_separator(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证无来源行间空格与后续上下标 HTML 可以同时保留。"""++ texts = "ModelNameH2"+ bboxes = tuple(+ (5.0 + index * 5.0, 40.0, 9.0 + index * 5.0, 50.0)+ if index < 9+ else (5.0 + (index - 9) * 5.0, 20.0, 9.0 + (index - 9) * 5.0, 30.0)+ for index in range(len(texts))+ )+ chars = tuple(_char(text, index, bboxes[index]) for index, text in enumerate(texts))+ glyphs = tuple(+ NativeTableGlyph(+ index,+ index,+ text,+ bboxes[index],+ 0 if index < 9 else 1,+ explicit_space_before=index == 5,+ )+ for index, text in enumerate(texts)+ )+ result = _result("Model Name H2", glyphs)+ table_input = NativeTableInput((0.0, 0.0, 60.0, 60.0), (60.0, 60.0), 0, chars)+ monkeypatch.setattr(+ pdf_table_text_styles,+ "_cell_script_roles",+ lambda *_args, **_kwargs: {10: "sub"},+ )++ styled = render_native_table_html_with_scripts(+ result,+ table_input,+ dict(enumerate(bboxes)),+ {index: (bbox[0], bbox[3]) for index, bbox in enumerate(bboxes)},+ )++ assert "Model Name H<sub>2</sub>" in styled+ assert BeautifulSoup(styled, "html.parser").get_text() == "Model Name H2"++@pytest.mark.parametrize("angle", [0, 90, 180, 270])def test_table_script_geometry_uses_upright_coordinates(angle: int) -> None:"""验证四种标准方向下 cell loose/tight/origin 同步正向化。"""