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 ODF and RTF parser review findings
myhlolidac6aa757def
diff --git a/mineru/model/flash/office/odf/models.py b/mineru/model/flash/office/odf/models.pyindex 00a3a84f..0d81e43d 100644--- a/mineru/model/flash/office/odf/models.py+++ b/mineru/model/flash/office/odf/models.py@@ -4,7 +4,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import TypeAlias, Union+from typing import Any, TypeAlias, Union@dataclass(frozen=True, slots=True)@@ -123,7 +123,15 @@ class InlineImage:alt: str = ""-InlineAtom: TypeAlias = Union[InlineText, InlineMath, InlineBreak, InlinePageBreak, InlineImage]+@dataclass(frozen=True, slots=True)+class InlineBlockGroup:+ """在行内流中保存段外 block 及其与内联图片的配对关系。"""++ blocks: tuple[dict[str, Any], ...]+ inline_image_rendered: bool = False+++InlineAtom: TypeAlias = Union[InlineText, InlineMath, InlineBreak, InlinePageBreak, InlineImage, InlineBlockGroup]@dataclass(slots=True)@@ -158,6 +166,7 @@ class TableGrid:__all__ = ["GridCell","InlineAtom",+ "InlineBlockGroup","InlineBreak","InlineImage","InlineMath",diff --git a/mineru/model/flash/office/odf/text.py b/mineru/model/flash/office/odf/text.pyindex ef8ba8c6..d58bc847 100644--- a/mineru/model/flash/office/odf/text.py+++ b/mineru/model/flash/office/odf/text.py@@ -22,6 +22,7 @@ from .chart import parse_chart_blockfrom .constants import qnamefrom .models import (InlineAtom,+ InlineBlockGroup,InlineBreak,InlineImage,InlineMath,@@ -138,6 +139,8 @@ def render_atoms_to_html(atoms: Sequence[InlineAtom]) -> str:parts.append("<br/>")elif isinstance(atom, InlineImage):parts.append(f'<img src="{html.escape(atom.data_uri, quote=True)}" alt="{html.escape(atom.alt, quote=True)}"/>')+ elif isinstance(atom, InlineBlockGroup):+ continuereturn "".join(parts)@@ -170,6 +173,8 @@ def render_atoms_to_model(atoms: Sequence[InlineAtom], *, trim_edges: bool = Falparts.append("\n")elif isinstance(atom, InlineImage) and atom.alt:parts.append(atom.alt)+ elif isinstance(atom, InlineBlockGroup):+ continueflush_segments()return "".join(parts).strip() if trim_edges else "".join(parts)@@ -236,7 +241,6 @@ class OdfBlockParser:style: TextStyle,hyperlink: str | None,atoms: list[InlineAtom],- extra_blocks: list[dict[str, Any]],) -> None:"""递归遍历段落行内节点,并把 frame 视觉对象旁路为 block。"""self._append_text_atom(atoms, element.text, style=style, hyperlink=hyperlink)@@ -255,7 +259,6 @@ class OdfBlockParser:style=span_style,hyperlink=hyperlink,atoms=atoms,- extra_blocks=extra_blocks,)elif child.tag == qname("text", "a"):target = _safe_hyperlink(child.get(qname("xlink", "href"))) or hyperlink@@ -264,7 +267,6 @@ class OdfBlockParser:style=style,hyperlink=target,atoms=atoms,- extra_blocks=extra_blocks,)elif child.tag == qname("text", "s"):count = min(_positive_space_count(child.get(qname("text", "c"))), 10_000)@@ -281,7 +283,13 @@ class OdfBlockParser:inline_atom, blocks = self._parse_frame(child)if inline_atom is not None:atoms.append(inline_atom)- extra_blocks.extend(blocks)+ if blocks:+ atoms.append(+ InlineBlockGroup(+ tuple(blocks),+ inline_image_rendered=isinstance(inline_atom, InlineImage),+ )+ )elif child.tag == qname("math", "math"):if latex := mathml_to_latex(child):atoms.append(InlineMath(latex))@@ -297,7 +305,6 @@ class OdfBlockParser:style=style,hyperlink=hyperlink,atoms=atoms,- extra_blocks=extra_blocks,)self._append_text_atom(atoms, child.tail, style=style, hyperlink=hyperlink)@@ -321,22 +328,20 @@ class OdfBlockParser:if visible:self.notes.append(f"[{citation_text}] {visible}")- def parse_inline_atoms(self, paragraph: etree._Element) -> tuple[list[InlineAtom], list[dict[str, Any]]]:- """解析一个段落的行内语义和段外视觉对象。"""+ def parse_inline_atoms(self, paragraph: etree._Element) -> list[InlineAtom]:+ """解析一个段落的行内语义,并用原位 marker 保留段外 block。"""paragraph_style = self.styles.text_style(paragraph.get(qname("text", "style-name")),family="paragraph",)atoms: list[InlineAtom] = []- extra_blocks: list[dict[str, Any]] = []self._walk_inlines(paragraph,style=paragraph_style,hyperlink=None,atoms=atoms,- extra_blocks=extra_blocks,)- return atoms, extra_blocks+ return atoms@staticmethoddef _paragraph_anchor(paragraph: etree._Element) -> str | None:@@ -349,7 +354,7 @@ 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)+ atoms = self.parse_inline_atoms(paragraph)groups = (split_atoms_on_page_break(atoms)if allow_page_breaks@@ -359,9 +364,10 @@ class OdfBlockParser:is_heading = paragraph.tag == qname("text", "h")style_name = paragraph.get(qname("text", "style-name"))for group_index, group in enumerate(groups):- content = render_atoms_to_model(group, trim_edges=True)- math_atoms = [atom for atom in group if isinstance(atom, InlineMath)]- visible_text = "".join(atom.text for atom in group if isinstance(atom, InlineText)).strip()+ content_atoms = [atom for atom in group if not isinstance(atom, InlineBlockGroup)]+ content = render_atoms_to_model(content_atoms, trim_edges=True)+ math_atoms = [atom for atom in content_atoms if isinstance(atom, InlineMath)]+ visible_text = "".join(atom.text for atom in content_atoms if isinstance(atom, InlineText)).strip()if content:if math_atoms and not visible_text and len(math_atoms) == 1 and len(group) == 1:results.append({"type": BlockType.EQUATION, "content": math_atoms[0].latex})@@ -386,9 +392,11 @@ class OdfBlockParser:results.append(block)else:results.append({"type": BlockType.TEXT, "content": content})+ for atom in group:+ if isinstance(atom, InlineBlockGroup):+ results.extend(atom.blocks)if group_index < len(groups) - 1:results.append(PAGE_BREAK)- results.extend(extra_blocks)return resultsdef parse_list(@@ -397,8 +405,8 @@ class OdfBlockParser:*,depth: int = 0,inherited_style: str | None = None,- ) -> dict[str, Any] | None:- """递归构造 Office LIST raw block,并保留起始编号与层级。"""+ ) -> list[dict[str, Any]]:+ """递归构造严格 LIST 分片,并把不允许嵌套的 block 提升为有序兄弟。"""items = [itemfor item in element@@ -413,8 +421,8 @@ class OdfBlockParser:*,depth: int,inherited_style: str | None,- ) -> dict[str, Any] | None:- """把一段不含章节标题的连续 list-item 序列构造成 LIST block。"""+ ) -> list[dict[str, Any]]:+ """按源条目构造 LIST 分片,每个条目只保留一个文本叶子和一个 marker。"""style_name = element.get(qname("text", "style-name")) or inherited_stylelevel = self.styles.list_level(style_name, depth)key = (style_name or "", depth)@@ -424,8 +432,26 @@ 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]] = []content: list[dict[str, Any]] = []item_count = 0++ 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()++ fragment_start = startfor item in items:is_header = item.tag == qname("text", "list-header")if not is_header:@@ -433,40 +459,68 @@ class OdfBlockParser:item_start = int(item.get(qname("text", "start-value"), str(start + item_count)))if item_count == 0:start = max(0, item_start)+ fragment_start = startexcept ValueError:passitem_count += 1+ text_parts: list[str] = []+ nested_blocks: list[dict[str, Any]] = []+ lifted_blocks: list[dict[str, Any]] = []for child in item:if not isinstance(child.tag, str):continueif child.tag in {qname("text", "p"), qname("text", "h")}:for block in self.parse_paragraph(child):- if isinstance(block, dict):- block["type"] = BlockType.TEXT- block.pop("level", None)- block.pop("anchor", None)- content.append(block)+ if not isinstance(block, dict):+ continue+ block_type = block.get("type")+ block_content = block.get("content")+ if block_type in {+ BlockType.TEXT,+ BlockType.REF_TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ } and isinstance(block_content, str):+ if block_content:+ text_parts.append(block_content)+ else:+ lifted_blocks.append(block)elif child.tag == qname("text", "list"):- nested = self.parse_list(child, depth=depth + 1, inherited_style=style_name)- if nested is not None:- content.append(nested)+ 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)+ else:+ lifted_blocks.extend(nested_flow)else:- content.extend(self.parse_container(child))- if not content:- return None+ for block in self.parse_container(child):+ block_type = block.get("type")+ block_content = block.get("content")+ if block_type in {+ BlockType.TEXT,+ BlockType.REF_TEXT,+ BlockType.DOC_TITLE,+ BlockType.PARAGRAPH_TITLE,+ } and isinstance(block_content, str):+ if block_content:+ text_parts.append(block_content)+ elif block_type == BlockType.LIST:+ nested_blocks.append(block)+ else:+ lifted_blocks.append(block)+ if text_parts:+ content.append({"type": BlockType.TEXT, "content": "\n".join(text_parts)})+ content.extend(nested_blocks)+ if lifted_blocks:+ flush_content(fragment_start)+ results.extend(lifted_blocks)+ fragment_start = start + item_count++ flush_content(fragment_start)next_value = start + item_countself._list_counters[key] = next_valueif list_id := element.get(qname("xml", "id")):self._list_ids[list_id] = next_value- result: dict[str, Any] = {- "type": BlockType.LIST,- "attribute": "ordered" if level.ordered else "unordered",- "ilevel": depth,- "content": content,- }- if level.ordered:- result["start"] = start- return result+ return resultsdef parse_list_blocks(self,@@ -477,8 +531,7 @@ class OdfBlockParser:) -> list[dict[str, Any]]:"""把含 text:h 的编号章节提升为标题,并保留其余连续列表。"""if next(element.iter(qname("text", "h")), None) is None:- block = self.parse_list(element, depth=depth, inherited_style=inherited_style)- return [block] if block is not None else []+ return self.parse_list(element, depth=depth, inherited_style=inherited_style)results: list[dict[str, Any]] = []pending_items: list[etree._Element] = []@@ -486,15 +539,14 @@ class OdfBlockParser:"""把标题之间积累的普通列表项写为独立连续 LIST block。"""if not pending_items:return- block = self._parse_list_items(+ blocks = self._parse_list_items(element,list(pending_items),depth=depth,inherited_style=inherited_style,)pending_items.clear()- if block is not None:- results.append(block)+ results.extend(blocks)for item in element:if not isinstance(item.tag, str) or item.tag not in {@@ -696,6 +748,30 @@ class OdfBlockParser:blocks.extend(self.parse_element(child))return blocks+ def _append_cell_blocks(+ self,+ parts: list[str],+ blocks: Sequence[dict[str, Any]],+ *,+ inline_image_rendered: bool,+ ) -> None:+ """按单元格视觉策略收集或内联 block,并避免重复输出配对图片。"""+ for block in blocks:+ block_type = block.get("type")+ if self._collect_cell_visuals and block_type in {+ BlockType.IMAGE,+ BlockType.CHART,+ BlockType.EQUATION,+ }:+ self._cell_visuals.append(block)+ continue+ if inline_image_rendered and block_type == BlockType.IMAGE:+ continue+ if block_type in {BlockType.TABLE, BlockType.CHART} and block.get("content"):+ parts.append(str(block["content"]))+ elif block.get("image_base64"):+ parts.append(f'<img src="{html.escape(str(block["image_base64"]), quote=True)}"/>')+def render_cell_html(self, cell: etree._Element) -> str:"""把表格单元格中的段落、列表、嵌套表和 frame 转为 HTML。"""parts: list[str] = []@@ -703,23 +779,18 @@ class OdfBlockParser:if not isinstance(child.tag, str):continueif child.tag in {qname("text", "p"), qname("text", "h")}:- atoms, extra = self.parse_inline_atoms(child)+ atoms = self.parse_inline_atoms(child)rendered_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:- if self._collect_cell_visuals and block.get("type") in {- BlockType.IMAGE,- BlockType.CHART,- BlockType.EQUATION,- }:- self._cell_visuals.append(block)- continue- if block.get("type") in {BlockType.TABLE, BlockType.CHART} and block.get("content"):- parts.append(str(block["content"]))- elif block.get("image_base64"):- parts.append(f'<img src="{html.escape(str(block["image_base64"]), quote=True)}"/>')+ for atom in atoms:+ if isinstance(atom, InlineBlockGroup):+ self._append_cell_blocks(+ parts,+ atom.blocks,+ inline_image_rendered=atom.inline_image_rendered and not self._collect_cell_visuals,+ )elif child.tag == qname("text", "list"):parts.append(self._render_list_html(child))elif child.tag == qname("table", "table"):@@ -727,23 +798,13 @@ class OdfBlockParser:parts.append(table_grid_to_html(nested))elif child.tag == qname("draw", "frame"):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}- )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 {- BlockType.IMAGE,- BlockType.CHART,- BlockType.EQUATION,- }:- continue- if block.get("content"):- parts.append(str(block["content"]))- elif block.get("image_base64"):- parts.append(f'<img src="{html.escape(str(block["image_base64"]), quote=True)}"/>')+ self._append_cell_blocks(+ parts,+ blocks,+ inline_image_rendered=isinstance(inline, InlineImage) and not self._collect_cell_visuals,+ )return "".join(part for part in parts if part)def _render_list_html(self, element: etree._Element, *, depth: int = 0, inherited_style: str | None = None) -> str:@@ -759,13 +820,13 @@ class OdfBlockParser:if item.tag == qname("text", "list-header"):for child in item:if child.tag in {qname("text", "p"), qname("text", "h")}:- atoms, _ = self.parse_inline_atoms(child)+ atoms = self.parse_inline_atoms(child)parts.append(f"<li>{render_atoms_to_html(atoms)}</li>")continueparts.append("<li>")for child in item:if child.tag in {qname("text", "p"), qname("text", "h")}:- atoms, _ = self.parse_inline_atoms(child)+ atoms = self.parse_inline_atoms(child)parts.append(render_atoms_to_html(atoms))elif child.tag == qname("text", "list"):parts.append(self._render_list_html(child, depth=depth + 1, inherited_style=style_name))diff --git a/mineru/model/flash/office/rtf/parser.py b/mineru/model/flash/office/rtf/parser.pyindex 657e177e..ee3a07ff 100644--- a/mineru/model/flash/office/rtf/parser.py+++ b/mineru/model/flash/office/rtf/parser.py@@ -49,6 +49,7 @@ from .models import (MAX_RTF_BYTES = MAX_ENTRY_BYTESMAX_RTF_LIST_DEPTH = 8MAX_RTF_TABLE_DEPTH = 4+MAX_RTF_ROMAN_VALUE = 3_999_CHARSET_ENCODINGS = {0: "cp1252",@@ -146,6 +147,25 @@ _HYPERLINK_RE = re.compile(_CONTROL_RE = re.compile(rb"\\(?P<name>[A-Za-z]+)(?P<param>-?\d+)?(?: )?")+@dataclass(frozen=True, slots=True)+class _TextStyleOverrides:+ """保存 stylesheet 中可区分缺省与显式关闭的字符样式覆盖。"""++ bold: bool | None = None+ italic: bool | None = None+ underline: bool | None = None+ strike: bool | None = None++ def resolve(self, base: RtfTextStyle = RtfTextStyle()) -> RtfTextStyle:+ """用当前显式值覆盖基样式,缺省字段继续继承。"""+ return RtfTextStyle(+ bold=base.bold if self.bold is None else self.bold,+ italic=base.italic if self.italic is None else self.italic,+ underline=base.underline if self.underline is None else self.underline,+ strike=base.strike if self.strike is None else self.strike,+ )++@dataclass(frozen=True, slots=True)class _StyleDefinition:"""保存 stylesheet 中与语义投影相关的段落样式。"""@@ -156,6 +176,7 @@ class _StyleDefinition:block_style: Literal["normal", "code", "quote"] = "normal"based_on: int | None = Nonetext_style: RtfTextStyle = RtfTextStyle()+ text_style_overrides: _TextStyleOverrides = _TextStyleOverrides()@dataclass(frozen=True, slots=True)@@ -290,11 +311,7 @@ class _TableBuilder:if not self._row_open:self.start_row()definition_index = len(self._cells)- definition = (- self._definitions[definition_index]- if definition_index < len(self._definitions)- else _CellDefinition()- )+ definition = self._definitions[definition_index] if definition_index < len(self._definitions) else _CellDefinition()self._cells.append(RtfTableCell(blocks=self._cell_blocks,@@ -317,9 +334,7 @@ class _TableBuilder:if target_cells:total_slots = sum(len(row.cells) for row in self.rows) + target_cellsif total_slots > MAX_GRID_SLOTS:- raise LegacyOfficeResourceLimitError(- f"RTF table exceeds max_grid_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._definitions = []self._cells = []@@ -369,6 +384,19 @@ class _GroupFrame:note_kind: Literal["footnote", "endnote"] = "footnote"+@dataclass(frozen=True, slots=True)+class _GroupSpan:+ """用原始 RTF buffer 上的起止位置表示 group,避免嵌套切片复制。"""++ data: bytes+ start: int+ end: int++ def materialize(self) -> bytes:+ """仅在实际解析匹配 destination 时物化当前 group。"""+ return self.data[self.start : self.end]++def _lookup_encoding(code_page: int, fallback: str = "cp1252") -> str:"""把 RTF code page 规范为 Python codec,不支持时返回稳定 fallback。"""candidate = f"cp{code_page}"@@ -394,11 +422,11 @@ def _default_encoding(data: bytes) -> str:return "cp1252"-def _group_slices(data: bytes, *, direct_only: bool = False) -> list[bytes]:- """按二进制安全 token 边界返回当前输入中的子 group 切片。"""+def _group_spans(data: bytes, *, direct_only: bool = False) -> list[_GroupSpan]:+ """按二进制安全 token 边界返回共享原始 buffer 的子 group 范围。"""depth = 0starts: list[int] = []- result: list[bytes] = []+ result: list[_GroupSpan] = []for token in RtfLexer(data):if isinstance(token, RtfOpen):depth += 1@@ -406,14 +434,15 @@ def _group_slices(data: bytes, *, direct_only: bool = False) -> list[bytes]:elif isinstance(token, RtfClose) and starts:start = starts.pop()if (direct_only and depth == 2) or (not direct_only and depth >= 2):- result.append(data[start : token.end])+ result.append(_GroupSpan(data, start, token.end))depth = max(depth - 1, 0)return result-def _group_destination(group: bytes) -> str | None:+def _group_destination(group: _GroupSpan) -> str | None:"""读取 group 开头最多两个 control word 以识别 destination。"""- controls = list(_CONTROL_RE.finditer(group[:256]))+ prefix = group.data[group.start : min(group.end, group.start + 256)]+ controls = list(_CONTROL_RE.finditer(prefix))for match in controls[:3]:name = match.group("name").decode("ascii").lower()if name not in {"rtf", "ansi", "deff"}:@@ -421,9 +450,9 @@ def _group_destination(group: bytes) -> str | None:return None-def _named_groups(data: bytes, destination: str) -> list[bytes]:- """返回全部以指定 control word 开头的 group。"""- return [group for group in _group_slices(data) if _group_destination(group) == destination]+def _named_groups(data: bytes, destination: str) -> list[_GroupSpan]:+ """返回全部匹配 destination 的零拷贝 group 范围。"""+ return [group for group in _group_spans(data) if _group_destination(group) == destination]def _decode_group_text(data: bytes, encoding: str) -> str:@@ -482,7 +511,9 @@ def _parse_fonts(data: bytes, default: str) -> dict[int, str]:if not groups:return {}result: dict[int, str] = {}- for font_group in _group_slices(groups[0], direct_only=True):+ font_table = groups[0].materialize()+ for font_span in _group_spans(font_table, direct_only=True):+ font_group = font_span.materialize()font_match = re.search(rb"\\f(?P<id>\d+)(?:\D|$)", font_group)if font_match is None:continue@@ -498,15 +529,15 @@ def _parse_fonts(data: bytes, default: str) -> dict[int, str]:return result-def _style_control_is_on(data: bytes, name: str) -> bool:- """读取样式 group 中指定 on/off control 的最后一次显式取值。"""+def _style_control_value(data: bytes, name: str) -> bool | None:+ """读取样式 on/off control 的三态值,缺省时返回空。"""pattern = re.compile(rb"\\" + name.encode("ascii") + rb"(?P<param>-?\d+)?(?=[^A-Za-z]|$)",re.IGNORECASE,)matches = list(pattern.finditer(data))if not matches:- return False+ return Noneraw_param = matches[-1].group("param")return raw_param is None or int(raw_param) != 0@@ -517,7 +548,9 @@ def _parse_styles(data: bytes, encoding: str) -> dict[int, _StyleDefinition]:if not groups:return {}result: dict[int, _StyleDefinition] = {}- for style_group in _group_slices(groups[0], direct_only=True):+ stylesheet = groups[0].materialize()+ for style_span in _group_spans(stylesheet, direct_only=True):+ style_group = style_span.materialize()style_match = re.search(rb"\\s(?P<id>-?\d+)(?:\D|$)", style_group)if style_match is None:continue@@ -538,11 +571,11 @@ def _parse_styles(data: bytes, encoding: str) -> dict[int, _StyleDefinition]:block_style = "quote"else:block_style = _BLOCK_STYLE_NAMES.get(normalized, "normal")- text_style = RtfTextStyle(- bold=_style_control_is_on(style_group, "b"),- italic=_style_control_is_on(style_group, "i"),- underline=_style_control_is_on(style_group, "ul"),- strike=_style_control_is_on(style_group, "strike"),+ text_style_overrides = _TextStyleOverrides(+ bold=_style_control_value(style_group, "b"),+ italic=_style_control_value(style_group, "i"),+ underline=_style_control_value(style_group, "ul"),+ strike=_style_control_value(style_group, "strike"),)result[style_id] = _StyleDefinition(name=name,@@ -550,7 +583,8 @@ def _parse_styles(data: bytes, encoding: str) -> dict[int, _StyleDefinition]:is_title=normalized in _TITLE_STYLE_NAMES,block_style=block_style, # type: ignore[arg-type]based_on=based_on,- text_style=text_style,+ text_style=text_style_overrides.resolve(),+ text_style_overrides=text_style_overrides,)resolved: dict[int, _StyleDefinition] = {}@@ -564,12 +598,7 @@ def _parse_styles(data: bytes, encoding: str) -> dict[int, _StyleDefinition]:resolved[style_id] = currentreturn currentbase = resolve(current.based_on, {*visiting, style_id})- merged_style = RtfTextStyle(- bold=current.text_style.bold or base.text_style.bold,- italic=current.text_style.italic or base.text_style.italic,- underline=current.text_style.underline or base.text_style.underline,- strike=current.text_style.strike or base.text_style.strike,- )+ merged_style = current.text_style_overrides.resolve(base.text_style)merged = _StyleDefinition(name=current.name,outline_level=current.outline_level if current.outline_level is not None else base.outline_level,@@ -577,6 +606,7 @@ def _parse_styles(data: bytes, encoding: str) -> dict[int, _StyleDefinition]:block_style=current.block_style if current.block_style != "normal" else base.block_style,based_on=current.based_on,text_style=merged_style,+ text_style_overrides=current.text_style_overrides,)resolved[style_id] = mergedreturn merged@@ -591,12 +621,15 @@ def _parse_lists(data: bytes) -> dict[int, _ListDefinition]:by_list_id: dict[int, tuple[_ListLevel, ...]] = {}list_tables = _named_groups(data, "listtable")if list_tables:- for list_group in _named_groups(list_tables[0], "list"):+ list_table = list_tables[0].materialize()+ for list_span in _named_groups(list_table, "list"):+ list_group = list_span.materialize()id_match = re.search(rb"\\listid(?P<id>-?\d+)", list_group)if id_match is None:continuelevels: list[_ListLevel] = []- for level_group in _named_groups(list_group, "listlevel")[: MAX_RTF_LIST_DEPTH + 1]:+ for level_span in _named_groups(list_group, "listlevel")[: MAX_RTF_LIST_DEPTH + 1]:+ level_group = level_span.materialize()nfc_match = re.search(rb"\\levelnfc(?P<nfc>\d+)", level_group)start_match = re.search(rb"\\levelstartat(?P<start>-?\d+)", level_group)nfc = int(nfc_match.group("nfc")) if nfc_match is not None else 0@@ -609,7 +642,9 @@ def _parse_lists(data: bytes) -> dict[int, _ListDefinition]:result: dict[int, _ListDefinition] = {}override_tables = _named_groups(data, "listoverridetable")if override_tables:- for override_group in _named_groups(override_tables[0], "listoverride"):+ override_table = override_tables[0].materialize()+ for override_span in _named_groups(override_table, "listoverride"):+ override_group = override_span.materialize()id_match = re.search(rb"\\listid(?P<id>-?\d+)", override_group)ls_match = re.search(rb"\\ls(?P<ls>\d+)", override_group)if id_match is None or ls_match is None:@@ -617,14 +652,17 @@ def _parse_lists(data: bytes) -> dict[int, _ListDefinition]:list_id = int(id_match.group("id"))ls = int(ls_match.group("ls"))levels = list(by_list_id.get(list_id, (_ListLevel(),)))- for level_index, level_override in enumerate(_named_groups(override_group, "lfolevel")):+ for level_index, level_span in enumerate(_named_groups(override_group, "lfolevel")):+ level_override = level_span.materialize()while len(levels) <= level_index:levels.append(_ListLevel())current = levels[level_index]start_match = re.search(rb"\\levelstartat(?P<start>-?\d+)", level_override)nfc_match = re.search(rb"\\levelnfc(?P<nfc>\d+)", level_override)start = max(int(start_match.group("start")), 0) if start_match is not None else current.start- marker = _NFC_MARKERS.get(int(nfc_match.group("nfc")), current.marker) if nfc_match is not None else current.marker+ marker = (+ _NFC_MARKERS.get(int(nfc_match.group("nfc")), current.marker) if nfc_match is not None else current.marker+ )levels[level_index] = _ListLevel(marker=marker, start=start)result[ls] = _ListDefinition(identity=ls, levels=tuple(levels))return result@@ -635,10 +673,11 @@ def _parse_metadata(data: bytes, encoding: str) -> RtfMetadata:info_groups = _named_groups(data, "info")if not info_groups:return RtfMetadata()+ info_group = info_groups[0].materialize()values: dict[str, str | None] = {}for name in ("title", "author", "subject", "keywords"):- groups = _named_groups(info_groups[0], name)- value = _decode_group_text(groups[0], encoding).strip() if groups else ""+ groups = _named_groups(info_group, name)+ value = _decode_group_text(groups[0].materialize(), encoding).strip() if groups else ""values[name] = value or Nonereturn RtfMetadata(**values)@@ -660,8 +699,8 @@ def parse_rtf_prelude(data: bytes) -> _Prelude:def _roman(value: int) -> str:- """把正整数格式化为常见 Roman 编号。"""- if value <= 0:+ """把受支持正整数格式化为 Roman 编号,越界时安全回退十进制。"""+ if value <= 0 or value > MAX_RTF_ROMAN_VALUE:return str(value)pairs = ((1000, "M"),@@ -1014,9 +1053,7 @@ class RtfParser:if len(payload) > MAX_ENTRY_BYTES:raise LegacyOfficeResourceLimitError(f"RTF pict exceeds max_entry_bytes={MAX_ENTRY_BYTES}")if self._asset_total + len(payload) > MAX_ASSET_TOTAL_BYTES:- raise LegacyOfficeResourceLimitError(- f"RTF pict assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"- )+ raise LegacyOfficeResourceLimitError(f"RTF pict assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}")self._asset_total += len(payload)return RtfImage(data=payload,@@ -1028,12 +1065,12 @@ class RtfParser:def _finish_math(self, frame: _GroupFrame, end: int) -> None:"""把 math group 转换为行内或行间 LaTeX,失败时静默保留其余正文。"""formulas, display = parse_rtf_math(- self.data[frame.start:end],+ self.data[frame.start : end],encoding=self._current_encoding(),)if not formulas:- for group in _named_groups(self.data[frame.start:end], "pict"):- capture = _capture_picture_group(group)+ for group in _named_groups(self.data[frame.start : end], "pict"):+ capture = _capture_picture_group(group.materialize())if capture is None:continueimage = self._materialize_picture(capture)@@ -1334,11 +1371,7 @@ class RtfParser:"""追加行内节点,并合并样式和链接完全相同的相邻文本 run。"""if isinstance(inline, RtfTextRun) and self.context.inlines:previous = self.context.inlines[-1]- if (- isinstance(previous, RtfTextRun)- and previous.style == inline.style- and previous.hyperlink == inline.hyperlink- ):+ if isinstance(previous, RtfTextRun) and previous.style == inline.style and previous.hyperlink == inline.hyperlink:self.context.inlines[-1] = replace(previous, text=f"{previous.text}{inline.text}")returnself.context.inlines.append(inline)@@ -1388,8 +1421,7 @@ class RtfParser:list_info = self._resolve_list_info()self.context.pending_list_label = Nonehas_visible = any(- not isinstance(inline, (RtfTextRun, RtfAnchor))- or (isinstance(inline, RtfTextRun) and bool(inline.text.strip()))+ not isinstance(inline, (RtfTextRun, RtfAnchor)) or (isinstance(inline, RtfTextRun) and bool(inline.text.strip()))for inline in inlines)if not has_visible and not any(isinstance(inline, RtfAnchor) for inline in inlines):@@ -1416,18 +1448,14 @@ class RtfParser:def _table_builder(self, depth: int) -> _TableBuilder:"""返回指定 depth 的 builder,并拒绝超出渲染能力的嵌套。"""if depth < 1 or depth > MAX_RTF_TABLE_DEPTH:- raise LegacyOfficeResourceLimitError(- f"RTF table nesting exceeds max_table_depth={MAX_RTF_TABLE_DEPTH}"- )+ raise LegacyOfficeResourceLimitError(f"RTF table nesting exceeds max_table_depth={MAX_RTF_TABLE_DEPTH}")return self.context.tables.setdefault(depth, _TableBuilder())def _set_table_depth(self, depth: int) -> None:"""切换 table depth,并把已结束的深层表格挂回父 cell。"""normalized = min(max(depth, 0), MAX_RTF_TABLE_DEPTH)if depth > MAX_RTF_TABLE_DEPTH:- raise LegacyOfficeResourceLimitError(- f"RTF table nesting exceeds max_table_depth={MAX_RTF_TABLE_DEPTH}"- )+ raise LegacyOfficeResourceLimitError(f"RTF table nesting exceeds max_table_depth={MAX_RTF_TABLE_DEPTH}")for current_depth in sorted([value for value in self.context.tables if value > normalized],reverse=True,diff --git a/tests/unittest/test_flash_odf.py b/tests/unittest/test_flash_odf.pyindex 585483bd..aa538bdb 100644--- a/tests/unittest/test_flash_odf.py+++ b/tests/unittest/test_flash_odf.py@@ -30,7 +30,7 @@ from mineru.parser.file_type import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.render import render_docx, render_html, render_markdown, render_structured_contentfrom mineru.types import BlockType-from _odf_test_utils import build_odf_package, build_odp_fixture, build_ods_fixture, build_odt_fixture+from _odf_test_utils import _PIXEL_PNG, build_odf_package, build_odp_fixture, build_ods_fixture, build_odt_fixture@pytest.mark.parametrize(@@ -114,6 +114,90 @@ def test_odt_promotes_numbered_heading_inside_list() -> None:assert middle.pages[0].blocks[0].content == "1 Chapter" # type: ignore[union-attr]+def test_odt_list_lifts_visual_blocks_outside_strict_list() -> None:+ """验证列表段落图片保留原类型并提升为 LIST 的有序兄弟块。"""+ content = """<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:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:automatic-styles><text:list-style style:name="L1">+ <text:list-level-style-number text:level="1" style:num-format="1"/>+ </text:list-style></office:automatic-styles>+ <office:body><office:text><text:list text:style-name="L1"><text:list-item text:start-value="3">+ <text:p>Illustrated item<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame></text:p>+ </text:list-item><text:list-item><text:p>Next item</text:p></text:list-item></text:list></office:text></office:body>+</office:document-content>"""++ middle, _ = doc_analyze(+ build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG}),+ file_suffix="odt",+ )++ assert [block.type for block in middle.pages[0].blocks] == [BlockType.LIST, BlockType.IMAGE, BlockType.LIST]+ assert [child.content for child in middle.pages[0].blocks[0].content] == ["3. Illustrated item"] # type: ignore[union-attr]+ assert [child.content for child in middle.pages[0].blocks[2].content] == ["4. Next item"] # type: ignore[union-attr]+++def test_odt_list_item_joins_multiple_paragraphs_before_markers() -> None:+ """验证一个源 list-item 的多个段落只生成一个 LIST 文本叶子和一个 marker。"""+ content = """<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">+ <office:body><office:text><text:list>+ <text:list-item><text:p>First paragraph</text:p><text:p>Second paragraph</text:p></text:list-item>+ <text:list-item><text:p>Next item</text:p></text:list-item>+ </text:list></office:text></office:body>+</office:document-content>"""++ middle, _ = doc_analyze(build_odf_package("odt", content), file_suffix="odt")+ list_block = middle.pages[0].blocks[0]++ assert list_block.type == BlockType.LIST+ assert [child.content for child in list_block.content] == ["- First paragraph\nSecond paragraph", "- Next item"] # type: ignore[union-attr]+ assert render_markdown(middle).count("- ") == 2+++def test_odt_table_cell_renders_inline_image_once() -> None:+ """验证 ODT/ODP 单元格内联图片不会再被对应段外 image block 重复输出。"""+ content = """<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:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"+ xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:body><office:text><table:table><table:table-row><table:table-cell>+ <text:p>Cell<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame></text:p>+ </table:table-cell></table:table-row></table:table></office:text></office:body>+</office:document-content>"""++ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})))++ assert pages[0][0]["type"] == BlockType.TABLE+ assert pages[0][0]["content"].count("<img") == 1+++def test_odt_inline_visual_stays_before_soft_page_break() -> None:+ """验证 soft-page-break 前遇到的段内视觉块仍留在来源逻辑页。"""+ content = """<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:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"+ xmlns:xlink="http://www.w3.org/1999/xlink">+ <office:body><office:text><text:p>+ Before<draw:frame><draw:image xlink:href="Pictures/pixel.png"/></draw:frame><text:soft-page-break/>After+ </text:p></office:text></office:body>+</office:document-content>"""++ pages = OdtModel().predict(BytesIO(build_odf_package("odt", content, extra_parts={"Pictures/pixel.png": _PIXEL_PNG})))++ assert [[block["type"] for block in page] for page in pages] == [+ [BlockType.TEXT, BlockType.IMAGE],+ [BlockType.TEXT],+ ]++def test_odp_preserves_empty_slide_chart_preview_and_notes() -> None:"""验证 ODP 空 slide 不丢失,图表同时保留数据和预览,备注归属原页。"""middle, model = doc_analyze(build_odp_fixture(), file_suffix="odp")diff --git a/tests/unittest/test_flash_rtf.py b/tests/unittest/test_flash_rtf.pyindex a0936f54..de02722d 100644--- a/tests/unittest/test_flash_rtf.py+++ b/tests/unittest/test_flash_rtf.py@@ -4,6 +4,7 @@ import asynciofrom io import BytesIOimport subprocessimport sys+import tracemallocfrom pathlib import Pathimport pytest@@ -44,7 +45,7 @@ def _complex_rtf() -> bytes:def test_rtf_lexer_bin_payload_is_position_explicit() -> None:"""验证 bin 中的花括号和反斜杠不改变 lexer group 结构。"""- tokens = list(RtfLexer(br"{\rtf1 before\bin5 }}{\x after}"))+ tokens = list(RtfLexer(rb"{\rtf1 before\bin5 }}{\x after}"))binaries = [token for token in tokens if isinstance(token, RtfBinary)]assert [token.data for token in binaries] == [b"}}{\\x"]@@ -53,7 +54,7 @@ def test_rtf_lexer_bin_payload_is_position_explicit() -> None:def test_rtf_lexer_rejects_truncated_bin_payload() -> None:"""验证截断 bin 在游标失去可信边界前立即失败。"""with pytest.raises(LegacyOfficeMalformedError, match="truncated"):- list(RtfLexer(br"{\rtf1\bin9 ab}"))+ list(RtfLexer(rb"{\rtf1\bin9 ab}"))def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:@@ -62,12 +63,12 @@ def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:japanese = b"".join(f"\\'{value:02x}".encode("ascii") for value in "こんにちは".encode("cp932"))source = b"".join([- br"{\rtf1\ansi{\fonttbl{\f0\fcharset204 Arial;}{\f1\fcharset128 MS Gothic;}}",- br"\pard\f0 ",+ rb"{\rtf1\ansi{\fonttbl{\f0\fcharset204 Arial;}{\f1\fcharset128 MS Gothic;}}",+ rb"\pard\f0 ",russian,- br" \f1 ",+ rb" \f1 ",japanese,- br" \u-10179?\u-8704?\par}",+ rb" \u-10179?\u-8704?\par}",])@@ -76,6 +77,33 @@ def test_rtf_font_codepages_and_unicode_surrogates_are_exact() -> None:assert pages == [[{"type": BlockType.TEXT, "content": "Привет こんにちは 😀"}]]+def test_rtf_inherited_style_honors_explicit_formatting_resets() -> None:+ """验证 derived stylesheet 的 b0/i0/ul0/strike0 覆盖基样式开启值。"""+ source = (+ rb"{\rtf1\ansi{\stylesheet{\s0\b\i\ul\strike Base;}{\s1\sbasedon0\b0\i0\ul0\strike0 Derived;}}\pard\s1 Reset text\par}"+ )++ pages = RtfModel().predict(BytesIO(source))++ assert pages == [[{"type": BlockType.TEXT, "content": "Reset text"}]]+++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"{\*\listoverridetable{\listoverride\listid7\listoverridecount0\ls2}}",+ rb"\pard\ls2\ilvl0 item\par}",+ ]+ )++ pages = RtfModel().predict(BytesIO(source))++ assert pages[0][0]["type"] == BlockType.LIST+ assert pages[0][0]["content"][0]["list_label"] == "1000000000000."++def test_rtf_model_recovers_unicode_styles_and_structures() -> None:"""验证完整 typed RTF 链路生成稳定单页 raw blocks。"""stream = BytesIO(_complex_rtf())@@ -126,7 +154,7 @@ def test_rtf_model_parses_real_libreoffice_fixture() -> None:def test_rtf_page_controls_remain_inside_one_semantic_page() -> None:"""验证 page/column 只保留换行,sect 只结束段落。"""- pages = RtfModel().predict(BytesIO(br"{\rtf1\ansi A\page B\column C\sect D\par}"))+ pages = RtfModel().predict(BytesIO(rb"{\rtf1\ansi A\page B\column C\sect D\par}"))assert len(pages) == 1assert pages[0] == [@@ -137,7 +165,7 @@ def test_rtf_page_controls_remain_inside_one_semantic_page() -> None:def test_rtf_nested_and_merged_tables_preserve_content() -> None:"""验证 nested table、cellx 投影及纵向 continuation 不丢可见文本。"""- source = br"""{\rtf1\ansi+ source = rb"""{\rtf1\ansi\trowd\clvmgf\cellx1000\cellx2000 A\cell B\cell\row\trowd\clvmrg\cellx1000\cellx2000 \cell C\cell\row\trowd\cellx1000\cellx2000@@ -158,16 +186,16 @@ def test_rtf_math_picture_is_only_used_when_formula_conversion_fails() -> None:"""验证 Office Math 成功时去重预览,失败时保留首个安全 fallback 图片。"""valid = b"".join([- br"{\rtf1{\mmath{\*\moMath{\mr x}}{\mmathPict{\pict\pngblip ",+ rb"{\rtf1{\mmath{\*\moMath{\mr x}}{\mmathPict{\pict\pngblip ",_PNG_HEX,- br"}}}}",+ rb"}}}}",])invalid = b"".join([- br"{\rtf1{\mmath{\*\moMath{\munknown x}}{\mmathPict{\pict\pngblip ",+ rb"{\rtf1{\mmath{\*\moMath{\munknown x}}{\mmathPict{\pict\pngblip ",_PNG_HEX,- br"}}}}",+ rb"}}}}",])@@ -327,7 +355,7 @@ def test_doclib_rejects_rtf_quality_tier_and_remote(def test_rtf_unknown_destination_and_unbalanced_tail_recover_visible_text() -> None:"""验证未知 ignorable destination 不泄漏,缺尾括号仍保留已恢复正文。"""- source = br"{\rtf1\ansi{\*\unknown hidden}\pard visible\par"+ source = rb"{\rtf1\ansi{\*\unknown hidden}\pard visible\par"pages = RtfModel().predict(BytesIO(source))@@ -337,7 +365,7 @@ def test_rtf_unknown_destination_and_unbalanced_tail_recover_visible_text() -> Ndef test_rtf_source_html_is_rendered_as_inert_text() -> None:"""验证源文档中的活动 HTML 外观不会进入 HTML renderer DOM。"""middle, _ = doc_analyze(- br"{\rtf1\ansi visible <script>alert(1)</script> and x < y\par}",+ rb"{\rtf1\ansi visible <script>alert(1)</script> and x < y\par}",file_suffix="rtf",)@@ -351,28 +379,26 @@ def test_rtf_source_html_is_rendered_as_inert_text() -> None:def test_rtf_object_keeps_safe_result_and_suppresses_objdata() -> None:"""验证对象载荷不执行不泄漏,但显式 result 文本仍可恢复。"""- pages = RtfModel().predict(- BytesIO(br"{\rtf1 before {\object{\*\objdata 41424344}{\result Visible object}} after\par}")- )+ pages = RtfModel().predict(BytesIO(rb"{\rtf1 before {\object{\*\objdata 41424344}{\result Visible object}} after\par}"))assert pages == [[{"type": BlockType.TEXT, "content": "before Visible object after"}]]def test_rtf_malformed_vector_picture_is_locally_dropped() -> None:"""验证伪装 WMF 的 bin 字节不会生成占位图或破坏周围正文。"""- pages = RtfModel().predict(- BytesIO(br"{\rtf1 before {\pict\wmetafile8\bin5 abcde} after\par}")- )+ pages = RtfModel().predict(BytesIO(rb"{\rtf1 before {\pict\wmetafile8\bin5 abcde} after\par}"))- assert pages == [[- {"type": BlockType.TEXT, "content": "before"},- {"type": BlockType.TEXT, "content": "after"},- ]]+ assert pages == [+ [+ {"type": BlockType.TEXT, "content": "before"},+ {"type": BlockType.TEXT, "content": "after"},+ ]+ ]def test_rtf_valid_empty_and_invalid_header_have_distinct_results() -> None:"""合法空 RTF 返回空逻辑页,非 RTF 输入返回稳定 malformed 错误。"""- assert RtfModel().predict(BytesIO(br"{\rtf1}")) == [[]]+ assert RtfModel().predict(BytesIO(rb"{\rtf1}")) == [[]]with pytest.raises(LegacyOfficeMalformedError, match="not an RTF"):RtfModel().predict(BytesIO(b"plain text"))@@ -381,7 +407,7 @@ def test_rtf_resource_limits_are_fixed_and_non_configurable(monkeypatch: pytest."""验证 token、group、input、asset、grid 和 nested-table 上限均硬失败。"""monkeypatch.setattr(lexer_module, "MAX_RECORDS", 3)with pytest.raises(LegacyOfficeResourceLimitError, match="max_tokens"):- list(RtfLexer(br"{\rtf1 text}"))+ list(RtfLexer(rb"{\rtf1 text}"))monkeypatch.setattr(lexer_module, "MAX_RECORDS", 16_000_000)with pytest.raises(LegacyOfficeResourceLimitError, match="max_group_depth"):@@ -389,30 +415,43 @@ def test_rtf_resource_limits_are_fixed_and_non_configurable(monkeypatch: pytest.monkeypatch.setattr(parser_module, "MAX_RTF_BYTES", 8)with pytest.raises(LegacyOfficeResourceLimitError, match="max_bytes"):- RtfModel().predict(BytesIO(br"{\rtf1 too long}"))+ RtfModel().predict(BytesIO(rb"{\rtf1 too long}"))monkeypatch.setattr(parser_module, "MAX_RTF_BYTES", 128 * 1024 * 1024)monkeypatch.setattr(parser_module, "MAX_ASSET_TOTAL_BYTES", 1)with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):- RtfModel().predict(BytesIO(br"{\rtf1{\pict\pngblip 89504e47}}"))+ RtfModel().predict(BytesIO(rb"{\rtf1{\pict\pngblip 89504e47}}"))monkeypatch.setattr(parser_module, "MAX_ASSET_TOTAL_BYTES", 128 * 1024 * 1024)monkeypatch.setattr(parser_module, "MAX_GRID_SLOTS", 1)with pytest.raises(LegacyOfficeResourceLimitError, match="max_grid_slots"):- RtfModel().predict(BytesIO(br"{\rtf1\trowd\cellx1\cellx2 A\cell B\cell\row}"))+ RtfModel().predict(BytesIO(rb"{\rtf1\trowd\cellx1\cellx2 A\cell B\cell\row}"))monkeypatch.setattr(parser_module, "MAX_GRID_SLOTS", 4_000_000)with pytest.raises(LegacyOfficeResourceLimitError, match="max_table_depth"):- RtfModel().predict(BytesIO(br"{\rtf1\pard\intbl\itap5 nested\par}"))+ RtfModel().predict(BytesIO(rb"{\rtf1\pard\intbl\itap5 nested\par}"))+++def test_rtf_prelude_nested_groups_do_not_materialize_overlapping_slices() -> None:+ """验证 prelude 扫描深层 group 时峰值内存保持为输入规模常数倍。"""+ payload_size = 256 * 1024+ depth = 64+ source = b"{\\rtf1" + b"{" * depth + b"x" * payload_size + b"}" * depth + b"}"++ tracemalloc.start()+ try:+ parser_module.parse_rtf_prelude(source)+ _, peak_bytes = tracemalloc.get_traced_memory()+ finally:+ tracemalloc.stop()++ assert peak_bytes < len(source) * 4def test_rtf_runtime_has_no_anydoc_dependency() -> None:"""验证依赖清单、源码导入和惰性模型加载均不包含 anydoc。"""assert "firecrawl-anydoc" not in (_PROJECT_ROOT / "pyproject.toml").read_text(encoding="utf-8").lower()- assert all(- "import anydoc" not in path.read_text(encoding="utf-8")- for path in (_PROJECT_ROOT / "mineru").rglob("*.py")- )+ assert all("import anydoc" not in path.read_text(encoding="utf-8") for path in (_PROJECT_ROOT / "mineru").rglob("*.py"))script = "\n".join(["import sys",