Skip to content

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

feat: enhance support for equations in XLS and PPT formats with native parsing and rendering

myhlolidf9313693dd3
diff --git a/mineru/model/flash/doc/doc_converter.py b/mineru/model/flash/doc/doc_converter.py
index 95e62254..195fcdb7 100644
--- a/mineru/model/flash/doc/doc_converter.py
+++ b/mineru/model/flash/doc/doc_converter.py
@@ -15,6 +15,7 @@ from mineru.types import RAW_CAPTION, BlockType
from mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segments
from .fib import parse_fib
+from mineru.model.flash.legacy_office.mtef import read_object_pool_equations
from .models import (
DocCharStyle,
DocDocument,
@@ -55,7 +56,14 @@ class DocConverter:
if not table_stream:
table_stream = ole.read_stream(alternate, required=bool(fib.base.complex))
data_stream = ole.read_stream("Data", required=False)
- document = parse_doc_document(word_document, table_stream, data_stream, fib)
+ native_equations = read_object_pool_equations(ole)
+ document = parse_doc_document(
+ word_document,
+ table_stream,
+ data_stream,
+ fib,
+ native_equations=native_equations,
+ )
self.pages = self._document_pages(document)
@staticmethod
@@ -83,16 +91,39 @@ class DocConverter:
def _rich_text(cls, runs: Iterable[DocTextRun], *, trim: bool = True) -> str:
"""把 DOC runs 转换为已转义的 Office 富文本协议。"""
- segments = [
- OfficeRichTextSegment(
- text=escape(run.text, quote=False).replace("\n", "<br/>"),
- style=cls._style_names(run.style),
- hyperlink=escape(run.hyperlink, quote=True) if run.hyperlink else None,
+ parts: list[str] = []
+ segments: list[OfficeRichTextSegment] = []
+
+ def flush_segments() -> None:
+ """输出公式边界前累计的普通富文本。"""
+
+ if not segments:
+ return
+ parts.append(
+ build_rich_text_from_segments(
+ segments,
+ trim_plain_edges=trim and not parts,
+ )
+ )
+ segments.clear()
+
+ for run in runs:
+ if not run.text:
+ continue
+ if run.formula:
+ flush_segments()
+ latex = run.text.replace("<", r"\lt ").replace(">", r"\gt ")
+ parts.append(f"<eq>{latex}</eq>")
+ continue
+ segments.append(
+ OfficeRichTextSegment(
+ text=escape(run.text, quote=False).replace("\n", "<br/>"),
+ style=cls._style_names(run.style),
+ hyperlink=escape(run.hyperlink, quote=True) if run.hyperlink else None,
+ )
)
- for run in runs
- if run.text
- ]
- return build_rich_text_from_segments(segments, trim_plain_edges=trim)
+ flush_segments()
+ return "".join(parts).strip() if trim else "".join(parts)
@staticmethod
def _plain_text(paragraph: DocParagraph) -> str:
@@ -228,11 +259,23 @@ class DocConverter:
content = cls._rich_text(paragraph.runs)
blocks: list[dict[str, Any]] = []
+ formula_runs = [run for run in paragraph.runs if run.formula and run.text]
+ ordinary_text = "".join(run.text for run in paragraph.runs if not run.formula).strip()
list_info = paragraph.list_info
exact_label = list_info.label if list_info is not None and list_info.ordered else None
if exact_label and (paragraph.is_title or paragraph.heading_level is not None):
content = f"{escape(exact_label, quote=False)} {content}".strip()
- if content:
+ if formula_runs and not ordinary_text and not (
+ paragraph.is_title
+ or paragraph.heading_level is not None
+ or paragraph.is_caption
+ or paragraph.is_code
+ ):
+ blocks.extend(
+ {"type": BlockType.EQUATION, "content": run.text}
+ for run in formula_runs
+ )
+ elif content:
if paragraph.is_title:
block: dict[str, Any] = {
"type": BlockType.DOC_TITLE,
diff --git a/mineru/model/flash/doc/fields.py b/mineru/model/flash/doc/fields.py
index 01183a71..98ebaaa8 100644
--- a/mineru/model/flash/doc/fields.py
+++ b/mineru/model/flash/doc/fields.py
@@ -105,5 +105,4 @@ def apply_field_result(instruction: str, runs: list[DocTextRun]) -> list[DocText
target = hyperlink_target(instruction)
if target is None:
return runs
- return [DocTextRun(run.text, run.style, target) for run in runs]
-
+ return [DocTextRun(run.text, run.style, target, run.formula) for run in runs]
diff --git a/mineru/model/flash/doc/models.py b/mineru/model/flash/doc/models.py
index c0da6018..40270578 100644
--- a/mineru/model/flash/doc/models.py
+++ b/mineru/model/flash/doc/models.py
@@ -30,6 +30,7 @@ class DocTextRun:
text: str
style: DocCharStyle = DocCharStyle()
hyperlink: str | None = None
+ formula: bool = False
@dataclass(frozen=True, slots=True)
diff --git a/mineru/model/flash/doc/parser.py b/mineru/model/flash/doc/parser.py
index 2976fc78..24e5f671 100644
--- a/mineru/model/flash/doc/parser.py
+++ b/mineru/model/flash/doc/parser.py
@@ -68,6 +68,7 @@ class _FieldFrame:
in_result: bool = False
transparent: bool = False
runs: list[DocTextRun] = field(default_factory=list)
+ native_formula: bool = False
@dataclass(slots=True)
@@ -93,6 +94,7 @@ class _Assembler:
data_stream: bytes,
image_store: ImageStore,
budget: DocBudget,
+ native_equations: dict[int, str] | None = None,
) -> None:
"""保存解析上下文;每个 story 开始时会重置字段栈。"""
@@ -105,6 +107,7 @@ class _Assembler:
self.data_stream = data_stream
self.image_store = image_store
self.budget = budget
+ self.native_equations = native_equations or {}
self._fields: list[_FieldFrame] = []
def _piece_prm(self, char_index: int) -> bytes:
@@ -152,9 +155,19 @@ class _Assembler:
if not run.text:
return
- if target and target[-1].style == run.style and target[-1].hyperlink == run.hyperlink:
+ if (
+ target
+ and target[-1].style == run.style
+ and target[-1].hyperlink == run.hyperlink
+ and target[-1].formula == run.formula
+ ):
previous = target[-1]
- target[-1] = DocTextRun(previous.text + run.text, previous.style, previous.hyperlink)
+ target[-1] = DocTextRun(
+ previous.text + run.text,
+ previous.style,
+ previous.hyperlink,
+ previous.formula,
+ )
else:
target.append(run)
@@ -292,6 +305,12 @@ class _Assembler:
continue
if char == "\x14":
self._field_separator(keywords)
+ character_run = self.formatting.character_at(fc)
+ location = chpx_picture_location(character_run.grpprl) if character_run is not None else None
+ formula = self.native_equations.get(location) if location is not None else None
+ if formula is not None and self._fields:
+ self._fields[-1].native_formula = True
+ self._push_visible_run(visible, DocTextRun(formula, formula=True))
continue
if char == "\x15":
self._field_end(visible, keywords)
@@ -321,6 +340,8 @@ class _Assembler:
paragraph_start = cp + 1
continue
if char == "\x01":
+ if self._fields and self._fields[-1].native_formula:
+ continue
character_run = self.formatting.character_at(fc)
location = chpx_picture_location(character_run.grpprl) if character_run is not None else None
if location is not None:
@@ -675,6 +696,8 @@ def parse_doc_document(
table_stream: bytes,
data_stream: bytes,
fib: FileInformationBlock,
+ *,
+ native_equations: dict[int, str] | None = None,
) -> DocDocument:
"""解析三个核心 streams 并返回逐 section 语义文档。"""
@@ -784,6 +807,7 @@ def parse_doc_document(
data_stream=data_stream,
image_store=store,
budget=budget,
+ native_equations=native_equations,
)
main_paragraphs = assembler.paragraphs(0, fib.ccp_text, note_refs=note_refs)
shape_pair = fib.pair(FCLCB_SHAPE_MAIN)
diff --git a/mineru/model/flash/legacy_office/mtef.py b/mineru/model/flash/legacy_office/mtef.py
new file mode 100644
index 00000000..8462a214
--- /dev/null
+++ b/mineru/model/flash/legacy_office/mtef.py
@@ -0,0 +1,631 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""安全解析 Equation Editor 3.x 的 Equation Native/MTEF v3 公式。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+import struct
+
+from loguru import logger
+
+from .limits import MAX_RECORD_DEPTH, MAX_RECORDS
+from .ole import BoundedOleReader
+
+_OBJECT_POOL_EQUATION_RE = re.compile(
+ r"^ObjectPool/_([0-9]+)/Equation Native$",
+ re.IGNORECASE,
+)
+
+_XF_NULL = 0x10
+_XF_RULER = 0x20
+_XF_EMBELL = 0x20
+_XF_LSPACE = 0x40
+_XF_LMOVE = 0x80
+
+
+class _MtefError(ValueError):
+ """MTEF 输入不完整、不受支持或超过安全限制。"""
+
+
+@dataclass(frozen=True, slots=True)
+class _Node:
+ """MTEF 解析后的最小公式语法节点。"""
+
+ kind: str
+ value: object | None = None
+ children: tuple[_Node, ...] = ()
+
+
+class _MtefReader:
+ """有界读取 MTEF v3 record tree。"""
+
+ def __init__(self, data: bytes) -> None:
+ """校验五字节 MTEF v3 头并初始化游标。"""
+
+ if len(data) < 5 or data[0] != 3:
+ raise _MtefError("Equation Native does not contain MTEF v3")
+ self.data = data
+ self.pos = 5
+ self.depth = 0
+ self.records = 0
+
+ def _charge(self) -> None:
+ """计入一条 record,超过共享上限时拒绝对象。"""
+
+ self.records += 1
+ if self.records > MAX_RECORDS:
+ raise _MtefError("MTEF record count exceeds the safety limit")
+
+ def _u8(self) -> int:
+ """有界读取一个无符号字节。"""
+
+ if self.pos >= len(self.data):
+ raise _MtefError("MTEF record is truncated")
+ value = self.data[self.pos]
+ self.pos += 1
+ return value
+
+ def _u16(self) -> int:
+ """有界读取小端 u16。"""
+
+ if self.pos + 2 > len(self.data):
+ raise _MtefError("MTEF u16 is truncated")
+ value = int(struct.unpack_from("<H", self.data, self.pos)[0])
+ self.pos += 2
+ return value
+
+ def _skip_nudge(self) -> None:
+ """跳过短或长格式的 nudge 偏移。"""
+
+ dx = self._u8()
+ dy = self._u8()
+ if dx == 128 and dy == 128:
+ self._u16()
+ self._u16()
+
+ def _enter(self) -> None:
+ """进入一个嵌套 object list 并限制深度。"""
+
+ self.depth += 1
+ if self.depth > MAX_RECORD_DEPTH:
+ raise _MtefError("MTEF nesting exceeds the safety limit")
+
+ def _leave(self) -> None:
+ """离开一个嵌套 object list。"""
+
+ self.depth -= 1
+
+ def _skip_ruler(self) -> None:
+ """跳过不影响公式语义的 RULER record。"""
+
+ count = self._u8()
+ for _ in range(count):
+ self._u8()
+ self._u16()
+
+ def _skip_font(self) -> None:
+ """跳过 FONT 的 typeface、style 和零结尾名称。"""
+
+ self._u8()
+ self._u8()
+ while self._u8() != 0:
+ pass
+
+ def _skip_size(self) -> None:
+ """跳过三种长度形式的 SIZE record。"""
+
+ first = self._u8()
+ if first == 100:
+ self._u8()
+ self._u16()
+ elif first == 101:
+ self._u16()
+ else:
+ self._u8()
+
+ def _parse_embellishments(self) -> tuple[int, ...]:
+ """读取 CHAR 后以 END 终止的 embellishment 列表。"""
+
+ values: list[int] = []
+ while True:
+ tag = self._u8()
+ self._charge()
+ record_type = tag & 0x0F
+ flags = tag & 0xF0
+ if record_type == 0:
+ return tuple(values)
+ if record_type != 6:
+ raise _MtefError("MTEF embellishment list contains a non-EMBELL record")
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ values.append(self._u8())
+
+ def _parse_line(self, flags: int) -> _Node:
+ """解析一个 LINE slot。"""
+
+ if flags & _XF_NULL:
+ return _Node("sequence")
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ if flags & _XF_LSPACE:
+ self._u8()
+ if flags & _XF_RULER:
+ ruler_tag = self._u8()
+ if ruler_tag & 0x0F != 7:
+ raise _MtefError("MTEF LINE ruler tag is invalid")
+ self._skip_ruler()
+ self._enter()
+ children = self._parse_list()
+ self._leave()
+ return _Node("sequence", children=children)
+
+ def _parse_template(self, flags: int) -> _Node:
+ """解析 TMPL selector、variation、options 和 slots。"""
+
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ selector = self._u8()
+ variation = self._u8()
+ options = self._u8()
+ self._enter()
+ slots = self._parse_slots()
+ self._leave()
+ return _Node("template", (selector, variation, options), slots)
+
+ def _parse_pile(self, flags: int) -> _Node:
+ """解析纵向 PILE 中的 LINE slots。"""
+
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ self._u8()
+ self._u8()
+ if flags & _XF_RULER:
+ ruler_tag = self._u8()
+ if ruler_tag & 0x0F != 7:
+ raise _MtefError("MTEF PILE ruler tag is invalid")
+ self._skip_ruler()
+ self._enter()
+ slots = self._parse_slots()
+ self._leave()
+ return _Node("pile", children=slots)
+
+ def _parse_matrix(self, flags: int) -> _Node:
+ """解析 MATRIX 维度、分隔线位图和逐格 LINE。"""
+
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ self._u8()
+ self._u8()
+ self._u8()
+ rows = self._u8()
+ cols = self._u8()
+ if rows == 0 or cols == 0 or rows * cols > 4096:
+ raise _MtefError("MTEF matrix dimensions are invalid")
+ for entry_count in (rows + 1, cols + 1):
+ for _ in range((2 * entry_count + 7) // 8):
+ self._u8()
+ cells: list[_Node] = []
+ self._enter()
+ while len(cells) < rows * cols:
+ tag = self._u8()
+ self._charge()
+ record_type = tag & 0x0F
+ flags = tag & 0xF0
+ if record_type == 0:
+ continue
+ if record_type == 1:
+ cells.append(self._parse_line(flags))
+ elif record_type == 7:
+ self._skip_ruler()
+ elif record_type == 8:
+ self._skip_font()
+ elif record_type == 9:
+ self._skip_size()
+ elif 10 <= record_type <= 14:
+ continue
+ else:
+ cells.append(self._parse_record(record_type, flags))
+ self._leave()
+ if self.pos < len(self.data) and self.data[self.pos] & 0x0F == 0:
+ self.pos += 1
+ self._charge()
+ return _Node("matrix", (rows, cols), tuple(cells))
+
+ def _parse_record(self, record_type: int, flags: int) -> _Node:
+ """解析一条已读取 tag 的语义 record。"""
+
+ if record_type == 1:
+ return self._parse_line(flags)
+ if record_type == 2:
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ typeface = self._u8()
+ character = self._u16()
+ embellishments = self._parse_embellishments() if flags & _XF_EMBELL else ()
+ return _Node("character", (typeface, character, embellishments))
+ if record_type == 3:
+ return self._parse_template(flags)
+ if record_type == 4:
+ return self._parse_pile(flags)
+ if record_type == 5:
+ return self._parse_matrix(flags)
+ if record_type == 6:
+ if flags & _XF_LMOVE:
+ self._skip_nudge()
+ return _Node("embellishment", self._u8())
+ if record_type == 7:
+ self._skip_ruler()
+ return _Node("metadata")
+ if record_type == 8:
+ self._skip_font()
+ return _Node("metadata")
+ if record_type == 9:
+ self._skip_size()
+ return _Node("metadata")
+ if 10 <= record_type <= 14:
+ return _Node("metadata")
+ raise _MtefError(f"unsupported MTEF v3 record type: {record_type}")
+
+ def _parse_list(self) -> tuple[_Node, ...]:
+ """解析以 END 终止的普通 object list。"""
+
+ nodes: list[_Node] = []
+ while True:
+ tag = self._u8()
+ self._charge()
+ record_type = tag & 0x0F
+ if record_type == 0:
+ return tuple(nodes)
+ node = self._parse_record(record_type, tag & 0xF0)
+ if node.kind != "metadata":
+ nodes.append(node)
+
+ def _parse_slots(self) -> tuple[_Node, ...]:
+ """解析 template/pile 中每个 LINE 对应的 slot。"""
+
+ slots: list[_Node] = []
+ while True:
+ tag = self._u8()
+ self._charge()
+ record_type = tag & 0x0F
+ flags = tag & 0xF0
+ if record_type == 0:
+ return tuple(slots)
+ if record_type == 1:
+ slots.append(self._parse_line(flags))
+ elif record_type == 7:
+ self._skip_ruler()
+ elif record_type == 8:
+ self._skip_font()
+ elif record_type == 9:
+ self._skip_size()
+ elif 10 <= record_type <= 14:
+ continue
+ else:
+ slots.append(self._parse_record(record_type, flags))
+
+ def parse(self) -> _Node:
+ """解析根 object list 并拒绝没有可见内容的对象。"""
+
+ children = self._parse_list()
+ root = _Node("sequence", children=children)
+ if not _render_node(root).strip():
+ raise _MtefError("MTEF formula contains no visible content")
+ return root
+
+
+_CHAR_LATEX = {
+ "α": r"\alpha ",
+ "β": r"\beta ",
+ "γ": r"\gamma ",
+ "δ": r"\delta ",
+ "ε": r"\epsilon ",
+ "θ": r"\theta ",
+ "λ": r"\lambda ",
+ "μ": r"\mu ",
+ "π": r"\pi ",
+ "ρ": r"\rho ",
+ "σ": r"\sigma ",
+ "φ": r"\phi ",
+ "ω": r"\omega ",
+ "Γ": r"\Gamma ",
+ "Δ": r"\Delta ",
+ "Θ": r"\Theta ",
+ "Λ": r"\Lambda ",
+ "Ξ": r"\Xi ",
+ "Π": r"\Pi ",
+ "Σ": r"\Sigma ",
+ "Φ": r"\Phi ",
+ "Ψ": r"\Psi ",
+ "Ω": r"\Omega ",
+ "≤": r"\leq ",
+ "≥": r"\geq ",
+ "≠": r"\ne ",
+ "±": r"\pm ",
+ "∓": r"\mp ",
+ "−": "-",
+ "×": r"\times ",
+ "÷": r"\div ",
+ "∞": r"\infty ",
+ "∂": r"\partial ",
+ "∈": r"\in ",
+ "∉": r"\notin ",
+ "∪": r"\cup ",
+ "∩": r"\cap ",
+ "→": r"\rightarrow ",
+ "←": r"\leftarrow ",
+ "↔": r"\leftrightarrow ",
+ "·": r"\cdot ",
+ "∑": r"\sum ",
+ "∫": r"\int ",
+}
+
+
+def _render_character(character: int) -> str:
+ """把 MTEF 字符转为安全 LaTeX。"""
+
+ try:
+ value = chr(character)
+ except ValueError as exc:
+ raise _MtefError("MTEF character code is invalid") from exc
+ mapped = _CHAR_LATEX.get(value)
+ if mapped is not None:
+ return mapped
+ if value == "\\":
+ return r"\backslash "
+ if value in "#$%&_{}":
+ return f"\\{value}"
+ if value == "~":
+ return r"\sim "
+ if value == "^":
+ return r"\hat{}"
+ if ord(value) < 0x20:
+ raise _MtefError("MTEF formula contains a control character")
+ return value
+
+
+def _apply_embellishments(value: str, embellishments: tuple[int, ...]) -> str:
+ """按记录顺序把常见 embellishment 转为 LaTeX。"""
+
+ for embellishment in embellishments:
+ if embellishment == 2:
+ value = rf"\dot{{{value}}}"
+ elif embellishment == 3:
+ value = rf"\ddot{{{value}}}"
+ elif embellishment == 4:
+ value = rf"\overset{{\ldots}}{{{value}}}"
+ elif embellishment == 5:
+ value = f"{value}'"
+ elif embellishment == 6:
+ value = f"{value}''"
+ elif embellishment == 8:
+ value = rf"\widetilde{{{value}}}"
+ elif embellishment == 9:
+ value = rf"\widehat{{{value}}}"
+ elif embellishment == 10:
+ value = rf"\not{{{value}}}"
+ elif embellishment == 11:
+ value = rf"\overrightarrow{{{value}}}"
+ elif embellishment == 12:
+ value = rf"\overleftarrow{{{value}}}"
+ elif embellishment == 13:
+ value = rf"\overleftrightarrow{{{value}}}"
+ elif embellishment == 16:
+ value = rf"\bar{{{value}}}"
+ elif embellishment == 17:
+ value = rf"\overline{{{value}}}"
+ elif embellishment == 18:
+ value = f"{value}'''"
+ elif embellishment == 19:
+ value = rf"\overparen{{{value}}}"
+ elif embellishment == 20:
+ value = rf"\underparen{{{value}}}"
+ else:
+ raise _MtefError(f"unsupported MTEF embellishment: {embellishment}")
+ return value
+
+
+def _slot(slots: tuple[_Node, ...], index: int) -> str:
+ """渲染一个可选 template slot。"""
+
+ return _render_node(slots[index]).strip() if index < len(slots) else ""
+
+
+def _fence(selector: int, variation: int, body: str) -> str:
+ """渲染左右 fence 及单边 variation。"""
+
+ pairs = {
+ 0: (r"\langle", r"\rangle"),
+ 1: ("(", ")"),
+ 2: (r"\{", r"\}"),
+ 3: ("[", "]"),
+ 4: ("|", "|"),
+ 5: (r"\|", r"\|"),
+ 6: (r"\lfloor", r"\rfloor"),
+ 7: (r"\lceil", r"\rceil"),
+ }
+ left, right = pairs[selector]
+ if variation == 1:
+ right = "."
+ elif variation == 2:
+ left = "."
+ elif variation != 0:
+ raise _MtefError("unsupported MTEF fence variation")
+ return rf"\left{left}{body}\right{right}"
+
+
+def _big_operator(selector: int, slots: tuple[_Node, ...]) -> str:
+ """渲染积分、求和、乘积及集合大运算。"""
+
+ operators = {
+ 21: r"\int",
+ 22: r"\iint",
+ 23: r"\iiint",
+ 24: r"\int",
+ 25: r"\iint",
+ 26: r"\iiint",
+ 29: r"\sum",
+ 30: r"\sum",
+ 31: r"\prod",
+ 32: r"\prod",
+ 33: r"\coprod",
+ 34: r"\coprod",
+ 35: r"\bigcup",
+ 36: r"\bigcup",
+ 37: r"\bigcap",
+ 38: r"\bigcap",
+ }
+ operator = operators[selector]
+ main = _slot(slots, 0)
+ upper = _slot(slots, 1)
+ lower = _slot(slots, 2)
+ limits = (rf"_{{{lower}}}" if lower else "") + (rf"^{{{upper}}}" if upper else "")
+ return rf"{operator}{limits}{{{main}}}"
+
+
+def _render_template(selector: int, variation: int, options: int, slots: tuple[_Node, ...]) -> str:
+ """把一个受支持的 MTEF v3 template 转为 LaTeX。"""
+
+ del options
+ if 0 <= selector <= 7:
+ return _fence(selector, variation, _slot(slots, 0))
+ if selector == 8:
+ return rf"\left\{{\left\{{{_slot(slots, 0)}"
+ if selector == 9:
+ return rf"{_slot(slots, 0)}\right\}}\right\}}"
+ if selector == 10:
+ return rf"{_slot(slots, 0)}\right\}}\left\{{"
+ if selector == 11:
+ return rf"\left\{{{_slot(slots, 0)}\right)"
+ if selector == 12:
+ return rf"\left({_slot(slots, 0)}\right\}}"
+ if selector == 13:
+ radicand = _slot(slots, 0)
+ index = _slot(slots, 1)
+ return rf"\sqrt[{index}]{{{radicand}}}" if variation == 1 and index else rf"\sqrt{{{radicand}}}"
+ if selector == 14:
+ return rf"\frac{{{_slot(slots, 0)}}}{{{_slot(slots, 1)}}}"
+ if selector in {15, 44}:
+ subscript = _slot(slots, 0)
+ superscript = _slot(slots, 1)
+ return (rf"_{{{subscript}}}" if subscript else "") + (rf"^{{{superscript}}}" if superscript else "")
+ if selector == 16:
+ return rf"\underline{{{_slot(slots, 0)}}}"
+ if selector == 17:
+ return rf"\overline{{{_slot(slots, 0)}}}"
+ if selector in {18, 19, 20}:
+ arrow = {18: r"\leftarrow", 19: r"\rightarrow", 20: r"\leftrightarrow"}[selector]
+ return rf"\overset{{{_slot(slots, 0)}}}{{{arrow}}}" if variation == 0 else rf"\underset{{{_slot(slots, 0)}}}{{{arrow}}}"
+ if selector == 27:
+ return rf"\overbrace{{{_slot(slots, 0)}}}^{{{_slot(slots, 1)}}}"
+ if selector == 28:
+ return rf"\underbrace{{{_slot(slots, 0)}}}_{{{_slot(slots, 1)}}}"
+ if 21 <= selector <= 38:
+ return _big_operator(selector, slots)
+ if selector == 39:
+ main = _slot(slots, 0)
+ lower = _slot(slots, 1)
+ upper = _slot(slots, 2)
+ return rf"\lim_{{{lower}}}^{{{upper}}}{{{main}}}"
+ if selector == 40:
+ return rf"\overline{{{_slot(slots, 1)}}}\smash{{\big) {_slot(slots, 0)}}}"
+ if selector == 41:
+ return rf"{{{_slot(slots, 0)}}}/{{{_slot(slots, 1)}}}"
+ if selector in {42, 43}:
+ operator = _slot(slots, 3) or (r"\int" if selector == 42 else r"\sum")
+ main = _slot(slots, 0)
+ upper = _slot(slots, 1)
+ lower = _slot(slots, 2)
+ return operator + (rf"_{{{lower}}}" if lower else "") + (rf"^{{{upper}}}" if upper else "") + rf"{{{main}}}"
+ if selector == 45:
+ return rf"\left\langle {_slot(slots, 0)}\middle|{_slot(slots, 1)}\right\rangle"
+ if selector in {46, 47}:
+ command = "under" if selector == 46 else "over"
+ direction = {0: "leftarrow", 1: "rightarrow", 2: "leftrightarrow"}.get(variation)
+ if direction is None:
+ raise _MtefError("unsupported MTEF vector variation")
+ return rf"\{command}{direction}{{{_slot(slots, 0)}}}"
+ if selector == 48:
+ return rf"\overparen{{{_slot(slots, 0)}}}"
+ raise _MtefError(f"unsupported MTEF v3 template selector: {selector}")
+
+
+def _render_node(node: _Node) -> str:
+ """递归序列化 MTEF AST。"""
+
+ if node.kind == "sequence":
+ return "".join(_render_node(child) for child in node.children)
+ if node.kind == "character":
+ _typeface, character, embellishments = node.value # type: ignore[misc]
+ return _apply_embellishments(_render_character(int(character)), tuple(embellishments))
+ if node.kind == "template":
+ selector, variation, options = node.value # type: ignore[misc]
+ return _render_template(int(selector), int(variation), int(options), node.children)
+ if node.kind == "pile":
+ rows = [_render_node(child).strip() for child in node.children]
+ return r"\begin{gathered}" + r"\\".join(rows) + r"\end{gathered}"
+ if node.kind == "matrix":
+ rows, cols = node.value # type: ignore[misc]
+ rendered = [_render_node(child).strip() for child in node.children]
+ matrix_rows = ["&".join(rendered[row * int(cols) : (row + 1) * int(cols)]) for row in range(int(rows))]
+ return r"\begin{matrix}" + r"\\".join(matrix_rows) + r"\end{matrix}"
+ if node.kind in {"metadata", "embellishment"}:
+ return ""
+ raise _MtefError(f"unknown MTEF AST node: {node.kind}")
+
+
+def decode_mtef_v3(data: bytes) -> str | None:
+ """把 MTEF v3 字节流转换为 LaTeX;不可信对象失败时返回 None。"""
+
+ try:
+ latex = _render_node(_MtefReader(data).parse()).strip()
+ except (ArithmeticError, IndexError, struct.error, UnicodeError, _MtefError, ValueError):
+ return None
+ return latex or None
+
+
+def decode_equation_native(data: bytes) -> str | None:
+ """校验 28 字节 EQNOLEFILEHDR 并解码其中的 MTEF v3。"""
+
+ if len(data) < 28:
+ return None
+ header_size, version, _clipboard_format, object_size = struct.unpack_from("<HIHI", data, 0)
+ if header_size < 28 or header_size > len(data) or version != 0x0002_0000:
+ return None
+ object_end = header_size + object_size
+ if object_end < header_size or object_end > len(data):
+ return None
+ return decode_mtef_v3(data[header_size:object_end])
+
+
+def decode_equation_object(data: bytes) -> str | None:
+ """从独立 Equation Editor OLE 对象读取 Equation Native 并转为 LaTeX。"""
+
+ try:
+ with BoundedOleReader(data) as ole:
+ native = ole.read_stream("Equation Native")
+ except ValueError:
+ return None
+ return decode_equation_native(native)
+
+
+def read_object_pool_equations(ole: BoundedOleReader) -> dict[int, str]:
+ """只读提取 DOC ObjectPool 中可安全解码的 Equation Native streams。"""
+
+ equations: dict[int, str] = {}
+ for stream_name in ole.stream_names(prefix="ObjectPool/"):
+ match = _OBJECT_POOL_EQUATION_RE.match(stream_name)
+ if match is None:
+ continue
+ storage_id = int(match.group(1))
+ latex = decode_equation_native(ole.read_stream(stream_name))
+ if latex is None:
+ logger.warning(
+ "DOC_MTEF_FALLBACK: storage_id={} has an invalid or unsupported Equation Native stream",
+ storage_id,
+ )
+ continue
+ equations.setdefault(storage_id, latex)
+ return equations
diff --git a/mineru/model/flash/legacy_office/ole.py b/mineru/model/flash/legacy_office/ole.py
index 30cde102..e64a71d3 100644
--- a/mineru/model/flash/legacy_office/ole.py
+++ b/mineru/model/flash/legacy_office/ole.py
@@ -54,6 +54,17 @@ class BoundedOleReader:
return name.casefold() in self._stream_names
+ def stream_names(self, *, prefix: str | None = None) -> tuple[str, ...]:
+ """返回完整 stream 名称;可按大小写无关前缀筛选。"""
+
+ normalized_prefix = prefix.casefold() if prefix is not None else None
+ names = (
+ "/".join(parts)
+ for key, parts in self._stream_names.items()
+ if normalized_prefix is None or key.startswith(normalized_prefix)
+ )
+ return tuple(sorted(names, key=str.casefold))
+
def read_stream(self, name: str, *, required: bool = True) -> bytes:
"""有界读取指定 stream;可选 stream 不存在时返回空字节。"""
diff --git a/mineru/model/flash/ppt/models.py b/mineru/model/flash/ppt/models.py
index 9a3bc5d8..f3155ce0 100644
--- a/mineru/model/flash/ppt/models.py
+++ b/mineru/model/flash/ppt/models.py
@@ -54,6 +54,16 @@ class PptImageElement:
shape_offset: int
+@dataclass(frozen=True, slots=True)
+class PptEquationElement:
+ """已经从 Equation Editor 原生对象恢复的 LaTeX 公式。"""
+
+ latex: str
+ bbox: tuple[float, float, float, float]
+ order: int
+ shape_offset: int
+
+
@dataclass(frozen=True, slots=True)
class PptTableCell:
"""表格原点单元格及其跨行跨列范围。"""
@@ -77,7 +87,9 @@ class PptTableElement:
shape_offsets: frozenset[tuple[int, ...]]
-PptSlideElement: TypeAlias = PptTextElement | PptImageElement | PptTableElement
+PptSlideElement: TypeAlias = (
+ PptTextElement | PptImageElement | PptEquationElement | PptTableElement
+)
@dataclass(slots=True)
diff --git a/mineru/model/flash/ppt/parser.py b/mineru/model/flash/ppt/parser.py
index c4619bc9..48ff1652 100644
--- a/mineru/model/flash/ppt/parser.py
+++ b/mineru/model/flash/ppt/parser.py
@@ -9,6 +9,7 @@ import struct
from typing import Iterable
import unicodedata
from urllib.parse import urlparse
+import zlib
from loguru import logger
@@ -19,10 +20,12 @@ from mineru.model.flash.legacy_office import (
)
from mineru.model.flash.legacy_office.limits import (
MAX_ASSET_TOTAL_BYTES,
+ MAX_ENTRY_BYTES,
MAX_GRID_SLOTS,
MAX_PICTURE_RECORDS,
MAX_USER_EDIT_CHAIN,
)
+from mineru.model.flash.legacy_office.mtef import decode_equation_object
from mineru.model.flash.legacy_office.officeart import (
OfficeArtRecord,
OfficeImagePayload,
@@ -31,6 +34,7 @@ from mineru.model.flash.legacy_office.officeart import (
from mineru.model.flash.office.image import serialize_office_image
from .models import (
+ PptEquationElement,
PptImageElement,
PptParagraph,
PptPresentation,
@@ -80,6 +84,9 @@ RT_USER_EDIT_ATOM = 0x0FF5
RT_OUTLINE_TEXT_REF_ATOM = 0x0F9E
RT_PERSIST_DIRECTORY_ATOM = 0x1772
RT_CRYPT_SESSION10_CONTAINER = 0x2F14
+RT_EXTERNAL_OBJECT_REF_ATOM = 0x0BC1
+RT_EXTERNAL_OLE_OBJECT_ATOM = 0x0FC3
+RT_EXTERNAL_OLE_OBJECT_STG = 0x1011
# OfficeArt records and properties.
RT_OFFICEART_DGG_CONTAINER = 0xF000
@@ -748,6 +755,130 @@ def _shape_properties(shape: PptRecord, budget: RecordBudget) -> dict[int, int]:
return properties
+def _shape_external_object_id(shape: PptRecord, budget: RecordBudget) -> int | None:
+ """从 OfficeArtClientData 读取 ExObjRefAtom 的外部对象 id。"""
+
+ for child in _direct_children(shape, budget):
+ if child.record_type != RT_OFFICEART_CLIENT_DATA:
+ continue
+ candidates: Iterable[PptRecord]
+ if child.version == CONTAINER_VERSION:
+ candidates = iter_descendants(child, budget=budget)
+ else:
+ candidates = iter_records(child.payload, budget=budget)
+ for candidate in candidates:
+ if candidate.record_type != RT_EXTERNAL_OBJECT_REF_ATOM:
+ continue
+ reference = get_u32(candidate.payload, 0)
+ return int(reference) if reference else None
+ return None
+
+
+def _equation_object_references(
+ document: PptRecord,
+ budget: RecordBudget,
+) -> dict[int, int]:
+ """收集 Equation subtype 的 exObjId 到 persistIdRef 映射。"""
+
+ references: dict[int, int] = {}
+ for atom in iter_descendants(document, budget=budget):
+ if atom.record_type != RT_EXTERNAL_OLE_OBJECT_ATOM or len(atom.payload) < 24:
+ continue
+ object_type = get_u32(atom.payload, 4)
+ object_id = get_u32(atom.payload, 8)
+ object_subtype = get_u32(atom.payload, 12)
+ persist_id = get_u32(atom.payload, 16)
+ if (
+ object_type == 0
+ and object_subtype == 0x0000_0006
+ and object_id
+ and persist_id
+ ):
+ references.setdefault(int(object_id), int(persist_id))
+ return references
+
+
+def _decompress_ole_storage(record: PptRecord) -> bytes | None:
+ """按 ExOleObjStg instance 有界恢复独立 CFB 字节。"""
+
+ if record.record_type != RT_EXTERNAL_OLE_OBJECT_STG:
+ return None
+ if record.instance == 0:
+ if len(record.payload) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"OLE object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ return record.payload
+ if record.instance != 1 or len(record.payload) < 4:
+ return None
+ declared_size = int(get_u32(record.payload, 0) or 0)
+ if declared_size <= 0:
+ return None
+ if declared_size > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"OLE object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ try:
+ inflater = zlib.decompressobj(zlib.MAX_WBITS)
+ storage = inflater.decompress(record.payload[4:], MAX_ENTRY_BYTES + 1)
+ if len(storage) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"OLE object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ storage += inflater.flush(MAX_ENTRY_BYTES + 1 - len(storage))
+ except (ValueError, zlib.error):
+ return None
+ if len(storage) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"OLE object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ if not inflater.eof or len(storage) != declared_size:
+ return None
+ return storage
+
+
+def _equation_map(
+ layout: _PersistLayout,
+ data: bytes,
+ budget: RecordBudget,
+) -> dict[int, str]:
+ """解析 PPT persist OLE storages 中可用的 Equation Native。"""
+
+ equations: dict[int, str] = {}
+ asset_total = 0
+ for object_id, persist_id in _equation_object_references(layout.document, budget).items():
+ offset = layout.persist.get(persist_id)
+ record = record_at(data, offset, budget=budget) if offset is not None else None
+ if record is None:
+ logger.warning(
+ "PPT_MTEF_FALLBACK: exObjId={} persistIdRef={} is missing",
+ object_id,
+ persist_id,
+ )
+ continue
+ storage = _decompress_ole_storage(record)
+ if storage is None:
+ logger.warning(
+ "PPT_MTEF_FALLBACK: exObjId={} has an invalid OLE storage",
+ object_id,
+ )
+ continue
+ asset_total += len(storage)
+ if asset_total > MAX_ASSET_TOTAL_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
+ )
+ latex = decode_equation_object(storage)
+ if latex is None:
+ logger.warning(
+ "PPT_MTEF_FALLBACK: exObjId={} has an invalid or unsupported Equation Native stream",
+ object_id,
+ )
+ continue
+ equations[object_id] = latex
+ return equations
+
+
def _shape_complex_properties(shape: PptRecord, budget: RecordBudget) -> dict[int, bytes]:
"""合并 shape 的复杂 FOPT 属性。"""
@@ -1367,10 +1498,11 @@ def _slide_elements(
master_styles: dict[int, list[MasterLevel]],
hyperlinks: dict[int, str],
image_map: dict[int, _ImagePayload],
+ equation_map: dict[int, str],
slide_width: int,
slide_height: int,
budget: RecordBudget,
-) -> list[PptTextElement | PptImageElement | PptTableElement]:
+) -> list[PptTextElement | PptImageElement | PptEquationElement | PptTableElement]:
"""把一张 slide 的 shapes 转换为文本、表格和图片语义元素。"""
collection = _collect_shapes(slide, budget)
@@ -1397,10 +1529,24 @@ def _slide_elements(
tables.append(table)
consumed_keys.update(shape.key for shape in group.shapes)
- elements: list[PptTextElement | PptImageElement | PptTableElement] = list(tables)
+ elements: list[
+ PptTextElement | PptImageElement | PptEquationElement | PptTableElement
+ ] = list(tables)
for shape in collection.shapes:
if shape.key in consumed_keys or _is_background_shape(shape.record, budget):
continue
+ external_object_id = _shape_external_object_id(shape.record, budget)
+ equation = equation_map.get(external_object_id or 0)
+ if equation:
+ elements.append(
+ PptEquationElement(
+ latex=equation,
+ bbox=shape.bbox,
+ order=shape.order,
+ shape_offset=shape.order,
+ )
+ )
+ continue
content = _shape_text_content(
shape,
external_text,
@@ -1612,6 +1758,7 @@ def parse_ppt_document(
width, height = _presentation_size(layout.document, budget)
hyperlinks = _hyperlink_targets(layout.document, budget)
image_map = _picture_map(layout.document, pictures, budget)
+ native_equations = _equation_map(layout, powerpoint_document, budget)
master_map, fallback_master = _collect_masters(
layout,
powerpoint_document,
@@ -1673,6 +1820,7 @@ def parse_ppt_document(
master_styles,
hyperlinks,
image_map,
+ native_equations,
width,
height,
budget,
@@ -1697,6 +1845,7 @@ def parse_ppt_document(
master_styles,
hyperlinks,
image_map,
+ native_equations,
width,
height,
budget,
diff --git a/mineru/model/flash/ppt/ppt_converter.py b/mineru/model/flash/ppt/ppt_converter.py
index f368c0c3..770ad10d 100644
--- a/mineru/model/flash/ppt/ppt_converter.py
+++ b/mineru/model/flash/ppt/ppt_converter.py
@@ -14,6 +14,7 @@ from mineru.types import BlockType
from mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segments
from .models import (
+ PptEquationElement,
PptImageElement,
PptParagraph,
PptPresentation,
@@ -198,7 +199,7 @@ class PptConverter:
@classmethod
def _element_blocks(
cls,
- element: PptTextElement | PptImageElement | PptTableElement,
+ element: PptTextElement | PptImageElement | PptEquationElement | PptTableElement,
*,
slide_height: int,
is_first_text_element: bool,
@@ -207,6 +208,8 @@ class PptConverter:
if isinstance(element, PptImageElement):
return [{"type": BlockType.IMAGE, "image_base64": element.image_base64}]
+ if isinstance(element, PptEquationElement):
+ return [{"type": BlockType.EQUATION, "content": element.latex}]
if isinstance(element, PptTableElement):
return [{"type": BlockType.TABLE, "content": cls._table_html(element)}]
diff --git a/mineru/model/flash/xls/models.py b/mineru/model/flash/xls/models.py
index e6b80643..5f4d9a31 100644
--- a/mineru/model/flash/xls/models.py
+++ b/mineru/model/flash/xls/models.py
@@ -55,6 +55,15 @@ class XlsImage:
image_base64: str
+@dataclass(frozen=True, slots=True)
+class XlsEquation:
+ """绑定到工作表 cell anchor 的 Equation Editor 原生公式。"""
+
+ row: int
+ col: int
+ latex: str
+
+
@dataclass(frozen=True, slots=True)
class XlsChart:
"""由嵌入 chart 引用恢复出的源数据坐标。"""
@@ -75,6 +84,7 @@ class XlsSheet:
cells: dict[tuple[int, int], XlsCell] = field(default_factory=dict)
merges: list[tuple[int, int, int, int]] = field(default_factory=list)
images: list[XlsImage] = field(default_factory=list)
+ equations: list[XlsEquation] = field(default_factory=list)
charts: list[XlsChart] = field(default_factory=list)
recovered: bool = False
diff --git a/mineru/model/flash/xls/parser.py b/mineru/model/flash/xls/parser.py
index fc8e3f6f..b1785166 100644
--- a/mineru/model/flash/xls/parser.py
+++ b/mineru/model/flash/xls/parser.py
@@ -27,6 +27,7 @@ from .chart import chart_source_axes
from .models import (
XlsCell,
XlsChart,
+ XlsEquation,
XlsFontStyle,
XlsImage,
XlsRichRun,
@@ -159,6 +160,7 @@ class _SheetObject:
object_type: int
object_id: int
checked: bool | None = None
+ embedding_storage: str | None = None
text: XlsRichText | None = None
shape: OfficeArtShape | None = None
@@ -457,13 +459,42 @@ def _read_label_string(
return DecodedString(decoded.text, tuple(starts))
+def _pict_embedding_storage(payload: bytes, picture_flags: int | None) -> str | None:
+ """从 FtPictFmla 读取嵌入对象的 MBD storage 名称。"""
+
+ if picture_flags is None:
+ return None
+ # DDE、ActiveX、controls stream 与 camera picture 都不是内嵌 Equation.3 对象。
+ if picture_flags & (0x0002 | 0x0010 | 0x0020 | 0x0080):
+ return None
+ if len(payload) < 10:
+ return None
+ cb_fmla = int(get_u16(payload, 0) or 0)
+ formula_end = 2 + cb_fmla
+ if cb_fmla <= 0 or cb_fmla % 2 or formula_end + 4 > len(payload):
+ return None
+ formula = payload[2:formula_end]
+ if len(formula) < 7 or int(get_u16(formula, 0) or 0) & 0x7FFF != 5:
+ return None
+ # ObjectParsedFormula 的四字节 unused 在部分生产器中省略,因此兼容两个合法落点。
+ if not any(
+ offset + 5 <= len(formula) and formula[offset] == 0x02
+ for offset in (6, 2)
+ ):
+ return None
+ location = get_u32(payload, formula_end)
+ return f"MBD{int(location):08X}" if location is not None else None
+
+
def _read_obj(payload: bytes) -> _SheetObject | None:
- """解析 OBJ subrecords 中的对象类型、id 与 checkbox 状态。"""
+ """解析 OBJ subrecords 中的对象类型、id、状态与嵌入 storage。"""
cursor = 0
object_type: int | None = None
object_id = 0
checked: bool | None = None
+ picture_flags: int | None = None
+ picture_formula: bytes | None = None
while cursor + 4 <= len(payload):
sub_type, length = struct.unpack_from("<HH", payload, cursor)
data_start = cursor + 4
@@ -476,12 +507,25 @@ def _read_obj(payload: bytes) -> _SheetObject | None:
elif sub_type == 0x0012 and len(body) >= 2:
state = int(get_u16(body, 0) or 0)
checked = state == 1 if state in {0, 1} else None
+ elif sub_type == 0x0008 and len(body) >= 2:
+ picture_flags = int(get_u16(body, 0) or 0)
+ elif sub_type == 0x0009:
+ picture_formula = body
if sub_type == 0:
break
cursor = data_end
if object_type is None:
return None
- return _SheetObject(int(object_type), int(object_id), checked=checked)
+ return _SheetObject(
+ int(object_type),
+ int(object_id),
+ checked=checked,
+ embedding_storage=(
+ _pict_embedding_storage(picture_formula, picture_flags)
+ if picture_formula is not None
+ else None
+ ),
+ )
def _sanitize_hyperlink_target(target: str) -> str | None:
@@ -631,6 +675,7 @@ def _bind_objects(
*,
globals_: _Globals,
sheet_index: int,
+ native_equations: dict[str, str],
budget: RecordBudget,
) -> None:
"""按 drawing/OBJ 顺序绑定文本框、复选框、图片与嵌入图表。"""
@@ -654,6 +699,14 @@ def _bind_objects(
if anchor is None:
continue
row, col = anchor
+ equation = (
+ native_equations.get(object_.embedding_storage.casefold())
+ if object_.object_type == OBJ_PICTURE and object_.embedding_storage
+ else None
+ )
+ if equation:
+ sheet.equations.append(XlsEquation(row=row, col=col, latex=equation))
+ continue
if object_.object_type == OBJ_TEXTBOX and object_.text is not None:
_append_cell_text(sheet, row, col, object_.text)
elif object_.object_type == OBJ_CHECKBOX and object_.checked is not None:
@@ -724,6 +777,7 @@ def _read_sheet(
*,
sheet_index: int,
recovered: bool,
+ native_equations: dict[str, str],
budget: RecordBudget,
) -> XlsSheet | None:
"""解析一个 worksheet substream 并绑定其 drawing/chart 对象。"""
@@ -964,6 +1018,7 @@ def _read_sheet(
chart_streams,
globals_=globals_,
sheet_index=sheet_index,
+ native_equations=native_equations,
budget=budget,
)
return sheet
@@ -990,12 +1045,20 @@ def _is_worksheet_offset(data: bytes, offset: int) -> bool:
)
-def parse_xls_workbook(data: bytes) -> XlsWorkbook:
- """解析一个 Workbook/Book stream,并按目录顺序恢复 worksheets。"""
+def parse_xls_workbook(
+ data: bytes,
+ *,
+ native_equations: dict[str, str] | None = None,
+) -> XlsWorkbook:
+ """解析 Workbook/Book stream,并按目录顺序恢复 worksheets 与原生公式。"""
if not data:
raise LegacyOfficeMalformedError("empty Workbook stream")
budget = RecordBudget()
+ normalized_equations = {
+ storage.casefold(): latex
+ for storage, latex in (native_equations or {}).items()
+ }
globals_ = _read_globals(data, budget)
candidates = _worksheet_bof_offsets(data)
used_offsets: set[int] = set()
@@ -1055,6 +1118,7 @@ def parse_xls_workbook(data: bytes) -> XlsWorkbook:
resolved_offset,
sheet_index=sheet_index,
recovered=recovered,
+ native_equations=normalized_equations,
budget=budget,
)
if parsed is None:
diff --git a/mineru/model/flash/xls/xls_converter.py b/mineru/model/flash/xls/xls_converter.py
index d7617355..0e25171e 100644
--- a/mineru/model/flash/xls/xls_converter.py
+++ b/mineru/model/flash/xls/xls_converter.py
@@ -4,6 +4,8 @@
from __future__ import annotations
+import collections
+import re
from typing import Any, BinaryIO
from loguru import logger
@@ -15,6 +17,7 @@ from openpyxl.worksheet.worksheet import Worksheet # type: ignore[reportMissing
from mineru.model.flash.legacy_office import BoundedOleReader, LegacyOfficeEncryptedError
from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
from mineru.model.flash.legacy_office.limits import MAX_GRID_SLOTS
+from mineru.model.flash.legacy_office.mtef import decode_equation_native
from mineru.model.flash.xlsx.xlsx_converter import ExcelTable, XlsxConverter
from mineru.model.office_stream import read_stream_bytes_from_start
from mineru.types import BlockType
@@ -22,6 +25,31 @@ from mineru.types import BlockType
from .models import XlsChart, XlsRichText, XlsSheet, XlsWorkbook
from .parser import parse_xls_workbook
+_XLS_EQUATION_STREAM_RE = re.compile(
+ r"^(MBD[0-9A-F]{8})/Equation Native$",
+ re.IGNORECASE,
+)
+
+
+def _read_embedded_equations(ole: BoundedOleReader) -> dict[str, str]:
+ """读取 XLS embedding storages 中可安全解码的 Equation Native。"""
+
+ equations: dict[str, str] = {}
+ for stream_name in ole.stream_names(prefix="MBD"):
+ match = _XLS_EQUATION_STREAM_RE.match(stream_name)
+ if match is None:
+ continue
+ storage = match.group(1)
+ latex = decode_equation_native(ole.read_stream(stream_name))
+ if latex is None:
+ logger.warning(
+ "XLS_MTEF_FALLBACK: storage={!r} has an invalid or unsupported Equation Native stream",
+ storage,
+ )
+ continue
+ equations.setdefault(storage, latex)
+ return equations
+
def _inline_font(rich_text: XlsRichText, start: int) -> InlineFont | None:
"""返回覆盖指定字符位置的 openpyxl 行内字体。"""
@@ -81,6 +109,7 @@ class _XlsPageBuilder(XlsxConverter):
self.workbook_model = workbook_model
self._sheet_by_title: dict[str, XlsSheet] = {}
self._active_xls_sheet: XlsSheet | None = None
+ self._used_cells: set[tuple[int, int]] = set()
self._grid_slots = 0
def _build_openpyxl_workbook(self) -> Workbook:
@@ -137,6 +166,27 @@ class _XlsPageBuilder(XlsxConverter):
for image in sheet_model.images
]
+ def _map_math_formulas_to_cells(self, sheet: Worksheet) -> dict:
+ """把 legacy Equation Editor 公式映射到表格 cell anchor。"""
+
+ math_map: dict[tuple[int, int], list[str]] = collections.defaultdict(list)
+ sheet_model = self._sheet_by_title.get(sheet.title)
+ if sheet_model is None:
+ return math_map
+ for equation in sheet_model.equations:
+ math_map[(equation.row, equation.col)].append(equation.latex)
+ return math_map
+
+ def _find_tables_in_sheet(
+ self,
+ sheet: Worksheet,
+ ) -> tuple[set[tuple[int, int]], list[tuple[tuple[int, int], int, dict]]]:
+ """记录表格已吸收坐标,供独立公式去重。"""
+
+ used_cells, artifacts = super()._find_tables_in_sheet(sheet)
+ self._used_cells = used_cells
+ return used_cells, artifacts
+
def _find_data_tables(self, sheet: Worksheet) -> list[ExcelTable]:
"""复用 XLSX 区域发现并累计限制实际物化网格。"""
@@ -189,6 +239,17 @@ class _XlsPageBuilder(XlsxConverter):
if block is None:
continue
artifacts.append(((chart.row, chart.col), 10_000 + order, block))
+ for order, equation in enumerate(sheet_model.equations):
+ anchor = (equation.row, equation.col)
+ if anchor in self._used_cells:
+ continue
+ artifacts.append(
+ (
+ anchor,
+ 20_000 + order,
+ {"type": BlockType.EQUATION, "content": equation.latex},
+ )
+ )
return artifacts
@@ -211,7 +272,11 @@ class XlsConverter:
workbook_stream = ole.read_stream("Workbook")
else:
workbook_stream = ole.read_stream("Book")
- workbook = parse_xls_workbook(workbook_stream)
+ native_equations = _read_embedded_equations(ole)
+ workbook = parse_xls_workbook(
+ workbook_stream,
+ native_equations=native_equations,
+ )
builder = _XlsPageBuilder(workbook)
self.pages = builder.build_pages()
logger.debug("XLS parsing produced {} visible worksheet pages", len(self.pages))
diff --git a/tests/unittest/_legacy_ppt_test_utils.py b/tests/unittest/_legacy_ppt_test_utils.py
index 0f9c431c..32a696ba 100644
--- a/tests/unittest/_legacy_ppt_test_utils.py
+++ b/tests/unittest/_legacy_ppt_test_utils.py
@@ -3,6 +3,9 @@
from __future__ import annotations
import struct
+import zlib
+
+from _mtef_test_utils import _TINY_PNG, build_equation_object
def _ppt_record(version_instance: int, record_type: int, payload: bytes) -> bytes:
@@ -17,6 +20,182 @@ def _ppt_container(instance: int, record_type: int, payload: bytes) -> bytes:
return _ppt_record((instance << 4) | 0xF, record_type, payload)
+def _officeart_record(
+ record_type: int,
+ payload: bytes,
+ *,
+ version: int = 0,
+ instance: int = 0,
+) -> bytes:
+ """构造一条可嵌入 PPT record tree 的 OfficeArt record。"""
+
+ return _ppt_record((instance << 4) | version, record_type, payload)
+
+
+def _equation_preview_bse() -> bytes:
+ """构造一个内嵌 PNG 的 OfficeArt BSE。"""
+
+ blip = _officeart_record(0xF01E, b"\x00" * 17 + _TINY_PNG)
+ return _officeart_record(0xF007, b"\x00" * 36 + blip, version=2)
+
+
+def _equation_shape(object_id: int, *, preview: bool) -> bytes:
+ """构造带 ExObjRefAtom、坐标及可选 pib 的 PPT shape。"""
+
+ fsp = _officeart_record(
+ 0xF00A,
+ struct.pack("<II", object_id + 1024, 0),
+ version=2,
+ instance=1,
+ )
+ fopt = (
+ _officeart_record(
+ 0xF00B,
+ struct.pack("<HI", 0x0104, 1),
+ version=3,
+ instance=1,
+ )
+ if preview
+ else b""
+ )
+ top = 320
+ left = 480
+ anchor = _officeart_record(
+ 0xF010,
+ struct.pack("<4h", top, left, 3000, 1900),
+ )
+ reference = _ppt_record(0, 0x0BC1, struct.pack("<I", object_id))
+ client_data = _officeart_record(0xF011, reference)
+ return _officeart_record(
+ 0xF004,
+ fsp + fopt + anchor + client_data,
+ version=0xF,
+ )
+
+
+def build_equation_ppt(
+ formulas: list[bytes],
+ *,
+ preview: bool = True,
+ compressed: bool = True,
+ declared_size: int | None = None,
+) -> bytes:
+ """构造每页一个 Equation Editor OLE 对象的 PPT persist fixture。"""
+
+ if not formulas:
+ raise ValueError("equation PPT fixture requires at least one formula")
+
+ def persist_atom(persist_ref: int, slide_id: int) -> bytes:
+ """构造 SlidePersistAtom。"""
+
+ return _ppt_record(
+ 0,
+ 0x03F3,
+ struct.pack("<IIIII", persist_ref, 0, 0, slide_id, 0),
+ )
+
+ slide_persist_ids = list(range(2, 2 + len(formulas)))
+ storage_persist_ids = list(
+ range(2 + len(formulas), 2 + len(formulas) * 2)
+ )
+ slide_list = _ppt_container(
+ 0,
+ 0x0FF0,
+ b"".join(
+ persist_atom(persist_id, 256 + index)
+ for index, persist_id in enumerate(slide_persist_ids)
+ ),
+ )
+ external_objects = []
+ for index, storage_id in enumerate(storage_persist_ids, start=1):
+ embed_atom = _ppt_record(0, 0x0FCD, b"\x00" * 8)
+ object_atom = _ppt_record(
+ 1,
+ 0x0FC3,
+ struct.pack("<6I", 1, 0, index, 6, storage_id, 0),
+ )
+ prog_id = _ppt_record(2 << 4, 0x0FBA, "Equation.3".encode("utf-16le"))
+ external_objects.append(
+ _ppt_container(0, 0x0FCC, embed_atom + object_atom + prog_id)
+ )
+ object_list = _ppt_container(0, 0x0409, b"".join(external_objects))
+ drawing_group = (
+ _officeart_record(
+ 0xF000,
+ _officeart_record(0xF001, _equation_preview_bse(), version=0xF),
+ version=0xF,
+ )
+ if preview
+ else b""
+ )
+ document = _ppt_container(0, 0x03E8, slide_list + object_list + drawing_group)
+
+ records: list[tuple[int, bytes]] = [(1, document)]
+ for index, persist_id in enumerate(slide_persist_ids, start=1):
+ slide_atom = _ppt_record(
+ 2,
+ 0x03EF,
+ struct.pack("<I", 0) + b"\x00" * 8 + struct.pack("<IIHH", 0, 0, 0, 0),
+ )
+ records.append(
+ (
+ persist_id,
+ _ppt_container(
+ 0,
+ 0x03EE,
+ slide_atom + _equation_shape(index, preview=preview),
+ ),
+ )
+ )
+ for persist_id, mtef in zip(storage_persist_ids, formulas, strict=True):
+ storage = build_equation_object(mtef)
+ if compressed:
+ size = len(storage) if declared_size is None else declared_size
+ payload = struct.pack("<I", size) + zlib.compress(storage)
+ record = _ppt_record(1 << 4, 0x1011, payload)
+ else:
+ record = _ppt_record(0, 0x1011, storage)
+ records.append((persist_id, record))
+
+ records.sort(key=lambda item: item[0])
+ stream = b""
+ offsets: dict[int, int] = {}
+ for persist_id, record in records:
+ offsets[persist_id] = len(stream)
+ stream += record
+ count = max(offsets)
+ directory = struct.pack("<I", 1 | (count << 20)) + struct.pack(
+ f"<{count}I",
+ *(offsets[index] for index in range(1, count + 1)),
+ )
+ directory_offset = len(stream)
+ stream += _ppt_record(0, 0x1772, directory)
+ edit_offset = len(stream)
+ stream += _ppt_record(
+ 0,
+ 0x0FF5,
+ struct.pack(
+ "<IIIIIIHH",
+ 0,
+ 0,
+ 0,
+ directory_offset,
+ 1,
+ count + 1,
+ 0,
+ 0,
+ ),
+ )
+ current_user = _ppt_record(
+ 0,
+ 0x0FF6,
+ struct.pack("<III", 20, 0xE391C05F, edit_offset),
+ )
+ return _build_cfb(
+ [("Current User", current_user), ("PowerPoint Document", stream)]
+ )
+
+
def _build_cfb(streams: list[tuple[str, bytes]]) -> bytes:
"""生成所有 stream 均使用常规 FAT sector 的最小 CFB v3。"""
diff --git a/tests/unittest/_legacy_xls_test_utils.py b/tests/unittest/_legacy_xls_test_utils.py
index 8a7565b3..96dbd0ee 100644
--- a/tests/unittest/_legacy_xls_test_utils.py
+++ b/tests/unittest/_legacy_xls_test_utils.py
@@ -6,6 +6,7 @@ from dataclasses import dataclass
import struct
import uuid
+from _mtef_test_utils import _TINY_PNG, _build_nested_cfb, equation_native
from _legacy_ppt_test_utils import _build_cfb
@@ -24,6 +25,152 @@ def biff_record(record_type: int, payload: bytes = b"") -> bytes:
return struct.pack("<HH", record_type, len(payload)) + payload
+def _officeart_record(
+ record_type: int,
+ payload: bytes,
+ *,
+ version: int = 0,
+ instance: int = 0,
+) -> bytes:
+ """构造一条 OfficeArt record。"""
+
+ return struct.pack(
+ "<HHI",
+ (instance << 4) | version,
+ record_type,
+ len(payload),
+ ) + payload
+
+
+def _equation_shape(row: int, col: int, object_id: int, *, preview: bool) -> bytes:
+ """构造带 cell anchor、可选 pib 与 ExObj 对应顺序的 Excel shape。"""
+
+ fsp = _officeart_record(
+ 0xF00A,
+ struct.pack("<II", object_id + 1024, 0),
+ version=2,
+ instance=1,
+ )
+ fopt = (
+ _officeart_record(
+ 0xF00B,
+ struct.pack("<HI", 0x0104, 1),
+ version=3,
+ instance=1,
+ )
+ if preview
+ else b""
+ )
+ anchor = _officeart_record(
+ 0xF010,
+ struct.pack(
+ "<9H",
+ 0,
+ col,
+ 0,
+ row,
+ 0,
+ min(col + 2, 255),
+ 0,
+ min(row + 3, 65_535),
+ 0,
+ ),
+ )
+ return _officeart_record(
+ 0xF004,
+ fsp + fopt + anchor,
+ version=0xF,
+ )
+
+
+def _equation_obj(location: int, object_id: int) -> bytes:
+ """构造以 FtPictFmla 指向 MBD storage 的 picture OBJ。"""
+
+ cmo = struct.pack("<HHH", 0x0008, object_id, 0) + b"\x00" * 12
+ pict_flags = struct.pack("<H", 0)
+ parsed_formula = struct.pack("<H", 5) + b"\x00" * 4 + b"\x02" + b"\x00" * 4
+ embed_info = b"\x03\x00\x00"
+ obj_formula = parsed_formula + embed_info
+ pict_formula = (
+ struct.pack("<H", len(obj_formula))
+ + obj_formula
+ + struct.pack("<I", location)
+ )
+ payload = b"".join(
+ (
+ struct.pack("<HH", 0x0015, len(cmo)) + cmo,
+ struct.pack("<HH", 0x0008, len(pict_flags)) + pict_flags,
+ struct.pack("<HH", 0x0009, len(pict_formula)) + pict_formula,
+ struct.pack("<HH", 0, 0),
+ )
+ )
+ return biff_record(0x005D, payload)
+
+
+def _preview_bstore() -> bytes:
+ """构造一个可由 XLS/PPT 共用解码器读取的内嵌 PNG BStore。"""
+
+ blip = _officeart_record(0xF01E, b"\x00" * 17 + _TINY_PNG)
+ bse = _officeart_record(0xF007, b"\x00" * 36 + blip, version=2)
+ return _officeart_record(0xF001, bse, version=0xF, instance=1)
+
+
+def _build_xls_with_embeddings(workbook: bytes, equations: dict[int, bytes]) -> bytes:
+ """把 Workbook 与多个 MBD Equation Native storage 写入同一 CFB。"""
+
+ none = 0xFFFF_FFFF
+ entries: list[dict[str, object]] = [
+ {"name": "Root Entry", "kind": 5},
+ ]
+ storage_indexes: list[int] = []
+ for location, mtef in equations.items():
+ storage_index = len(entries)
+ storage_indexes.append(storage_index)
+ entries.append(
+ {
+ "name": f"MBD{location:08X}",
+ "kind": 1,
+ "child": storage_index + 1,
+ }
+ )
+ entries.extend(
+ [
+ {
+ "name": "Equation Native",
+ "kind": 2,
+ "right": storage_index + 2,
+ "data": equation_native(mtef),
+ },
+ {
+ "name": "\x01CompObj",
+ "kind": 2,
+ "right": storage_index + 3,
+ "data": b"Equation.3\x00",
+ },
+ {
+ "name": "\x03ObjInfo",
+ "kind": 2,
+ "right": none,
+ "data": b"\x00" * 6,
+ },
+ ]
+ )
+ workbook_index = len(entries)
+ entries.append(
+ {
+ "name": "Workbook",
+ "kind": 2,
+ "right": none,
+ "data": workbook,
+ }
+ )
+ root_children = storage_indexes + [workbook_index]
+ for current, following in zip(root_children, root_children[1:]):
+ entries[current]["right"] = following
+ entries[0]["child"] = root_children[0]
+ return _build_nested_cfb(entries)
+
+
def biff_bof(substream_type: int, *, version: int = 0x0600) -> bytes:
"""构造 BIFF8 BOF 记录。"""
@@ -157,6 +304,7 @@ def build_xls(
globals_records: bytes = b"",
corrupt_first_offset: bool = False,
encrypted: bool = False,
+ equations: dict[int, bytes] | None = None,
) -> bytes:
"""构造含 Workbook Globals 与多个 worksheet substreams 的 OLE 文件。"""
@@ -191,9 +339,38 @@ def build_xls(
for offset, sheet in zip(offsets, sheets, strict=True)
)
workbook = prefix + directory + biff_record(0x000A) + b"".join(sheet_streams)
+ if equations:
+ return _build_xls_with_embeddings(workbook, equations)
return _build_cfb([("Workbook", workbook)])
+def build_equation_xls(
+ formulas: list[tuple[int, bytes]],
+ *,
+ cell_records: bytes = b"",
+ preview: bool = True,
+) -> bytes:
+ """构造带 Equation.3 picture OBJ、MBD storages 和可选预览的 XLS。"""
+
+ drawing_records = b""
+ for index, (location, _mtef) in enumerate(formulas, start=1):
+ drawing_records += biff_record(
+ 0x00EC,
+ _equation_shape(index - 1, 0, index, preview=preview),
+ )
+ drawing_records += _equation_obj(location, index)
+ globals_records = (
+ biff_record(0x00EB, _preview_bstore())
+ if preview
+ else b""
+ )
+ return build_xls(
+ [SheetFixture("Equations", cell_records + drawing_records)],
+ globals_records=globals_records,
+ equations=dict(formulas),
+ )
+
+
def build_biff5_xls(text: str) -> bytes:
"""构造使用 Book stream 和 cp1252 LABEL 的 BIFF5 文件。"""
diff --git a/tests/unittest/_mtef_test_utils.py b/tests/unittest/_mtef_test_utils.py
new file mode 100644
index 00000000..90ed28b5
--- /dev/null
+++ b/tests/unittest/_mtef_test_utils.py
@@ -0,0 +1,462 @@
+"""构造结果已知的 Equation Editor 3.x MTEF/OLE/DOC 测试对象。"""
+
+from __future__ import annotations
+
+import base64
+import struct
+from typing import cast
+import uuid
+
+_TINY_PNG = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
+)
+
+
+def mtef_char(value: str, *, embellishments: tuple[int, ...] = ()) -> bytes:
+ """构造一个 Unicode CHAR 及可选 embellishment 列表。"""
+
+ if len(value) != 1 or ord(value) > 0xFFFF:
+ raise ValueError("MTEF v3 CHAR fixture requires one BMP character")
+ tag = 0x22 if embellishments else 0x02
+ payload = bytes([tag, 131]) + struct.pack("<H", ord(value))
+ if embellishments:
+ payload += b"".join(bytes([0x06, embellishment]) for embellishment in embellishments)
+ payload += b"\x00"
+ return payload
+
+
+def mtef_text(value: str) -> bytes:
+ """把短文本构造成连续 CHAR records。"""
+
+ return b"".join(mtef_char(character) for character in value)
+
+
+def mtef_line(*records: bytes) -> bytes:
+ """构造一个以 END 结束的非空 LINE slot。"""
+
+ return b"\x01" + b"".join(records) + b"\x00"
+
+
+def mtef_null_line() -> bytes:
+ """构造不带 END 的 NULL LINE slot。"""
+
+ return b"\x11"
+
+
+def mtef_template(
+ selector: int,
+ *slots: bytes,
+ variation: int = 0,
+ options: int = 0,
+) -> bytes:
+ """构造一个 TMPL 及其 LINE slots。"""
+
+ return bytes([0x03, selector, variation, options]) + b"".join(slots) + b"\x00"
+
+
+def mtef_matrix(rows: list[list[bytes]]) -> bytes:
+ """构造无分隔线的 MATRIX record。"""
+
+ if not rows or not rows[0] or any(len(row) != len(rows[0]) for row in rows):
+ raise ValueError("matrix fixture must be rectangular")
+ row_count = len(rows)
+ col_count = len(rows[0])
+ row_parts = b"\x00" * ((2 * (row_count + 1) + 7) // 8)
+ col_parts = b"\x00" * ((2 * (col_count + 1) + 7) // 8)
+ cells = b"".join(mtef_line(cell) for row in rows for cell in row)
+ return bytes([0x05, 0, 0, 0, row_count, col_count]) + row_parts + col_parts + cells + b"\x00"
+
+
+def mtef_equation(*records: bytes) -> bytes:
+ """构造完整 MTEF v3 头、FULL size 和根 LINE。"""
+
+ header = bytes([3, 1, 1, 3, 0])
+ return header + b"\x0A" + mtef_line(*records) + b"\x00"
+
+
+def equation_native(mtef: bytes) -> bytes:
+ """为 MTEF 添加 28 字节 EQNOLEFILEHDR。"""
+
+ return struct.pack(
+ "<HIHI4I",
+ 28,
+ 0x0002_0000,
+ 0xC1C2,
+ len(mtef),
+ 0,
+ 0,
+ 0,
+ 0,
+ ) + mtef
+
+
+def formula_corpus() -> list[tuple[str, bytes, str]]:
+ """返回覆盖常见 Equation Editor 结构的名称、MTEF 和期望 LaTeX。"""
+
+ fraction = mtef_template(
+ 14,
+ mtef_line(mtef_text("a+b")),
+ mtef_line(mtef_char("c")),
+ )
+ superscript = mtef_template(
+ 15,
+ mtef_null_line(),
+ mtef_line(mtef_char("2")),
+ variation=0,
+ )
+ square_root = mtef_template(
+ 13,
+ mtef_line(mtef_char("x"), superscript, mtef_text("+1")),
+ variation=0,
+ )
+ nth_root = mtef_template(
+ 13,
+ mtef_line(mtef_char("x")),
+ mtef_line(mtef_char("3")),
+ variation=1,
+ )
+ sub_sup = mtef_char("x") + mtef_template(
+ 15,
+ mtef_line(mtef_char("i")),
+ mtef_line(mtef_char("2")),
+ variation=2,
+ )
+ fenced_fraction = mtef_template(1, mtef_line(fraction))
+ summation = mtef_template(
+ 29,
+ mtef_line(mtef_char("i")),
+ mtef_line(mtef_char("n")),
+ mtef_line(mtef_text("i=1")),
+ mtef_line(mtef_char("∑")),
+ variation=1,
+ )
+ integral = mtef_template(
+ 21,
+ mtef_line(mtef_char("x")),
+ mtef_line(mtef_char("1")),
+ mtef_line(mtef_char("0")),
+ mtef_line(mtef_char("∫")),
+ variation=2,
+ )
+ matrix = mtef_matrix(
+ [
+ [mtef_char("a"), mtef_char("b")],
+ [mtef_char("c"), mtef_char("d")],
+ ]
+ )
+ return [
+ ("linear", mtef_equation(mtef_text("x+y")), "x+y"),
+ ("fraction", mtef_equation(fraction), r"\frac{a+b}{c}"),
+ ("square_root", mtef_equation(square_root), r"\sqrt{x^{2}+1}"),
+ ("nth_root", mtef_equation(nth_root), r"\sqrt[3]{x}"),
+ ("sub_sup", mtef_equation(sub_sup), r"x_{i}^{2}"),
+ ("fence", mtef_equation(fenced_fraction), r"\left(\frac{a+b}{c}\right)"),
+ ("summation", mtef_equation(summation), r"\sum_{i=1}^{n}{i}"),
+ ("integral", mtef_equation(integral), r"\int_{0}^{1}{x}"),
+ ("matrix", mtef_equation(matrix), r"\begin{matrix}a&b\\c&d\end{matrix}"),
+ ("embellishment", mtef_equation(mtef_char("x", embellishments=(9,))), r"\widehat{x}"),
+ ("greek_relation", mtef_equation(mtef_char("α"), mtef_char("≤"), mtef_char("β")), r"\alpha \leq \beta"),
+ ]
+
+
+def _directory_entry(
+ name: str,
+ kind: int,
+ *,
+ left: int,
+ right: int,
+ child: int,
+ start: int,
+ size: int,
+ clsid: bytes = b"\x00" * 16,
+) -> bytes:
+ """构造一个支持 storage 层级的 CFB directory entry。"""
+
+ raw_name = name.encode("utf-16le") + b"\x00\x00"
+ if len(raw_name) > 64:
+ raise ValueError("CFB fixture directory name is too long")
+ return (
+ raw_name
+ + b"\x00" * (64 - len(raw_name))
+ + struct.pack("<HBBIII", len(raw_name), kind, 1, left, right, child)
+ + clsid
+ + b"\x00" * 4
+ + b"\x00" * 16
+ + struct.pack("<IQ", start, size)
+ )
+
+
+def _build_nested_cfb(entries: list[dict[str, object]]) -> bytes:
+ """生成所有 stream 使用常规 FAT sector 的层级 CFB v3。"""
+
+ sector_size = 512
+ end_of_chain = 0xFFFF_FFFE
+ fat_sector = 0xFFFF_FFFD
+ free_sector = 0xFFFF_FFFF
+ fat: list[int] = []
+ sectors: list[bytes] = []
+
+ def add_chain(data: bytes) -> int:
+ """追加 FAT chain 并返回首 sector。"""
+
+ if not data:
+ return end_of_chain
+ padded = data + b"\x00" * (-len(data) % sector_size)
+ first = len(sectors)
+ count = len(padded) // sector_size
+ for index in range(count):
+ sectors.append(padded[index * sector_size : (index + 1) * sector_size])
+ fat.append(first + index + 1 if index + 1 < count else end_of_chain)
+ return first
+
+ stream_locations: dict[int, tuple[int, int]] = {}
+ for index, entry in enumerate(entries):
+ if entry["kind"] != 2:
+ continue
+ payload = bytes(cast(bytes, entry.get("data", b"")))
+ padded = payload + b"\x00" * (4096 - len(payload)) if 0 < len(payload) < 4096 else payload
+ stream_locations[index] = (add_chain(padded), len(padded))
+
+ directory_parts: list[bytes] = []
+ for index, entry in enumerate(entries):
+ start, size = stream_locations.get(index, (end_of_chain, 0))
+ directory_parts.append(
+ _directory_entry(
+ str(entry["name"]),
+ cast(int, entry["kind"]),
+ left=cast(int, entry.get("left", free_sector)),
+ right=cast(int, entry.get("right", free_sector)),
+ child=cast(int, entry.get("child", free_sector)),
+ start=start,
+ size=size,
+ clsid=bytes(cast(bytes, entry.get("clsid", b"\x00" * 16))),
+ )
+ )
+ directory = b"".join(directory_parts)
+ directory += b"\x00" * (-len(directory) % sector_size)
+ directory_start = add_chain(directory)
+
+ fat_count = 1
+ while (len(fat) + fat_count + 127) // 128 > fat_count:
+ fat_count += 1
+ fat_start = len(sectors)
+ fat_ids = list(range(fat_start, fat_start + fat_count))
+ full_fat = fat + [fat_sector] * fat_count
+ full_fat += [free_sector] * (fat_count * 128 - len(full_fat))
+ for index in range(fat_count):
+ sectors.append(struct.pack("<128I", *full_fat[index * 128 : (index + 1) * 128]))
+ difat = fat_ids + [free_sector] * (109 - len(fat_ids))
+ header = (
+ b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
+ + b"\x00" * 16
+ + struct.pack(
+ "<HHHHHHIIIIIIIII",
+ 0x003E,
+ 0x0003,
+ 0xFFFE,
+ 9,
+ 6,
+ 0,
+ 0,
+ 0,
+ fat_count,
+ directory_start,
+ 0,
+ 4096,
+ end_of_chain,
+ 0,
+ end_of_chain,
+ )
+ + struct.pack("<I", 0)
+ + struct.pack("<109I", *difat)
+ )
+ return header + b"".join(sectors)
+
+
+def build_equation_object(mtef: bytes) -> bytes:
+ """构造含 Equation Native 的独立 Equation.3 OLE 对象。"""
+
+ none = 0xFFFF_FFFF
+ equation_clsid = uuid.UUID("0002CE02-0000-0000-C000-000000000046").bytes_le
+ entries = [
+ {"name": "Root Entry", "kind": 5, "child": 1, "clsid": equation_clsid},
+ {"name": "\x01CompObj", "kind": 2, "right": 2, "data": b"Equation.3\x00"},
+ {"name": "\x03ObjInfo", "kind": 2, "right": 3, "data": b"\x00" * 6},
+ {"name": "Equation Native", "kind": 2, "right": none, "data": equation_native(mtef)},
+ ]
+ return _build_nested_cfb(entries)
+
+
+def _piece_table(text_fc: int, cp_count: int) -> bytes:
+ """构造单一 Unicode piece 的 CLX。"""
+
+ plc = struct.pack("<II", 0, cp_count)
+ plc += b"\x00\x00" + struct.pack("<I", text_fc) + b"\x00\x00"
+ return b"\x02" + struct.pack("<I", len(plc)) + plc
+
+
+def _chpx_fkp(
+ text_fc: int,
+ cp_count: int,
+ anchors: list[tuple[int, int, bool]],
+) -> tuple[bytes, int, int]:
+ """构造仅在字段分隔符上携带 OLE storage id 的 ChpxFkp。"""
+
+ end_fc = text_fc + cp_count * 2
+ boundaries = [text_fc]
+ location_by_start: dict[int, tuple[int, bool]] = {}
+ for cp, location, is_ole in anchors:
+ start = text_fc + cp * 2
+ boundaries.extend([start, start + 2])
+ location_by_start[start] = (location, is_ole)
+ boundaries.append(end_fc)
+ boundaries = sorted(set(boundaries))
+ run_count = len(boundaries) - 1
+ page = bytearray(512)
+ struct.pack_into(f"<{len(boundaries)}I", page, 0, *boundaries)
+ offsets_start = len(boundaries) * 4
+ payload_cursor = offsets_start + run_count
+ if payload_cursor % 2:
+ payload_cursor += 1
+ for index, start in enumerate(boundaries[:-1]):
+ location_info = location_by_start.get(start)
+ if location_info is None:
+ continue
+ location, is_ole = location_info
+ grpprl = struct.pack("<HI", 0x6A03, location)
+ if is_ole:
+ grpprl += struct.pack("<HB", 0x080A, 1) + struct.pack("<HB", 0x0856, 1)
+ page[offsets_start + index] = payload_cursor // 2
+ page[payload_cursor] = len(grpprl)
+ page[payload_cursor + 1 : payload_cursor + 1 + len(grpprl)] = grpprl
+ payload_cursor += 1 + len(grpprl)
+ if payload_cursor % 2:
+ payload_cursor += 1
+ page[511] = run_count
+ page_number = 4
+ bte = struct.pack("<III", text_fc, end_fc, page_number)
+ return bytes(page), page_number, len(bte)
+
+
+def _png_picf(png: bytes) -> bytes:
+ """把 PNG 包装成最小 PICFAndOfficeArtData。"""
+
+ blip_body = b"\x00" * 16 + b"\x00" + png
+ blip = struct.pack("<HHI", 0, 0xF01E, len(blip_body)) + blip_body
+ header_size = 68
+ header = bytearray(header_size)
+ struct.pack_into("<IH", header, 0, header_size + len(blip), header_size)
+ return bytes(header) + blip
+
+
+def build_equation_doc(
+ formulas: list[tuple[int, bytes]],
+ *,
+ preview_storage_ids: set[int] | None = None,
+) -> bytes:
+ """构造多个 ObjectPool Equation.3 字段的最小 DOC 集成 fixture。"""
+
+ text_parts: list[str] = []
+ anchors: list[tuple[int, int, bool]] = []
+ data_stream = bytearray()
+ previews = preview_storage_ids or set()
+ cp_cursor = 0
+ for storage_id, _mtef in formulas:
+ prefix = "\x13 EMBED Equation.3 "
+ field = prefix + "\x14\x01\x15\r"
+ separator_cp = cp_cursor + len(prefix)
+ anchors.append((separator_cp, storage_id, True))
+ if storage_id in previews:
+ preview_offset = len(data_stream)
+ data_stream.extend(_png_picf(_TINY_PNG))
+ anchors.append((separator_cp + 1, preview_offset, False))
+ text_parts.append(field)
+ cp_cursor += len(field)
+ text = "".join(text_parts)
+ encoded = text.encode("utf-16le")
+ cp_count = len(encoded) // 2
+ text_fc = 1024
+ clx = _piece_table(text_fc, cp_count)
+ section = struct.pack("<II", 0, cp_count) + b"\x00" * 12
+ fkp, page_number, bte_size = _chpx_fkp(text_fc, cp_count, anchors)
+ bte = struct.pack("<III", text_fc, text_fc + cp_count * 2, page_number)
+ table = clx + section + bte
+
+ pair_count = 75
+ pairs = [(0, 0)] * pair_count
+ pairs[6] = (len(clx), len(section))
+ pairs[12] = (len(clx) + len(section), bte_size)
+ pairs[33] = (0, len(clx))
+ base = bytearray(32)
+ struct.pack_into("<HH", base, 0, 0xA5EC, 0x00C1)
+ struct.pack_into("<H", base, 6, 0x0409)
+ struct.pack_into("<H", base, 10, 0x020C)
+ struct.pack_into("<II", base, 24, text_fc, text_fc + len(encoded))
+ rgw = [0] * 14
+ rglw = [0] * 11
+ rglw[0] = max(text_fc + len(encoded), (page_number + 1) * 512)
+ rglw[3] = cp_count
+ fib = bytes(base)
+ fib += struct.pack("<H", len(rgw)) + struct.pack(f"<{len(rgw)}H", *rgw)
+ fib += struct.pack("<H", len(rglw)) + struct.pack(f"<{len(rglw)}I", *rglw)
+ fib += struct.pack("<H", pair_count)
+ fib += b"".join(struct.pack("<II", offset, size) for offset, size in pairs)
+ fib += struct.pack("<H", 0)
+ word_document = bytearray(max((page_number + 1) * 512, text_fc + len(encoded)))
+ word_document[: len(fib)] = fib
+ word_document[text_fc : text_fc + len(encoded)] = encoded
+ word_document[page_number * 512 : (page_number + 1) * 512] = fkp
+
+ none = 0xFFFF_FFFF
+ equation_clsid = uuid.UUID("0002CE02-0000-0000-C000-000000000046").bytes_le
+ entries: list[dict[str, object]] = [
+ {"name": "Root Entry", "kind": 5, "child": 1},
+ {"name": "ObjectPool", "kind": 1},
+ ]
+ storage_indexes: list[int] = []
+ for storage_id, mtef in formulas:
+ storage_index = len(entries)
+ storage_indexes.append(storage_index)
+ entries.append(
+ {
+ "name": f"_{storage_id}",
+ "kind": 1,
+ "child": storage_index + 1,
+ "clsid": equation_clsid,
+ }
+ )
+ entries.extend(
+ [
+ {
+ "name": "Equation Native",
+ "kind": 2,
+ "right": storage_index + 2,
+ "data": equation_native(mtef),
+ },
+ {
+ "name": "\x01CompObj",
+ "kind": 2,
+ "right": storage_index + 3,
+ "data": b"Equation.3\x00",
+ },
+ {
+ "name": "\x03ObjInfo",
+ "kind": 2,
+ "right": none,
+ "data": b"\x00" * 6,
+ },
+ ]
+ )
+ for current, following in zip(storage_indexes, storage_indexes[1:]):
+ entries[current]["right"] = following
+ entries[1]["child"] = storage_indexes[0]
+ table_index = len(entries)
+ entries[1]["right"] = table_index
+ entries.extend(
+ [
+ {"name": "1Table", "kind": 2, "right": table_index + 1, "data": table},
+ {"name": "Data", "kind": 2, "right": table_index + 2, "data": bytes(data_stream)},
+ {"name": "WordDocument", "kind": 2, "right": none, "data": bytes(word_document)},
+ ]
+ )
+ return _build_nested_cfb(entries)
diff --git a/tests/unittest/test_flash_legacy_doc_mtef.py b/tests/unittest/test_flash_legacy_doc_mtef.py
new file mode 100644
index 00000000..c5dbf1fb
--- /dev/null
+++ b/tests/unittest/test_flash_legacy_doc_mtef.py
@@ -0,0 +1,174 @@
+from __future__ import annotations
+
+import asyncio
+from io import BytesIO
+
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.model.flash import DocModel
+from mineru.model.flash.legacy_office.mtef import (
+ decode_equation_native,
+ decode_equation_object,
+ decode_mtef_v3,
+)
+from mineru.render.contracts import RenderMode
+from mineru.render.html import render_html
+from mineru.render.markdown import render_markdown
+from mineru.types import BlockType, MiddleJson, ModelJson
+
+from _mtef_test_utils import (
+ build_equation_doc,
+ build_equation_object,
+ equation_native,
+ formula_corpus,
+ mtef_equation,
+ mtef_line,
+ mtef_template,
+ mtef_text,
+)
+
+_CAPTURED_EQUATION_NATIVE = bytes.fromhex(
+ """
+ 1c0000000200d4c0410000000000000050a414003cbc14000000000003010103
+ 010a0112836300030f01000b01128376000011000a030f00000b110102883200
+ 00000a028612220288340012836d0012836b0002863c00028830000000
+ """
+)
+
+
+ ("name", "mtef", "expected"),
+ formula_corpus(),
+ ids=[name for name, _mtef, _expected in formula_corpus()],
+)
+def test_mtef_v3_corpus_decodes_to_exact_latex(
+ name: str,
+ mtef: bytes,
+ expected: str,
+) -> None:
+ """验证各类手工 MTEF v3 结构精确转换为预期 LaTeX。"""
+
+ assert name
+ assert decode_mtef_v3(mtef) == expected
+
+
+def test_equation_native_header_and_standalone_ole_object_decode() -> None:
+ """验证 28 字节 EQNOLEFILEHDR 和独立 Equation.3 OLE 对象均可读取。"""
+
+ _name, mtef, expected = formula_corpus()[1]
+ native = equation_native(mtef)
+ equation_object = build_equation_object(mtef)
+
+ assert decode_equation_native(native) == expected
+ assert decode_equation_object(equation_object) == expected
+
+
+def test_captured_equation_editor_native_stream_decodes_independently() -> None:
+ """验证独立采集的 Equation.3 stream 恢复上下标、减号和关系式。"""
+
+ assert decode_equation_native(_CAPTURED_EQUATION_NATIVE) == "c_{v}^{2}-4mk<0"
+
+
+def test_equation_editor_object_doc_integrates_as_native_equation_blocks() -> None:
+ """验证 ObjectPool storage id、字段分隔符和 MTEF 形成完整 DOC 原生公式链。"""
+
+ corpus = formula_corpus()
+ file_bytes = build_equation_doc(
+ [(1000 + index, mtef) for index, (_name, mtef, _expected) in enumerate(corpus)]
+ )
+ stream = BytesIO(file_bytes)
+
+ pages = DocModel().predict(stream)
+
+ assert not stream.closed
+ assert pages == [
+ [
+ {"type": BlockType.EQUATION, "content": expected}
+ for _name, _mtef, expected in corpus
+ ]
+ ]
+ assert all(block.get("type") != BlockType.IMAGE for block in pages[0])
+
+
+def test_equation_editor_doc_sync_async_middle_json_and_renderers() -> None:
+ """验证原生公式贯穿同步/异步 Analyze、严格 MiddleJson、Markdown 和 HTML。"""
+
+ corpus = formula_corpus()
+ file_bytes = build_equation_doc(
+ [(2000 + index, mtef) for index, (_name, mtef, _expected) in enumerate(corpus)]
+ )
+ middle, model = doc_analyze(file_bytes, file_suffix="doc")
+ async_middle, async_model = asyncio.run(aio_doc_analyze(file_bytes, file_suffix="doc"))
+
+ assert isinstance(model, ModelJson)
+ assert isinstance(middle, MiddleJson)
+ assert async_model == model
+ assert async_middle == middle
+ assert [block.type for block in middle.pages[0].blocks] == [BlockType.EQUATION] * len(corpus)
+ markdown = render_markdown(middle, mode=RenderMode.FULL)
+ html = render_html(middle, mode=RenderMode.FULL)
+ for _name, _mtef, expected in corpus:
+ assert expected in markdown
+ assert expected.replace("&", "&amp;") in html or expected in html
+
+
+def test_native_equation_wins_over_preview_and_invalid_native_keeps_preview() -> None:
+ """验证有效 MTEF 抑制缓存图,坏 MTEF 则安全回退到原图片。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+ native_pages = DocModel().predict(
+ BytesIO(
+ build_equation_doc(
+ [(42, mtef)],
+ preview_storage_ids={42},
+ )
+ )
+ )
+ fallback_pages = DocModel().predict(
+ BytesIO(
+ build_equation_doc(
+ [(43, b"invalid MTEF")],
+ preview_storage_ids={43},
+ )
+ )
+ )
+
+ assert native_pages == [[{"type": BlockType.EQUATION, "content": expected}]]
+ assert fallback_pages[0][0]["type"] == BlockType.IMAGE
+ assert fallback_pages[0][0]["image_base64"].startswith("data:image/")
+
+
+ "payload",
+ [
+ b"",
+ b"\x02\x01\x01\x03\x00\x00",
+ mtef_equation(mtef_template(49, mtef_line(mtef_text("x")))),
+ bytes([3, 1, 1, 3, 0, 5, 0, 0, 0, 255, 255]),
+ bytes([3, 1, 1, 3, 0, 8, 131, 0x41]),
+ ],
+)
+def test_invalid_or_unsupported_mtef_fails_closed(payload: bytes) -> None:
+ """验证截断、未知 template、异常矩阵和坏 FONT 不制造错误 LaTeX。"""
+
+ assert decode_mtef_v3(payload) is None
+
+
+def test_invalid_equation_native_header_fails_closed() -> None:
+ """验证错误 header size、版本和对象长度均被拒绝。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+ valid = bytearray(equation_native(mtef))
+ cases: list[bytes] = []
+ broken = bytearray(valid)
+ broken[0:2] = (27).to_bytes(2, "little")
+ cases.append(bytes(broken))
+ broken = bytearray(valid)
+ broken[2:6] = (0x0001_0000).to_bytes(4, "little")
+ cases.append(bytes(broken))
+ broken = bytearray(valid)
+ broken[8:12] = (len(mtef) + 100).to_bytes(4, "little")
+ cases.append(bytes(broken))
+
+ assert all(decode_equation_native(case) is None for case in cases)
diff --git a/tests/unittest/test_flash_legacy_xls_ppt_mtef.py b/tests/unittest/test_flash_legacy_xls_ppt_mtef.py
new file mode 100644
index 00000000..fdca80eb
--- /dev/null
+++ b/tests/unittest/test_flash_legacy_xls_ppt_mtef.py
@@ -0,0 +1,158 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+from io import BytesIO
+
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.model.flash import PptModel, XlsModel
+from mineru.model.flash.legacy_office import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_ENTRY_BYTES
+from mineru.types import BlockType, MiddleJson, ModelJson
+
+from _legacy_ppt_test_utils import build_equation_ppt
+from _legacy_xls_test_utils import build_equation_xls, label_cell
+from _mtef_test_utils import formula_corpus
+
+
+def test_xls_equation_editor_corpus_decodes_to_exact_equation_blocks() -> None:
+ """验证 XLS 的 MBD/OBJ 绑定把完整公式语料恢复为精确 LaTeX。"""
+
+ corpus = formula_corpus()
+ file_bytes = build_equation_xls(
+ [
+ (100 + index, mtef)
+ for index, (_name, mtef, _expected) in enumerate(corpus)
+ ],
+ preview=False,
+ )
+
+ pages = XlsModel().predict(BytesIO(file_bytes))
+
+ assert pages == [
+ [
+ {"type": BlockType.EQUATION, "content": expected}
+ for _name, _mtef, expected in corpus
+ ]
+ ]
+
+
+def test_ppt_equation_editor_corpus_stays_bound_to_its_slides() -> None:
+ """验证 PPT 的 ExObjRef/persist 绑定逐 slide 恢复完整公式语料。"""
+
+ corpus = formula_corpus()
+ file_bytes = build_equation_ppt(
+ [mtef for _name, mtef, _expected in corpus],
+ preview=False,
+ )
+
+ pages = PptModel().predict(BytesIO(file_bytes))
+
+ assert pages == [
+ [{"type": BlockType.EQUATION, "content": expected}]
+ for _name, _mtef, expected in corpus
+ ]
+
+
+def test_xls_equation_inside_table_is_not_duplicated_as_top_level_block() -> None:
+ """验证落在表格坐标内的 XLS 公式进入 cell HTML 且不重复输出。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+ pages = XlsModel().predict(
+ BytesIO(
+ build_equation_xls(
+ [(42, mtef)],
+ cell_records=label_cell(0, 0, "value"),
+ )
+ )
+ )
+
+ assert len(pages[0]) == 1
+ assert pages[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{expected}</eq>" in pages[0][0]["content"]
+
+
+ ("model", "valid_file", "invalid_file"),
+ [
+ (
+ XlsModel(),
+ lambda mtef: build_equation_xls([(42, mtef)]),
+ lambda: build_equation_xls([(43, b"invalid MTEF")]),
+ ),
+ (
+ PptModel(),
+ lambda mtef: build_equation_ppt([mtef]),
+ lambda: build_equation_ppt([b"invalid MTEF"]),
+ ),
+ ],
+ ids=["xls", "ppt"],
+)
+def test_native_equation_wins_and_invalid_native_keeps_preview(
+ model: XlsModel | PptModel,
+ valid_file: Callable[[bytes], bytes],
+ invalid_file: Callable[[], bytes],
+) -> None:
+ """验证 XLS/PPT 都优先原生公式,坏 MTEF 则保留缓存预览。"""
+
+ _name, mtef, expected = formula_corpus()[1]
+ native_pages = model.predict(BytesIO(valid_file(mtef)))
+ fallback_pages = model.predict(BytesIO(invalid_file()))
+
+ assert native_pages == [[{"type": BlockType.EQUATION, "content": expected}]]
+ assert fallback_pages[0][0]["type"] == BlockType.IMAGE
+ assert fallback_pages[0][0]["image_base64"].startswith("data:image/")
+
+
+def test_ppt_uncompressed_equation_storage_is_supported() -> None:
+ """验证 recInstance=0 的未压缩 ExOleObjStg 同样可以恢复公式。"""
+
+ _name, mtef, expected = formula_corpus()[2]
+
+ pages = PptModel().predict(
+ BytesIO(build_equation_ppt([mtef], compressed=False, preview=False))
+ )
+
+ assert pages == [[{"type": BlockType.EQUATION, "content": expected}]]
+
+
[email protected]("file_suffix", ["xls", "ppt"])
+def test_backend_analyze_preserves_native_equations_sync_and_async(
+ file_suffix: str,
+) -> None:
+ """验证原生公式贯穿 XLS/PPT 同步与异步严格 Analyze 契约。"""
+
+ _name, mtef, expected = formula_corpus()[3]
+ file_bytes = (
+ build_equation_xls([(42, mtef)], preview=False)
+ if file_suffix == "xls"
+ else build_equation_ppt([mtef], preview=False)
+ )
+ middle, model = doc_analyze(file_bytes, file_suffix=file_suffix) # type: ignore[arg-type]
+ async_middle, async_model = asyncio.run(
+ aio_doc_analyze(file_bytes, file_suffix=file_suffix) # type: ignore[arg-type]
+ )
+
+ assert isinstance(model, ModelJson)
+ assert isinstance(middle, MiddleJson)
+ assert model.file_suffix == middle.file_suffix == file_suffix
+ assert middle.pages[0].blocks[0].type == BlockType.EQUATION
+ assert middle.pages[0].blocks[0].content == expected
+ assert async_model == model
+ assert async_middle == middle
+
+
+def test_ppt_equation_decompression_honors_shared_entry_limit() -> None:
+ """验证恶意 ExOleObjStg 声明长度触发稳定资源限制。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+ file_bytes = build_equation_ppt(
+ [mtef],
+ declared_size=MAX_ENTRY_BYTES + 1,
+ preview=False,
+ )
+
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_entry_bytes"):
+ PptModel().predict(BytesIO(file_bytes))