Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix: enforce ODF and RTF parser boundaries

myhloliee04b7310652
diff --git a/mineru/model/flash/office/odf/chart.py b/mineru/model/flash/office/odf/chart.py
index 988789f1..065859de 100644
--- a/mineru/model/flash/office/odf/chart.py
+++ b/mineru/model/flash/office/odf/chart.py
@@ -10,7 +10,14 @@ from lxml import etree # type: ignore[reportMissingImports]
from .....types import BlockType
from .constants import qname
from .models import TableGrid
-from .table import crop_table_grid, parse_cell_range_bounds, parse_table_grid, table_grid_to_html, union_bounds
+from .table import (
+ OdfTableExpansionBudget,
+ crop_table_grid,
+ parse_cell_range_bounds,
+ parse_table_grid,
+ table_grid_to_html,
+ union_bounds,
+)
def _chart_range_bounds(chart: etree._Element) -> tuple[int, int, int, int] | None:
@@ -39,12 +46,16 @@ def parse_chart_block(
*,
render_cell: Callable[[etree._Element], str],
preview_data_uri: str | None,
+ table_expansion_budget: OdfTableExpansionBudget | None = None,
) -> dict | None:
"""按精确引用优先、唯一表回退的规则构造图表 raw block。"""
chart = next(object_root.iter(qname("chart", "chart")), None)
if chart is None:
return None
- grids = [parse_table_grid(table, render_cell) for table in object_root.iter(qname("table", "table"))]
+ grids = [
+ parse_table_grid(table, render_cell, expansion_budget=table_expansion_budget)
+ for table in object_root.iter(qname("table", "table"))
+ ]
selected: TableGrid | None = None
if grids and (bounds := _chart_range_bounds(chart)) is not None:
selected = crop_table_grid(grids[0], bounds)
diff --git a/mineru/model/flash/office/odf/converters.py b/mineru/model/flash/office/odf/converters.py
index 2a77aa3f..190890b5 100644
--- a/mineru/model/flash/office/odf/converters.py
+++ b/mineru/model/flash/office/odf/converters.py
@@ -15,8 +15,14 @@ from .constants import OdfSuffix, qname
from .models import InlineNote
from .package import OdfPackage
from .styles import OdfStyles
-from .table import parse_table_grid, split_table_regions, table_grid_to_html
-from .text import OdfBlockParser, OdfTextExpansionBudget, collect_emittable_anchor_targets, flatten_block_text
+from .table import OdfTableExpansionBudget, parse_table_grid, split_table_regions, table_grid_to_html
+from .text import (
+ OdfBlockParser,
+ OdfMasterPageChange,
+ OdfTextExpansionBudget,
+ collect_emittable_anchor_targets,
+ flatten_block_text,
+)
_LENGTH_RE = re.compile(r"^\s*(?P<value>[+-]?(?:\d+(?:\.\d*)?|\.\d+))(?P<unit>cm|mm|in|pt|pc|px)?\s*$")
@@ -99,6 +105,7 @@ def _master_auxiliary_blocks(
styles: OdfStyles,
anchor_targets: frozenset[str],
text_expansion_budget: OdfTextExpansionBudget,
+ table_expansion_budget: OdfTableExpansionBudget,
) -> list[dict[str, Any]]:
"""从 master-page 的 header/footer 中提取页面辅助文本。"""
if master_page is None:
@@ -108,6 +115,7 @@ def _master_auxiliary_blocks(
styles,
anchor_targets=anchor_targets,
text_expansion_budget=text_expansion_budget,
+ table_expansion_budget=table_expansion_budget,
)
result: list[dict[str, Any]] = []
for tag_name, block_type in (("header", BlockType.HEADER), ("footer", BlockType.FOOTER)):
@@ -137,23 +145,25 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
page_masters: list[str | None] = [None]
current_master: str | None = None
+ def apply_master_page(requested_master: str | None) -> None:
+ """按段落或列表事件切换 ODT 虚拟页及其 master-page。"""
+ nonlocal current_master
+ master_changed = requested_master is not None and current_master is not None and requested_master != current_master
+ if master_changed and pages[-1]:
+ _flush_notes(parser, pages[-1])
+ _new_page(pages, page_masters, requested_master)
+ if requested_master is not None:
+ current_master = requested_master
+ page_masters[-1] = current_master
+
def walk(parent: etree._Element) -> None:
"""递归遍历 ODT block 容器并维护当前页与 master-page。"""
- nonlocal current_master
for child in parent:
if not isinstance(child.tag, str):
continue
if child.tag in {qname("text", "p"), qname("text", "h")}:
requested_master = context.styles.paragraph_master_page_name(child.get(qname("text", "style-name")))
- master_changed = (
- requested_master is not None and current_master is not None and requested_master != current_master
- )
- if master_changed and pages[-1]:
- _flush_notes(parser, pages[-1])
- _new_page(pages, page_masters, requested_master)
- if requested_master is not None:
- current_master = requested_master
- page_masters[-1] = current_master
+ apply_master_page(requested_master)
_append_flow_items(
parser.parse_paragraph(child),
parser=parser,
@@ -166,7 +176,13 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
}:
walk(child)
elif child.tag == qname("text", "list"):
- pages[-1].extend(parser.parse_list_blocks(child))
+ for item in parser.parse_list_blocks(child, emit_master_page_changes=True):
+ if isinstance(item, OdfMasterPageChange):
+ apply_master_page(item.master_page_name)
+ elif isinstance(item, InlineNote):
+ parser.notes.append(item.content)
+ else:
+ pages[-1].append(item)
else:
pages[-1].extend(parser.parse_element(child))
@@ -183,6 +199,7 @@ def _parse_odt_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
styles=context.styles,
anchor_targets=anchor_targets,
text_expansion_budget=text_expansion_budget,
+ table_expansion_budget=parser.table_expansion_budget,
)
)
return pages or [[]]
@@ -300,7 +317,7 @@ def _parse_odp_pages(context: _OdfContext) -> list[list[dict[str, Any]]]:
def _sheet_blocks(sheet: etree._Element, parser: OdfBlockParser) -> list[dict[str, Any]]:
"""把一个可见 ODS sheet 拆为数据区域和锚定视觉对象。"""
- grid = parse_table_grid(sheet, parser.render_cell_html)
+ grid = parse_table_grid(sheet, parser.render_cell_html, expansion_budget=parser.table_expansion_budget)
blocks: list[dict[str, Any]] = []
for region in split_table_regions(grid):
content = table_grid_to_html(region)
diff --git a/mineru/model/flash/office/odf/table.py b/mineru/model/flash/office/odf/table.py
index 15eb35d5..410e0c98 100644
--- a/mineru/model/flash/office/odf/table.py
+++ b/mineru/model/flash/office/odf/table.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import html
import re
from collections.abc import Callable, Iterator
+from dataclasses import dataclass
from lxml import etree # type: ignore[reportMissingImports]
@@ -20,12 +21,62 @@ _HTML_TEXT_RE = re.compile(r"<[^>]+>")
_CELL_ADDRESS_RE = re.compile(r"\$?(?P<col>[A-Za-z]+)\$?(?P<row>[1-9][0-9]*)")
+@dataclass(slots=True)
+class OdfTableExpansionBudget:
+ """累计单个 ODF 文档全部表格的网格与重复文本膨胀。"""
+
+ used_grid_slots: int = 0
+ used_duplicated_text_bytes: int = 0
+
+ def start_table(self) -> _TableGridReservation:
+ """为一次表格解析创建只累计新增矩形面积的局部预留。"""
+ return _TableGridReservation(self)
+
+ def charge_grid_slots(self, additional_slots: int) -> None:
+ """在表格网格扩容前累计文档级槽位。"""
+ if additional_slots < 0 or self.used_grid_slots > MAX_GRID_SLOTS - additional_slots:
+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")
+ self.used_grid_slots += additional_slots
+
+ def charge_duplicated_text(self, byte_count: int) -> None:
+ """在复制单元格文本前累计文档级膨胀字节。"""
+ if byte_count < 0 or self.used_duplicated_text_bytes > MAX_EXPANSION_TEXT_BYTES - byte_count:
+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_expansion_text_bytes={MAX_EXPANSION_TEXT_BYTES}")
+ self.used_duplicated_text_bytes += byte_count
+
+
+@dataclass(slots=True)
+class _TableGridReservation:
+ """记录当前表格已经计入文档预算的最大矩形面积。"""
+
+ budget: OdfTableExpansionBudget
+ reserved_slots: int = 0
+
+ def reserve(self, row_count: int, width: int) -> None:
+ """仅把当前表格增长部分计入文档级预算。"""
+ projected_slots = row_count * max(width, 1)
+ if projected_slots <= self.reserved_slots:
+ return
+ self.budget.charge_grid_slots(projected_slots - self.reserved_slots)
+ self.reserved_slots = projected_slots
+
+
def _positive_int(value: str | None, default: int = 1) -> int:
- """把不可信 ODF 计数属性解析为至少为一的整数。"""
- try:
- return max(1, int(value or default))
- except (TypeError, ValueError):
+ """在转换前约束 ODF 计数属性,并把损坏值回退为至少一。"""
+ if value is None:
return default
+ normalized = value.strip()
+ if normalized.startswith("+"):
+ normalized = normalized[1:]
+ if not normalized.isascii() or not normalized.isdigit():
+ return default
+ limit_text = str(MAX_GRID_SLOTS)
+ if len(normalized) > len(limit_text):
+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")
+ significant = normalized.lstrip("0") or "0"
+ if len(significant) > len(limit_text) or (len(significant) == len(limit_text) and significant > limit_text):
+ raise OdfResourceLimitError(f"ODF resource limit exceeded: max_grid_slots={MAX_GRID_SLOTS}")
+ return max(1, int(significant))
def _iter_rows(container: etree._Element, *, header: bool = False) -> Iterator[tuple[etree._Element, bool]]:
@@ -84,9 +135,16 @@ def _validate_grid_extent(row_count: int, width: int) -> None:
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]:
+def _ensure_row(
+ grid: TableGrid,
+ row_index: int,
+ width: int = 0,
+ reservation: _TableGridReservation | None = None,
+) -> list[GridCell | None]:
"""确保网格存在指定行和最小列宽。"""
_validate_grid_extent(max(len(grid.rows), row_index + 1), max(grid.width, width))
+ if reservation is not None:
+ reservation.reserve(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]
@@ -100,13 +158,26 @@ def _charge_grid(grid: TableGrid) -> None:
_validate_grid_extent(len(grid.rows), grid.width)
-def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableGrid:
+def parse_table_grid(
+ table: etree._Element,
+ render_cell: CellRenderer,
+ *,
+ expansion_budget: OdfTableExpansionBudget | None = None,
+) -> TableGrid:
"""展开受限重复行列与合并单元格,构造规范二维网格。"""
grid = TableGrid()
+ reservation = expansion_budget.start_table() if expansion_budget is not None else None
duplicated_text_bytes = 0
row_index = 0
pending_empty_rows = 0
pending_empty_width = 0
+
+ def ensure_row(target_row: int, width: int = 0) -> list[GridCell | None]:
+ """在兼容独立表格调用的同时应用可选文档级预留。"""
+ if reservation is None:
+ return _ensure_row(grid, target_row, width)
+ return _ensure_row(grid, target_row, width, reservation)
+
for row_element, header in _iter_rows(table):
row_repeat = _positive_int(row_element.get(qname("table", "number-rows-repeated")))
_validate_grid_extent(row_index + row_repeat, grid.width)
@@ -127,9 +198,15 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG
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}")
+ duplicated_bytes = len(cell_html.encode("utf-8")) * max(0, row_repeat * column_repeat - 1)
+ if expansion_budget is None:
+ duplicated_text_bytes += duplicated_bytes
+ if duplicated_text_bytes > MAX_EXPANSION_TEXT_BYTES:
+ raise OdfResourceLimitError(
+ f"ODF resource limit exceeded: max_expansion_text_bytes={MAX_EXPANSION_TEXT_BYTES}"
+ )
+ else:
+ expansion_budget.charge_duplicated_text(duplicated_bytes)
cell_templates.append(
(
False,
@@ -151,12 +228,12 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG
if pending_empty_rows:
_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)
+ ensure_row(row_index, pending_empty_width)
row_index += 1
pending_empty_rows = 0
pending_empty_width = 0
for _ in range(row_repeat):
- row = _ensure_row(grid, row_index)
+ row = ensure_row(row_index)
col_index = 0
pending_empty_columns = 0
for is_covered, repeat, template in cell_templates:
@@ -173,14 +250,14 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG
continue
if pending_empty_columns:
col_index += pending_empty_columns
- _ensure_row(grid, row_index, col_index)
+ ensure_row(row_index, col_index)
pending_empty_columns = 0
if not is_covered:
_validate_grid_extent(row_index + 1, max(grid.width, col_index + repeat))
for _ in range(repeat):
if is_covered:
if (row_index, col_index) in grid.covered:
- _ensure_row(grid, row_index, col_index + 1)
+ ensure_row(row_index, col_index + 1)
col_index += 1
continue
while (row_index, col_index) in grid.covered:
@@ -196,10 +273,10 @@ def parse_table_grid(table: etree._Element, render_cell: CellRenderer) -> TableG
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 = ensure_row(row_index, col_index + placed.col_span)
row[col_index] = placed
for row_offset in range(placed.row_span):
- covered_row = _ensure_row(grid, row_index + row_offset, col_index + placed.col_span)
+ covered_row = ensure_row(row_index + row_offset, col_index + placed.col_span)
for col_offset in range(placed.col_span):
if row_offset == 0 and col_offset == 0:
continue
@@ -382,6 +459,7 @@ def union_bounds(bounds: list[tuple[int, int, int, int]]) -> tuple[int, int, int
__all__ = [
+ "OdfTableExpansionBudget",
"crop_table_grid",
"parse_cell_range_bounds",
"parse_table_grid",
diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.py
index 3f894731..8ef6ef66 100644
--- a/mineru/model/flash/office/odf/text.py
+++ b/mineru/model/flash/office/odf/text.py
@@ -33,7 +33,7 @@ from .models import (
)
from .package import OdfPackage
from .styles import OdfStyles
-from .table import parse_table_grid, table_grid_to_html
+from .table import OdfTableExpansionBudget, parse_table_grid, table_grid_to_html
_WHITESPACE_RE = re.compile(r"[\t\r\n ]+")
@@ -53,7 +53,15 @@ class OdfTextExpansionBudget:
self.used_bytes += byte_count
+@dataclass(frozen=True, slots=True)
+class OdfMasterPageChange:
+ """表示列表流中由段落样式请求的 master-page 变化。"""
+
+ master_page_name: str
+
+
RawFlowItem = dict[str, Any] | InlineNote
+OdfListFlowItem = dict[str, Any] | InlineNote | OdfMasterPageChange
def _clean_xml_text(value: str | None) -> str:
@@ -241,6 +249,7 @@ class OdfBlockParser:
shared_cell_visuals: list[dict[str, Any]] | None = None,
anchor_targets: frozenset[str] | None = None,
text_expansion_budget: OdfTextExpansionBudget | None = None,
+ table_expansion_budget: OdfTableExpansionBudget | None = None,
) -> None:
"""绑定单次解析包、样式、子文档路径及可跨 parser 共享的状态。"""
self.package = package
@@ -253,6 +262,7 @@ class OdfBlockParser:
self._cell_visuals = shared_cell_visuals if shared_cell_visuals is not None else []
self._anchor_targets = anchor_targets or frozenset()
self._text_expansion_budget = text_expansion_budget or OdfTextExpansionBudget()
+ self.table_expansion_budget = table_expansion_budget or OdfTableExpansionBudget()
def _append_text_atom(
self,
@@ -438,14 +448,21 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- ) -> list[dict[str, Any]]:
+ emit_master_page_changes: bool = False,
+ ) -> list[OdfListFlowItem]:
"""递归构造严格 LIST 分片,并把不允许嵌套的 block 提升为有序兄弟。"""
items = [
item
for item in element
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)
+ return self._parse_list_items(
+ element,
+ items,
+ depth=depth,
+ inherited_style=inherited_style,
+ emit_master_page_changes=emit_master_page_changes,
+ )
def _parse_list_items(
self,
@@ -454,7 +471,8 @@ class OdfBlockParser:
*,
depth: int,
inherited_style: str | None,
- ) -> list[dict[str, Any]]:
+ emit_master_page_changes: bool,
+ ) -> list[OdfListFlowItem]:
"""按源条目构造 LIST 分片,每个条目只保留一个文本叶子和一个 marker。"""
style_name = element.get(qname("text", "style-name")) or inherited_style
level = self.styles.list_level(style_name, depth)
@@ -465,24 +483,28 @@ class OdfBlockParser:
start = self._list_ids[continue_list]
elif element.get(qname("text", "continue-numbering")) == "true" and key in self._list_counters:
start = self._list_counters[key]
- results: list[dict[str, Any]] = []
+ results: list[OdfListFlowItem] = []
content: list[dict[str, Any]] = []
+ fragment_notes: list[InlineNote] = []
item_count = 0
+ active_master: str | None = None
def flush_content(fragment_start: int) -> None:
"""把当前合法子块冻结为一个 LIST 分片。"""
- if not content:
- return
- block: dict[str, Any] = {
- "type": BlockType.LIST,
- "attribute": "ordered" if level.ordered else "unordered",
- "ilevel": depth,
- "content": list(content),
- }
- if level.ordered:
- block["start"] = fragment_start
- results.append(block)
- content.clear()
+ if content:
+ block: dict[str, Any] = {
+ "type": BlockType.LIST,
+ "attribute": "ordered" if level.ordered else "unordered",
+ "ilevel": depth,
+ "content": list(content),
+ }
+ if level.ordered:
+ block["start"] = fragment_start
+ results.append(block)
+ content.clear()
+ if fragment_notes:
+ results.extend(fragment_notes)
+ fragment_notes.clear()
fragment_start = start
for item in items:
@@ -497,15 +519,36 @@ class OdfBlockParser:
pass
# 统一 LIST 只支持列表级起始值,后续逐项重启按连续序号投影。
item_count += 1
+ first_paragraph = next(
+ (
+ child
+ for child in item
+ if isinstance(child.tag, str) and child.tag in {qname("text", "p"), qname("text", "h")}
+ ),
+ None,
+ )
+ requested_master = (
+ self.styles.paragraph_master_page_name(first_paragraph.get(qname("text", "style-name")))
+ if first_paragraph is not None
+ else None
+ )
+ if emit_master_page_changes and requested_master is not None and requested_master != active_master:
+ flush_content(fragment_start)
+ results.append(OdfMasterPageChange(requested_master))
+ active_master = requested_master
+ fragment_start = start + item_count - (0 if is_header else 1)
text_parts: list[str] = []
nested_blocks: list[dict[str, Any]] = []
- lifted_blocks: list[dict[str, Any]] = []
+ lifted_blocks: list[OdfListFlowItem] = []
def consume_flow(flow: Sequence[RawFlowItem]) -> None:
"""把段落子流投影到列表文本、嵌套列表或提升块。"""
for block in flow:
if isinstance(block, InlineNote):
- self.notes.append(block.content)
+ if emit_master_page_changes:
+ fragment_notes.append(block)
+ else:
+ self.notes.append(block.content)
continue
block_type = block.get("type")
block_content = block.get("content")
@@ -528,9 +571,17 @@ class OdfBlockParser:
if child.tag in {qname("text", "p"), qname("text", "h")}:
consume_flow(self.parse_paragraph(child))
elif child.tag == qname("text", "list"):
- nested_flow = self.parse_list_blocks(child, depth=depth + 1, inherited_style=style_name)
- if all(block.get("type") == BlockType.LIST for block in nested_flow):
- nested_blocks.extend(nested_flow)
+ nested_flow = self.parse_list_blocks(
+ child,
+ depth=depth + 1,
+ inherited_style=style_name,
+ emit_master_page_changes=emit_master_page_changes,
+ )
+ if not any(isinstance(block, OdfMasterPageChange) for block in nested_flow) and all(
+ isinstance(block, InlineNote) or block.get("type") == BlockType.LIST for block in nested_flow
+ ):
+ nested_blocks.extend(block for block in nested_flow if isinstance(block, dict))
+ fragment_notes.extend(block for block in nested_flow if isinstance(block, InlineNote))
else:
lifted_blocks.extend(nested_flow)
else:
@@ -556,12 +607,19 @@ class OdfBlockParser:
*,
depth: int = 0,
inherited_style: str | None = None,
- ) -> list[dict[str, Any]]:
+ emit_master_page_changes: bool = False,
+ ) -> list[OdfListFlowItem]:
"""把含 text:h 的编号章节提升为标题,并保留其余连续列表。"""
if next(element.iter(qname("text", "h")), None) is None:
- return self.parse_list(element, depth=depth, inherited_style=inherited_style)
- results: list[dict[str, Any]] = []
+ return self.parse_list(
+ element,
+ depth=depth,
+ inherited_style=inherited_style,
+ emit_master_page_changes=emit_master_page_changes,
+ )
+ results: list[OdfListFlowItem] = []
pending_items: list[etree._Element] = []
+ active_master: str | None = None
def flush_pending() -> None:
"""把标题之间积累的普通列表项写为独立连续 LIST block。"""
@@ -572,6 +630,7 @@ class OdfBlockParser:
list(pending_items),
depth=depth,
inherited_style=inherited_style,
+ emit_master_page_changes=emit_master_page_changes,
)
pending_items.clear()
results.extend(blocks)
@@ -590,9 +649,16 @@ class OdfBlockParser:
if not isinstance(child.tag, str):
continue
if child.tag in {qname("text", "p"), qname("text", "h")}:
+ requested_master = self.styles.paragraph_master_page_name(child.get(qname("text", "style-name")))
+ if emit_master_page_changes and requested_master is not None and requested_master != active_master:
+ results.append(OdfMasterPageChange(requested_master))
+ active_master = requested_master
for parsed in self.parse_paragraph(child):
if isinstance(parsed, InlineNote):
- self.notes.append(parsed.content)
+ if emit_master_page_changes:
+ results.append(parsed)
+ else:
+ self.notes.append(parsed.content)
continue
if child.tag == qname("text", "h") and parsed.get("type") == BlockType.PARAGRAPH_TITLE:
parsed["is_numbered_style"] = True
@@ -603,6 +669,7 @@ class OdfBlockParser:
child,
depth=depth + 1,
inherited_style=element.get(qname("text", "style-name")) or inherited_style,
+ emit_master_page_changes=emit_master_page_changes,
)
)
else:
@@ -628,7 +695,7 @@ class OdfBlockParser:
def parse_table(self, element: etree._Element) -> dict[str, Any] | None:
"""把一个 ODF table 转为包含合并语义的 TABLE raw block。"""
- grid = parse_table_grid(element, self.render_cell_html)
+ grid = parse_table_grid(element, self.render_cell_html, expansion_budget=self.table_expansion_budget)
content = table_grid_to_html(grid)
return {"type": BlockType.TABLE, "content": content} if content else None
@@ -715,11 +782,13 @@ class OdfBlockParser:
shared_cell_visuals=self._cell_visuals,
anchor_targets=self._anchor_targets,
text_expansion_budget=self._text_expansion_budget,
+ table_expansion_budget=self.table_expansion_budget,
)
chart = parse_chart_block(
object_root,
render_cell=object_parser.render_cell_html,
preview_data_uri=preview_uri,
+ table_expansion_budget=self.table_expansion_budget,
)
if chart is not None:
return None, [chart]
@@ -839,7 +908,7 @@ class OdfBlockParser:
elif child.tag == qname("text", "list"):
parts.append(self._render_list_html(child))
elif child.tag == qname("table", "table"):
- nested = parse_table_grid(child, self.render_cell_html)
+ nested = parse_table_grid(child, self.render_cell_html, expansion_budget=self.table_expansion_budget)
parts.append(table_grid_to_html(nested))
elif child.tag == qname("draw", "frame"):
inline, blocks = self._parse_frame(child)
@@ -923,6 +992,7 @@ def flatten_block_text(blocks: list[dict[str, Any]]) -> str:
__all__ = [
"OdfBlockParser",
+ "OdfMasterPageChange",
"OdfTextExpansionBudget",
"RawFlowItem",
"flatten_block_text",
diff --git a/mineru/model/flash/office/rtf/lexer.py b/mineru/model/flash/office/rtf/lexer.py
index e87e5333..7a0dbf17 100644
--- a/mineru/model/flash/office/rtf/lexer.py
+++ b/mineru/model/flash/office/rtf/lexer.py
@@ -10,6 +10,9 @@ from ..errors import LegacyOfficeMalformedError, LegacyOfficeResourceLimitError
from ..limits import MAX_RECORDS
MAX_RTF_GROUP_DEPTH = 256
+MAX_RTF_CONTROL_PARAMETER_DIGITS = 10
+MIN_RTF_CONTROL_PARAMETER = -(2**31)
+MAX_RTF_CONTROL_PARAMETER = 2**31 - 1
@dataclass(frozen=True, slots=True)
@@ -116,9 +119,7 @@ class RtfLexer:
cursor += 1
depth += 1
if depth > MAX_RTF_GROUP_DEPTH:
- raise LegacyOfficeResourceLimitError(
- f"RTF group nesting exceeds max_group_depth={MAX_RTF_GROUP_DEPTH}"
- )
+ raise LegacyOfficeResourceLimitError(f"RTF group nesting exceeds max_group_depth={MAX_RTF_GROUP_DEPTH}")
token = RtfOpen(start, cursor)
elif value == ord("}"):
cursor += 1
@@ -166,7 +167,14 @@ class RtfLexer:
cursor += 1
param = None
if cursor > number_start:
+ digit_count = cursor - number_start
+ if digit_count > MAX_RTF_CONTROL_PARAMETER_DIGITS:
+ raise LegacyOfficeResourceLimitError(
+ f"RTF control parameter exceeds max_digits={MAX_RTF_CONTROL_PARAMETER_DIGITS}"
+ )
param = sign * int(data[number_start:cursor])
+ if param < MIN_RTF_CONTROL_PARAMETER or param > MAX_RTF_CONTROL_PARAMETER:
+ raise LegacyOfficeResourceLimitError("RTF control parameter exceeds signed 32-bit range")
if cursor < len(data) and data[cursor] == ord(" "):
cursor += 1
if name == "bin":
diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.py
index 2367b173..d7e1cc10 100644
--- a/tests/unittest/test_flash_odf.py
+++ b/tests/unittest/test_flash_odf.py
@@ -314,6 +314,89 @@ def test_odt_ignores_physical_breaks_and_pages_only_on_master_change() -> None:
]
+def test_odt_list_master_changes_split_pages_and_preserve_numbering_notes() -> None:
+ """验证列表条目中的 master 变化会切页并保持编号、脚注和页眉归属。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:automatic-styles>
+ <style:style style:name="A" style:family="paragraph" style:master-page-name="MasterA"/>
+ <style:style style:name="B" style:family="paragraph" style:master-page-name="MasterB"/>
+ <text:list-style style:name="L1">
+ <text:list-level-style-number text:level="1" style:num-format="1" text:start-value="3"/>
+ </text:list-style>
+ </office:automatic-styles>
+ <office:body><office:text>
+ <text:p text:style-name="A">Before list</text:p>
+ <text:list text:style-name="L1">
+ <text:list-item><text:p>First <text:note><text:note-citation>1</text:note-citation>
+ <text:note-body><text:p>First note</text:p></text:note-body></text:note></text:p></text:list-item>
+ <text:list-item><text:p text:style-name="B">Second <text:note><text:note-citation>2</text:note-citation>
+ <text:note-body><text:p>Second note</text:p></text:note-body></text:note></text:p></text:list-item>
+ <text:list-item><text:p>Third</text:p></text:list-item>
+ </text:list>
+ </office:text></office:body></office:document-content>"""
+ styles = """<office:document-styles
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:master-styles>
+ <style:master-page style:name="MasterA">
+ <style:header><text:p>Header A</text:p></style:header>
+ </style:master-page>
+ <style:master-page style:name="MasterB">
+ <style:header><text:p>Header B</text:p></style:header>
+ </style:master-page>
+ </office:master-styles></office:document-styles>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))
+
+ assert len(pages) == 2
+ first_list = next(block for block in pages[0] if block["type"] == BlockType.LIST)
+ second_list = next(block for block in pages[1] if block["type"] == BlockType.LIST)
+ assert first_list["start"] == 3
+ assert second_list["start"] == 4
+ assert [child["content"] for child in first_list["content"]] == ["First [1]"]
+ assert [child["content"] for child in second_list["content"]] == ["Second [2]", "Third"]
+ assert any(block["type"] == BlockType.PAGE_FOOTNOTE and "First note" in block["content"] for block in pages[0])
+ assert any(block["type"] == BlockType.PAGE_FOOTNOTE and "Second note" in block["content"] for block in pages[1])
+ assert any(block["type"] == BlockType.HEADER and block["content"] == "Header A" for block in pages[0])
+ assert any(block["type"] == BlockType.HEADER and block["content"] == "Header B" for block in pages[1])
+
+
+def test_odt_list_can_select_nondefault_master_on_first_page() -> None:
+ """验证文档从列表开始时使用首个列表段落请求的 master-page。"""
+ content = """<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:automatic-styles>
+ <style:style style:name="B" style:family="paragraph" style:master-page-name="MasterB"/>
+ </office:automatic-styles>
+ <office:body><office:text><text:list><text:list-item>
+ <text:p text:style-name="B">First list item</text:p>
+ </text:list-item></text:list></office:text></office:body></office:document-content>"""
+ styles = """<office:document-styles
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:master-styles>
+ <style:master-page style:name="MasterA">
+ <style:header><text:p>Header A</text:p></style:header>
+ </style:master-page>
+ <style:master-page style:name="MasterB">
+ <style:header><text:p>Header B</text:p></style:header>
+ </style:master-page>
+ </office:master-styles></office:document-styles>"""
+
+ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, styles_xml=styles)))
+
+ assert len(pages) == 1
+ assert any(block["type"] == BlockType.HEADER and block["content"] == "Header B" for block in pages[0])
+ assert all(block.get("content") != "Header A" for block in pages[0])
+
+
def test_odf_covered_placeholder_reuses_colspan_coordinate() -> None:
"""验证 colspan 后的 covered placeholder 不会额外扩宽表格。"""
table = etree.fromstring(
@@ -573,6 +656,93 @@ def test_odf_rejects_projected_span_extent_before_extending_existing_row(monkeyp
assert observed_widths and max(observed_widths) <= 3
+def test_odf_rejects_overlong_repeat_before_integer_conversion(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证超长 repeat 计数在 int 和单元格渲染前触发网格预算。"""
+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)
+
+ def unexpected_render(_cell: object) -> str:
+ """超限 repeat 不得进入单元格渲染。"""
+ pytest.fail("oversized ODF repeat reached cell rendering")
+
+ table = etree.fromstring(
+ (
+ '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'
+ f'<table:table-row table:number-rows-repeated="{"9" * 100_000}">'
+ "<table:table-cell/>"
+ "</table:table-row></table:table>"
+ ).encode()
+ )
+
+ with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):
+ odf_table_module.parse_table_grid(table, unexpected_render)
+
+
+def test_odf_document_grid_budget_is_shared_across_tables(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证多个独立表格共同消耗同一个文档网格预算。"""
+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)
+ budget = odf_table_module.OdfTableExpansionBudget()
+ table_xml = (
+ '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'
+ '<table:table-row table:number-rows-repeated="2">'
+ '<table:table-cell table:number-columns-repeated="2"/>'
+ "</table:table-row></table:table>"
+ )
+
+ first = odf_table_module.parse_table_grid(
+ etree.fromstring(table_xml.encode()),
+ lambda _cell: "x",
+ expansion_budget=budget,
+ )
+ assert len(first.rows) * first.width == 4
+ with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):
+ odf_table_module.parse_table_grid(
+ etree.fromstring(table_xml.encode()),
+ lambda _cell: "x",
+ expansion_budget=budget,
+ )
+
+
+def test_odf_document_text_expansion_budget_is_shared_across_tables(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证多个表格的重复单元格文本共同消耗文档级字节预算。"""
+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 100)
+ monkeypatch.setattr(odf_table_module, "MAX_EXPANSION_TEXT_BYTES", 4)
+ budget = odf_table_module.OdfTableExpansionBudget()
+ table_xml = (
+ '<table:table xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0">'
+ '<table:table-row><table:table-cell table:number-columns-repeated="2"/></table:table-row>'
+ "</table:table>"
+ )
+
+ odf_table_module.parse_table_grid(
+ etree.fromstring(table_xml.encode()),
+ lambda _cell: "xxx",
+ expansion_budget=budget,
+ )
+ with pytest.raises(OdfResourceLimitError, match="max_expansion_text_bytes"):
+ odf_table_module.parse_table_grid(
+ etree.fromstring(table_xml.encode()),
+ lambda _cell: "xxx",
+ expansion_budget=budget,
+ )
+
+
+def test_odt_parser_wires_one_table_budget_across_document(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 ODT 中多个普通表格通过 parser 共享同一文档预算。"""
+ monkeypatch.setattr(odf_table_module, "MAX_GRID_SLOTS", 4)
+ table = """<table:table><table:table-row table:number-rows-repeated="2">
+ <table:table-cell table:number-columns-repeated="2"><text:p>x</text:p></table:table-cell>
+ </table:table-row></table:table>"""
+ content = f"""<office:document-content
+ xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
+ xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
+ xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
+ <office:body><office:text>{table}{table}</office:text></office:body>
+ </office:document-content>"""
+
+ with pytest.raises(OdfResourceLimitError, match="max_grid_slots"):
+ OdtModel().predict(BytesIO(build_odf_package("odt", content)))
+
+
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)
diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.py
index 6fc35bed..15ee0665 100644
--- a/tests/unittest/test_flash_rtf.py
+++ b/tests/unittest/test_flash_rtf.py
@@ -59,6 +59,32 @@ def test_rtf_lexer_rejects_truncated_bin_payload() -> None:
list(RtfLexer(rb"{\rtf1\bin9 ab}"))
+ "control",
+ [
+ b"\\foo99999999999",
+ b"\\foo2147483648",
+ b"\\foo-2147483649",
+ b"\\bin99999999999 payload",
+ ],
+)
+def test_rtf_lexer_rejects_control_parameters_before_unbounded_int(control: bytes) -> None:
+ """验证超长或越界 control parameter 在整数转换和 bin 定位前失败。"""
+ with pytest.raises(LegacyOfficeResourceLimitError, match="control parameter"):
+ list(RtfLexer(b"{\\rtf1" + control + b"}"))
+
+
+def test_rtf_lexer_accepts_signed_32_bit_control_parameter_boundaries() -> None:
+ """验证十位词法限制仍允许有符号 32 位参数边界。"""
+ tokens = list(RtfLexer(rb"{\rtf1\foo2147483647\bar-2147483648}"))
+ controls = [token for token in tokens if isinstance(token, lexer_module.RtfControlWord)]
+
+ assert [(token.name, token.param) for token in controls[-2:]] == [
+ ("foo", 2_147_483_647),
+ ("bar", -2_147_483_648),
+ ]
+
+
def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:
"""验证 per-font CP1251/CP932、多字节 hex 和 UTF-16 代理对恢复。"""
russian = b"".join(f"\\'{value:02x}".encode("ascii") for value in "Привет".encode("cp1251"))
@@ -120,7 +146,7 @@ def test_rtf_large_roman_list_start_falls_back_to_decimal() -> None:
"""验证超出规范范围的 Roman 起始值直接回退十进制而不线性扩张。"""
source = b"".join(
[
- rb"{\rtf1\ansi{\*\listtable{\list{\listlevel\levelnfc1\levelstartat1000000000000}\listid7}}",
+ rb"{\rtf1\ansi{\*\listtable{\list{\listlevel\levelnfc1\levelstartat2147483647}\listid7}}",
rb"{\*\listoverridetable{\listoverride\listid7\listoverridecount0\ls2}}",
rb"\pard\ls2\ilvl0 item\par}",
]
@@ -129,7 +155,7 @@ def test_rtf_large_roman_list_start_falls_back_to_decimal() -> None:
pages = RtfModel().predict(BytesIO(source))
assert pages[0][0]["type"] == BlockType.LIST
- assert pages[0][0]["content"][0]["list_label"] == "1000000000000."
+ assert pages[0][0]["content"][0]["list_label"] == "2147483647."
def test_rtf_model_recovers_unicode_styles_and_structures() -> None: