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: address flash parser review findings
myhlolifc53c49b5058
diff --git a/mineru/model/flash/_shared/mathml.py b/mineru/model/flash/_shared/mathml.pyindex 3337434a..9aeadeb1 100644--- a/mineru/model/flash/_shared/mathml.py+++ b/mineru/model/flash/_shared/mathml.py@@ -140,6 +140,8 @@ def _convert(element: etree._Element) -> str:def mathml_to_latex(math_element: etree._Element) -> str | None:"""转换 MathML 根节点,并优先采用生产者保留的 TeX annotation。"""for annotation in math_element.iter():+ if not isinstance(annotation.tag, str):+ continueif _local_name(annotation) != "annotation":continueencoding = (annotation.get("encoding") or "").casefold()diff --git a/mineru/model/flash/epub/styles.py b/mineru/model/flash/epub/styles.pyindex 2b36236f..d51e0030 100644--- a/mineru/model/flash/epub/styles.py+++ b/mineru/model/flash/epub/styles.py@@ -4,12 +4,13 @@from __future__ import annotationsimport re-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom lxml import etree # type: ignore[reportMissingImports]_CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)+_TEXT_STYLE_FIELDS = ("bold", "italic", "underline", "strikethrough", "superscript", "subscript")@dataclass(frozen=True, slots=True)@@ -95,16 +96,22 @@ class ElementStyle:hidden: bool = False-@dataclass(frozen=True, slots=True)-class _Rule:- """保存一个受支持的简单 CSS selector 及其声明。"""+@dataclass(slots=True)+class _SelectorCascade:+ """按 selector 聚合各属性最后一次声明及其源码顺序。"""- tag: str | None- class_name: str | Nonepriority: int- order: int- style: TextStyleDelta- hidden: bool | None+ declarations: dict[str, tuple[int, bool]] = field(default_factory=dict)+ hidden: tuple[int, bool] | None = None++ def update(self, style: TextStyleDelta, hidden: bool | None, order: int) -> None:+ """用同 selector 的较新声明更新逐属性级联结果。"""+ for name in _TEXT_STYLE_FIELDS:+ value = getattr(style, name)+ if value is not None:+ self.declarations[name] = (order, value)+ if hidden is not None:+ self.hidden = (order, hidden)def _local_name(element: etree._Element) -> str:@@ -147,8 +154,20 @@ class EpubStylesheet:"""保存按文档顺序解析的简单 tag/class CSS 规则。"""def __init__(self) -> None:- """初始化空规则列表。"""- self._rules: list[_Rule] = []+ """初始化按 tag、class 与 tag.class 分桶的 selector 索引。"""+ self._tag_cascades: dict[str, _SelectorCascade] = {}+ self._class_cascades: dict[str, _SelectorCascade] = {}+ self._tag_class_cascades: dict[tuple[str, str], _SelectorCascade] = {}+ self._source_order = 0++ def _selector_cascade(self, tag: str | None, class_name: str | None, priority: int) -> _SelectorCascade:+ """返回指定简单 selector 的聚合级联槽。"""+ if class_name is None:+ assert tag is not None+ return self._tag_cascades.setdefault(tag, _SelectorCascade(priority))+ if tag is None:+ return self._class_cascades.setdefault(class_name, _SelectorCascade(priority))+ return self._tag_class_cascades.setdefault((tag, class_name), _SelectorCascade(priority))def add(self, css: str) -> None:"""追加一个 stylesheet 中受支持的简单 selector 规则。"""@@ -165,7 +184,9 @@ class EpubStylesheet:if parsed is None:continuetag, class_name, priority = parsed- self._rules.append(_Rule(tag, class_name, priority, len(self._rules), style, hidden))+ cascade = self._selector_cascade(tag, class_name, priority)+ cascade.update(style, hidden, self._source_order)+ self._source_order += 1@staticmethoddef _parse_selector(selector: str) -> tuple[str | None, str | None, int] | None:@@ -194,19 +215,35 @@ class EpubStylesheet:)style = inherited.merge(tag_style)hidden = element.get("hidden") is not None or (element.get("aria-hidden") or "").casefold() == "true"- matching = sorted(- (- rule- for rule in self._rules- if (rule.tag is None or rule.tag == tag)- and (rule.class_name is None or rule.class_name in classes)- ),- key=lambda rule: (rule.priority, rule.order),- )- for rule in matching:- style = rule.style.apply(style)- if rule.hidden is not None:- hidden = rule.hidden+ matching: list[_SelectorCascade] = []+ if cascade := self._tag_cascades.get(tag):+ matching.append(cascade)+ for class_name in classes:+ if cascade := self._class_cascades.get(class_name):+ matching.append(cascade)+ if cascade := self._tag_class_cascades.get((tag, class_name)):+ matching.append(cascade)++ resolved_values: dict[str, bool] = {}+ for name in _TEXT_STYLE_FIELDS:+ candidates = [+ (cascade.priority, order, value)+ for cascade in matching+ if (declaration := cascade.declarations.get(name)) is not None+ for order, value in (declaration,)+ ]+ if candidates:+ resolved_values[name] = max(candidates, key=lambda item: (item[0], item[1]))[2]+ style = TextStyleDelta(**resolved_values).apply(style)++ hidden_candidates = [+ (cascade.priority, order, value)+ for cascade in matching+ if cascade.hidden is not None+ for order, value in (cascade.hidden,)+ ]+ if hidden_candidates:+ hidden = max(hidden_candidates, key=lambda item: (item[0], item[1]))[2]inline_style, inline_hidden = _parse_declarations(element.get("style") or "")style = inline_style.apply(style)if inline_hidden is not None:diff --git a/mineru/model/flash/office/odf/table.py b/mineru/model/flash/office/odf/table.pyindex ceef5de9..ce83f356 100644--- a/mineru/model/flash/office/odf/table.py+++ b/mineru/model/flash/office/odf/table.py@@ -329,12 +329,19 @@ def table_grid_to_html(grid: TableGrid) -> str:return "".join(parts)-def _column_index(label: str) -> int:- """把 A1 地址中的列字母转换为零基列号。"""+def _column_index(label: str) -> int | None:+ """在共享网格预算内把 A1 地址中的列字母转换为零基列号。"""+ max_label_length = 0+ remaining = MAX_GRID_SLOTS+ while remaining > 0:+ max_label_length += 1+ remaining = (remaining - 1) // 26+ if not label or len(label) > max_label_length:+ return Noneresult = 0for char in label.upper():result = result * 26 + ord(char) - ord("A") + 1- return result - 1+ return result - 1 if result <= MAX_GRID_SLOTS else Nonedef parse_cell_range_bounds(address: str) -> tuple[int, int, int, int] | None:@@ -348,6 +355,8 @@ def parse_cell_range_bounds(address: str) -> tuple[int, int, int, int] | None:col_start = _column_index(first.group("col"))row_end = int(last.group("row")) - 1col_end = _column_index(last.group("col"))+ if col_start is None or col_end is None:+ return Nonereturn min(row_start, row_end), max(row_start, row_end), min(col_start, col_end), max(col_start, col_end)diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.pyindex e2e14b72..69bf1221 100644--- a/mineru/model/flash/office/rtf/parser.py+++ b/mineru/model/flash/office/rtf/parser.py@@ -393,6 +393,7 @@ class _GroupFrame:instruction: list[str] = field(default_factory=list)pict: _PictCapture | None = Nonenote_kind: Literal["footnote", "endnote"] = "footnote"+ upr_child_count: int = 0@dataclass(frozen=True, slots=True)@@ -873,7 +874,14 @@ class RtfParser:def _open_group(self, token: RtfOpen) -> None:"""压入当前状态,新的 group 初始继承所有属性。"""self._flush_bytes()+ parent = self._current_frame()self.frames.append(_GroupFrame(previous_state=replace(self.state), start=token.start))+ if parent is not None and parent.destination == "upr":+ parent.upr_child_count += 1+ if parent.upr_child_count == 2:+ self.state.destination = "upr_unicode"+ else:+ self.state.destination = "suppressed"def _close_group(self, token: RtfClose) -> None:"""收束当前 destination 并恢复父 group 状态。"""@@ -898,8 +906,18 @@ class RtfParser:frame = self._current_frame()if frame is None or frame.destination is not None:return False+ if name == "ud" and self.state.destination == "upr_unicode":+ upr_frame = self._nearest_frame("upr")+ if upr_frame is not None:+ frame.destination = "ud"+ self.state.destination = upr_frame.previous_state.destination+ return Trueif self.state.destination in {"math", "pict", "suppressed"}:return False+ if name == "upr":+ frame.destination = "upr"+ self.state.destination = "upr"+ return Trueif name in _SUPPRESSED_DESTINATIONS:frame.destination = nameself.state.destination = "suppressed"diff --git a/mineru/model/flash/office/xls/xls_converter.py b/mineru/model/flash/office/xls/xls_converter.pyindex 4f19b18f..798d20d1 100644--- a/mineru/model/flash/office/xls/xls_converter.py+++ b/mineru/model/flash/office/xls/xls_converter.py@@ -112,6 +112,7 @@ class _XlsPageBuilder(SpreadsheetProjector):"""把 BIFF 语义模型投影成不落盘的 worksheet 对象。"""workbook = Workbook()+ merge_grid_slots = 0default_sheet = workbook.activeif default_sheet is not None:workbook.remove(default_sheet)@@ -126,6 +127,10 @@ class _XlsPageBuilder(SpreadsheetProjector):if cell_model.hyperlink:cell.hyperlink = cell_model.hyperlinkfor row_first, col_first, row_last, col_last in sheet_model.merges:+ merge_slots = (row_last - row_first + 1) * (col_last - col_first + 1)+ if merge_slots > MAX_GRID_SLOTS - merge_grid_slots:+ raise LegacyOfficeResourceLimitError(f"workbook extent exceeds max_grid_slots={MAX_GRID_SLOTS}")+ merge_grid_slots += merge_slotsworksheet.merge_cells(start_row=row_first + 1,start_column=col_first + 1,diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.pyindex bc89edb3..0c8addc1 100644--- a/tests/unittest/test_flash_epub.py+++ b/tests/unittest/test_flash_epub.py@@ -21,6 +21,7 @@ from mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestErrorfrom mineru.model.flash import EpubModelfrom mineru.model.flash.epub import EpubEncryptedError, EpubPackage, EpubParseError, EpubResourceLimitError, detect_epub+from mineru.model.flash.epub.styles import EpubStylesheet, TextStylefrom mineru.model.flash.epub.xhtml import EpubChapterConverter, build_anchor_registryfrom mineru.parser import MinerUParser, parse, parse_asyncfrom mineru.parser import api_server@@ -557,6 +558,24 @@ def test_epub_resource_limits_fail_before_semantic_conversion(monkeypatch: pytesEpubPackage(payload)+def test_epub_stylesheet_indexes_repeated_selectors_and_preserves_cascade_order() -> None:+ """验证重复 selector 按属性聚合,交错同优先级规则仍遵守源码顺序。"""+ stylesheet = EpubStylesheet()+ stylesheet.add(+ ".x { font-weight: bold; display: none; }"+ ".y { font-weight: normal; display: block; }"+ ".x { font-style: italic; }" + ".unused { text-decoration: underline; }" * 10_000+ )+ element = etree.fromstring(b'<span class="x y"/>')++ resolved = stylesheet.resolve(element, TextStyle())++ assert resolved.text.bold is False+ assert resolved.text.italic is True+ assert resolved.hidden is False+ assert len(stylesheet._class_cascades) == 3++def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:"""验证 doclib 从 OPF 读取元数据和 spine 逻辑页数。"""source = tmp_path / "book.epub"diff --git a/tests/unittest/test_flash_legacy_xls.py b/tests/unittest/test_flash_legacy_xls.pyindex e27925e8..9efee996 100644--- a/tests/unittest/test_flash_legacy_xls.py+++ b/tests/unittest/test_flash_legacy_xls.py@@ -256,6 +256,51 @@ def test_xls_record_and_grid_limits_are_hard_failures(XlsModel().predict(BytesIO(build_xls([SheetFixture("Data", label_cell(0, 0, "value"))])))+def test_xls_rejects_oversized_merge_before_openpyxl_materialization(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证单个超限 BIFF merge 不会进入 openpyxl 单元格物化。"""+ monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 4)++ def unexpected_merge(*_args: object, **_kwargs: object) -> None:+ """超限 merge 不得调用 openpyxl。"""+ pytest.fail("oversized BIFF merge reached openpyxl materialization")++ monkeypatch.setattr(xls_converter_module.Worksheet, "merge_cells", unexpected_merge)+ source = build_xls([SheetFixture("Data", merged_cells((0, 0, 2, 1)))])++ with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):+ XlsModel().predict(BytesIO(source))+++def test_xls_charges_cumulative_merge_budget_before_each_materialization(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证多个合法 merge 的累计面积会在下一次物化前触发预算。"""+ monkeypatch.setattr(xls_converter_module, "MAX_GRID_SLOTS", 4)+ original_merge = xls_converter_module.Worksheet.merge_cells+ materialized: list[tuple[object, ...]] = []++ def tracking_merge(self: object, *args: object, **kwargs: object) -> None:+ """记录预算内实际进入 openpyxl 的 merge。"""+ materialized.append(args or tuple(kwargs.values()))+ original_merge(self, *args, **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(xls_converter_module.Worksheet, "merge_cells", tracking_merge)+ source = build_xls(+ [+ SheetFixture(+ "Data",+ merged_cells(+ (0, 0, 0, 1),+ (1, 0, 1, 1),+ (2, 0, 2, 1),+ ),+ )+ ]+ )++ with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):+ XlsModel().predict(BytesIO(source))+ assert len(materialized) == 2++def test_xls_is_supported_by_public_parser(tmp_path: Path) -> None:"""验证公共 parser 通过统一 MinerUParser 路由 XLS。"""diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex eae1a432..02c7ba71 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -573,6 +573,15 @@ def test_odf_rejects_projected_span_extent_before_extending_existing_row(monkeypassert observed_widths and max(observed_widths) <= 3+def test_odf_rejects_overlong_chart_columns_before_bigint_conversion(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 chart A1 列名在大整数转换前受共享网格预算约束。"""+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)++ assert odf_table_module.parse_cell_range_bounds("local-table.D1:D2") == (0, 1, 3, 3)+ assert odf_table_module.parse_cell_range_bounds("local-table.E1:E2") is None+ assert odf_table_module.parse_cell_range_bounds(f"local-table.{'A' * 100_000}1") is None++@pytest.mark.parametrize("target",[diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex e56069e2..6fc35bed 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -96,6 +96,15 @@ def test_rtf_unicode_controls_buffer_adjacent_text_without_repeated_run_copy() -assert text_replacements == []+def test_rtf_upr_prefers_unicode_branch_without_leaking_ansi_fallback() -> None:+ """验证 Unicode-aware parser 在 upr 中只输出 ud 分支。"""+ source = rb"{\rtf1\ansi Before {\upr{?}{\*\ud{\u20013?}}} After\par}"++ pages = RtfModel().predict(BytesIO(source))++ assert pages == [[{"type": BlockType.TEXT, "content": "Before 中 After"}]]++def test_rtf_inherited_style_honors_explicit_formatting_resets() -> None:"""验证 derived stylesheet 的 b0/i0/ul0/strike0 覆盖基样式开启值。"""source = (diff --git a/tests/unittest/test_flash_shared_helpers.py b/tests/unittest/test_flash_shared_helpers.pyindex be3e4dd4..877c4c4b 100644--- a/tests/unittest/test_flash_shared_helpers.py+++ b/tests/unittest/test_flash_shared_helpers.py@@ -55,6 +55,21 @@ def test_mathml_semantics_ignores_non_tex_alternate_annotations() -> None:assert mathml_to_latex(math) == r"\frac{x}{2}"[email protected]("extra_node", ["<!--producer note-->", "<?producer note?>"])+def test_mathml_annotation_scan_skips_non_element_nodes(extra_node: str) -> None:+ """验证 TeX annotation 扫描跳过 XML comment 与处理指令。"""+ math = etree.fromstring(+ (+ '<math xmlns="http://www.w3.org/1998/Math/MathML">'+ f"{extra_node}"+ '<semantics><mi>x</mi><annotation encoding="application/x-tex">x^2</annotation></semantics>'+ "</math>"+ ).encode()+ )++ assert mathml_to_latex(math) == "x^2"++def test_legacy_binary_readers_preserve_bounds_and_values() -> None:"""验证旧版 Office 共用读取器只在完整边界内返回小端数值。"""data = struct.pack("<HhId", 0xABCD, -123, 0x1234_5678, 1.25)