Skip to content

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

feat: implement OLE equation handling for XLSX and PPTX formats with new decoding and artifact management

myhlolice7033f98e14
diff --git a/mineru/model/flash/docx/docx_converter.py b/mineru/model/flash/docx/docx_converter.py
index 1f04eef7..cf7a6719 100644
--- a/mineru/model/flash/docx/docx_converter.py
+++ b/mineru/model/flash/docx/docx_converter.py
@@ -21,6 +21,10 @@ from mineru.model.flash.office.chart import extract_chart_html_from_ooxml
from mineru.model.flash.office.image import (
serialize_office_image,
)
+from mineru.model.flash.office.ooxml_equation import (
+ OoxmlEquationDecoder,
+ is_equation_3_prog_id,
+)
from mineru.types import RAW_CAPTION
from mineru.model.flash.docx.package_normalizer import normalize_docx_package
from mineru.model.flash.docx.tools.math.omml import oMath2Latex
@@ -49,6 +53,7 @@ class DocxConverter:
"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
"wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
"mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
+ "o": "urn:schemas-microsoft-com:office:office",
"v": "urn:schemas-microsoft-com:vml",
"wps": "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
"w10": "urn:schemas-microsoft-com:office:word",
@@ -106,6 +111,8 @@ class DocxConverter:
self._numbering_start_cache: dict[tuple[int, int], int] = {}
self._style_lookup_cache: dict[tuple[Any, Optional[str]], Any] = {}
self._style_bool_cache: dict[tuple[int, str], Optional[bool]] = {}
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._mtef_warned_relations: set[tuple[str, str]] = set()
@staticmethod
def _local_name(element: Any) -> Optional[str]:
@@ -123,6 +130,133 @@ class DocxConverter:
self._style_lookup_cache = {}
self._style_bool_cache = {}
+ @staticmethod
+ def _docx_part_key(part: Any) -> str:
+ """返回用于公式关系缓存和告警去重的 DOCX part 名称。"""
+
+ return str(getattr(part, "partname", ""))
+
+ def _require_document_part(self) -> Any:
+ """返回已加载的主文档 part,生命周期异常时立即失败。"""
+
+ if self.docx_obj is None:
+ raise ValueError("DOCX document part is not initialized")
+ return self.docx_obj.part
+
+ def _decode_docx_ole_equation(
+ self,
+ ole_element: Any,
+ part: Any,
+ ) -> str | None:
+ """从当前 DOCX part 的内部 OLE relationship 解码 Equation.3。"""
+
+ prog_id = ole_element.get("ProgID") or ole_element.get("ProgId")
+ if not is_equation_3_prog_id(prog_id):
+ return None
+ object_type = (ole_element.get("Type") or "Embed").strip().casefold()
+ if object_type != "embed":
+ return None
+ draw_aspect = (ole_element.get("DrawAspect") or "Content").strip().casefold()
+ if draw_aspect == "icon":
+ return None
+
+ relationship_id = ole_element.get(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
+ )
+ relationships = getattr(part, "rels", None)
+ relationship = relationships.get(relationship_id) if relationships is not None else None
+ if relationship is None or getattr(relationship, "is_external", False):
+ return None
+ reltype = str(getattr(relationship, "reltype", ""))
+ if not reltype.rstrip("/").casefold().endswith("/oleobject"):
+ return None
+ try:
+ blob = relationship.target_part.blob
+ except (AttributeError, KeyError, ValueError):
+ blob = None
+ latex = self._ooxml_equation_decoder.decode(
+ blob,
+ prog_id=prog_id,
+ )
+ if latex is not None:
+ return latex
+
+ warning_key = (self._docx_part_key(part), str(relationship_id))
+ if warning_key not in self._mtef_warned_relations:
+ self._mtef_warned_relations.add(warning_key)
+ logger.warning(
+ "DOCX_MTEF_FALLBACK: part={!r}, relationship={!r} has an invalid or unsupported Equation.3 object",
+ warning_key[0],
+ relationship_id,
+ )
+ return None
+
+ def _docx_formula_tokens(
+ self,
+ element: Any,
+ part: Any,
+ ) -> list[tuple[str, str]]:
+ """按文档顺序提取文本、OMML 和 MTEF,并选择单一兼容分支。"""
+
+ tag_name = self._local_name(element)
+ if tag_name is None:
+ return []
+ tag = str(getattr(element, "tag", ""))
+
+ if tag_name == "AlternateContent":
+ branch_tokens = [
+ self._docx_formula_tokens(child, part)
+ for child in element
+ if self._local_name(child) in {"Choice", "Fallback"}
+ ]
+ for token_kind in ("omml", "mtef"):
+ for tokens in branch_tokens:
+ if any(kind == token_kind for kind, _value in tokens):
+ return tokens
+ return branch_tokens[0] if branch_tokens else []
+
+ if tag_name == "txbxContent":
+ # 外层段落会单独遍历文本框内容,避免在此重复提取公式和文字。
+ return []
+
+ if tag_name == "oMath" and "officeDocument/2006/math" in tag:
+ try:
+ latex = str(oMath2Latex(element)).strip()
+ except Exception as exc:
+ logger.debug(f"Failed to convert DOCX OMML equation to LaTeX: {exc}")
+ return []
+ return [("omml", latex)] if latex else []
+
+ if tag_name == "OLEObject":
+ latex = self._decode_docx_ole_equation(element, part)
+ return [("mtef", latex)] if latex else []
+
+ if tag_name == "t" and "officeDocument/2006/math" not in tag:
+ return [("text", element.text)] if isinstance(element.text, str) else []
+
+ tokens: list[tuple[str, str]] = []
+ for child in element:
+ tokens.extend(self._docx_formula_tokens(child, part))
+ return tokens
+
+ def _picture_is_equation_preview(self, image: Any, part: Any) -> bool:
+ """判断图片是否属于同一容器中已恢复的 OMML/MTEF 公式预览。"""
+
+ for ancestor in image.iterancestors():
+ ancestor_name = self._local_name(ancestor)
+ if ancestor_name == "object":
+ for ole_element in ancestor.findall(
+ ".//o:OLEObject",
+ namespaces=DocxConverter._BLIP_NAMESPACES,
+ ):
+ if self._decode_docx_ole_equation(ole_element, part):
+ return True
+ continue
+ if ancestor_name == "AlternateContent":
+ tokens = self._docx_formula_tokens(ancestor, part)
+ return any(kind in {"omml", "mtef"} for kind, _value in tokens)
+ return False
+
def _get_style_id_from_property(
self,
xml_element: Optional[BaseOxmlElement],
@@ -730,6 +864,8 @@ class DocxConverter:
self._numbering_level_cache = {}
self._numbering_start_cache = {}
self._reset_style_caches()
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._mtef_warned_relations = set()
# 读取文件字节,以便 mammoth 和 python-docx 各自使用独立读取流
file_bytes = self._sanitize_missing_internal_relationships(file_stream.read())
# 使用完整 DOCX 上下文预解析顶层表格,避免转换非表格正文带来的资源浪费
@@ -852,10 +988,16 @@ class DocxConverter:
# 锚定图片在段落中浮动定位,段落文本应出现在图片之前
if is_anchored and tag_name == "p":
self._handle_text_elements(element)
- self._handle_pictures(picture_refs)
+ self._handle_pictures(
+ picture_refs,
+ part=self._require_document_part(),
+ )
else:
# 处理图片元素
- self._handle_pictures(picture_refs)
+ self._handle_pictures(
+ picture_refs,
+ part=self._require_document_part(),
+ )
# 如果是段落元素,同时处理其中的文本内容(如描述性文字)
if tag_name == "p":
self._handle_text_elements(element)
@@ -900,7 +1042,7 @@ class DocxConverter:
图片会被 mammoth 转换为内联 data-URI base64 格式(<img src="data:...">)。
- 注意:mammoth 不支持 OMML(Office Math Markup Language)公式,会静默丢弃
+ 注意:mammoth 不支持 OMML 或 Equation.3/MTEF 公式,会静默丢弃
表格单元格内的公式。本方法在获取 mammoth HTML 后,会同步遍历原始 DOCX XML,
将丢失的公式重新注入对应的 HTML 单元格。
@@ -928,13 +1070,22 @@ class DocxConverter:
logger.debug(f"Pre-parsed {len(top_level_tables)} top-level tables via filtered mammoth conversion")
- result_tables = self._align_mammoth_tables_to_xml_tables(top_level_tables, xml_top_tables)
+ result_tables = self._align_mammoth_tables_to_xml_tables(
+ top_level_tables,
+ xml_top_tables,
+ docx_obj.part,
+ )
return result_tables
except Exception as e:
logger.debug(f"Could not pre-parse tables with filtered mammoth conversion: {e}")
return []
- def _align_mammoth_tables_to_xml_tables(self, html_tables, xml_tables) -> list:
+ def _align_mammoth_tables_to_xml_tables(
+ self,
+ html_tables: Any,
+ xml_tables: Any,
+ source_part: Any,
+ ) -> list:
"""
将 Mammoth 输出表格按正文顶层 XML 表格重新对齐。
@@ -964,7 +1115,11 @@ class DocxConverter:
aligned_tables.append(None)
continue
- matched_html_table = self._inject_equations_into_table(matched_html_table, xml_table)
+ matched_html_table = self._inject_equations_into_table(
+ matched_html_table,
+ xml_table,
+ source_part,
+ )
aligned_tables.append(str(matched_html_table))
if len(html_tables) != len(xml_tables):
@@ -1050,7 +1205,11 @@ class DocxConverter:
return {
"row_count": len(xml_table.xpath('./*[local-name()="tr"]')),
"cell_count": len(xml_table.xpath('.//*[local-name()="tc"]')),
- "image_count": len(xml_table.xpath('.//*[local-name()="blip"]')),
+ "image_count": len(
+ xml_table.xpath(
+ './/*[local-name()="blip" or local-name()="imagedata"]'
+ )
+ ),
"text": DocxConverter._normalize_table_match_text(text),
}
@@ -1078,11 +1237,16 @@ class DocxConverter:
return True
return xml_text.startswith(html_text) or html_text.startswith(xml_text)
- def _inject_equations_into_table(self, html_table, xml_table):
+ def _inject_equations_into_table(
+ self,
+ html_table: Any,
+ xml_table: Any,
+ source_part: Any,
+ ) -> Any:
"""
- 将 DOCX XML 表格中的 OMML 公式注入到 mammoth 生成的 HTML 表格中。
+ 将 DOCX XML 表格中的 OMML/MTEF 公式注入 mammoth HTML 表格。
- mammoth 会静默丢弃 OMML(Office Math Markup Language)公式,导致含公式
+ mammoth 会静默丢弃 OMML 与 Equation.3 公式,导致含公式
的表格单元格在 HTML 中为空。本方法并行遍历 HTML 表格(BeautifulSoup 对象)
和 XML 表格(lxml 元素),对含有 OMML 公式的单元格用包含公式占位符的内容
替换原来的空内容。
@@ -1094,11 +1258,13 @@ class DocxConverter:
Returns:
BeautifulSoup Tag: 注入公式后的 <table> 元素(原地修改并返回)
"""
- OMML_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
# 快速检查:该表格是否含有任何公式
- if not xml_table.findall(f".//{{{OMML_NS}}}oMath"):
+ if not any(
+ kind in {"omml", "mtef"}
+ for kind, _value in self._docx_formula_tokens(xml_table, source_part)
+ ):
return html_table
from bs4 import BeautifulSoup
@@ -1118,11 +1284,20 @@ class DocxConverter:
continue
for html_cell, xml_cell in zip(html_cells, xml_cells):
- if not xml_cell.findall(f".//{{{OMML_NS}}}oMath"):
+ if not any(
+ kind in {"omml", "mtef"}
+ for kind, _value in self._docx_formula_tokens(
+ xml_cell,
+ source_part,
+ )
+ ):
continue
# 该单元格含公式,重建其 HTML 内容以保留公式
- new_content = self._build_cell_html_with_equations(xml_cell)
+ new_content = self._build_cell_html_with_equations(
+ xml_cell,
+ source_part,
+ )
if new_content:
html_cell.clear()
new_soup = BeautifulSoup(new_content, "html.parser")
@@ -1131,11 +1306,15 @@ class DocxConverter:
return html_table
- def _build_cell_html_with_equations(self, xml_cell) -> str:
+ def _build_cell_html_with_equations(
+ self,
+ xml_cell: Any,
+ source_part: Any,
+ ) -> str:
"""
- 为含 OMML 公式的表格单元格构建 HTML 内容字符串。
+ 为含 OMML/MTEF 公式的表格单元格构建 HTML 内容字符串。
- 遍历单元格内的段落,将普通文本和 OMML 公式(转换为 LaTeX 占位符)
+ 遍历单元格内的段落,将普通文本和 OMML/MTEF 公式
混合在一起,生成与 mammoth 输出风格一致的 HTML 片段。
Args:
@@ -1145,23 +1324,50 @@ class DocxConverter:
str: 单元格内容的 HTML 字符串,如 "<p>text<eq>latex</eq></p>";
若单元格为空则返回空字符串
"""
- W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
-
parts = []
for child in xml_cell:
child_tag = self._local_name(child)
if child_tag is None:
continue
if child_tag == "p":
- para_html = self._build_paragraph_html_with_equations(child)
+ para_html = self._build_paragraph_html_with_equations(
+ child,
+ source_part,
+ )
if para_html is not None:
parts.append(para_html)
# 嵌套表格暂不处理,由外层逻辑负责
return "".join(parts)
- def _build_paragraph_html_with_equations(self, xml_para) -> Optional[str]:
+ def _inject_equations_into_table_html(
+ self,
+ html: str,
+ xml_table: Any,
+ source_part: Any,
+ ) -> str:
+ """把孤立表格 HTML 包装为 Tag 后复用 OMML/MTEF 注入逻辑。"""
+
+ from bs4 import BeautifulSoup
+
+ soup = BeautifulSoup(html, "html.parser")
+ html_table = soup.find("table")
+ if html_table is None:
+ return html
+ return str(
+ self._inject_equations_into_table(
+ html_table,
+ xml_table,
+ source_part,
+ )
+ )
+
+ def _build_paragraph_html_with_equations(
+ self,
+ xml_para: Any,
+ source_part: Any,
+ ) -> Optional[str]:
"""
- 为可能含 OMML 公式的段落构建 HTML 字符串。
+ 为可能含 OMML/MTEF 公式的段落构建 HTML 字符串。
使用与 _handle_equations_in_text 相同的迭代逻辑:
- 普通 <w:t> 元素的文本直接收集
@@ -1175,24 +1381,12 @@ class DocxConverter:
Returns:
str | None: 格式为 "<p>...</p>" 的 HTML 字符串;段落为空时返回 None
"""
- items = []
- for subt in xml_para.iter():
- tag_name = self._local_name(subt)
- if tag_name is None:
- continue
- tag = subt.tag
- # 普通文本节点(排除 math 命名空间下的 <m:t>)
- if tag_name == "t" and "math" not in tag:
- if isinstance(subt.text, str) and subt.text:
- items.append(subt.text)
- # OMML 公式元素(排除 oMathPara 容器避免重复处理)
- elif "oMath" in tag and "oMathPara" not in tag:
- try:
- latex = str(oMath2Latex(subt)).strip()
- if latex:
- items.append(self.equation_bookends.format(EQ=latex))
- except Exception as e:
- logger.debug(f"Failed to convert OMML equation to LaTeX: {e}")
+ items: list[str] = []
+ for token_kind, value in self._docx_formula_tokens(xml_para, source_part):
+ if token_kind == "text":
+ items.append(value)
+ else:
+ items.append(self.equation_bookends.format(EQ=value))
if not items:
return None
@@ -1229,6 +1423,11 @@ class DocxConverter:
t = body_reader.read_all([table])
res = convert_document_element_to_html(t.value[0])
html = self._normalize_table_colspans(res.value)
+ html = self._inject_equations_into_table_html(
+ html,
+ element,
+ self._require_document_part(),
+ )
table_block = {
"type": BlockType.TABLE,
"content": html,
@@ -1354,7 +1553,11 @@ class DocxConverter:
paragraph_elements = self._get_paragraph_elements(paragraph)
paragraph_text = self._get_paragraph_text(paragraph)
paragraph_anchor = self._extract_paragraph_bookmark(element)
- text, equations = self._handle_equations_in_text(element=element, text=paragraph_text)
+ text, equations = self._handle_equations_in_text(
+ element=element,
+ text=paragraph_text,
+ part=paragraph.part,
+ )
if text is None:
return None
@@ -1521,7 +1724,12 @@ class DocxConverter:
if is_section_end:
self._start_new_page()
- def _handle_pictures(self, picture_refs: Any):
+ def _handle_pictures(
+ self,
+ picture_refs: Any,
+ *,
+ part: Any | None = None,
+ ) -> None:
"""
处理图片。
@@ -1538,6 +1746,8 @@ class DocxConverter:
rel_id = image.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")
return rel_id
+ source_part = part or self._require_document_part()
+
def get_docx_image_part(image: Any) -> Optional[Any]:
"""
获取 DOCX 图像 part。
@@ -1550,14 +1760,16 @@ class DocxConverter:
Optional[Any]: 图像 part
"""
rId = get_docx_image_rel_id(image)
- if rId in self.docx_obj.part.rels:
+ if rId in source_part.rels:
# 使用关系 ID 访问图像部分
- return self.docx_obj.part.rels[rId].target_part
+ return source_part.rels[rId].target_part
return None
seen_rel_ids: set[str] = set()
# 遍历所有图片引用元素,支持 DrawingML blip 和 VML imagedata。
for image in picture_refs:
+ if self._picture_is_equation_preview(image, source_part):
+ continue
rel_id = get_docx_image_rel_id(image)
if rel_id and rel_id in seen_rel_ids:
continue
@@ -1966,38 +2178,36 @@ class DocxConverter:
script=script,
)
- def _handle_equations_in_text(self, element, text):
+ def _handle_equations_in_text(
+ self,
+ element: Any,
+ text: str,
+ *,
+ part: Any | None = None,
+ ) -> tuple[str, list[str]]:
"""
处理文本中的公式。
Args:
element: 元素对象
text: 文本内容
+ part: 当前段落所属的 OOXML part,用于解析局部 relationship
Returns:
tuple: (处理后的文本, 公式列表)
"""
- only_texts = []
- only_equations = []
- texts_and_equations = []
- for subt in element.iter():
- tag_name = self._local_name(subt)
- if tag_name is None:
+ source_part = part or self._require_document_part()
+ only_texts: list[str] = []
+ only_equations: list[str] = []
+ texts_and_equations: list[str] = []
+ for token_kind, value in self._docx_formula_tokens(element, source_part):
+ if token_kind == "text":
+ only_texts.append(value)
+ texts_and_equations.append(value)
continue
- tag = subt.tag
- if tag_name == "t" and "math" not in tag:
- if isinstance(subt.text, str):
- only_texts.append(subt.text)
- texts_and_equations.append(subt.text)
- elif "oMath" in tag and "oMathPara" not in tag:
- try:
- latex_equation = str(oMath2Latex(subt)).strip()
- except Exception as e:
- logger.debug(f"Failed to convert OMML equation to LaTeX: {e}")
- continue
- if len(latex_equation) > 0:
- only_equations.append(self.equation_bookends.format(EQ=latex_equation))
- texts_and_equations.append(self.equation_bookends.format(EQ=latex_equation))
+ equation = self.equation_bookends.format(EQ=value)
+ only_equations.append(equation)
+ texts_and_equations.append(equation)
if len(only_equations) < 1:
return text, []
@@ -2927,7 +3137,11 @@ class DocxConverter:
try:
p_obj = Paragraph(p, self.docx_obj)
paragraph_elements = self._get_paragraph_elements(p_obj)
- text, equations = self._handle_equations_in_text(element=p, text=p_obj.text)
+ text, equations = self._handle_equations_in_text(
+ element=p,
+ text=p_obj.text,
+ part=p_obj.part,
+ )
target_anchor = self._extract_toc_target_anchor(p)
if target_anchor and target_anchor.startswith("_Toc"):
self.toc_anchor_set.add(target_anchor)
@@ -3044,7 +3258,11 @@ class DocxConverter:
"""
paragraph_elements = self._get_paragraph_elements(paragraph)
paragraph_text = self._get_paragraph_text(paragraph)
- text, equations = self._handle_equations_in_text(element=paragraph._element, text=paragraph_text)
+ text, equations = self._handle_equations_in_text(
+ element=paragraph._element,
+ text=paragraph_text,
+ part=paragraph.part,
+ )
if text is None:
return ""
diff --git a/mineru/model/flash/legacy_office/mtef.py b/mineru/model/flash/legacy_office/mtef.py
index 8462a214..efc9fc56 100644
--- a/mineru/model/flash/legacy_office/mtef.py
+++ b/mineru/model/flash/legacy_office/mtef.py
@@ -10,6 +10,7 @@ import struct
from loguru import logger
+from .errors import LegacyOfficeResourceLimitError
from .limits import MAX_RECORD_DEPTH, MAX_RECORDS
from .ole import BoundedOleReader
@@ -606,6 +607,8 @@ def decode_equation_object(data: bytes) -> str | None:
try:
with BoundedOleReader(data) as ole:
native = ole.read_stream("Equation Native")
+ except LegacyOfficeResourceLimitError:
+ raise
except ValueError:
return None
return decode_equation_native(native)
diff --git a/mineru/model/flash/office/ooxml_equation.py b/mineru/model/flash/office/ooxml_equation.py
new file mode 100644
index 00000000..a772055a
--- /dev/null
+++ b/mineru/model/flash/office/ooxml_equation.py
@@ -0,0 +1,66 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""现代 Office OOXML 包中的 Equation.3 OLE 公式解码适配器。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+
+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import (
+ MAX_ASSET_TOTAL_BYTES,
+ MAX_ENTRY_BYTES,
+)
+from mineru.model.flash.legacy_office.mtef import decode_equation_object
+
+CFB_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
+EQUATION_3_PROG_ID = "equation.3"
+
+
+def is_equation_3_prog_id(prog_id: object | None) -> bool:
+ """判断 OOXML OLE ProgID 是否精确指向 Equation.3。"""
+
+ return isinstance(prog_id, str) and prog_id.strip().casefold() == EQUATION_3_PROG_ID
+
+
+@dataclass(slots=True)
+class OoxmlEquationDecoder:
+ """按共享资源上限缓存并解码 OOXML 中的 Equation.3 对象。"""
+
+ total_bytes: int = 0
+ _cache: dict[bytes, str | None] = field(default_factory=dict)
+
+ def decode(
+ self,
+ blob: bytes | None,
+ *,
+ prog_id: object | None,
+ show_as_icon: bool = False,
+ ) -> str | None:
+ """校验 ProgID、图标模式、CFB 头和资源预算后返回 LaTeX。"""
+
+ if show_as_icon or not is_equation_3_prog_id(prog_id) or blob is None:
+ return None
+ if not isinstance(blob, bytes):
+ return None
+ if len(blob) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"OOXML Equation.3 object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ if not blob.startswith(CFB_MAGIC):
+ return None
+
+ digest = hashlib.sha256(blob).digest()
+ if digest in self._cache:
+ return self._cache[digest]
+ if self.total_bytes + len(blob) > MAX_ASSET_TOTAL_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ "OOXML Equation.3 objects exceed "
+ f"max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
+ )
+
+ self.total_bytes += len(blob)
+ latex = decode_equation_object(blob)
+ self._cache[digest] = latex
+ return latex
diff --git a/mineru/model/flash/pptx/pptx_converter.py b/mineru/model/flash/pptx/pptx_converter.py
index 050ed47e..77ef983d 100644
--- a/mineru/model/flash/pptx/pptx_converter.py
+++ b/mineru/model/flash/pptx/pptx_converter.py
@@ -14,6 +14,10 @@ from pptx.oxml.text import CT_TextLineBreak
from mineru.model.flash.office.chart import extract_chart_html_from_ooxml
from mineru.model.flash.office.image import PIL_IMAGE_LOAD_ERRORS, is_vector_image, serialize_vector_image_with_placeholder
+from mineru.model.flash.office.ooxml_equation import (
+ OoxmlEquationDecoder,
+ is_equation_3_prog_id,
+)
from mineru.model.flash.docx.tools.math.omml import oMath2Latex
from mineru.model.office_stream import read_stream_bytes_from_start, rewind_stream
from mineru.model.flash.pptx.package_normalizer import normalize_pptx_package
@@ -107,6 +111,8 @@ class PptxConverter:
Optional[MSO_SHAPE_TYPE],
] = {}
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._mtef_warned_shapes: set[tuple[str, int | None]] = set()
def convert(
self,
@@ -135,6 +141,76 @@ class PptxConverter:
self._shape_type_cache = {}
self.file_stream = None
self.pptx_obj = None
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._mtef_warned_shapes = set()
+
+ @staticmethod
+ def _pptx_ole_format(shape: Any) -> Any | None:
+ """安全返回 PPTX graphic-frame 的 OLE format。"""
+
+ try:
+ return shape.ole_format
+ except (AttributeError, KeyError, ValueError):
+ return None
+
+ def _is_equation_ole_shape(self, shape: Any) -> bool:
+ """判断 PPTX OLE shape 的 ProgID 是否为 Equation.3。"""
+
+ ole_format = self._pptx_ole_format(shape)
+ return bool(
+ ole_format is not None
+ and is_equation_3_prog_id(getattr(ole_format, "prog_id", None))
+ )
+
+ def _decode_pptx_ole_equation(self, shape: Any) -> str | None:
+ """解码 PPTX 内嵌 Equation.3;链接、图标和坏对象返回空。"""
+
+ ole_format = self._pptx_ole_format(shape)
+ if ole_format is None:
+ return None
+ prog_id = getattr(ole_format, "prog_id", None)
+ if not is_equation_3_prog_id(prog_id):
+ return None
+ if bool(getattr(ole_format, "show_as_icon", False)):
+ return None
+ if self._safe_shape_type(shape) != MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT:
+ return None
+ try:
+ blob = ole_format.blob
+ except (AttributeError, KeyError, ValueError):
+ blob = None
+ latex = self._ooxml_equation_decoder.decode(
+ blob,
+ prog_id=prog_id,
+ )
+ if latex is not None:
+ return latex
+
+ warning_key = (
+ str(getattr(getattr(shape, "part", None), "partname", "")),
+ getattr(shape, "shape_id", None),
+ )
+ if warning_key not in self._mtef_warned_shapes:
+ self._mtef_warned_shapes.add(warning_key)
+ logger.warning(
+ "PPTX_MTEF_FALLBACK: part={!r}, shape_id={!r} has an invalid or unsupported Equation.3 object",
+ warning_key[0],
+ warning_key[1],
+ )
+ return None
+
+ def _pptx_ole_shape_omml(self, shape: Any) -> list[str]:
+ """提取 OLE 兼容容器内可表达的 OMML,作为 MTEF 的高优先级分支。"""
+
+ element = getattr(shape, "_element", None)
+ if element is None:
+ return []
+ equations: list[str] = []
+ for math in element.findall(f".//{{{OMML_NS}}}oMath"):
+ latex = self._convert_math_node_to_latex(math)
+ if latex:
+ equations.append(latex)
+ return equations
def _convert_package_bytes(self, file_bytes: bytes) -> None:
"""用独立字节流解析 PPTX 包,便于原始包失败后用规范化包重试。"""
@@ -308,13 +384,40 @@ class PptxConverter:
self.list_block_stack = []
try:
+ shape_type = self._safe_shape_type(shape)
+ if shape_type in {
+ MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT,
+ MSO_SHAPE_TYPE.LINKED_OLE_OBJECT,
+ }:
+ if self._is_equation_ole_shape(shape):
+ omml_equations = self._pptx_ole_shape_omml(shape)
+ if omml_equations:
+ self.cur_page.extend(
+ {
+ "type": BlockType.EQUATION,
+ "content": latex,
+ }
+ for latex in omml_equations
+ )
+ return shape_blocks
+ latex = self._decode_pptx_ole_equation(shape)
+ if latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.EQUATION,
+ "content": latex,
+ }
+ )
+ else:
+ self._handle_pictures(shape)
+ return shape_blocks
+
if shape.has_table:
self._handle_tables(shape)
if getattr(shape, "has_chart", False):
self._handle_chart(shape)
- shape_type = self._safe_shape_type(shape)
if shape_type == MSO_SHAPE_TYPE.PICTURE:
later_shapes = linear_shapes[shape_index + 1 :]
if not self._should_skip_picture(
@@ -561,6 +664,31 @@ class PptxConverter:
handle_notes_shape(grouped_shape)
return
+ if shape_type in {
+ MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT,
+ MSO_SHAPE_TYPE.LINKED_OLE_OBJECT,
+ }:
+ if self._is_equation_ole_shape(shape):
+ omml_equations = self._pptx_ole_shape_omml(shape)
+ if omml_equations:
+ self.cur_page.extend(
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": self.equation_bookends.format(EQ=latex),
+ }
+ for latex in omml_equations
+ )
+ return
+ latex = self._decode_pptx_ole_equation(shape)
+ if latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": self.equation_bookends.format(EQ=latex),
+ }
+ )
+ return
+
if self._should_skip_notes_shape(shape):
return
diff --git a/mineru/model/flash/xlsx/ooxml_ole.py b/mineru/model/flash/xlsx/ooxml_ole.py
new file mode 100644
index 00000000..866b9be7
--- /dev/null
+++ b/mineru/model/flash/xlsx/ooxml_ole.py
@@ -0,0 +1,483 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""读取 XLSX worksheet 中的 Equation.3 OLE 对象、anchor 与预览。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import posixpath
+import re
+from zipfile import ZipFile
+import xml.etree.ElementTree as ET
+
+from loguru import logger
+
+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_ENTRY_BYTES
+from mineru.model.flash.office.image import serialize_office_image
+from mineru.model.flash.office.ooxml_equation import (
+ OoxmlEquationDecoder,
+ is_equation_3_prog_id,
+)
+
+WORKBOOK_PART = "xl/workbook.xml"
+RELATIONSHIP_NS_SUFFIX = "/relationships"
+
+
+@dataclass(frozen=True, slots=True)
+class XlsxOleEquationArtifact:
+ """一个已绑定 worksheet anchor 的 Equation.3 公式或预览。"""
+
+ row: int | None
+ col: int | None
+ latex: str | None
+ preview_base64: str | None
+ order: int
+ shape_id: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class _Relationship:
+ """一个经过安全路径规范化的 OPC relationship。"""
+
+ target: str | None
+ reltype: str
+ external: bool
+
+
+def _local_name(value: object) -> str:
+ """返回 XML QName 或普通属性名的本地名称。"""
+
+ text = str(value)
+ return text.rsplit("}", 1)[-1].rsplit(":", 1)[-1]
+
+
+def _relationship_id(element: ET.Element) -> str | None:
+ """读取 r:id,避免把普通 shape id 误当 relationship。"""
+
+ for attribute, value in element.attrib.items():
+ if not attribute.endswith("}id"):
+ continue
+ namespace = attribute[1:].split("}", 1)[0] if attribute.startswith("{") else ""
+ if namespace.rstrip("/").endswith(RELATIONSHIP_NS_SUFFIX):
+ return value
+ return None
+
+
+def _relationship_embed_id(element: ET.Element) -> str | None:
+ """读取 DrawingML a:blip 的 r:embed relationship id。"""
+
+ for attribute, value in element.attrib.items():
+ if not attribute.endswith("}embed"):
+ continue
+ namespace = attribute[1:].split("}", 1)[0] if attribute.startswith("{") else ""
+ if namespace.rstrip("/").endswith(RELATIONSHIP_NS_SUFFIX):
+ return value
+ return None
+
+
+def _relationship_part_name(source_part: str) -> str:
+ """由源 part 生成同目录的 .rels part 名称。"""
+
+ directory, basename = posixpath.split(source_part)
+ return posixpath.join(directory, "_rels", f"{basename}.rels")
+
+
+def _resolve_internal_target(source_part: str, target: str) -> str | None:
+ """解析 OPC 内部 target,并拒绝反斜杠和越界路径。"""
+
+ candidate = target.strip()
+ if not candidate or "\\" in candidate:
+ return None
+ if candidate.startswith("/"):
+ normalized = posixpath.normpath(candidate.lstrip("/"))
+ else:
+ normalized = posixpath.normpath(
+ posixpath.join(posixpath.dirname(source_part), candidate)
+ )
+ if normalized in {"", "."} or normalized == ".." or normalized.startswith("../"):
+ return None
+ return normalized
+
+
+def _read_xml(source: ZipFile, part_name: str) -> ET.Element | None:
+ """尽力读取一个 XML part,坏可选 part 返回空。"""
+
+ if part_name not in source.namelist():
+ return None
+ try:
+ return ET.fromstring(source.read(part_name))
+ except (ET.ParseError, KeyError, OSError, RuntimeError):
+ return None
+
+
+def _relationships(source: ZipFile, source_part: str) -> dict[str, _Relationship]:
+ """读取源 part 的 relationships,并规范化所有内部 target。"""
+
+ root = _read_xml(source, _relationship_part_name(source_part))
+ if root is None:
+ return {}
+ result: dict[str, _Relationship] = {}
+ for element in root.iter():
+ if _local_name(element.tag) != "Relationship":
+ continue
+ relationship_id = element.get("Id")
+ if not relationship_id:
+ continue
+ external = (element.get("TargetMode") or "").casefold() == "external"
+ target = None
+ if not external:
+ target = _resolve_internal_target(
+ source_part,
+ element.get("Target") or "",
+ )
+ result[relationship_id] = _Relationship(
+ target=target,
+ reltype=element.get("Type") or "",
+ external=external,
+ )
+ return result
+
+
+def _read_member_bounded(source: ZipFile, part_name: str | None) -> bytes | None:
+ """按共享单 part 上限读取 XLSX ZIP 成员。"""
+
+ if part_name is None:
+ return None
+ try:
+ info = source.getinfo(part_name)
+ except KeyError:
+ return None
+ if info.file_size > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"XLSX embedded part exceeds max_entry_bytes={MAX_ENTRY_BYTES}: {part_name}"
+ )
+ payload = source.read(info)
+ if len(payload) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"XLSX embedded part exceeds max_entry_bytes={MAX_ENTRY_BYTES}: {part_name}"
+ )
+ return payload
+
+
+def workbook_sheet_parts(source: ZipFile) -> dict[str, str]:
+ """按 workbook sheet 名称建立 worksheet part 映射。"""
+
+ workbook = _read_xml(source, WORKBOOK_PART)
+ if workbook is None:
+ return {}
+ relationships = _relationships(source, WORKBOOK_PART)
+ result: dict[str, str] = {}
+ for sheet in workbook.iter():
+ if _local_name(sheet.tag) != "sheet":
+ continue
+ name = sheet.get("name")
+ relationship_id = _relationship_id(sheet)
+ relationship = relationships.get(relationship_id or "")
+ if (
+ not name
+ or relationship is None
+ or relationship.external
+ or relationship.target is None
+ or not relationship.reltype.rstrip("/").casefold().endswith("/worksheet")
+ ):
+ continue
+ result[name] = relationship.target
+ return result
+
+
+def package_has_sheet_ole_objects(
+ source: ZipFile,
+ worksheet_parts: dict[str, str],
+) -> bool:
+ """判断任一 worksheet 是否包含 openpyxl 无法安全忽略的 oleObjects。"""
+
+ for part_name in worksheet_parts.values():
+ root = _read_xml(source, part_name)
+ if root is None:
+ continue
+ if any(_local_name(node.tag) == "oleObjects" for node in root):
+ return True
+ return False
+
+
+def _child_int(element: ET.Element, name: str) -> int | None:
+ """读取指定本地名称的首个整数子元素。"""
+
+ for child in element.iter():
+ if _local_name(child.tag) != name or child.text is None:
+ continue
+ try:
+ return int(child.text.strip())
+ except ValueError:
+ return None
+ return None
+
+
+def _anchor_from_object_properties(ole_object: ET.Element) -> tuple[int, int] | None:
+ """优先从 objectPr/anchor/from 读取零基 row/col。"""
+
+ for object_properties in ole_object:
+ if _local_name(object_properties.tag) != "objectPr":
+ continue
+ for anchor in object_properties:
+ if _local_name(anchor.tag) != "anchor":
+ continue
+ from_marker = next(
+ (
+ child
+ for child in anchor
+ if _local_name(child.tag) == "from"
+ ),
+ None,
+ )
+ if from_marker is None:
+ continue
+ row = _child_int(from_marker, "row")
+ col = _child_int(from_marker, "col")
+ if row is not None and col is not None and row >= 0 and col >= 0:
+ return row, col
+ return None
+
+
+def _object_preview_relationship_id(ole_object: ET.Element) -> str | None:
+ """读取 objectPr 指向缓存预览图片的 relationship id。"""
+
+ for child in ole_object:
+ if _local_name(child.tag) == "objectPr":
+ return _relationship_id(child)
+ return None
+
+
+def _shape_id_matches(raw_id: str | None, shape_id: str) -> bool:
+ """兼容 DrawingML 数字 id 和 VML `_x0000_sNNN` 写法。"""
+
+ if raw_id is None:
+ return False
+ if raw_id == shape_id:
+ return True
+ match = re.search(r"(?:^|[_s])(\d+)$", raw_id)
+ return bool(match and match.group(1) == shape_id)
+
+
+def _drawing_shape_info(
+ source: ZipFile,
+ drawing_part: str,
+ shape_id: str,
+) -> tuple[tuple[int, int] | None, str | None]:
+ """从 DrawingML anchor 按 cNvPr id 查找坐标和预览 part。"""
+
+ root = _read_xml(source, drawing_part)
+ if root is None:
+ return None, None
+ relationships = _relationships(source, drawing_part)
+ for anchor in root:
+ if _local_name(anchor.tag) not in {"oneCellAnchor", "twoCellAnchor", "absoluteAnchor"}:
+ continue
+ if not any(
+ _local_name(node.tag) == "cNvPr"
+ and _shape_id_matches(node.get("id"), shape_id)
+ for node in anchor.iter()
+ ):
+ continue
+ from_marker = next(
+ (
+ child
+ for child in anchor
+ if _local_name(child.tag) == "from"
+ ),
+ None,
+ )
+ coordinate = None
+ if from_marker is not None:
+ row = _child_int(from_marker, "row")
+ col = _child_int(from_marker, "col")
+ if row is not None and col is not None and row >= 0 and col >= 0:
+ coordinate = (row, col)
+ for node in anchor.iter():
+ if _local_name(node.tag) != "blip":
+ continue
+ relationship = relationships.get(_relationship_embed_id(node) or "")
+ if relationship is not None and not relationship.external:
+ return coordinate, relationship.target
+ return coordinate, None
+ return None, None
+
+
+def _vml_shape_info(
+ source: ZipFile,
+ drawing_part: str,
+ shape_id: str,
+) -> tuple[tuple[int, int] | None, str | None]:
+ """从 VML ClientData/Anchor 按 shape id 查找坐标和预览 part。"""
+
+ root = _read_xml(source, drawing_part)
+ if root is None:
+ return None, None
+ relationships = _relationships(source, drawing_part)
+ for shape in root.iter():
+ if _local_name(shape.tag) != "shape" or not _shape_id_matches(
+ shape.get("id"),
+ shape_id,
+ ):
+ continue
+ coordinate = None
+ client_data = next(
+ (node for node in shape.iter() if _local_name(node.tag) == "ClientData"),
+ None,
+ )
+ if client_data is not None:
+ anchor_text = next(
+ (
+ node.text
+ for node in client_data
+ if _local_name(node.tag) == "Anchor" and node.text
+ ),
+ None,
+ )
+ if anchor_text:
+ try:
+ values = [int(value.strip()) for value in anchor_text.split(",")]
+ except ValueError:
+ values = []
+ if len(values) >= 4 and values[0] >= 0 and values[2] >= 0:
+ coordinate = (values[2], values[0])
+ if coordinate is None:
+ row = _child_int(client_data, "Row")
+ col = _child_int(client_data, "Column")
+ if row is not None and col is not None and row >= 0 and col >= 0:
+ coordinate = (row, col)
+ for node in shape.iter():
+ if _local_name(node.tag) != "imagedata":
+ continue
+ relationship = relationships.get(_relationship_id(node) or "")
+ if relationship is not None and not relationship.external:
+ return coordinate, relationship.target
+ return coordinate, None
+ return None, None
+
+
+def _shape_anchor_and_preview(
+ source: ZipFile,
+ worksheet_relationships: dict[str, _Relationship],
+ shape_id: str,
+) -> tuple[tuple[int, int] | None, str | None]:
+ """按 DrawingML 后 VML 的顺序恢复 shape anchor 与预览。"""
+
+ candidates = [
+ relationship
+ for relationship in worksheet_relationships.values()
+ if not relationship.external and relationship.target is not None
+ ]
+ for relationship in candidates:
+ reltype = relationship.reltype.rstrip("/").casefold()
+ if reltype.endswith("/drawing"):
+ coordinate, preview = _drawing_shape_info(
+ source,
+ relationship.target or "",
+ shape_id,
+ )
+ if coordinate is not None or preview is not None:
+ return coordinate, preview
+ for relationship in candidates:
+ reltype = relationship.reltype.rstrip("/").casefold()
+ if reltype.endswith("/vmldrawing"):
+ coordinate, preview = _vml_shape_info(
+ source,
+ relationship.target or "",
+ shape_id,
+ )
+ if coordinate is not None or preview is not None:
+ return coordinate, preview
+ return None, None
+
+
+def _preview_data_uri(source: ZipFile, part_name: str | None) -> str | None:
+ """读取并按现有 Office 图片策略序列化 OLE 缓存预览。"""
+
+ payload = _read_member_bounded(source, part_name)
+ if payload is None:
+ return None
+ return serialize_office_image(
+ payload,
+ part_name=part_name,
+ content_type=None,
+ )
+
+
+def read_sheet_equation_artifacts(
+ source: ZipFile,
+ worksheet_part: str,
+ decoder: OoxmlEquationDecoder,
+) -> list[XlsxOleEquationArtifact]:
+ """读取一个 worksheet 的 Equation.3 对象并绑定公式或图片回退。"""
+
+ worksheet = _read_xml(source, worksheet_part)
+ if worksheet is None:
+ return []
+ relationships = _relationships(source, worksheet_part)
+ artifacts: list[XlsxOleEquationArtifact] = []
+ for order, ole_object in enumerate(
+ node for node in worksheet.iter() if _local_name(node.tag) == "oleObject"
+ ):
+ prog_id = ole_object.get("progId") or ole_object.get("ProgID")
+ if not is_equation_3_prog_id(prog_id):
+ continue
+ relationship = relationships.get(_relationship_id(ole_object) or "")
+ is_linked = bool(ole_object.get("link")) or (
+ relationship is not None and relationship.external
+ )
+ draw_aspect = (ole_object.get("dvAspect") or "").casefold()
+ show_as_icon = "icon" in draw_aspect
+
+ latex = None
+ if (
+ not is_linked
+ and relationship is not None
+ and relationship.target is not None
+ and relationship.reltype.rstrip("/").casefold().endswith("/oleobject")
+ ):
+ blob = _read_member_bounded(source, relationship.target)
+ latex = decoder.decode(
+ blob,
+ prog_id=prog_id,
+ show_as_icon=show_as_icon,
+ )
+ if latex is None and not show_as_icon:
+ logger.warning(
+ "XLSX_MTEF_FALLBACK: worksheet={!r}, relationship={!r} has an invalid or unsupported Equation.3 object",
+ worksheet_part,
+ _relationship_id(ole_object),
+ )
+
+ coordinate = _anchor_from_object_properties(ole_object)
+ preview_relationship = relationships.get(
+ _object_preview_relationship_id(ole_object) or ""
+ )
+ preview_part = (
+ preview_relationship.target
+ if preview_relationship is not None and not preview_relationship.external
+ else None
+ )
+ shape_coordinate, shape_preview = _shape_anchor_and_preview(
+ source,
+ relationships,
+ ole_object.get("shapeId") or "",
+ )
+ coordinate = coordinate or shape_coordinate
+ preview_part = preview_part or shape_preview
+ preview = _preview_data_uri(source, preview_part)
+
+ if latex is None and preview is None:
+ continue
+ artifacts.append(
+ XlsxOleEquationArtifact(
+ row=coordinate[0] if coordinate is not None else None,
+ col=coordinate[1] if coordinate is not None else None,
+ latex=latex,
+ preview_base64=preview,
+ order=order,
+ shape_id=ole_object.get("shapeId"),
+ )
+ )
+ return artifacts
diff --git a/mineru/model/flash/xlsx/package_normalizer.py b/mineru/model/flash/xlsx/package_normalizer.py
index 06c2fd3a..40e742bb 100644
--- a/mineru/model/flash/xlsx/package_normalizer.py
+++ b/mineru/model/flash/xlsx/package_normalizer.py
@@ -57,6 +57,43 @@ def normalize_xlsx_package(file_bytes: bytes) -> bytes:
return _write_package(rewritten_members)
+def strip_xlsx_ole_objects_for_openpyxl(file_bytes: bytes) -> bytes:
+ """仅为 openpyxl 读取副本移除会被误判为列定义的 oleObjects。"""
+
+ try:
+ with ZipFile(BytesIO(file_bytes)) as source:
+ rewritten_members: list[tuple[ZipInfo, bytes]] = []
+ changed = False
+ for info in source.infolist():
+ member_data = source.read(info.filename)
+ if _is_worksheet_xml(info.filename):
+ normalized_data = _remove_worksheet_ole_objects(member_data)
+ changed = changed or normalized_data != member_data
+ member_data = normalized_data
+ rewritten_members.append((info, member_data))
+ except BadZipFile as exc:
+ raise ValueError("Invalid XLSX package: file is not a ZIP archive.") from exc
+ return _write_package(rewritten_members) if changed else file_bytes
+
+
+def _remove_worksheet_ole_objects(xml_bytes: bytes) -> bytes:
+ """删除 worksheet 的 oleObjects 容器,原始 ZIP 仍由公式解析器持有。"""
+
+ try:
+ root = ET.fromstring(xml_bytes)
+ except ET.ParseError:
+ return xml_bytes
+ changed = False
+ for child in list(root):
+ if child.tag.rsplit("}", 1)[-1] != "oleObjects":
+ continue
+ root.remove(child)
+ changed = True
+ if not changed:
+ return xml_bytes
+ return ET.tostring(root, encoding="utf-8", xml_declaration=True)
+
+
def _normalize_xlsx_member(member_name: str, member_data: bytes) -> bytes:
"""根据 XLSX 包内成员路径分发 XML 兼容性规范化逻辑。"""
if member_name == SHARED_STRINGS_PATH:
diff --git a/mineru/model/flash/xlsx/xlsx_converter.py b/mineru/model/flash/xlsx/xlsx_converter.py
index 5640ac25..88e0aa59 100644
--- a/mineru/model/flash/xlsx/xlsx_converter.py
+++ b/mineru/model/flash/xlsx/xlsx_converter.py
@@ -20,9 +20,19 @@ from pydantic import BaseModel, Field, NonNegativeInt, PositiveInt
from pydantic.dataclasses import dataclass
from mineru.model.flash.office.image import is_vector_image, serialize_vector_image_with_placeholder
+from mineru.model.flash.office.ooxml_equation import OoxmlEquationDecoder
from mineru.model.flash.docx.tools.math.omml import oMath2Latex
from mineru.model.office_stream import read_stream_bytes_from_start, rewind_stream
-from mineru.model.flash.xlsx.package_normalizer import normalize_xlsx_package
+from mineru.model.flash.xlsx.package_normalizer import (
+ normalize_xlsx_package,
+ strip_xlsx_ole_objects_for_openpyxl,
+)
+from mineru.model.flash.xlsx.ooxml_ole import (
+ XlsxOleEquationArtifact,
+ package_has_sheet_ole_objects,
+ read_sheet_equation_artifacts,
+ workbook_sheet_parts,
+)
from mineru.types import BlockType
from mineru.utils.pdf_reader import image_to_b64str
@@ -165,6 +175,14 @@ class XlsxConverter:
self.sheet_images = []
self.table_image_map = {}
self.math_map = {}
+ self._sheet_part_by_title: dict[str, str] = {}
+ self._ole_artifacts: list[XlsxOleEquationArtifact] = []
+ self._omml_shape_ids: set[str] = set()
+ self._omml_artifacts: list[tuple[int, int, str, int]] = []
+ self._suppressed_ole_previews: set[
+ tuple[tuple[int, int], str]
+ ] = set()
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
self._merged_cell_lookup_cache = {}
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
@@ -200,6 +218,12 @@ class XlsxConverter:
self.table_image_map = {}
self.cell_image_map = {}
self.math_map = {}
+ self._sheet_part_by_title = {}
+ self._ole_artifacts = []
+ self._omml_shape_ids = set()
+ self._omml_artifacts = []
+ self._suppressed_ole_previews = set()
+ self._ooxml_equation_decoder = OoxmlEquationDecoder()
self._merged_cell_lookup_cache = {}
def _convert_package_bytes(self, file_bytes: bytes) -> None:
@@ -211,14 +235,25 @@ class XlsxConverter:
self._reset_state()
try:
self.zf = zipfile.ZipFile(file_stream)
+ self._sheet_part_by_title = workbook_sheet_parts(self.zf)
except Exception as e:
logger.warning(f"Failed to open zip file: {e}")
self.zf = None
try:
- rewind_stream(file_stream)
+ workbook_stream: BinaryIO = file_stream
+ if self.zf is not None and package_has_sheet_ole_objects(
+ self.zf,
+ self._sheet_part_by_title,
+ ):
+ file_bytes = read_stream_bytes_from_start(file_stream)
+ workbook_stream = BytesIO(
+ strip_xlsx_ole_objects_for_openpyxl(file_bytes)
+ )
+ else:
+ rewind_stream(file_stream)
self.workbook = load_workbook(
- filename=file_stream,
+ filename=workbook_stream,
data_only=True,
rich_text=True,
)
@@ -287,16 +322,61 @@ class XlsxConverter:
if isinstance(sheet, Worksheet):
# Pre-calc maps
self.math_map = self._map_math_formulas_to_cells(sheet)
+ self._ole_artifacts = self._read_ole_equation_artifacts(sheet)
+ self._suppressed_ole_previews = {
+ ((artifact.row, artifact.col), artifact.preview_base64)
+ for artifact in self._ole_artifacts
+ if artifact.shape_id in self._omml_shape_ids
+ and artifact.row is not None
+ and artifact.col is not None
+ and artifact.preview_base64 is not None
+ }
+ self._ole_artifacts = [
+ artifact
+ for artifact in self._ole_artifacts
+ if artifact.shape_id not in self._omml_shape_ids
+ ]
+ for artifact in self._ole_artifacts:
+ if artifact.latex is None or artifact.row is None or artifact.col is None:
+ continue
+ self.math_map[(artifact.row, artifact.col)].append(artifact.latex)
self.sheet_images = self._collect_sheet_images(sheet)
+ ole_previews = self._suppressed_ole_previews | {
+ ((artifact.row, artifact.col), artifact.preview_base64)
+ for artifact in self._ole_artifacts
+ if artifact.row is not None
+ and artifact.col is not None
+ and artifact.preview_base64
+ }
+ self.sheet_images = [
+ image_info
+ for image_info in self.sheet_images
+ if (image_info.get("anchor"), image_info.get("base64"))
+ not in ole_previews
+ ]
self.table_image_map = collections.defaultdict(list)
for image_info in self.sheet_images:
anchor = image_info["anchor"]
if anchor[0] is None or anchor[1] is None:
continue
self.table_image_map[anchor].append(f'<img src="{image_info["base64"]}" />')
+ for artifact in self._ole_artifacts:
+ if (
+ artifact.latex is not None
+ or artifact.preview_base64 is None
+ or artifact.row is None
+ or artifact.col is None
+ ):
+ continue
+ self.table_image_map[(artifact.row, artifact.col)].append(
+ f'<img src="{artifact.preview_base64}" />'
+ )
used_cells, visual_artifacts = self._find_tables_in_sheet(sheet)
visual_artifacts.extend(self._find_charts_in_sheet(sheet))
+ visual_artifacts.extend(
+ self._find_equation_artifacts_in_sheet(used_cells)
+ )
for _, _, block in sorted(
visual_artifacts,
key=lambda item: (item[0][0], item[0][1], item[1]),
@@ -304,6 +384,69 @@ class XlsxConverter:
self.cur_page.append(block)
self._find_images_in_sheet(used_cells) # 提取图片
+ def _read_ole_equation_artifacts(
+ self,
+ sheet: Worksheet,
+ ) -> list[XlsxOleEquationArtifact]:
+ """从当前 worksheet part 读取 Equation.3 公式和预览。"""
+
+ if self.zf is None:
+ return []
+ worksheet_part = self._sheet_part_by_title.get(sheet.title)
+ if worksheet_part is None:
+ return []
+ return read_sheet_equation_artifacts(
+ self.zf,
+ worksheet_part,
+ self._ooxml_equation_decoder,
+ )
+
+ def _find_equation_artifacts_in_sheet(
+ self,
+ used_cells: set[tuple[int, int]],
+ ) -> list[tuple[tuple[int, int], int, dict]]:
+ """输出未被表格吸收的 OMML/MTEF 公式或缓存预览。"""
+
+ artifacts: list[tuple[tuple[int, int], int, dict]] = []
+ for row, col, latex, order in self._omml_artifacts:
+ if (row, col) in used_cells:
+ continue
+ artifacts.append(
+ (
+ (row, col),
+ 15_000 + order,
+ {
+ "type": BlockType.EQUATION,
+ "content": latex,
+ },
+ )
+ )
+ for artifact in self._ole_artifacts:
+ coordinate = (
+ artifact.row if artifact.row is not None else 10**9,
+ artifact.col if artifact.col is not None else 10**9,
+ )
+ if (
+ artifact.row is not None
+ and artifact.col is not None
+ and (artifact.row, artifact.col) in used_cells
+ ):
+ continue
+ block = None
+ if artifact.latex is not None:
+ block = {
+ "type": BlockType.EQUATION,
+ "content": artifact.latex,
+ }
+ elif artifact.preview_base64 is not None:
+ block = {
+ "type": BlockType.IMAGE,
+ "image_base64": artifact.preview_base64,
+ }
+ if block is not None:
+ artifacts.append((coordinate, 20_000 + artifact.order, block))
+ return artifacts
+
@staticmethod
def _serialize_sheet_image(image: XlsImage) -> str:
pil_image = Image.open(image.ref) # type: ignore[arg-type]
@@ -337,6 +480,8 @@ class XlsxConverter:
def _map_math_formulas_to_cells(self, sheet: Worksheet) -> dict:
"""Parse drawings to find math formulas and map them to cells."""
math_map = collections.defaultdict(list)
+ self._omml_shape_ids = set()
+ self._omml_artifacts = []
if not self.zf:
return math_map
@@ -402,6 +547,7 @@ class XlsxConverter:
# Usually in graphicalFrame -> graphic -> graphicData -> oMathPara
# But simpler to search descendant m:oMath
maths = anchor.findall(".//m:oMath", ns)
+ anchor_latex: list[str] = []
for math in maths:
# # Simple text extraction
# text = "".join(math.itertext())
@@ -413,6 +559,15 @@ class XlsxConverter:
latex = str(oMath2Latex(math)).strip()
if latex:
math_map[(r, c)].append(latex)
+ anchor_latex.append(latex)
+ self._omml_artifacts.append(
+ (r, c, latex, len(self._omml_artifacts))
+ )
+ if anchor_latex:
+ for node in anchor.findall(".//xdr:cNvPr", ns):
+ shape_id = node.get("id")
+ if shape_id:
+ self._omml_shape_ids.add(shape_id)
except Exception as e:
logger.warning(f"Error parsing math formulas: {e}")
@@ -446,7 +601,6 @@ class XlsxConverter:
used_cells = set()
visual_artifacts = []
if self.workbook is not None:
- content_layer = self._get_sheet_content_layer(sheet) # 检测工作表的可见性
tables = self._find_data_tables(sheet) # 检测工作表中的所有数据表格
for order, excel_table in enumerate(tables):
diff --git a/tests/unittest/_ooxml_mtef_test_utils.py b/tests/unittest/_ooxml_mtef_test_utils.py
new file mode 100644
index 00000000..303a7f52
--- /dev/null
+++ b/tests/unittest/_ooxml_mtef_test_utils.py
@@ -0,0 +1,732 @@
+"""构造带 Equation.3 OLE 对象的确定性 DOCX/PPTX/XLSX 测试包。"""
+
+from __future__ import annotations
+
+from io import BytesIO
+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
+
+from docx import Document
+from lxml import etree # type: ignore[reportAttributeAccessIssue]
+from openpyxl import Workbook
+from pptx import Presentation
+from pptx.util import Inches
+
+from _mtef_test_utils import _TINY_PNG, build_equation_object
+
+CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+PACKAGE_RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+M_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+V_NS = "urn:schemas-microsoft-com:vml"
+O_NS = "urn:schemas-microsoft-com:office:office"
+X_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
+XDR_NS = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
+A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+XVML_NS = "urn:schemas-microsoft-com:office:excel"
+OLE_REL_TYPE = f"{REL_NS}/oleObject"
+IMAGE_REL_TYPE = f"{REL_NS}/image"
+
+
+def _rewrite_zip(
+ package: bytes,
+ replacements: dict[str, bytes],
+ additions: dict[str, bytes],
+) -> bytes:
+ """在内存中替换或新增 OPC 成员并保持确定性压缩。"""
+
+ source_buffer = BytesIO(package)
+ output = BytesIO()
+ with ZipFile(source_buffer) as source, ZipFile(output, "w", ZIP_DEFLATED) as target:
+ existing = set()
+ for info in source.infolist():
+ existing.add(info.filename)
+ payload = replacements.get(info.filename, source.read(info.filename))
+ normalized = ZipInfo(info.filename, date_time=(1980, 1, 1, 0, 0, 0))
+ normalized.compress_type = ZIP_DEFLATED
+ normalized.external_attr = info.external_attr
+ target.writestr(normalized, payload)
+ for name, payload in additions.items():
+ if name in existing:
+ continue
+ info = ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
+ info.compress_type = ZIP_DEFLATED
+ target.writestr(info, payload)
+ return output.getvalue()
+
+
+def _content_types_with_ole(content_types: bytes) -> bytes:
+ """为 .bin Equation.3 persistence part 添加默认内容类型。"""
+
+ root = etree.fromstring(content_types)
+ if not any(
+ child.get("Extension", "").casefold() == "bin"
+ for child in root
+ ):
+ etree.SubElement(
+ root,
+ f"{{{CONTENT_TYPES_NS}}}Default",
+ Extension="bin",
+ ContentType="application/vnd.openxmlformats-officedocument.oleObject",
+ )
+ if not any(
+ child.get("Extension", "").casefold() == "png"
+ for child in root
+ ):
+ etree.SubElement(
+ root,
+ f"{{{CONTENT_TYPES_NS}}}Default",
+ Extension="png",
+ ContentType="image/png",
+ )
+ return etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True)
+
+
+def _relationships_root(payload: bytes | None) -> etree._Element:
+ """读取 relationships XML,不存在时创建空根。"""
+
+ if payload:
+ return etree.fromstring(payload)
+ return etree.Element(f"{{{PACKAGE_RELS_NS}}}Relationships")
+
+
+def _append_relationship(
+ root: etree._Element,
+ relationship_id: str,
+ reltype: str,
+ target: str,
+ *,
+ external: bool = False,
+) -> None:
+ """向 relationships 根追加一个确定性关系。"""
+
+ attributes = {
+ "Id": relationship_id,
+ "Type": reltype,
+ "Target": target,
+ }
+ if external:
+ attributes["TargetMode"] = "External"
+ etree.SubElement(
+ root,
+ f"{{{PACKAGE_RELS_NS}}}Relationship",
+ **attributes,
+ )
+
+
+def _word_ole_run(
+ object_index: int,
+ ole_relationship_id: str,
+ image_relationship_id: str,
+) -> etree._Element:
+ """构造包含 VML 预览和 o:OLEObject 的 Word run。"""
+
+ run = etree.Element(f"{{{W_NS}}}r")
+ object_element = etree.SubElement(run, f"{{{W_NS}}}object")
+ shape_id = f"_x0000_i{1025 + object_index}"
+ shape = etree.SubElement(
+ object_element,
+ f"{{{V_NS}}}shape",
+ id=shape_id,
+ style="width:120pt;height:36pt",
+ )
+ etree.SubElement(
+ shape,
+ f"{{{V_NS}}}imagedata",
+ {f"{{{REL_NS}}}id": image_relationship_id},
+ )
+ etree.SubElement(
+ object_element,
+ f"{{{O_NS}}}OLEObject",
+ {
+ "Type": "Embed",
+ "ProgID": "Equation.3",
+ "ShapeID": shape_id,
+ "DrawAspect": "Content",
+ "ObjectID": f"_{1200000000 + object_index}",
+ f"{{{REL_NS}}}id": ole_relationship_id,
+ },
+ )
+ return run
+
+
+def _replace_word_placeholder(
+ root: etree._Element,
+ placeholder: str,
+ replacement: etree._Element,
+) -> None:
+ """用公式 run 或 AlternateContent 替换指定占位 run。"""
+
+ text_node = next(
+ (
+ node
+ for node in root.findall(f".//{{{W_NS}}}t")
+ if node.text == placeholder
+ ),
+ None,
+ )
+ if text_node is None:
+ raise ValueError(f"DOCX fixture placeholder is missing: {placeholder}")
+ run = text_node.getparent()
+ parent = run.getparent()
+ parent.replace(run, replacement)
+
+
+def _patch_word_part(
+ source: ZipFile,
+ part_name: str,
+ formulas: list[tuple[str, bytes, bool]],
+ additions: dict[str, bytes],
+) -> tuple[bytes, bytes]:
+ """向一个 Word XML part 及其 relationships 注入多个 Equation.3 对象。"""
+
+ root = etree.fromstring(source.read(part_name))
+ directory, basename = part_name.rsplit("/", 1)
+ part_token = basename.rsplit(".", 1)[0]
+ rels_name = f"{directory}/_rels/{basename}.rels"
+ rels = _relationships_root(source.read(rels_name) if rels_name in source.namelist() else None)
+ for index, (placeholder, mtef, alternate_omml) in enumerate(formulas, start=1):
+ ole_rid = f"rIdMtefOle{index}"
+ image_rid = f"rIdMtefImage{index}"
+ object_part = f"word/embeddings/oleObjectMtef_{part_token}_{index}.bin"
+ image_part = f"word/media/equationMtef_{part_token}_{index}.png"
+ _append_relationship(
+ rels,
+ ole_rid,
+ OLE_REL_TYPE,
+ f"../embeddings/{object_part.rsplit('/', 1)[-1]}"
+ if directory != "word"
+ else f"embeddings/{object_part.rsplit('/', 1)[-1]}",
+ )
+ _append_relationship(
+ rels,
+ image_rid,
+ IMAGE_REL_TYPE,
+ f"../media/{image_part.rsplit('/', 1)[-1]}"
+ if directory != "word"
+ else f"media/{image_part.rsplit('/', 1)[-1]}",
+ )
+ additions[object_part] = build_equation_object(mtef)
+ additions[image_part] = _TINY_PNG
+ ole_run = _word_ole_run(index, ole_rid, image_rid)
+ if alternate_omml:
+ alternate = etree.Element(f"{{{MC_NS}}}AlternateContent")
+ choice = etree.SubElement(
+ alternate,
+ f"{{{MC_NS}}}Choice",
+ Requires="m",
+ )
+ math = etree.SubElement(choice, f"{{{M_NS}}}oMath")
+ math_run = etree.SubElement(math, f"{{{M_NS}}}r")
+ etree.SubElement(math_run, f"{{{M_NS}}}t").text = "z"
+ fallback = etree.SubElement(alternate, f"{{{MC_NS}}}Fallback")
+ fallback.append(ole_run)
+ replacement = alternate
+ else:
+ replacement = ole_run
+ _replace_word_placeholder(root, placeholder, replacement)
+ return (
+ etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True),
+ etree.tostring(rels, xml_declaration=True, encoding="UTF-8", standalone=True),
+ )
+
+
+def _wrap_word_equations_in_textboxes(document_xml: bytes) -> bytes:
+ """把正文 Equation.3 run 包入 VML textbox,验证文本框独立遍历。"""
+
+ root = etree.fromstring(document_xml)
+ for index, ole_object in enumerate(
+ root.findall(f".//{{{O_NS}}}OLEObject"),
+ start=1,
+ ):
+ object_element = ole_object.getparent()
+ equation_run = object_element.getparent()
+ parent = equation_run.getparent()
+ outer_run = etree.Element(f"{{{W_NS}}}r")
+ pict = etree.SubElement(outer_run, f"{{{W_NS}}}pict")
+ shape = etree.SubElement(
+ pict,
+ f"{{{V_NS}}}shape",
+ id=f"_x0000_txbx{index}",
+ )
+ textbox = etree.SubElement(shape, f"{{{V_NS}}}textbox")
+ content = etree.SubElement(textbox, f"{{{W_NS}}}txbxContent")
+ paragraph = etree.SubElement(content, f"{{{W_NS}}}p")
+ parent.replace(equation_run, outer_run)
+ paragraph.append(equation_run)
+ return etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+
+
+def _set_word_equations_as_icons(document_xml: bytes) -> bytes:
+ """把 Word OLE 对象切换为 DrawAspect=Icon。"""
+
+ root = etree.fromstring(document_xml)
+ for ole_object in root.findall(f".//{{{O_NS}}}OLEObject"):
+ ole_object.set("DrawAspect", "Icon")
+ return etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+
+
+def build_equation_docx(
+ formulas: list[bytes],
+ *,
+ inline: bool = False,
+ table: bool = False,
+ header_footer: bool = False,
+ alternate_omml: bool = False,
+ textbox: bool = False,
+ show_as_icon: bool = False,
+) -> bytes:
+ """构造正文、表格或页眉页脚中含 Equation.3 对象的 DOCX。"""
+
+ document = Document()
+ target_part = "word/document.xml"
+ placeholders: list[str] = []
+ if table:
+ cell = document.add_table(rows=1, cols=1).cell(0, 0)
+ for index in range(len(formulas)):
+ placeholder = f"[[MTEF_{index}]]"
+ cell.paragraphs[0].add_run(placeholder)
+ placeholders.append(placeholder)
+ elif header_footer:
+ header = document.sections[0].header
+ footer = document.sections[0].footer
+ for index in range(len(formulas)):
+ placeholder = f"[[MTEF_{index}]]"
+ target = header if index % 2 == 0 else footer
+ target.paragraphs[0].add_run(placeholder)
+ placeholders.append(placeholder)
+ target_part = "word/header1.xml"
+ else:
+ for index in range(len(formulas)):
+ paragraph = document.add_paragraph()
+ if inline:
+ paragraph.add_run("before ")
+ placeholder = f"[[MTEF_{index}]]"
+ paragraph.add_run(placeholder)
+ placeholders.append(placeholder)
+ if inline:
+ paragraph.add_run(" after")
+
+ buffer = BytesIO()
+ document.save(buffer)
+ package = buffer.getvalue()
+ replacements: dict[str, bytes] = {}
+ additions: dict[str, bytes] = {}
+ with ZipFile(BytesIO(package)) as source:
+ if header_footer:
+ header_parts = sorted(
+ name
+ for name in source.namelist()
+ if name.startswith("word/header") and name.endswith(".xml")
+ )
+ footer_parts = sorted(
+ name
+ for name in source.namelist()
+ if name.startswith("word/footer") and name.endswith(".xml")
+ )
+ assignments: dict[str, list[tuple[str, bytes, bool]]] = {}
+ for index, (placeholder, mtef) in enumerate(zip(placeholders, formulas, strict=True)):
+ part = header_parts[0] if index % 2 == 0 else footer_parts[0]
+ assignments.setdefault(part, []).append((placeholder, mtef, False))
+ for part, entries in assignments.items():
+ xml, rels = _patch_word_part(source, part, entries, additions)
+ replacements[part] = xml
+ directory, basename = part.rsplit("/", 1)
+ rels_name = f"{directory}/_rels/{basename}.rels"
+ if rels_name in source.namelist():
+ replacements[rels_name] = rels
+ else:
+ additions[rels_name] = rels
+ else:
+ entries = [
+ (
+ placeholder,
+ mtef,
+ alternate_omml and index == 0,
+ )
+ for index, (placeholder, mtef) in enumerate(
+ zip(placeholders, formulas, strict=True)
+ )
+ ]
+ xml, rels = _patch_word_part(source, target_part, entries, additions)
+ if textbox:
+ xml = _wrap_word_equations_in_textboxes(xml)
+ if show_as_icon:
+ xml = _set_word_equations_as_icons(xml)
+ replacements[target_part] = xml
+ replacements["word/_rels/document.xml.rels"] = rels
+ replacements["[Content_Types].xml"] = _content_types_with_ole(
+ source.read("[Content_Types].xml")
+ )
+ return _rewrite_zip(package, replacements, additions)
+
+
+def build_equation_pptx(
+ formulas: list[bytes],
+ *,
+ show_as_icon: bool = False,
+ notes: bool = False,
+ alternate_omml: bool = False,
+) -> bytes:
+ """使用 python-pptx 生成每页一个 Equation.3 OLE 对象的 PPTX。"""
+
+ presentation = Presentation()
+ presentation.slides.add_slide(presentation.slide_layouts[6])
+ for index, mtef in enumerate(formulas):
+ slide = (
+ presentation.slides[0]
+ if index == 0
+ else presentation.slides.add_slide(presentation.slide_layouts[6])
+ )
+ slide.shapes.add_ole_object(
+ BytesIO(build_equation_object(mtef)),
+ "Equation.3",
+ Inches(1),
+ Inches(1),
+ Inches(4),
+ Inches(1.5),
+ icon_file=BytesIO(_TINY_PNG),
+ )
+ if notes:
+ _ = slide.notes_slide
+ buffer = BytesIO()
+ presentation.save(buffer)
+ package = buffer.getvalue()
+ if notes:
+ return _move_pptx_equations_to_notes(
+ package,
+ show_as_icon=show_as_icon,
+ )
+ if show_as_icon:
+ return package
+
+ replacements: dict[str, bytes] = {}
+ with ZipFile(BytesIO(package)) as source:
+ for name in source.namelist():
+ if not name.startswith("ppt/slides/slide") or not name.endswith(".xml"):
+ continue
+ root = etree.fromstring(source.read(name))
+ changed = False
+ for ole_object in root.xpath(".//*[local-name()='oleObj']"):
+ ole_object.set("showAsIcon", "0")
+ changed = True
+ if alternate_omml:
+ graphic_data = ole_object.getparent()
+ math = etree.SubElement(graphic_data, f"{{{M_NS}}}oMath")
+ math_run = etree.SubElement(math, f"{{{M_NS}}}r")
+ etree.SubElement(math_run, f"{{{M_NS}}}t").text = "z"
+ if changed:
+ replacements[name] = etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ return _rewrite_zip(package, replacements, {})
+
+
+def _move_pptx_equations_to_notes(
+ package: bytes,
+ *,
+ show_as_icon: bool,
+) -> bytes:
+ """把每页 OLE graphicFrame 移到对应 notesSlide 并重建关系。"""
+
+ replacements: dict[str, bytes] = {}
+ with ZipFile(BytesIO(package)) as source:
+ slide_parts = sorted(
+ name
+ for name in source.namelist()
+ if name.startswith("ppt/slides/slide") and name.endswith(".xml")
+ )
+ for index, slide_part in enumerate(slide_parts, start=1):
+ notes_part = f"ppt/notesSlides/notesSlide{index}.xml"
+ if notes_part not in source.namelist():
+ continue
+ slide_root = etree.fromstring(source.read(slide_part))
+ graphic_frame = next(
+ iter(slide_root.xpath(".//*[local-name()='graphicFrame'][.//*[local-name()='oleObj']]")),
+ None,
+ )
+ if graphic_frame is None:
+ continue
+ for ole_object in graphic_frame.xpath(".//*[local-name()='oleObj']"):
+ ole_object.set("showAsIcon", "1" if show_as_icon else "0")
+
+ slide_rels_name = f"ppt/slides/_rels/slide{index}.xml.rels"
+ slide_rels = _relationships_root(source.read(slide_rels_name))
+ referenced_ids = {
+ value
+ for node in graphic_frame.iter()
+ for attribute, value in node.attrib.items()
+ if attribute in {f"{{{REL_NS}}}id", f"{{{REL_NS}}}embed"}
+ }
+ copied_relationships = [
+ relationship
+ for relationship in slide_rels
+ if relationship.get("Id") in referenced_ids
+ ]
+ notes_rels_name = f"ppt/notesSlides/_rels/notesSlide{index}.xml.rels"
+ notes_rels = _relationships_root(source.read(notes_rels_name))
+ id_mapping: dict[str, str] = {}
+ for relation_index, relationship in enumerate(copied_relationships, start=1):
+ old_id = relationship.get("Id") or ""
+ new_id = f"rIdMtef{relation_index}"
+ id_mapping[old_id] = new_id
+ _append_relationship(
+ notes_rels,
+ new_id,
+ relationship.get("Type") or "",
+ relationship.get("Target") or "",
+ )
+ for node in graphic_frame.iter():
+ for attribute in (f"{{{REL_NS}}}id", f"{{{REL_NS}}}embed"):
+ old_id = node.get(attribute)
+ if old_id in id_mapping:
+ node.set(attribute, id_mapping[old_id])
+
+ graphic_frame.getparent().remove(graphic_frame)
+ notes_root = etree.fromstring(source.read(notes_part))
+ shape_tree = next(
+ iter(notes_root.xpath(".//*[local-name()='spTree']")),
+ None,
+ )
+ if shape_tree is None:
+ continue
+ shape_tree.append(graphic_frame)
+ replacements[slide_part] = etree.tostring(
+ slide_root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ replacements[notes_part] = etree.tostring(
+ notes_root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ replacements[notes_rels_name] = etree.tostring(
+ notes_rels,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ return _rewrite_zip(package, replacements, {})
+
+
+def _xlsx_anchor(
+ ole_object: etree._Element,
+ row: int,
+ col: int,
+ preview_relationship_id: str,
+) -> None:
+ """向 x:oleObject 写入 objectPr/anchor/from/to。"""
+
+ object_properties = etree.SubElement(
+ ole_object,
+ f"{{{X_NS}}}objectPr",
+ {f"{{{REL_NS}}}id": preview_relationship_id},
+ )
+ anchor = etree.SubElement(object_properties, f"{{{X_NS}}}anchor")
+ from_marker = etree.SubElement(anchor, f"{{{X_NS}}}from")
+ etree.SubElement(from_marker, f"{{{X_NS}}}col").text = str(col)
+ etree.SubElement(from_marker, f"{{{X_NS}}}row").text = str(row)
+ to_marker = etree.SubElement(anchor, f"{{{X_NS}}}to")
+ etree.SubElement(to_marker, f"{{{X_NS}}}col").text = str(col + 2)
+ etree.SubElement(to_marker, f"{{{X_NS}}}row").text = str(row + 3)
+
+
+def _xlsx_drawing_parts(
+ shape_id: int,
+ row: int,
+ col: int,
+ *,
+ omml: bool = False,
+) -> tuple[bytes, bytes]:
+ """构造按 cNvPr id 绑定预览的 DrawingML part 及 relationships。"""
+
+ root = etree.Element(f"{{{XDR_NS}}}wsDr", nsmap={"xdr": XDR_NS, "a": A_NS, "r": REL_NS})
+ anchor = etree.SubElement(root, f"{{{XDR_NS}}}twoCellAnchor")
+ from_marker = etree.SubElement(anchor, f"{{{XDR_NS}}}from")
+ etree.SubElement(from_marker, f"{{{XDR_NS}}}col").text = str(col)
+ etree.SubElement(from_marker, f"{{{XDR_NS}}}row").text = str(row)
+ picture = etree.SubElement(anchor, f"{{{XDR_NS}}}pic")
+ non_visual = etree.SubElement(picture, f"{{{XDR_NS}}}nvPicPr")
+ etree.SubElement(
+ non_visual,
+ f"{{{XDR_NS}}}cNvPr",
+ id=str(shape_id),
+ name="Equation preview",
+ )
+ fill = etree.SubElement(picture, f"{{{XDR_NS}}}blipFill")
+ etree.SubElement(fill, f"{{{A_NS}}}blip", {f"{{{REL_NS}}}embed": "rIdPreview"})
+ if omml:
+ math = etree.SubElement(anchor, f"{{{M_NS}}}oMath")
+ math_run = etree.SubElement(math, f"{{{M_NS}}}r")
+ etree.SubElement(math_run, f"{{{M_NS}}}t").text = "z"
+ rels = _relationships_root(None)
+ _append_relationship(rels, "rIdPreview", IMAGE_REL_TYPE, "../media/equationMtef.png")
+ return (
+ etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True),
+ etree.tostring(rels, xml_declaration=True, encoding="UTF-8", standalone=True),
+ )
+
+
+def _xlsx_vml_parts(
+ shape_id: int,
+ row: int,
+ col: int,
+) -> tuple[bytes, bytes]:
+ """构造按 `_x0000_sNNN` 绑定预览的 VML drawing 与 relationships。"""
+
+ root = etree.Element("xml", nsmap={"v": V_NS, "x": XVML_NS, "r": REL_NS})
+ shape = etree.SubElement(root, f"{{{V_NS}}}shape", id=f"_x0000_s{shape_id}")
+ etree.SubElement(shape, f"{{{V_NS}}}imagedata", {f"{{{REL_NS}}}id": "rIdPreview"})
+ client_data = etree.SubElement(shape, f"{{{XVML_NS}}}ClientData")
+ etree.SubElement(client_data, f"{{{XVML_NS}}}Anchor").text = (
+ f"{col}, 0, {row}, 0, {col + 2}, 0, {row + 3}, 0"
+ )
+ rels = _relationships_root(None)
+ _append_relationship(rels, "rIdPreview", IMAGE_REL_TYPE, "../media/equationMtef.png")
+ return (
+ etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True),
+ etree.tostring(rels, xml_declaration=True, encoding="UTF-8", standalone=True),
+ )
+
+
+def build_equation_xlsx(
+ formulas: list[bytes],
+ *,
+ anchor_mode: str = "objectPr",
+ cell_value: str | None = None,
+ hidden: bool = False,
+ linked: bool = False,
+ show_as_icon: bool = False,
+ alternate_omml: bool = False,
+) -> bytes:
+ """构造使用 objectPr、DrawingML 或 VML anchor 的 Equation.3 XLSX。"""
+
+ workbook = Workbook()
+ worksheet = workbook.active
+ if worksheet is None:
+ raise ValueError("XLSX fixture workbook has no active sheet")
+ worksheet.title = "Equations"
+ if cell_value is not None:
+ worksheet.cell(row=1, column=1, value=cell_value)
+ if hidden:
+ worksheet.sheet_state = "hidden"
+ workbook.create_sheet("Visible")
+ buffer = BytesIO()
+ workbook.save(buffer)
+ package = buffer.getvalue()
+
+ replacements: dict[str, bytes] = {}
+ additions: dict[str, bytes] = {}
+ with ZipFile(BytesIO(package)) as source:
+ worksheet_part = "xl/worksheets/sheet1.xml"
+ root = etree.fromstring(source.read(worksheet_part))
+ ole_objects = etree.SubElement(root, f"{{{X_NS}}}oleObjects")
+ rels_name = "xl/worksheets/_rels/sheet1.xml.rels"
+ rels = _relationships_root(source.read(rels_name) if rels_name in source.namelist() else None)
+ for index, mtef in enumerate(formulas, start=1):
+ shape_id = 1024 + index
+ ole_rid = f"rIdMtefOle{index}"
+ preview_rid = f"rIdMtefPreview{index}"
+ ole_object = etree.SubElement(
+ ole_objects,
+ f"{{{X_NS}}}oleObject",
+ {
+ "progId": "Equation.3",
+ "shapeId": str(shape_id),
+ f"{{{REL_NS}}}id": ole_rid,
+ },
+ )
+ if show_as_icon:
+ ole_object.set("dvAspect", "DVASPECT_ICON")
+ if anchor_mode == "objectPr":
+ _xlsx_anchor(ole_object, index - 1, 0, preview_rid)
+ _append_relationship(
+ rels,
+ preview_rid,
+ IMAGE_REL_TYPE,
+ "../media/equationMtef.png",
+ )
+ _append_relationship(
+ rels,
+ ole_rid,
+ OLE_REL_TYPE,
+ (
+ "https://example.test/equation.bin"
+ if linked
+ else f"../embeddings/oleObjectMtef{index}.bin"
+ ),
+ external=linked,
+ )
+ if linked:
+ ole_object.set("link", "https://example.test/equation.bin")
+ else:
+ additions[f"xl/embeddings/oleObjectMtef{index}.bin"] = build_equation_object(mtef)
+
+ if anchor_mode == "drawing":
+ etree.SubElement(root, f"{{{X_NS}}}drawing", {f"{{{REL_NS}}}id": "rIdMtefDrawing"})
+ _append_relationship(
+ rels,
+ "rIdMtefDrawing",
+ f"{REL_NS}/drawing",
+ "../drawings/drawingMtef.xml",
+ )
+ drawing, drawing_rels = _xlsx_drawing_parts(
+ 1025,
+ 0,
+ 0,
+ omml=alternate_omml,
+ )
+ additions["xl/drawings/drawingMtef.xml"] = drawing
+ additions["xl/drawings/_rels/drawingMtef.xml.rels"] = drawing_rels
+ elif anchor_mode == "vml":
+ etree.SubElement(root, f"{{{X_NS}}}legacyDrawing", {f"{{{REL_NS}}}id": "rIdMtefVml"})
+ _append_relationship(
+ rels,
+ "rIdMtefVml",
+ f"{REL_NS}/vmlDrawing",
+ "../drawings/vmlDrawingMtef.vml",
+ )
+ drawing, drawing_rels = _xlsx_vml_parts(1025, 0, 0)
+ additions["xl/drawings/vmlDrawingMtef.vml"] = drawing
+ additions["xl/drawings/_rels/vmlDrawingMtef.vml.rels"] = drawing_rels
+ elif anchor_mode not in {"objectPr", "none"}:
+ raise ValueError(f"unsupported XLSX equation anchor fixture: {anchor_mode}")
+
+ additions["xl/media/equationMtef.png"] = _TINY_PNG
+ replacements[worksheet_part] = etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ rels_payload = etree.tostring(
+ rels,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ )
+ if rels_name in source.namelist():
+ replacements[rels_name] = rels_payload
+ else:
+ additions[rels_name] = rels_payload
+ replacements["[Content_Types].xml"] = _content_types_with_ole(
+ source.read("[Content_Types].xml")
+ )
+ return _rewrite_zip(package, replacements, additions)
diff --git a/tests/unittest/test_flash_ooxml_mtef.py b/tests/unittest/test_flash_ooxml_mtef.py
new file mode 100644
index 00000000..4d7144c5
--- /dev/null
+++ b/tests/unittest/test_flash_ooxml_mtef.py
@@ -0,0 +1,346 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+from io import BytesIO
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.model.flash import DocxModel, PptxModel, XlsxModel
+from mineru.model.flash.docx.docx_converter import DocxConverter
+from mineru.model.flash.legacy_office import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_ASSET_TOTAL_BYTES
+from mineru.model.flash.office.ooxml_equation import OoxmlEquationDecoder
+from mineru.model.flash.pptx.pptx_converter import PptxConverter
+from mineru.model.flash.xlsx.xlsx_converter import XlsxConverter
+from mineru.types import BlockType, MiddleJson, ModelJson
+
+from _mtef_test_utils import build_equation_object, formula_corpus
+from _ooxml_mtef_test_utils import (
+ build_equation_docx,
+ build_equation_pptx,
+ build_equation_xlsx,
+)
+
+
+def _equation_contents(pages: list[list[dict]]) -> list[str]:
+ """按分页顺序返回所有独立 equation block 内容。"""
+
+ return [
+ block["content"]
+ for page in pages
+ for block in page
+ if block.get("type") == BlockType.EQUATION
+ ]
+
+
+def test_ooxml_equation_decoder_enforces_scope_icon_and_total_budget() -> None:
+ """验证共享入口只接受 Equation.3、非图标及预算内的 CFB。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+ blob = build_equation_object(mtef)
+ decoder = OoxmlEquationDecoder()
+
+ assert decoder.decode(blob, prog_id="Equation.3") == expected
+ assert decoder.decode(blob, prog_id="equation.3") == expected
+ assert decoder.decode(blob, prog_id="Equation.DSMT4") is None
+ assert decoder.decode(blob, prog_id="Equation.3", show_as_icon=True) is None
+ assert decoder.decode(b"not CFB", prog_id="Equation.3") is None
+
+ exhausted = OoxmlEquationDecoder(total_bytes=MAX_ASSET_TOTAL_BYTES)
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):
+ exhausted.decode(blob, prog_id="Equation.3")
+
+
+def test_docx_pptx_xlsx_decode_the_full_mtef_corpus_exactly() -> None:
+ """验证三种 OOXML Model 对11类MTEF公式给出完全一致的LaTeX。"""
+
+ corpus = formula_corpus()
+ formulas = [mtef for _name, mtef, _expected in corpus]
+ expected = [value for _name, _mtef, value in corpus]
+
+ docx_pages = DocxModel().predict(BytesIO(build_equation_docx(formulas)))
+ pptx_pages = PptxModel().predict(BytesIO(build_equation_pptx(formulas)))
+ xlsx_pages = XlsxModel().predict(BytesIO(build_equation_xlsx(formulas)))
+
+ assert _equation_contents(docx_pages) == expected
+ assert _equation_contents(pptx_pages) == expected
+ assert _equation_contents(xlsx_pages) == expected
+ assert len(pptx_pages) == len(corpus)
+
+
+def test_docx_mtef_flows_inline_table_header_footer_and_omml_precedence() -> None:
+ """验证 DOCX 行内、表格、页眉页脚和 OMML 优先级语义。"""
+
+ corpus = formula_corpus()
+ first = corpus[0]
+ second = corpus[1]
+
+ inline = DocxModel().predict(
+ BytesIO(build_equation_docx([first[1]], inline=True))
+ )
+ table = DocxModel().predict(
+ BytesIO(build_equation_docx([first[1]], table=True))
+ )
+ header_footer = DocxModel().predict(
+ BytesIO(build_equation_docx([first[1], second[1]], header_footer=True))
+ )
+ alternate = DocxModel().predict(
+ BytesIO(build_equation_docx([first[1]], alternate_omml=True))
+ )
+ textbox = DocxModel().predict(
+ BytesIO(build_equation_docx([first[1]], textbox=True))
+ )
+
+ assert inline == [[{"type": BlockType.TEXT, "content": "before <eq>x+y</eq> after"}]]
+ assert table[0][0]["type"] == BlockType.TABLE
+ assert "<eq>x+y</eq>" in table[0][0]["content"]
+ assert header_footer == [
+ [
+ {"type": BlockType.HEADER, "content": "<eq>x+y</eq>"},
+ {
+ "type": BlockType.FOOTER,
+ "content": r"<eq>\frac{a+b}{c}</eq>",
+ },
+ ]
+ ]
+ assert alternate == [[{"type": BlockType.EQUATION, "content": "z"}]]
+ assert textbox == [[{"type": BlockType.EQUATION, "content": "x+y"}]]
+
+
+def test_omml_precedes_mtef_and_preview_for_the_same_ooxml_object() -> None:
+ """验证三种 OOXML 兼容对象只输出 OMML 分支且不重复预览。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+ cases = [
+ (
+ DocxModel(),
+ build_equation_docx([b"invalid MTEF"], alternate_omml=True),
+ ),
+ (
+ PptxModel(),
+ build_equation_pptx([mtef], alternate_omml=True),
+ ),
+ (
+ XlsxModel(),
+ build_equation_xlsx(
+ [mtef],
+ anchor_mode="drawing",
+ alternate_omml=True,
+ ),
+ ),
+ ]
+
+ for model, file_bytes in cases:
+ assert model.predict(BytesIO(file_bytes)) == [
+ [{"type": BlockType.EQUATION, "content": "z"}]
+ ]
+
+
+ ("model", "valid_file", "invalid_file"),
+ [
+ (
+ DocxModel(),
+ lambda mtef: build_equation_docx([mtef]),
+ lambda: build_equation_docx([b"invalid MTEF"]),
+ ),
+ (
+ PptxModel(),
+ lambda mtef: build_equation_pptx([mtef]),
+ lambda: build_equation_pptx([b"invalid MTEF"]),
+ ),
+ (
+ XlsxModel(),
+ lambda mtef: build_equation_xlsx([mtef]),
+ lambda: build_equation_xlsx([b"invalid MTEF"]),
+ ),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_valid_ooxml_mtef_suppresses_preview_and_invalid_keeps_it(
+ model: Any,
+ valid_file: Callable[[bytes], bytes],
+ invalid_file: Callable[[], bytes],
+) -> None:
+ """验证有效原生公式胜出,坏 MTEF 在三种格式均保留缓存图。"""
+
+ _name, mtef, expected = formula_corpus()[1]
+ valid_pages = model.predict(BytesIO(valid_file(mtef)))
+ invalid_pages = model.predict(BytesIO(invalid_file()))
+
+ assert valid_pages == [[{"type": BlockType.EQUATION, "content": expected}]]
+ assert invalid_pages[0][0]["type"] == BlockType.IMAGE
+ assert invalid_pages[0][0]["image_base64"].startswith("data:image/")
+
+
[email protected]("file_suffix", ["docx", "pptx", "xlsx"])
+def test_ooxml_icon_mode_preserves_preview_instead_of_expanding_formula(
+ file_suffix: str,
+) -> None:
+ """验证 DrawAspect/showAsIcon/dvAspect 图标模式不展开公式。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+ builders = {
+ "docx": build_equation_docx,
+ "pptx": build_equation_pptx,
+ "xlsx": build_equation_xlsx,
+ }
+ models = {
+ "docx": DocxModel(),
+ "pptx": PptxModel(),
+ "xlsx": XlsxModel(),
+ }
+
+ pages = models[file_suffix].predict(
+ BytesIO(builders[file_suffix]([mtef], show_as_icon=True))
+ )
+
+ assert pages[0][0]["type"] == BlockType.IMAGE
+ assert all(block["type"] != BlockType.EQUATION for block in pages[0])
+
+
+def test_pptx_notes_equation_is_appended_as_page_footnote() -> None:
+ """验证 notesSlide 中的 Equation.3 公式精确归属当前幻灯片。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+
+ pages = PptxModel().predict(
+ BytesIO(build_equation_pptx([mtef], notes=True))
+ )
+
+ assert pages == [
+ [
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": f"<eq>{expected}</eq>",
+ }
+ ]
+ ]
+
+
[email protected]("anchor_mode", ["objectPr", "drawing", "vml", "none"])
+def test_xlsx_equation_anchor_variants_and_tail_fallback(anchor_mode: str) -> None:
+ """验证 XLSX objectPr、DrawingML、VML 与无 anchor 的稳定输出。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+
+ pages = XlsxModel().predict(
+ BytesIO(build_equation_xlsx([mtef], anchor_mode=anchor_mode))
+ )
+
+ assert pages == [[{"type": BlockType.EQUATION, "content": expected}]]
+
+
+def test_xlsx_mtef_inside_table_and_hidden_sheet_behavior() -> None:
+ """验证表内公式不重复输出,隐藏公式工作表沿用现有跳过策略。"""
+
+ _name, mtef, expected = formula_corpus()[0]
+ table_pages = XlsxModel().predict(
+ BytesIO(build_equation_xlsx([mtef], cell_value="value"))
+ )
+ hidden_pages = XlsxModel().predict(
+ BytesIO(build_equation_xlsx([mtef], hidden=True))
+ )
+
+ assert len(table_pages[0]) == 1
+ assert table_pages[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{expected}</eq>" in table_pages[0][0]["content"]
+ assert hidden_pages == [[]]
+
+
+def test_xlsx_linked_equation_never_loads_external_target() -> None:
+ """验证外链 Equation.3 只保留包内预览,不访问外部对象。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+
+ pages = XlsxModel().predict(
+ BytesIO(build_equation_xlsx([mtef], linked=True))
+ )
+
+ assert pages[0][0]["type"] == BlockType.IMAGE
+ assert all(block["type"] != BlockType.EQUATION for block in pages[0])
+
+
[email protected]("file_suffix", ["docx", "pptx", "xlsx"])
+def test_ooxml_mtef_backend_analyze_sync_async_contract(file_suffix: str) -> None:
+ """验证 MTEF 公式贯穿三种现代 Office 同步与异步严格契约。"""
+
+ _name, mtef, expected = formula_corpus()[2]
+ builders = {
+ "docx": build_equation_docx,
+ "pptx": build_equation_pptx,
+ "xlsx": build_equation_xlsx,
+ }
+ file_bytes = builders[file_suffix]([mtef])
+ 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_ooxml_mtef_model_input_streams_remain_open() -> None:
+ """验证三种 Model 均不关闭调用方持有的输入流。"""
+
+ _name, mtef, _expected = formula_corpus()[0]
+ cases = [
+ (DocxModel(), build_equation_docx([mtef])),
+ (PptxModel(), build_equation_pptx([mtef])),
+ (XlsxModel(), build_equation_xlsx([mtef])),
+ ]
+ for model, file_bytes in cases:
+ stream = BytesIO(file_bytes)
+ model.predict(stream)
+ assert not stream.closed
+
+
+def test_ooxml_converter_reuse_does_not_leak_equations_between_documents() -> None:
+ """验证三个 converter 重用时公式缓存和分页状态都会重置。"""
+
+ first = formula_corpus()[0]
+ second = formula_corpus()[1]
+ cases = [
+ (DocxConverter(), build_equation_docx),
+ (PptxConverter(), build_equation_pptx),
+ (XlsxConverter(), build_equation_xlsx),
+ ]
+ for converter, builder in cases:
+ converter.convert(BytesIO(builder([first[1]])))
+ assert _equation_contents(converter.pages) == [first[2]]
+ converter.convert(BytesIO(builder([second[1]])))
+ assert _equation_contents(converter.pages) == [second[2]]
+
+
[email protected]("file_suffix", ["docx", "pptx", "xlsx"])
+def test_invalid_ooxml_mtef_preview_exports_to_sidecar(
+ file_suffix: str,
+ tmp_path: Path,
+) -> None:
+ """验证三种格式的图片回退导出后没有 base64 残留。"""
+
+ builders = {
+ "docx": build_equation_docx,
+ "pptx": build_equation_pptx,
+ "xlsx": build_equation_xlsx,
+ }
+ middle, _model = doc_analyze(
+ builders[file_suffix]([b"invalid MTEF"]),
+ file_suffix=file_suffix, # type: ignore[arg-type]
+ )
+
+ result = middle.export(tmp_path / file_suffix)
+
+ assert len(result.image_paths) == 1
+ assert result.image_paths[0].stat().st_size > 0
+ assert "base64," not in result.json_path.read_text(encoding="utf-8")