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: optimize grid slot validation and improve hyperlink safety checks
myhloli5ea57a06e0ec
diff --git a/mineru/model/flash/office/odf/constants.py b/mineru/model/flash/office/odf/constants.pyindex baef4642..5526f9a4 100644--- a/mineru/model/flash/office/odf/constants.py+++ b/mineru/model/flash/office/odf/constants.py@@ -33,9 +33,7 @@ ODF_MIME_BY_SUFFIX: Final[dict[OdfSuffix, str]] = {"ods": "application/vnd.oasis.opendocument.spreadsheet","odp": "application/vnd.oasis.opendocument.presentation",}-ODF_SUFFIX_BY_MIME: Final[dict[str, OdfSuffix]] = {- mime: suffix for suffix, mime in ODF_MIME_BY_SUFFIX.items()-}+ODF_SUFFIX_BY_MIME: Final[dict[str, OdfSuffix]] = {mime: suffix for suffix, mime in ODF_MIME_BY_SUFFIX.items()}ODF_BODY_BY_SUFFIX: Final[dict[OdfSuffix, str]] = {"odt": "text","ods": "spreadsheet",@@ -47,7 +45,6 @@ MAX_TOTAL_BYTES: Final = 512 * 1024 * 1024MAX_ENTRY_COUNT: Final = 100_000MAX_XML_DEPTH: Final = 256MAX_XML_NODES: Final = 2_000_000-MAX_GRID_SLOTS: Final = 4_000_000MAX_EXPANSION_TEXT_BYTES: Final = 64 * 1024 * 1024MAX_ASSET_TOTAL_BYTES: Final = 128 * 1024 * 1024@@ -62,7 +59,6 @@ __all__ = ["MAX_ENTRY_BYTES","MAX_ENTRY_COUNT","MAX_EXPANSION_TEXT_BYTES",- "MAX_GRID_SLOTS","MAX_TOTAL_BYTES","MAX_XML_DEPTH","MAX_XML_NODES",diff --git a/mineru/model/flash/office/odf/table.py b/mineru/model/flash/office/odf/table.pyindex f30ad9fe..c3c8e20f 100644--- a/mineru/model/flash/office/odf/table.py+++ b/mineru/model/flash/office/odf/table.py@@ -9,7 +9,8 @@ from collections.abc import Callable, Iteratorfrom lxml import etree # type: ignore[reportMissingImports]-from .constants import MAX_EXPANSION_TEXT_BYTES, MAX_GRID_SLOTS, qname+from ..limits import MAX_GRID_SLOTS+from .constants import MAX_EXPANSION_TEXT_BYTES, qnamefrom .errors import OdfResourceLimitErrorfrom .models import GridCell, TableGrid@@ -76,8 +77,16 @@ def _has_visible_html(value: str) -> bool:return bool(html.unescape(_HTML_TEXT_RE.sub("", value)).strip())+def _validate_grid_extent(row_count: int, width: int) -> None:+ """在分配或遍历前校验预计矩形不会超过共享网格预算。"""+ projected_width = max(width, 1)+ if row_count > MAX_GRID_SLOTS // projected_width:+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")++def _ensure_row(grid: TableGrid, row_index: int, width: int = 0) -> list[GridCell | None]:"""确保网格存在指定行和最小列宽。"""+ _validate_grid_extent(max(len(grid.rows), row_index + 1), max(grid.width, width))while len(grid.rows) <= row_index:grid.rows.append([])row = grid.rows[row_index]@@ -88,9 +97,7 @@ def _ensure_row(grid: TableGrid, row_index: int, width: int = 0) -> list[GridCeldef _charge_grid(grid: TableGrid) -> None:"""按当前矩形边界检查最大网格槽位。"""- slots = len(grid.rows) * grid.width- if slots > MAX_GRID_SLOTS:- raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")+ _validate_grid_extent(len(grid.rows), grid.width)def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableGrid:@@ -102,31 +109,27 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableGpending_empty_width = 0for row_element, header in _iter_rows(table):row_repeat = _positive_int(row_element.get(qname("table", "number-rows-repeated")))- if row_repeat * max(grid.width, 1) > MAX_GRID_SLOTS:- raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")+ _validate_grid_extent(row_index + row_repeat, grid.width)cell_templates: list[tuple[bool, int, GridCell | None]] = []for cell in row_element:if not isinstance(cell.tag, str):continueif cell.tag == qname("table", "covered-table-cell"):- cell_templates.append(- (True, _positive_int(cell.get(qname("table", "number-columns-repeated"))), None)- )+ cell_templates.append((True, _positive_int(cell.get(qname("table", "number-columns-repeated"))), None))continueif cell.tag != qname("table", "table-cell"):continuecolumn_repeat = _positive_int(cell.get(qname("table", "number-columns-repeated")))row_span = _positive_int(cell.get(qname("table", "number-rows-spanned")))col_span = _positive_int(cell.get(qname("table", "number-columns-spanned")))+ _validate_grid_extent(row_span, col_span)cell_html = render_cell(cell)if not _has_visible_html(cell_html):typed_value = _typed_value_text(cell)cell_html = html.escape(typed_value) if typed_value else ""duplicated_text_bytes += len(cell_html.encode("utf-8")) * max(0, row_repeat * column_repeat - 1)if duplicated_text_bytes > MAX_EXPANSION_TEXT_BYTES:- raise OdfResourceLimitError(- f"ODF resource limit exceeded: max_expansion_text_bytes={MAX_EXPANSION_TEXT_BYTES}"- )+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_expansion_text_bytes={MAX_EXPANSION_TEXT_BYTES}")cell_templates.append((False,@@ -146,8 +149,7 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG)continueif pending_empty_rows:- if (row_index + pending_empty_rows) * max(grid.width, pending_empty_width, 1) > MAX_GRID_SLOTS:- raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")+ _validate_grid_extent(row_index + pending_empty_rows, max(grid.width, pending_empty_width))for _ in range(pending_empty_rows):_ensure_row(grid, row_index, pending_empty_width)row_index += 1@@ -173,6 +175,7 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableGcol_index += pending_empty_columns_ensure_row(grid, row_index, col_index)pending_empty_columns = 0+ _validate_grid_extent(row_index + 1, max(grid.width, col_index + repeat))for _ in range(repeat):if is_covered:_ensure_row(grid, row_index, col_index + 1)@@ -188,6 +191,10 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableGcol_span=template.col_span,header=template.header,)+ _validate_grid_extent(+ row_index + placed.row_span,+ max(grid.width, col_index + placed.col_span),+ )row = _ensure_row(grid, row_index, col_index + placed.col_span)row[col_index] = placedfor row_offset in range(placed.row_span):@@ -223,11 +230,7 @@ def trim_table_grid(grid: TableGrid) -> TableGrid:if len(row) < last_col + 1:row.extend([None] * (last_col + 1 - len(row)))rows.append(row)- covered = {- (row, col)- for row, col in grid.covered- if row <= last_row and col <= last_col- }+ covered = {(row, col) for row, col in grid.covered if row <= last_row and col <= last_col}return TableGrid(rows=rows, header_rows=min(grid.header_rows, len(rows)), covered=covered)@@ -319,10 +322,7 @@ def table_grid_to_html(grid: TableGrid) -> str:parts.append("</thead>")if header_rows < len(grid.rows):parts.append("<tbody>")- parts.extend(- _render_html_row(grid, row_index, header=False)- for row_index in range(header_rows, len(grid.rows))- )+ parts.extend(_render_html_row(grid, row_index, header=False) for row_index in range(header_rows, len(grid.rows)))parts.append("</tbody>")parts.append("</table>")return "".join(parts)diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.pyindex c86b18d2..ef8ba8c6 100644--- a/mineru/model/flash/office/odf/text.py+++ b/mineru/model/flash/office/odf/text.py@@ -9,6 +9,7 @@ import refrom collections.abc import Sequencefrom dataclasses import dataclassfrom typing import Any+from urllib.parse import urlsplitfrom lxml import etree # type: ignore[reportMissingImports]@@ -34,6 +35,7 @@ from .table import parse_table_grid, table_grid_to_html_WHITESPACE_RE = re.compile(r"[\t\r\n ]+")+_SAFE_EXTERNAL_HYPERLINK_SCHEMES = frozenset({"http", "https", "mailto", "tel"})@dataclass(frozen=True, slots=True)@@ -58,11 +60,32 @@ def _escape_href(value: str) -> str:def _safe_hyperlink(value: str | None) -> str | None:- """拒绝会破坏内部 URL 容器的尖括号和控制字符。"""- if value is None or any(char in value for char in ("<", ">", "\x00")):+ """保留安全相对链接与允许协议,拒绝活动协议和协议相对地址。"""+ if value is None:return None- normalized = "".join(char for char in value.strip() if ord(char) >= 32 or char in "\t\r\n")- return normalized or None+ normalized = value.strip()+ if not normalized or any(ord(char) < 32 for char in normalized) or any(char in normalized for char in ("<", ">")):+ return None+ if normalized.startswith(("//", "\\")):+ return None+ try:+ parsed = urlsplit(normalized)+ except ValueError:+ return None+ scheme = parsed.scheme.casefold()+ if not scheme:+ return normalized+ if scheme not in _SAFE_EXTERNAL_HYPERLINK_SCHEMES:+ return None+ if scheme in {"http", "https"}:+ try:+ if not parsed.netloc or parsed.hostname is None:+ return None+ except ValueError:+ return None+ elif not parsed.path:+ return None+ return normalizeddef _style_html(text: str, style: TextStyle) -> str:@@ -327,9 +350,11 @@ class OdfBlockParser:def parse_paragraph(self, paragraph: etree._Element, *, allow_page_breaks: bool = False) -> list[RawFlowItem]:"""把 text:p/text:h 转为标题、正文、公式及显式分页项。"""atoms, extra_blocks = self.parse_inline_atoms(paragraph)- groups = split_atoms_on_page_break(atoms) if allow_page_breaks else [[- InlineBreak() if isinstance(atom, InlinePageBreak) else atom for atom in atoms- ]]+ groups = (+ split_atoms_on_page_break(atoms)+ if allow_page_breaks+ else [[InlineBreak() if isinstance(atom, InlinePageBreak) else atom for atom in atoms]]+ )results: list[RawFlowItem] = []is_heading = paragraph.tag == qname("text", "h")style_name = paragraph.get(qname("text", "style-name"))@@ -377,8 +402,7 @@ class OdfBlockParser:items = [itemfor item in element- if isinstance(item.tag, str)- and item.tag in {qname("text", "list-item"), qname("text", "list-header")}+ if isinstance(item.tag, str) and item.tag in {qname("text", "list-item"), qname("text", "list-header")}]return self._parse_list_items(element, items, depth=depth, inherited_style=inherited_style)@@ -585,9 +609,13 @@ class OdfBlockParser:if object_element is not None:object_root, object_part = self._object_root(object_element)if object_root is not None:- math_element = object_root if object_root.tag == qname("math", "math") else next(- object_root.iter(qname("math", "math")),- None,+ math_element = (+ object_root+ if object_root.tag == qname("math", "math")+ else next(+ object_root.iter(qname("math", "math")),+ None,+ ))if math_element is not None and (latex := mathml_to_latex(math_element)):return InlineMath(latex), []@@ -677,9 +705,7 @@ class OdfBlockParser:if child.tag in {qname("text", "p"), qname("text", "h")}:atoms, extra = self.parse_inline_atoms(child)rendered_atoms = (- [atom for atom in atoms if not isinstance(atom, InlineImage)]- if self._collect_cell_visuals- else atoms+ [atom for atom in atoms if not isinstance(atom, InlineImage)] if self._collect_cell_visuals else atoms)parts.append(f"<p>{render_atoms_to_html(rendered_atoms)}</p>")for block in extra:@@ -703,13 +729,9 @@ class OdfBlockParser:inline, blocks = self._parse_frame(child)if self._collect_cell_visuals:self._cell_visuals.extend(- block- for block in blocks- if block.get("type") in {BlockType.IMAGE, BlockType.CHART, BlockType.EQUATION}+ block for block in blocks if block.get("type") in {BlockType.IMAGE, BlockType.CHART, BlockType.EQUATION})- if inline is not None and not (- self._collect_cell_visuals and isinstance(inline, InlineImage)- ):+ if inline is not None and not (self._collect_cell_visuals and isinstance(inline, InlineImage)):parts.append(render_atoms_to_html([inline]))for block in blocks:if self._collect_cell_visuals and block.get("type") in {diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex ff918b0c..585483bd 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -11,7 +11,9 @@ from typing import Anyfrom zipfile import ZIP_DEFLATED, ZipFileimport pytest+from lxml import etree+import mineru.model.flash.office.odf.table as odf_table_modulefrom mineru.backend.analyze import aio_doc_analyze, doc_analyzefrom mineru.doclib.core.file_io import extract_metadatafrom mineru.doclib.core.db import DatabaseManager@@ -25,7 +27,7 @@ from mineru.parser import parse, parse_asyncfrom mineru.parser import api_serverfrom mineru.parser.api_server import CreateJobRequest, FileStorefrom mineru.parser.file_type import guess_suffix_by_bytes, guess_suffix_by_path-from mineru.render import render_html, render_markdown, render_structured_content+from mineru.render import render_docx, render_html, render_markdown, render_structured_contentfrom mineru.types import BlockTypefrom _odf_test_utils import build_odf_package, build_odp_fixture, build_ods_fixture, build_odt_fixture@@ -79,14 +81,10 @@ def test_odt_recovers_structure_and_all_renderers() -> None:assert BlockType.FOOTER in raw_typesassert any('style="bold"' in str(block.get("content")) for block in raw_blocks)assert any(- "rowspan" not in str(block.get("content")) and 'colspan="2"' in str(block.get("content"))- for block in raw_blocks+ "rowspan" not in str(block.get("content")) and 'colspan="2"' in str(block.get("content")) for block in raw_blocks)assert any(block.get("content") == r"\frac{x}{2}" for block in raw_blocks)- assert any(- block.get("type") == BlockType.PAGE_FOOTNOTE and "Note body" in block.get("content", "")- for block in raw_blocks- )+ assert any(block.get("type") == BlockType.PAGE_FOOTNOTE and "Note body" in block.get("content", "") for block in raw_blocks)markdown = render_markdown(middle)html_output = render_html(middle)@@ -162,7 +160,7 @@ def test_odf_content_detection_precedes_csv_extension(def test_rtf_signature_still_precedes_odf_extension(tmp_path: Path) -> None:"""验证新增 ZIP 探测不改变 RTF 强签名的最高优先级。"""source = tmp_path / "disguised.odt"- source.write_bytes(br"{\rtf1\ansi visible}")+ source.write_bytes(rb"{\rtf1\ansi visible}")assert guess_suffix_by_path(source) == "rtf"assert guess_suffix_by_bytes(source.read_bytes(), str(source)) == "rtf"@@ -202,6 +200,117 @@ def test_odf_rejects_mismatched_encrypted_and_expanding_packages() -> None:OdsModel().predict(BytesIO(expanding))[email protected]("span_attribute", ["number-rows-spanned", "number-columns-spanned"])+def test_odf_rejects_oversized_cell_spans_before_grid_materialization(+ monkeypatch: pytest.MonkeyPatch,+ span_attribute: str,+) -> None:+ """验证超大行列跨度在渲染单元格或扩容网格前立即失败。"""+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)++ def unexpected_materialization(*_args: object, **_kwargs: object) -> None:+ """超限 span 不得进入单元格渲染或网格扩容。"""+ pytest.fail("oversized span reached grid materialization")++ monkeypatch.setattr(odf_table_module, "_ensure_row", unexpected_materialization)+ table = etree.fromstring(+ f'<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'+ f'<table:table-row><table:table-cell table:{span_attribute}="5"/></table:table-row>'+ "</table:table>"+ )++ with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):+ odf_table_module.parse_table_grid(table, unexpected_materialization)+++def test_odf_rejects_projected_span_extent_before_extending_existing_row(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证单个 span 合法但累计宽度超限时不会先扩展现有行。"""+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)+ original_ensure_row = odf_table_module._ensure_row+ observed_widths: list[int] = []++ def tracking_ensure_row(grid: object, row_index: int, width: int = 0) -> object:+ """记录实际扩容宽度,确保失败前未越过共享预算。"""+ observed_widths.append(width)+ return original_ensure_row(grid, row_index, width) # type: ignore[arg-type]++ monkeypatch.setattr(odf_table_module, "_ensure_row", tracking_ensure_row)+ table = etree.fromstring(+ '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'+ '<table:table-row><table:table-cell table:number-columns-spanned="3"/>'+ '<table:table-cell table:number-columns-spanned="2"/></table:table-row>'+ "</table:table>"+ )++ with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):+ odf_table_module.parse_table_grid(table, lambda _cell: "x")+ assert observed_widths and max(observed_widths) <= 3+++ "target",+ [+ "javascript:alert(1)",+ "JaVaScRiPt:alert(1)",+ "data:text/plain,unsafe",+ "vbscript:msgbox(1)",+ "file:///tmp/unsafe",+ "ftp://example.com/file",+ "//example.com/path",+ "\\\\server\\share",+ ],+)+def test_odf_rejects_unsafe_hyperlinks_before_shared_renderers(target: str) -> None:+ """验证危险 ODF 链接在 Raw 阶段降级,Markdown 与 DOCX 不再携带目标。"""+ content = f'''<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:body><office:text><text:p>before <text:a xlink:href="{target}">click</text:a> after</text:p>+ </office:text></office:body></office:document-content>'''+ payload = build_odf_package("odt", content)+ pages = OdtModel().predict(BytesIO(payload))+ middle, _ = doc_analyze(payload, file_suffix="odt")+ markdown = render_markdown(middle)+ docx = render_docx(middle)+ with ZipFile(BytesIO(docx)) as package:+ relationships = package.read("word/_rels/document.xml.rels").decode("utf-8")++ assert pages == [[{"type": BlockType.TEXT, "content": "before click after"}]]+ assert markdown == "before click after"+ assert target not in relationships+++ "target",+ [+ "https://example.com/path",+ "mailto:[email protected]",+ "tel:+123456",+ "#section-one",+ "chapter.odt#section-one",+ ],+)+def test_odf_preserves_allowed_external_and_relative_hyperlinks(target: str) -> None:+ """验证允许协议、相对地址和 fragment 继续进入共享 hyperlink 协议。"""+ content = f'''<office:document-content+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:body><office:text><text:p><text:a xlink:href="{target}">click</text:a></text:p>+ </office:text></office:body></office:document-content>'''+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content)))++ assert pages == [+ [+ {+ "type": BlockType.TEXT,+ "content": f"<hyperlink><text>click</text><url>{target}</url></hyperlink>",+ }+ ]+ ]++def test_odf_corrupt_optional_styles_and_external_image_degrade_locally() -> None:"""验证可选样式损坏和外部图片不会阻断正文或触发网络读取。"""content = """<office:document-content