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: harden ODF metadata and RTF parsing
myhlolie6f52e3b38e9
diff --git a/mineru/model/flash/office/odf/metadata.py b/mineru/model/flash/office/odf/metadata.pyindex ace5eae7..3a1af22f 100644--- a/mineru/model/flash/office/odf/metadata.py+++ b/mineru/model/flash/office/odf/metadata.py@@ -3,7 +3,7 @@from __future__ import annotations-from typing import BinaryIO+from typing import BinaryIO, Finalfrom lxml import etree # type: ignore[reportMissingImports]@@ -12,6 +12,9 @@ from .package import OdfPackagefrom .styles import OdfStyles+MAX_ODT_METADATA_PAGE_COUNT: Final = 10_000++def _first_text(root: etree._Element | None, *tags: str) -> str | None:"""返回多个候选标签中首个非空文本。"""if root is None:@@ -36,7 +39,7 @@ def _odt_page_count(meta_root: etree._Element | None) -> int | None:value = int(statistic.get(qname("meta", "page-count"), ""))except ValueError:return None- return value if value >= 1 else None+ return min(value, MAX_ODT_METADATA_PAGE_COUNT) if value >= 1 else Nonedef _visible_sheet_count(body: etree._Element, styles: OdfStyles) -> int:diff --git a/mineru/model/flash/office/rtf/converter.py b/mineru/model/flash/office/rtf/converter.pyindex e0b10530..3e489ef7 100644--- a/mineru/model/flash/office/rtf/converter.py+++ b/mineru/model/flash/office/rtf/converter.py@@ -192,11 +192,12 @@ class RtfConverter:for inline in inlines:if isinstance(inline, RtfTextRun):+ hyperlink = self._resolved_hyperlink(inline.hyperlink)segments.append(OfficeRichTextSegment(- text=inline.text,+ text=escape(inline.text, quote=False),style=_style_names(inline),- hyperlink=self._resolved_hyperlink(inline.hyperlink),+ hyperlink=escape(hyperlink, quote=False) if hyperlink is not None else None,))elif isinstance(inline, RtfInlineEquation):diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.pyindex ee3a07ff..2a142ec6 100644--- a/mineru/model/flash/office/rtf/parser.py+++ b/mineru/model/flash/office/rtf/parser.py@@ -50,6 +50,7 @@ MAX_RTF_BYTES = MAX_ENTRY_BYTESMAX_RTF_LIST_DEPTH = 8MAX_RTF_TABLE_DEPTH = 4MAX_RTF_ROMAN_VALUE = 3_999+MAX_RTF_TABLE_CELLS = 100_000_CHARSET_ENCODINGS = {0: "cp1252",@@ -250,6 +251,13 @@ class _TableBuilder:self._pending_horizontal: Literal["none", "start", "continue"] = "none"self._pending_vertical: Literal["none", "start", "continue"] = "none"self._row_open = False+ self._total_slots = 0++ def _check_cell_budget(self, row_cell_count: int) -> None:+ """在保存定义或物化 cell 前校验当前表格对象预算。"""+ limit = min(MAX_GRID_SLOTS, MAX_RTF_TABLE_CELLS)+ if self._total_slots + row_cell_count > limit:+ raise LegacyOfficeResourceLimitError(f"RTF table exceeds max_grid_slots={limit}")def start_row(self) -> None:"""开始新行;若上一行未显式结束则先安全收束。"""@@ -283,6 +291,7 @@ class _TableBuilder:"""在 cellx 边界冻结当前单元格定义。"""if not self._row_open:self.start_row()+ self._check_cell_budget(max(len(self._definitions) + 1, len(self._cells)))self._definitions.append(_CellDefinition(horizontal_merge=self._pending_horizontal,@@ -310,6 +319,7 @@ class _TableBuilder:"""结束当前单元格,并按同位置 cellx 定义附加合并属性。"""if not self._row_open:self.start_row()+ self._check_cell_budget(max(len(self._definitions), len(self._cells) + 1))definition_index = len(self._cells)definition = self._definitions[definition_index] if definition_index < len(self._definitions) else _CellDefinition()self._cells.append(@@ -329,13 +339,12 @@ class _TableBuilder:if self._cell_blocks:self.end_cell()target_cells = max(len(self._definitions), len(self._cells))+ self._check_cell_budget(target_cells)while len(self._cells) < target_cells:self.end_cell()if target_cells:- total_slots = sum(len(row.cells) for row in self.rows) + target_cells- if total_slots > MAX_GRID_SLOTS:- raise LegacyOfficeResourceLimitError(f"RTF table exceeds max_grid_slots={MAX_GRID_SLOTS}")self.rows.append(RtfTableRow(cells=self._cells, header=self._row_header))+ self._total_slots += target_cellsself._definitions = []self._cells = []self._cell_blocks = []@@ -1520,6 +1529,7 @@ def parse_rtf(file_binary: BinaryIO) -> RtfDocument:__all__ = ["MAX_RTF_BYTES","MAX_RTF_LIST_DEPTH",+ "MAX_RTF_TABLE_CELLS","MAX_RTF_TABLE_DEPTH","RtfParser","parse_rtf",diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex 5e0180af..08699c08 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -22,6 +22,7 @@ from mineru.doclib.services.parse_svc import ParseServicefrom mineru.errors import InvalidRequestErrorfrom mineru.model.flash import OdpModel, OdsModel, OdtModelfrom mineru.model.flash.office.odf.errors import OdfEncryptedError, OdfParseError, OdfResourceLimitError+from mineru.model.flash.office.odf.metadata import MAX_ODT_METADATA_PAGE_COUNT, extract_odf_metadatafrom mineru.model.flash.office.odf.package import OdfPackagefrom mineru.parser import parse, parse_asyncfrom mineru.parser import api_server@@ -606,6 +607,24 @@ def test_doclib_extracts_odf_metadata(assert metadata[key] == value+def test_odt_metadata_page_count_is_bounded_before_doclib_range_expansion() -> None:+ """验证 producer page-count 不会把微小 ODT 扩张为无界任务范围。"""+ content = """<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0">+ <office:body><office:text/></office:body>+</office:document-content>"""+ meta = """<office:document-meta+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0">+ <office:meta><meta:document-statistic meta:page-count="999999999999"/></office:meta>+</office:document-meta>"""++ metadata = extract_odf_metadata(BytesIO(build_odf_package("odt", content, meta_xml=meta)), "odt")++ assert MAX_ODT_METADATA_PAGE_COUNT == 10_000+ assert metadata["page_count"] == MAX_ODT_METADATA_PAGE_COUNT++@pytest.mark.parametrize(("suffix", "payload"),[("odt", build_odt_fixture()), ("ods", build_ods_fixture()), ("odp", build_odp_fixture())],diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex de02722d..b02d3302 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -373,8 +373,27 @@ def test_rtf_source_html_is_rendered_as_inert_text() -> None:markdown = render_markdown(middle)assert "<script>" not in html- assert "<script>alert(1)</script>" in html- assert "script" in markdown and "alert(1)" in markdown+ assert "&lt;script&gt;alert(1)&lt;/script&gt;" in html+ assert "<script>alert(1)</script>" in markdown+++def test_rtf_literal_inline_protocol_is_escaped_before_rendering() -> None:+ """验证普通 RTF 文本不能注入 equation 或 hyperlink 内部协议。"""+ source = (+ rb"{\rtf1\ansi literal <eq>x</eq> and "+ rb"<hyperlink><text>click</text><url>javascript:alert(1)</url></hyperlink>\par}"+ )++ pages = RtfModel().predict(BytesIO(source))+ middle, _ = doc_analyze(source, file_suffix="rtf")+ markdown = render_markdown(middle)++ content = pages[0][0]["content"]+ assert "<eq>x</eq>" in content+ assert "<hyperlink>" in content+ assert "<eq>" not in content+ assert "<hyperlink>" not in content+ assert "](javascript:alert(1))" not in markdowndef test_rtf_object_keeps_safe_result_and_suppresses_objdata() -> None:@@ -432,6 +451,15 @@ def test_rtf_resource_limits_are_fixed_and_non_configurable(monkeypatch: pytest.RtfModel().predict(BytesIO(rb"{\rtf1\pard\intbl\itap5 nested\par}"))+def test_rtf_cell_definitions_enforce_budget_before_row_materialization(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证 cellx 在定义列表增长阶段即执行 RTF 专用 cell 预算。"""+ monkeypatch.setattr(parser_module, "MAX_RTF_TABLE_CELLS", 3)+ source = rb"{\rtf1\trowd\cellx1\cellx2\cellx3\cellx4}"++ with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots=3"):+ RtfModel().predict(BytesIO(source))++def test_rtf_prelude_nested_groups_do_not_materialize_overlapping_slices() -> None:"""验证 prelude 扫描深层 group 时峰值内存保持为输入规模常数倍。"""payload_size = 256 * 1024