Skip to content

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

feat: enhance equation handling by adding support for MathType/Equation OLE objects and improving image equation decoding

myhloli63b4d1479e77
diff --git a/mineru/model/flash/doc/doc_converter.py b/mineru/model/flash/doc/doc_converter.py
index 195fcdb7..c95c4133 100644
--- a/mineru/model/flash/doc/doc_converter.py
+++ b/mineru/model/flash/doc/doc_converter.py
@@ -143,7 +143,13 @@ class DocConverter:
@classmethod
def _image_block(cls, payload: DocImagePayload) -> dict[str, Any] | None:
- """把原始图片载荷转换为 raw image block。"""
+ """把原始图片载荷转换为 equation 或 image block。"""
+
+ if payload.equation_latex:
+ return {
+ "type": BlockType.EQUATION,
+ "content": payload.equation_latex,
+ }
image_base64 = cls._serialize_image(payload)
if image_base64 is None:
@@ -183,6 +189,11 @@ class DocConverter:
"""把一个 TOC 段落追加到对应层级的 index 树。"""
content = cls._rich_text(cls._toc_runs(paragraph))
+ content += "".join(
+ f"<eq>{escape(payload.equation_latex, quote=False)}</eq>"
+ for payload in paragraph.images
+ if payload.equation_latex
+ )
if not content:
return
level = min(max(paragraph.toc_level or 0, 0), 8)
@@ -219,6 +230,11 @@ class DocConverter:
if info is None:
return identity or -1
content = cls._rich_text(paragraph.runs)
+ content += "".join(
+ f"<eq>{escape(payload.equation_latex, quote=False)}</eq>"
+ for payload in paragraph.images
+ if payload.equation_latex
+ )
if not content and not paragraph.images:
return identity or info.identity
if identity != info.identity:
@@ -328,7 +344,10 @@ class DocConverter:
result.append(f"</{stack.pop()}><{tag}>")
stack.append(tag)
label = f"{escape(info.label)} " if info.label and info.ordered else ""
- result.append(f"<li>{label}{cls._rich_text(paragraph.runs)}</li>")
+ result.append(
+ f"<li>{label}{cls._rich_text(paragraph.runs)}"
+ f"{cls._cell_images_html(paragraph.images)}</li>"
+ )
while stack:
result.append(f"</{stack.pop()}>")
return "".join(result)
@@ -341,7 +360,23 @@ class DocConverter:
content = cls._rich_text(paragraph.runs, trim=False)
if content:
parts.append(f"<p>{content}</p>")
- for payload in paragraph.images:
+ parts.append(cls._cell_images_html(paragraph.images))
+ return "".join(parts)
+
+ @classmethod
+ def _cell_images_html(
+ cls,
+ payloads: list[DocImagePayload],
+ ) -> str:
+ """把表格段落中的图片或 comment 公式序列化为内联 HTML。"""
+
+ parts: list[str] = []
+ for payload in payloads:
+ if payload.equation_latex:
+ parts.append(
+ f"<eq>{escape(payload.equation_latex, quote=False)}</eq>"
+ )
+ continue
image = cls._serialize_image(payload)
if image:
parts.append(f'<img src="{escape(image, quote=True)}"/>')
@@ -370,6 +405,13 @@ class DocConverter:
parts.append(cls._table_html(block))
elif isinstance(block, DocImage):
flush()
+ if block.payload.equation_latex:
+ parts.append(
+ "<eq>"
+ f"{escape(block.payload.equation_latex, quote=False)}"
+ "</eq>"
+ )
+ continue
image = cls._serialize_image(block.payload)
if image:
parts.append(f'<img src="{escape(image, quote=True)}"/>')
@@ -435,6 +477,8 @@ class DocConverter:
list_identity = None
cls._append_index_item(page, index_stack, element)
for payload in element.images:
+ if payload.equation_latex:
+ continue
image = cls._image_block(payload)
if image is not None:
page.append(image)
@@ -445,6 +489,8 @@ class DocConverter:
):
list_identity = cls._append_list_item(page, list_stack, list_identity, element)
for payload in element.images:
+ if payload.equation_latex:
+ continue
image = cls._image_block(payload)
if image is not None:
page.append(image)
diff --git a/mineru/model/flash/doc/images.py b/mineru/model/flash/doc/images.py
index 6cbe3e9b..23ccf11e 100644
--- a/mineru/model/flash/doc/images.py
+++ b/mineru/model/flash/doc/images.py
@@ -18,10 +18,15 @@ from mineru.model.flash.legacy_office.officeart import (
first_blip,
record_at,
)
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
+)
from .models import DocImage, DocImagePayload
from .records import DocBudget, bounded_slice, get_u16, get_u32, parse_plc
+_PLACEABLE_WMF_MAGIC = b"\xd7\xcd\xc6\x9a"
+
@dataclass(slots=True)
class ImageStore:
@@ -29,6 +34,9 @@ class ImageStore:
total: int = 0
cache: dict[bytes, DocImagePayload] = field(default_factory=dict)
+ equation_decoder: OfficeImageEquationDecoder = field(
+ default_factory=OfficeImageEquationDecoder
+ )
def add(self, payload: OfficeImagePayload) -> DocImagePayload:
"""计入一张唯一图片并返回内部载荷。"""
@@ -41,7 +49,16 @@ class ImageStore:
raise LegacyOfficeResourceLimitError(
f"embedded assets exceed max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
)
- converted = DocImagePayload(payload.data, payload.extension, payload.content_type)
+ converted = DocImagePayload(
+ payload.data,
+ payload.extension,
+ payload.content_type,
+ self.equation_decoder.decode(
+ payload.data,
+ part_name=f"image.{payload.extension}",
+ content_type=payload.content_type,
+ ),
+ )
self.total += len(payload.data)
self.cache[digest] = converted
return converted
@@ -69,6 +86,7 @@ def inline_picture(
if decoded is None:
# 少量旧文件把原始位图直接放在 PICF 尾部,按 magic 尽力保留。
signatures = (
+ (_PLACEABLE_WMF_MAGIC, "wmf", "image/wmf"),
(b"\x89PNG\r\n\x1a\n", "png", "image/png"),
(b"\xff\xd8\xff", "jpg", "image/jpeg"),
(b"GIF8", "gif", "image/gif"),
diff --git a/mineru/model/flash/doc/models.py b/mineru/model/flash/doc/models.py
index 40270578..b741507b 100644
--- a/mineru/model/flash/doc/models.py
+++ b/mineru/model/flash/doc/models.py
@@ -95,6 +95,7 @@ class DocImagePayload:
data: bytes
extension: str
content_type: str
+ equation_latex: str | None = None
@dataclass(slots=True)
diff --git a/mineru/model/flash/docx/docx_converter.py b/mineru/model/flash/docx/docx_converter.py
index cf7a6719..68fa5236 100644
--- a/mineru/model/flash/docx/docx_converter.py
+++ b/mineru/model/flash/docx/docx_converter.py
@@ -1,4 +1,5 @@
# Copyright (c) Opendatalab. All rights reserved.
+import hashlib
import re
from io import BytesIO
from pathlib import Path
@@ -23,9 +24,13 @@ from mineru.model.flash.office.image import (
)
from mineru.model.flash.office.ooxml_equation import (
OoxmlEquationDecoder,
- is_equation_3_prog_id,
+ is_mathtype_equation_prog_id,
+)
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
)
from mineru.types import RAW_CAPTION
+from mineru.model.flash.docx.equationxml import DocxEquationXmlDecoder
from mineru.model.flash.docx.package_normalizer import normalize_docx_package
from mineru.model.flash.docx.tools.math.omml import oMath2Latex
from mineru.model.flash.docx.tools.office_xml import read_str
@@ -69,6 +74,15 @@ class DocxConverter:
"moveTo",
"smartTag",
}
+ _FORMULA_TOKEN_KINDS: Final = frozenset(
+ {"omml", "equationxml", "mtef", "image_mtef"}
+ )
+ _FORMULA_SOURCE_PRIORITY: Final = (
+ "omml",
+ "equationxml",
+ "mtef",
+ "image_mtef",
+ )
"""
Word 文档中使用的 XML 命名空间映射。
@@ -113,6 +127,9 @@ class DocxConverter:
self._style_bool_cache: dict[tuple[int, str], Optional[bool]] = {}
self._ooxml_equation_decoder = OoxmlEquationDecoder()
self._mtef_warned_relations: set[tuple[str, str]] = set()
+ self._equationxml_decoder = DocxEquationXmlDecoder()
+ self._equationxml_warned_shapes: set[tuple[str, str, str]] = set()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
@staticmethod
def _local_name(element: Any) -> Optional[str]:
@@ -148,10 +165,10 @@ class DocxConverter:
ole_element: Any,
part: Any,
) -> str | None:
- """从当前 DOCX part 的内部 OLE relationship 解码 Equation.3。"""
+ """从当前 DOCX part 的内部 OLE relationship 解码公式对象。"""
prog_id = ole_element.get("ProgID") or ole_element.get("ProgId")
- if not is_equation_3_prog_id(prog_id):
+ if not is_mathtype_equation_prog_id(prog_id):
return None
object_type = (ole_element.get("Type") or "Embed").strip().casefold()
if object_type != "embed":
@@ -185,18 +202,115 @@ class DocxConverter:
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",
+ "DOCX_MTEF_FALLBACK: part={!r}, relationship={!r} has an invalid or unsupported equation OLE object",
warning_key[0],
relationship_id,
)
return None
+ def _decode_docx_equationxml(
+ self,
+ shape_element: Any,
+ part: Any,
+ ) -> str | None:
+ """解码当前 VML shape 的 ``equationxml`` 并对失败告警去重。"""
+
+ vml_shape_tag = f"{{{DocxConverter._BLIP_NAMESPACES['v']}}}shape"
+ if getattr(shape_element, "tag", None) != vml_shape_tag:
+ return None
+ equation_xml = shape_element.get("equationxml")
+ if equation_xml is None:
+ return None
+
+ latex = self._equationxml_decoder.decode(equation_xml)
+ if latex is not None:
+ return latex
+
+ digest = hashlib.sha256(
+ equation_xml.encode("utf-8", errors="replace")
+ ).hexdigest()[:16]
+ warning_key = (
+ self._docx_part_key(part),
+ str(shape_element.get("id") or ""),
+ digest,
+ )
+ if warning_key not in self._equationxml_warned_shapes:
+ self._equationxml_warned_shapes.add(warning_key)
+ logger.warning(
+ "DOCX_EQUATIONXML_FALLBACK: part={!r}, shape_id={!r}, payload_sha256={!r} is malformed or unsupported",
+ warning_key[0],
+ warning_key[1],
+ warning_key[2],
+ )
+ return None
+
+ @staticmethod
+ def _docx_image_relationship_id(image: Any) -> str | None:
+ """读取 DrawingML/VML 图片元素的内部 relationship id。"""
+
+ relationship_id = image.get(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"
+ )
+ if not relationship_id:
+ relationship_id = image.get(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
+ )
+ return str(relationship_id) if relationship_id else None
+
+ @classmethod
+ def _docx_image_part(cls, image: Any, part: Any) -> Any | None:
+ """通过当前 part 的内部关系解析图片 part。"""
+
+ relationship_id = cls._docx_image_relationship_id(image)
+ relationships = getattr(part, "rels", None)
+ if not relationship_id or relationships is None:
+ return None
+ relationship = relationships.get(relationship_id)
+ if relationship is None or getattr(relationship, "is_external", False):
+ return None
+ try:
+ return relationship.target_part
+ except (AttributeError, KeyError, ValueError):
+ return None
+
+ def _decode_docx_image_equation(
+ self,
+ image: Any,
+ part: Any,
+ ) -> str | None:
+ """从当前图片 part 的 WMF/GIF comment 解码 MTEF。"""
+
+ image_part = self._docx_image_part(image, part)
+ if image_part is None:
+ return None
+ try:
+ blob = image_part.blob
+ except (AttributeError, KeyError, ValueError):
+ return None
+ return self._image_equation_decoder.decode(
+ blob,
+ part_name=getattr(image_part, "partname", None),
+ content_type=getattr(image_part, "content_type", None),
+ )
+
+ @staticmethod
+ def _select_docx_compatibility_tokens(
+ token_groups: list[list[tuple[str, str]]],
+ ) -> list[tuple[str, str]]:
+ """按 OMML、Equation XML、OLE MTEF、图片 MTEF 选择兼容分支。"""
+
+ for token_kind in DocxConverter._FORMULA_SOURCE_PRIORITY:
+ for tokens in token_groups:
+ if any(kind == token_kind for kind, _value in tokens):
+ return tokens
+ return token_groups[0] if token_groups else []
+
def _docx_formula_tokens(
self,
element: Any,
part: Any,
) -> list[tuple[str, str]]:
- """按文档顺序提取文本、OMML 和 MTEF,并选择单一兼容分支。"""
+ """按文档顺序提取文本、OMML、Equation XML 和 MTEF。"""
tag_name = self._local_name(element)
if tag_name is None:
@@ -209,11 +323,17 @@ class DocxConverter:
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 []
+ return self._select_docx_compatibility_tokens(branch_tokens)
+
+ if (
+ tag_name == "object"
+ and tag
+ == f"{{{DocxConverter._BLIP_NAMESPACES['w']}}}object"
+ ):
+ child_tokens = [
+ self._docx_formula_tokens(child, part) for child in element
+ ]
+ return self._select_docx_compatibility_tokens(child_tokens)
if tag_name == "txbxContent":
# 外层段落会单独遍历文本框内容,避免在此重复提取公式和文字。
@@ -227,10 +347,29 @@ class DocxConverter:
return []
return [("omml", latex)] if latex else []
+ if (
+ tag_name == "shape"
+ and tag == f"{{{DocxConverter._BLIP_NAMESPACES['v']}}}shape"
+ ):
+ latex = self._decode_docx_equationxml(element, part)
+ if latex is not None:
+ return [("equationxml", latex)]
+
if tag_name == "OLEObject":
latex = self._decode_docx_ole_equation(element, part)
return [("mtef", latex)] if latex else []
+ if (
+ tag_name == "blip"
+ and tag
+ == "{http://schemas.openxmlformats.org/drawingml/2006/main}blip"
+ ) or (
+ tag_name == "imagedata"
+ and tag == f"{{{DocxConverter._BLIP_NAMESPACES['v']}}}imagedata"
+ ):
+ latex = self._decode_docx_image_equation(element, part)
+ return [("image_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 []
@@ -240,21 +379,25 @@ class DocxConverter:
return tokens
def _picture_is_equation_preview(self, image: Any, part: Any) -> bool:
- """判断图片是否属于同一容器中已恢复的 OMML/MTEF 公式预览。"""
+ """判断图片是否属于同一容器中已恢复的公式预览。"""
+
+ if self._decode_docx_image_equation(image, part):
+ return True
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
+ if ancestor_name == "shape":
+ if self._decode_docx_equationxml(ancestor, part):
+ return True
continue
- if ancestor_name == "AlternateContent":
+ if ancestor_name in {"object", "AlternateContent"}:
tokens = self._docx_formula_tokens(ancestor, part)
- return any(kind in {"omml", "mtef"} for kind, _value in tokens)
+ if any(
+ kind in DocxConverter._FORMULA_TOKEN_KINDS
+ for kind, _value in tokens
+ ):
+ return True
+ continue
return False
def _get_style_id_from_property(
@@ -866,6 +1009,9 @@ class DocxConverter:
self._reset_style_caches()
self._ooxml_equation_decoder = OoxmlEquationDecoder()
self._mtef_warned_relations = set()
+ self._equationxml_decoder = DocxEquationXmlDecoder()
+ self._equationxml_warned_shapes = set()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
# 读取文件字节,以便 mammoth 和 python-docx 各自使用独立读取流
file_bytes = self._sanitize_missing_internal_relationships(file_stream.read())
# 使用完整 DOCX 上下文预解析顶层表格,避免转换非表格正文带来的资源浪费
@@ -1042,7 +1188,7 @@ class DocxConverter:
图片会被 mammoth 转换为内联 data-URI base64 格式(<img src="data:...">)。
- 注意:mammoth 不支持 OMML 或 Equation.3/MTEF 公式,会静默丢弃
+ 注意:mammoth 不支持 OMML、Equation XML 或 MTEF OLE 公式,会静默丢弃
表格单元格内的公式。本方法在获取 mammoth HTML 后,会同步遍历原始 DOCX XML,
将丢失的公式重新注入对应的 HTML 单元格。
@@ -1244,9 +1390,9 @@ class DocxConverter:
source_part: Any,
) -> Any:
"""
- 将 DOCX XML 表格中的 OMML/MTEF 公式注入 mammoth HTML 表格。
+ 将 DOCX XML 表格中的 OMML/Equation XML/MTEF 公式注入 mammoth HTML 表格。
- mammoth 会静默丢弃 OMML 与 Equation.3 公式,导致含公式
+ mammoth 会静默丢弃 OMML、Equation XML 与 MTEF OLE 公式,导致含公式
的表格单元格在 HTML 中为空。本方法并行遍历 HTML 表格(BeautifulSoup 对象)
和 XML 表格(lxml 元素),对含有 OMML 公式的单元格用包含公式占位符的内容
替换原来的空内容。
@@ -1262,7 +1408,7 @@ class DocxConverter:
# 快速检查:该表格是否含有任何公式
if not any(
- kind in {"omml", "mtef"}
+ kind in DocxConverter._FORMULA_TOKEN_KINDS
for kind, _value in self._docx_formula_tokens(xml_table, source_part)
):
return html_table
@@ -1285,7 +1431,7 @@ class DocxConverter:
for html_cell, xml_cell in zip(html_cells, xml_cells):
if not any(
- kind in {"omml", "mtef"}
+ kind in DocxConverter._FORMULA_TOKEN_KINDS
for kind, _value in self._docx_formula_tokens(
xml_cell,
source_part,
@@ -1312,9 +1458,9 @@ class DocxConverter:
source_part: Any,
) -> str:
"""
- 为含 OMML/MTEF 公式的表格单元格构建 HTML 内容字符串。
+ 为含 OMML/Equation XML/MTEF 公式的表格单元格构建 HTML 内容字符串。
- 遍历单元格内的段落,将普通文本和 OMML/MTEF 公式
+ 遍历单元格内的段落,将普通文本和 OMML/Equation XML/MTEF 公式
混合在一起,生成与 mammoth 输出风格一致的 HTML 片段。
Args:
@@ -1345,7 +1491,7 @@ class DocxConverter:
xml_table: Any,
source_part: Any,
) -> str:
- """把孤立表格 HTML 包装为 Tag 后复用 OMML/MTEF 注入逻辑。"""
+ """把孤立表格 HTML 包装为 Tag 后复用统一公式注入逻辑。"""
from bs4 import BeautifulSoup
@@ -1367,7 +1513,7 @@ class DocxConverter:
source_part: Any,
) -> Optional[str]:
"""
- 为可能含 OMML/MTEF 公式的段落构建 HTML 字符串。
+ 为可能含 OMML/Equation XML/MTEF 公式的段落构建 HTML 字符串。
使用与 _handle_equations_in_text 相同的迭代逻辑:
- 普通 <w:t> 元素的文本直接收集
@@ -1740,42 +1886,19 @@ class DocxConverter:
"""
- def get_docx_image_rel_id(image: Any) -> Optional[str]:
- rel_id = image.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed")
- if not rel_id:
- 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。
-
- Args:
- image: 单个 blip 元素
-
- Returns:
-
- Optional[Any]: 图像 part
- """
- rId = get_docx_image_rel_id(image)
- if rId in source_part.rels:
- # 使用关系 ID 访问图像部分
- 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)
+ rel_id = self._docx_image_relationship_id(image)
if rel_id and rel_id in seen_rel_ids:
continue
if rel_id:
seen_rel_ids.add(rel_id)
- image_part = get_docx_image_part(image)
+ image_part = self._docx_image_part(image, source_part)
if image_part is None:
logger.warning("Warning: image cannot be found")
continue
diff --git a/mineru/model/flash/docx/equationxml.py b/mineru/model/flash/docx/equationxml.py
new file mode 100644
index 00000000..aff249ae
--- /dev/null
+++ b/mineru/model/flash/docx/equationxml.py
@@ -0,0 +1,130 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""DOCX 兼容模式 VML ``equationxml`` 公式解码器。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+
+from lxml import etree # type: ignore[reportAttributeAccessIssue]
+
+from mineru.model.flash.docx.tools.math.omml import oMath2Latex
+from mineru.model.flash.legacy_office.errors import (
+ LegacyOfficeResourceLimitError,
+)
+from mineru.model.flash.legacy_office.limits import (
+ MAX_ASSET_TOTAL_BYTES,
+ MAX_ENTRY_BYTES,
+)
+
+WORD_2003_XML_NAMESPACE = "http://schemas.microsoft.com/office/word/2003/wordml"
+OFFICE_MATH_NAMESPACE = "http://schemas.openxmlformats.org/officeDocument/2006/math"
+
+_WORD_DOCUMENT_TAG = f"{{{WORD_2003_XML_NAMESPACE}}}wordDocument"
+_WORD_PARAGRAPH_TAG = f"{{{WORD_2003_XML_NAMESPACE}}}p"
+_MATH_PARAGRAPH_TAG = f"{{{OFFICE_MATH_NAMESPACE}}}oMathPara"
+_MATH_TAG = f"{{{OFFICE_MATH_NAMESPACE}}}oMath"
+_FORBIDDEN_EQUATIONXML_ELEMENTS = frozenset(
+ {
+ "annotation",
+ "endnote",
+ "footnote",
+ "ftr",
+ "hdr",
+ "pict",
+ "textbox",
+ "txbxContent",
+ }
+)
+
+
+def _has_forbidden_equationxml_content(root: etree._Element) -> bool:
+ """判断 Equation XML 是否包含规范禁止或无法可靠恢复的 Word 2003 节点。"""
+
+ if root.getroottree().xpath("boolean(//comment())"):
+ return True
+ for element in root.iter():
+ tag = getattr(element, "tag", None)
+ if not isinstance(tag, str):
+ continue
+ qname = etree.QName(tag)
+ if qname.localname in _FORBIDDEN_EQUATIONXML_ELEMENTS:
+ return True
+ return False
+
+
+def _decode_equationxml_document(payload: bytes) -> str | None:
+ """安全解析完整 Word 2003 XML 文档并把唯一 OMML 公式转换为 LaTeX。"""
+
+ parser = etree.XMLParser(
+ resolve_entities=False,
+ load_dtd=False,
+ no_network=True,
+ recover=False,
+ huge_tree=False,
+ )
+ try:
+ root = etree.fromstring(payload, parser=parser)
+ except (etree.XMLSyntaxError, TypeError, ValueError):
+ return None
+
+ if root.tag != _WORD_DOCUMENT_TAG:
+ return None
+ if root.getroottree().docinfo.doctype:
+ return None
+ if _has_forbidden_equationxml_content(root):
+ return None
+
+ paragraphs = root.findall(f".//{_WORD_PARAGRAPH_TAG}")
+ if len(paragraphs) != 1:
+ return None
+ math_paragraphs = paragraphs[0].findall(f"./{_MATH_PARAGRAPH_TAG}")
+ if len(math_paragraphs) != 1:
+ return None
+ equations = math_paragraphs[0].findall(f"./{_MATH_TAG}")
+ if len(equations) != 1 or len(root.findall(f".//{_MATH_TAG}")) != 1:
+ return None
+
+ try:
+ latex = str(oMath2Latex(equations[0])).strip()
+ except Exception:
+ return None
+ return latex or None
+
+
+@dataclass(slots=True)
+class DocxEquationXmlDecoder:
+ """按共享资源上限缓存并解码 DOCX VML ``equationxml``。"""
+
+ total_bytes: int = 0
+ _cache: dict[bytes, str | None] = field(default_factory=dict)
+
+ def decode(self, equation_xml: object | None) -> str | None:
+ """校验属性类型、资源预算和 Word 2003 XML 结构后返回 LaTeX。"""
+
+ if not isinstance(equation_xml, str) or not equation_xml.strip():
+ return None
+ try:
+ payload = equation_xml.encode("utf-8")
+ except UnicodeEncodeError:
+ return None
+ if len(payload) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ "DOCX equationxml exceeds "
+ f"max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+
+ digest = hashlib.sha256(payload).digest()
+ if digest in self._cache:
+ return self._cache[digest]
+ if self.total_bytes + len(payload) > MAX_ASSET_TOTAL_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ "DOCX equationxml payloads exceed "
+ f"max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
+ )
+
+ self.total_bytes += len(payload)
+ latex = _decode_equationxml_document(payload)
+ self._cache[digest] = latex
+ return latex
diff --git a/mineru/model/flash/legacy_office/mtef.py b/mineru/model/flash/legacy_office/mtef.py
index efc9fc56..570eee8d 100644
--- a/mineru/model/flash/legacy_office/mtef.py
+++ b/mineru/model/flash/legacy_office/mtef.py
@@ -1,6 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""安全解析 Equation Editor 3.x 的 Equation Native/MTEF v3 公式。"""
+"""安全解析 Equation Native 中的 MTEF v3/v5 公式。"""
from __future__ import annotations
@@ -57,7 +57,9 @@ class _MtefReader:
self.records += 1
if self.records > MAX_RECORDS:
- raise _MtefError("MTEF record count exceeds the safety limit")
+ raise LegacyOfficeResourceLimitError(
+ f"MTEF record count exceeds max_records={MAX_RECORDS}"
+ )
def _u8(self) -> int:
"""有界读取一个无符号字节。"""
@@ -91,7 +93,9 @@ class _MtefReader:
self.depth += 1
if self.depth > MAX_RECORD_DEPTH:
- raise _MtefError("MTEF nesting exceeds the safety limit")
+ raise LegacyOfficeResourceLimitError(
+ f"MTEF nesting exceeds max_record_depth={MAX_RECORD_DEPTH}"
+ )
def _leave(self) -> None:
"""离开一个嵌套 object list。"""
@@ -360,7 +364,11 @@ _CHAR_LATEX = {
"↔": r"\leftrightarrow ",
"·": r"\cdot ",
"∑": r"\sum ",
+ "∏": r"\prod ",
+ "∐": r"\coprod ",
"∫": r"\int ",
+ "∮": r"\oint ",
+ "ℏ": r"\hbar ",
}
@@ -387,6 +395,24 @@ def _render_character(character: int) -> str:
return value
+def _escape_latex_text(value: str) -> str:
+ """转义 ``\text{}`` 中会改变 LaTeX 结构的字符。"""
+
+ replacements = {
+ "\\": r"\textbackslash{}",
+ "{": r"\{",
+ "}": r"\}",
+ "#": r"\#",
+ "$": r"\$",
+ "%": r"\%",
+ "&": r"\&",
+ "_": r"\_",
+ "^": r"\textasciicircum{}",
+ "~": r"\textasciitilde{}",
+ }
+ return "".join(replacements.get(character, character) for character in value)
+
+
def _apply_embellishments(value: str, embellishments: tuple[int, ...]) -> str:
"""按记录顺序把常见 embellishment 转为 LaTeX。"""
@@ -401,6 +427,8 @@ def _apply_embellishments(value: str, embellishments: tuple[int, ...]) -> str:
value = f"{value}'"
elif embellishment == 6:
value = f"{value}''"
+ elif embellishment == 7:
+ value = f"{{}}'{value}"
elif embellishment == 8:
value = rf"\widetilde{{{value}}}"
elif embellishment == 9:
@@ -413,6 +441,10 @@ def _apply_embellishments(value: str, embellishments: tuple[int, ...]) -> str:
value = rf"\overleftarrow{{{value}}}"
elif embellishment == 13:
value = rf"\overleftrightarrow{{{value}}}"
+ elif embellishment == 14:
+ value = rf"\overrightharpoon{{{value}}}"
+ elif embellishment == 15:
+ value = rf"\overleftharpoon{{{value}}}"
elif embellishment == 16:
value = rf"\bar{{{value}}}"
elif embellishment == 17:
@@ -423,6 +455,40 @@ def _apply_embellishments(value: str, embellishments: tuple[int, ...]) -> str:
value = rf"\overparen{{{value}}}"
elif embellishment == 20:
value = rf"\underparen{{{value}}}"
+ elif embellishment == 21:
+ value = rf"\xcancel{{{value}}}"
+ elif embellishment == 22:
+ value = rf"\cancel{{{value}}}"
+ elif embellishment == 23:
+ value = rf"\bcancel{{{value}}}"
+ elif embellishment == 24:
+ value = rf"\overset{{\cdots}}{{{value}}}"
+ elif embellishment == 25:
+ value = rf"\underset{{\cdot}}{{{value}}}"
+ elif embellishment == 26:
+ value = rf"\underset{{\cdot\cdot}}{{{value}}}"
+ elif embellishment == 27:
+ value = rf"\underset{{\cdots}}{{{value}}}"
+ elif embellishment == 28:
+ value = rf"\underset{{\cdots\cdot}}{{{value}}}"
+ elif embellishment == 29:
+ value = rf"\underline{{{value}}}"
+ elif embellishment == 30:
+ value = rf"\underset{{\sim}}{{{value}}}"
+ elif embellishment == 31:
+ value = rf"\underparen{{{value}}}"
+ elif embellishment == 32:
+ value = rf"\underset{{\frown}}{{{value}}}"
+ elif embellishment == 33:
+ value = rf"\underrightarrow{{{value}}}"
+ elif embellishment == 34:
+ value = rf"\underleftarrow{{{value}}}"
+ elif embellishment == 35:
+ value = rf"\underleftrightarrow{{{value}}}"
+ elif embellishment == 36:
+ value = rf"\underrightharpoon{{{value}}}"
+ elif embellishment == 37:
+ value = rf"\underleftharpoon{{{value}}}"
else:
raise _MtefError(f"unsupported MTEF embellishment: {embellishment}")
return value
@@ -561,9 +627,180 @@ def _render_node(node: _Node) -> str:
if node.kind == "character":
_typeface, character, embellishments = node.value # type: ignore[misc]
return _apply_embellishments(_render_character(int(character)), tuple(embellishments))
+ if node.kind == "character_v5":
+ character, embellishments, style_bits, typeface, _function_start = node.value # type: ignore[misc]
+ value = _apply_embellishments(
+ _render_character(character)
+ if isinstance(character, int)
+ else str(character),
+ tuple(embellishments),
+ )
+ if int(typeface) in {1, 12}:
+ value = rf"\mathrm{{{value}}}"
+ if int(style_bits) == 1:
+ return rf"\mathbf{{{value}}}"
+ if int(style_bits) == 2:
+ return rf"\mathit{{{value}}}"
+ if int(style_bits) == 3:
+ return rf"\boldsymbol{{\mathit{{{value}}}}}"
+ return value
+ if node.kind == "text":
+ return rf"\text{{{_escape_latex_text(str(node.value))}}}"
+ if node.kind == "function":
+ function_name = str(node.value)
+ known = {
+ "arccos",
+ "arcsin",
+ "arctan",
+ "cos",
+ "cosh",
+ "cot",
+ "coth",
+ "csc",
+ "det",
+ "exp",
+ "gcd",
+ "hom",
+ "ker",
+ "lg",
+ "lim",
+ "ln",
+ "log",
+ "max",
+ "min",
+ "sec",
+ "sin",
+ "sinh",
+ "sup",
+ "tan",
+ "tanh",
+ }
+ return rf"\{function_name} " if function_name in known else rf"\operatorname{{{function_name}}}"
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 == "fraction_semantic":
+ numerator = _slot(node.children, 0)
+ denominator = _slot(node.children, 1)
+ if bool(node.value):
+ return rf"{{{numerator}}}/{{{denominator}}}"
+ return rf"\frac{{{numerator}}}{{{denominator}}}"
+ if node.kind == "root_semantic":
+ radicand = _slot(node.children, 0)
+ index = _slot(node.children, 1)
+ return rf"\sqrt[{index}]{{{radicand}}}" if bool(node.value) and index else rf"\sqrt{{{radicand}}}"
+ if node.kind == "scripts_semantic":
+ subscript = _slot(node.children, 0)
+ superscript = _slot(node.children, 1)
+ scripts = (rf"_{{{subscript}}}" if subscript else "") + (rf"^{{{superscript}}}" if superscript else "")
+ return ("{}" if bool(node.value) else "") + scripts
+ if node.kind == "fence_semantic":
+ default_left, default_right = node.value # type: ignore[misc]
+ body = _slot(node.children, 0)
+ left = _slot(node.children, 1) or str(default_left)
+ right = _slot(node.children, 2) or str(default_right)
+ if re.fullmatch(r"\\[A-Za-z]+", left):
+ left += " "
+ if re.fullmatch(r"\\[A-Za-z]+", right):
+ right += " "
+ return rf"\left{left}{body}\right{right}"
+ if node.kind == "bar_semantic":
+ under, doubled = node.value # type: ignore[misc]
+ command = "underline" if bool(under) else "overline"
+ value = rf"\{command}{{{_slot(node.children, 0)}}}"
+ return rf"\{command}{{{value}}}" if bool(doubled) else value
+ if node.kind == "arrow_semantic":
+ if not isinstance(node.value, int):
+ raise _MtefError("MTEF arrow semantic value is invalid")
+ variation = node.value
+ body = _slot(node.children, 0)
+ arrow = _slot(node.children, 1)
+ if not arrow:
+ if variation & 0x02:
+ arrow = r"\leftrightharpoons"
+ elif variation & 0x01:
+ arrow = r"\Leftrightarrow"
+ elif variation & 0x10 and not variation & 0x20:
+ arrow = r"\leftarrow"
+ elif variation & 0x20 and not variation & 0x10:
+ arrow = r"\rightarrow"
+ else:
+ arrow = r"\leftrightarrow"
+ if variation & 0x08 and not variation & 0x04:
+ return rf"\underset{{{body}}}{{{arrow}}}"
+ return rf"\overset{{{body}}}{{{arrow}}}" if body else arrow
+ if node.kind == "big_operator_semantic":
+ main = _slot(node.children, 0)
+ upper = _slot(node.children, 1)
+ lower = _slot(node.children, 2)
+ default_operator = str(node.value)
+ if default_operator in {
+ r"\sum",
+ r"\prod",
+ r"\coprod",
+ r"\bigcup",
+ r"\bigcap",
+ }:
+ operator = default_operator
+ else:
+ operator = _slot(node.children, 3) or default_operator
+ if not operator:
+ raise _MtefError("MTEF big operator has no visible operator")
+ limits = (rf"_{{{lower}}}" if lower else "") + (rf"^{{{upper}}}" if upper else "")
+ return operator + limits + rf"{{{main}}}"
+ if node.kind == "limit_semantic":
+ main = _slot(node.children, 0)
+ lower = _slot(node.children, 1)
+ upper = _slot(node.children, 2)
+ return r"\lim" + (rf"_{{{lower}}}" if lower else "") + (rf"^{{{upper}}}" if upper else "") + rf"{{{main}}}"
+ if node.kind == "horizontal_fence_semantic":
+ brace, top = node.value # type: ignore[misc]
+ main = _slot(node.children, 0)
+ small = _slot(node.children, 1)
+ if bool(brace):
+ command = "overbrace" if bool(top) else "underbrace"
+ else:
+ command = "overbracket" if bool(top) else "underbracket"
+ suffix = rf"^{{{small}}}" if bool(top) and small else rf"_{{{small}}}" if small else ""
+ return rf"\{command}{{{main}}}{suffix}"
+ if node.kind == "long_division_semantic":
+ dividend = _slot(node.children, 0)
+ quotient = _slot(node.children, 1)
+ return rf"\overline{{{quotient}}}\smash{{\big) {dividend}}}" if bool(node.value) else rf"\smash{{\big) {dividend}}}"
+ if node.kind == "dirac_semantic":
+ if not isinstance(node.value, int):
+ raise _MtefError("MTEF Dirac semantic value is invalid")
+ variation = node.value
+ left = _slot(node.children, 0)
+ right = _slot(node.children, 1)
+ if variation == 0x01:
+ return rf"\left\langle {left}\right|"
+ if variation == 0x02:
+ return rf"\left|{right}\right\rangle"
+ return rf"\left\langle {left}\middle|{right}\right\rangle"
+ if node.kind == "vector_semantic":
+ if not isinstance(node.value, int):
+ raise _MtefError("MTEF vector semantic value is invalid")
+ variation = node.value
+ left = bool(variation & 0x01)
+ right = bool(variation & 0x02)
+ under = bool(variation & 0x04)
+ harpoon = bool(variation & 0x08)
+ if harpoon:
+ direction = "leftharpoon" if left else "rightharpoon"
+ elif left and right:
+ direction = "leftrightarrow"
+ elif left:
+ direction = "leftarrow"
+ else:
+ direction = "rightarrow"
+ return rf"\{'under' if under else 'over'}{direction}{{{_slot(node.children, 0)}}}"
+ if node.kind == "accent_semantic":
+ return rf"\{str(node.value)}{{{_slot(node.children, 0)}}}"
+ if node.kind == "strike_semantic":
+ return rf"\{str(node.value)}{{{_slot(node.children, 0)}}}"
+ if node.kind == "box_semantic":
+ return rf"\boxed{{{_slot(node.children, 0)}}}"
if node.kind == "pile":
rows = [_render_node(child).strip() for child in node.children]
return r"\begin{gathered}" + r"\\".join(rows) + r"\end{gathered}"
@@ -582,13 +819,35 @@ def decode_mtef_v3(data: bytes) -> str | None:
try:
latex = _render_node(_MtefReader(data).parse()).strip()
+ except LegacyOfficeResourceLimitError:
+ raise
except (ArithmeticError, IndexError, struct.error, UnicodeError, _MtefError, ValueError):
return None
return latex or None
+def decode_mtef_v5(data: bytes) -> str | None:
+ """延迟加载独立 v5 reader,并返回其完整 LaTeX 结果。"""
+
+ from .mtef_v5 import decode_mtef_v5 as _decode_mtef_v5
+
+ return _decode_mtef_v5(data)
+
+
+def decode_mtef(data: bytes) -> str | None:
+ """仅按 MTEF header 首字节分派 v3/v5,其他版本整体拒绝。"""
+
+ if not data:
+ return None
+ if data[0] == 3:
+ return decode_mtef_v3(data)
+ if data[0] == 5:
+ return decode_mtef_v5(data)
+ return None
+
+
def decode_equation_native(data: bytes) -> str | None:
- """校验 28 字节 EQNOLEFILEHDR 并解码其中的 MTEF v3。"""
+ """校验 28 字节 EQNOLEFILEHDR 并按 header 解码 MTEF v3/v5。"""
if len(data) < 28:
return None
@@ -598,11 +857,11 @@ def decode_equation_native(data: bytes) -> str | 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])
+ return decode_mtef(data[header_size:object_end])
def decode_equation_object(data: bytes) -> str | None:
- """从独立 Equation Editor OLE 对象读取 Equation Native 并转为 LaTeX。"""
+ """从独立公式 OLE 对象读取 Equation Native 并转为 LaTeX。"""
try:
with BoundedOleReader(data) as ole:
diff --git a/mineru/model/flash/legacy_office/mtef_v5.py b/mineru/model/flash/legacy_office/mtef_v5.py
new file mode 100644
index 00000000..10f4f2bb
--- /dev/null
+++ b/mineru/model/flash/legacy_office/mtef_v5.py
@@ -0,0 +1,991 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""按照 WIRIS 规范安全读取 MathType MTEF v5 record tree。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import struct
+
+from .errors import LegacyOfficeResourceLimitError
+from .limits import MAX_RECORD_DEPTH, MAX_RECORDS
+from .mtef import _MtefError, _Node, _render_node
+
+_OPT_NUDGE = 0x08
+_CHAR_EMBELL = 0x01
+_CHAR_FUNC_START = 0x02
+_CHAR_ENC_8 = 0x04
+_CHAR_ENC_16 = 0x10
+_CHAR_NO_MTCODE = 0x20
+_LINE_NULL = 0x01
+_LINE_RULER = 0x02
+_LINE_LSPACE = 0x04
+_PILE_RULER = 0x02
+_BUILTIN_TYPEFACES = frozenset({*range(1, 13), 22, 23, 24})
+
+_PREDEFINED_ENCODINGS = {
+ 1: "MTCode",
+ 2: "Unknown",
+ 3: "Symbol",
+ 4: "MTExtra",
+}
+
+# Adobe Symbol/MathType Symbol 编码中常见且语义稳定的字符。
+_SYMBOL_FONT_POSITION_TO_UNICODE = {
+ 0x41: 0x0391,
+ 0x42: 0x0392,
+ 0x43: 0x03A7,
+ 0x44: 0x0394,
+ 0x45: 0x0395,
+ 0x46: 0x03A6,
+ 0x47: 0x0393,
+ 0x48: 0x0397,
+ 0x49: 0x0399,
+ 0x4A: 0x03D1,
+ 0x4B: 0x039A,
+ 0x4C: 0x039B,
+ 0x4D: 0x039C,
+ 0x4E: 0x039D,
+ 0x4F: 0x039F,
+ 0x50: 0x03A0,
+ 0x51: 0x0398,
+ 0x52: 0x03A1,
+ 0x53: 0x03A3,
+ 0x54: 0x03A4,
+ 0x55: 0x03A5,
+ 0x56: 0x03C2,
+ 0x57: 0x03A9,
+ 0x58: 0x039E,
+ 0x59: 0x03A8,
+ 0x5A: 0x0396,
+ 0x61: 0x03B1,
+ 0x62: 0x03B2,
+ 0x63: 0x03C7,
+ 0x64: 0x03B4,
+ 0x65: 0x03B5,
+ 0x66: 0x03C6,
+ 0x67: 0x03B3,
+ 0x68: 0x03B7,
+ 0x69: 0x03B9,
+ 0x6A: 0x03D5,
+ 0x6B: 0x03BA,
+ 0x6C: 0x03BB,
+ 0x6D: 0x03BC,
+ 0x6E: 0x03BD,
+ 0x6F: 0x03BF,
+ 0x70: 0x03C0,
+ 0x71: 0x03B8,
+ 0x72: 0x03C1,
+ 0x73: 0x03C3,
+ 0x74: 0x03C4,
+ 0x75: 0x03C5,
+ 0x76: 0x03D6,
+ 0x77: 0x03C9,
+ 0x78: 0x03BE,
+ 0x79: 0x03C8,
+ 0x7A: 0x03B6,
+ 0xA3: 0x2264,
+ 0xA5: 0x221E,
+ 0xAB: 0x2194,
+ 0xAC: 0x2190,
+ 0xAE: 0x2192,
+ 0xB1: 0x00B1,
+ 0xB3: 0x2265,
+ 0xB9: 0x2260,
+ 0xC7: 0x2229,
+ 0xC8: 0x222A,
+ 0xD5: 0x220F,
+ 0xE5: 0x2211,
+ 0xF2: 0x222B,
+}
+
+# MathType v5 常见私有 MTCode;未列出的 PUA 继续整体回退,避免猜测字符。
+_MTCODE_PUA_TO_LATEX = {
+ 0xE90B: r"\supseteqq ",
+ 0xE90C: r"\subseteqq ",
+ 0xE922: r"\lesseqqgtr ",
+ 0xE92D: r"\gtreqqless ",
+ 0xE92E: r"\shortmid ",
+ 0xE92F: r"\shortparallel ",
+ 0xE930: r"\leqslant ",
+ 0xE931: r"\geqslant ",
+ 0xE932: r"\lessapprox ",
+ 0xE933: r"\gtrapprox ",
+ 0xE938: r"\preceq ",
+ 0xE939: r"\succeq ",
+ 0xE981: r"\circleddash ",
+ 0xE98F: r"\centerdot ",
+ 0xEA06: r"\nleq ",
+ 0xEA07: r"\ngeq ",
+ 0xEA11: r"\nsim ",
+ 0xEF02: r"\,",
+ 0xEF03: r"\;",
+ 0xEF04: r"\ ",
+ 0xEF05: r"\quad ",
+ 0xEF06: r"\qquad ",
+ 0xEF22: r"\!",
+}
+
+_MTEXTRA_FONT_POSITION_TO_UNICODE = {
+ 0x20: 0x0020,
+ 0x3C: 0x25C3,
+ 0x3E: 0x25B9,
+ 0x43: 0x2210,
+ 0x44: 0x019B,
+ 0x49: 0x2229,
+ 0x4B: 0x2026,
+ 0x4C: 0x22EF,
+ 0x4D: 0x22EE,
+ 0x4E: 0x22F0,
+ 0x4F: 0x22F1,
+ 0x51: 0x2235,
+ 0x55: 0x222A,
+ 0x60: 0x2035,
+ 0x61: 0x21A6,
+ 0x62: 0x2195,
+ 0x63: 0x21D5,
+ 0x66: 0x227B,
+ 0x68: 0x210F,
+ 0x6C: 0x2113,
+ 0x6D: 0x2213,
+ 0x6F: 0x2218,
+ 0x70: 0x227A,
+}
+
+
+@dataclass(frozen=True, slots=True)
+class _FontDefinition:
+ """记录一个 FONT_DEF 的 encoding 索引和字体名称。"""
+
+ encoding_index: int
+ name: str
+
+
+@dataclass(frozen=True, slots=True)
+class _FontStyleDefinition:
+ """记录一个 FONT_STYLE_DEF 的字体引用和粗斜体位。"""
+
+ font_definition_index: int
+ style_bits: int
+
+
+class _MtefV5Reader:
+ """有界读取 MTEF v5 header、定义记录和公式对象树。"""
+
+ def __init__(self, data: bytes) -> None:
+ """校验 v5 header 并初始化 definition tables 与安全计数器。"""
+
+ if len(data) < 7 or data[0] != 5:
+ raise _MtefError("Equation Native does not contain MTEF v5")
+ if data[1] not in {0, 1} or data[2] not in {0, 1} or data[3] < 4:
+ raise _MtefError("MTEF v5 generator header is invalid")
+ self.data = data
+ self.pos = 5
+ self.depth = 0
+ self.records = 0
+ self.encoding_definitions: dict[int, str] = dict(_PREDEFINED_ENCODINGS)
+ self.font_definitions: list[_FontDefinition | None] = [None]
+ self.font_style_definitions: list[_FontStyleDefinition | None] = [None]
+ self.equation_styles: list[_FontStyleDefinition | None] = []
+ self.color_definition_count = 0
+ application_key = self._cstring(max_bytes=4096)
+ if not application_key:
+ raise _MtefError("MTEF v5 application key is empty")
+ equation_options = self._u8()
+ if equation_options & ~0x01:
+ raise _MtefError("MTEF v5 equation options are invalid")
+
+ def _charge(self) -> None:
+ """计入一条 record,超过共享上限时抛稳定资源错误。"""
+
+ self.records += 1
+ if self.records > MAX_RECORDS:
+ raise LegacyOfficeResourceLimitError(
+ f"MTEF record count exceeds max_records={MAX_RECORDS}"
+ )
+
+ def _enter(self) -> None:
+ """进入嵌套 object list 并限制共享深度。"""
+
+ self.depth += 1
+ if self.depth > MAX_RECORD_DEPTH:
+ raise LegacyOfficeResourceLimitError(
+ f"MTEF nesting exceeds max_record_depth={MAX_RECORD_DEPTH}"
+ )
+
+ def _leave(self) -> None:
+ """离开当前 object list。"""
+
+ self.depth -= 1
+
+ def _u8(self) -> int:
+ """有界读取一个无符号字节。"""
+
+ if self.pos >= len(self.data):
+ raise _MtefError("MTEF v5 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 v5 u16 is truncated")
+ value = int(struct.unpack_from("<H", self.data, self.pos)[0])
+ self.pos += 2
+ return value
+
+ def _bytes(self, size: int) -> bytes:
+ """按显式长度有界读取 payload。"""
+
+ if size < 0 or self.pos + size < self.pos or self.pos + size > len(self.data):
+ raise _MtefError("MTEF v5 payload length is invalid")
+ value = self.data[self.pos : self.pos + size]
+ self.pos += size
+ return value
+
+ def _cstring(self, *, max_bytes: int) -> str:
+ """读取有长度上限的零结尾单字节字符串。"""
+
+ end_limit = min(len(self.data), self.pos + max_bytes + 1)
+ end = self.data.find(b"\x00", self.pos, end_limit)
+ if end < 0:
+ raise _MtefError("MTEF v5 string is not null-terminated")
+ raw = self.data[self.pos:end]
+ self.pos = end + 1
+ try:
+ return raw.decode("ascii")
+ except UnicodeDecodeError:
+ return raw.decode("latin-1")
+
+ def _signed(self) -> int:
+ """读取 MTEF v5 紧凑有符号整数。"""
+
+ first = self._u8()
+ if first == 0xFF:
+ return self._u16() - 0x8000
+ return first - 0x80
+
+ def _unsigned(self) -> int:
+ """读取 MTEF v5 紧凑无符号整数。"""
+
+ first = self._u8()
+ return self._u16() if first == 0xFF else first
+
+ def _variation(self) -> int:
+ """读取一或两字节 template variation。"""
+
+ first = self._u8()
+ if first & 0x80:
+ return (first & 0x7F) | (self._u8() << 8)
+ return first
+
+ def _skip_nudge(self) -> None:
+ """跳过短或长格式 nudge。"""
+
+ dx = self._u8()
+ dy = self._u8()
+ if dx == 0x80 and dy == 0x80:
+ self._u16()
+ self._u16()
+
+ def _skip_ruler(self) -> None:
+ """解析并跳过 RULER record 的 tab stops。"""
+
+ count = self._u8()
+ for _ in range(count):
+ tab_type = self._u8()
+ if tab_type > 4:
+ raise _MtefError("MTEF v5 ruler tab type is invalid")
+ self._u16()
+
+ def _skip_size(self) -> None:
+ """解析并跳过 SIZE record 的三种编码。"""
+
+ first = self._u8()
+ if first == 100:
+ logical_size = self._u8()
+ if logical_size > 7:
+ raise _MtefError("MTEF v5 logical size is invalid")
+ self._u16()
+ elif first == 101:
+ self._u16()
+ else:
+ if first > 7:
+ raise _MtefError("MTEF v5 logical size is invalid")
+ self._u8()
+
+ def _dimension_array(self) -> None:
+ """有界消费 EQN_PREFS 中按 nibble 编码的 dimension array。"""
+
+ count = self._u8()
+ current = 0
+ use_low = False
+
+ def next_nibble() -> int:
+ """按高四位优先顺序读取一个 nibble。"""
+
+ nonlocal current, use_low
+ if not use_low:
+ current = self._u8()
+ use_low = True
+ return current >> 4
+ use_low = False
+ return current & 0x0F
+
+ for _ in range(count):
+ units = next_nibble()
+ if units > 4:
+ raise _MtefError("MTEF v5 dimension units are invalid")
+ while True:
+ value = next_nibble()
+ if value == 0x0F:
+ break
+ if value > 0x0B:
+ raise _MtefError("MTEF v5 dimension digit is invalid")
+ if use_low and current & 0x0F:
+ raise _MtefError("MTEF v5 dimension padding nibble is invalid")
+
+ def _parse_font_style_definition(self) -> _Node:
+ """读取 FONT_STYLE_DEF 并验证先前 FONT_DEF 引用。"""
+
+ font_index = self._unsigned()
+ style_bits = self._u8()
+ if style_bits & ~0x03:
+ raise _MtefError("MTEF v5 font style bits are invalid")
+ if font_index <= 0 or font_index >= len(self.font_definitions):
+ raise _MtefError("MTEF v5 FONT_STYLE_DEF reference is invalid")
+ self.font_style_definitions.append(
+ _FontStyleDefinition(font_index, style_bits)
+ )
+ return _Node("metadata")
+
+ def _parse_color_definition(self) -> _Node:
+ """读取 COLOR_DEF,颜色只校验结构而不进入现有 schema。"""
+
+ options = self._u8()
+ if options & ~0x07:
+ raise _MtefError("MTEF v5 color options are invalid")
+ component_count = 4 if options & 0x01 else 3
+ for _ in range(component_count):
+ if self._u16() > 1000:
+ raise _MtefError("MTEF v5 color component is invalid")
+ if options & 0x04:
+ self._cstring(max_bytes=4096)
+ self.color_definition_count += 1
+ return _Node("metadata")
+
+ def _parse_font_definition(self) -> _Node:
+ """读取 FONT_DEF 并绑定已声明 encoding。"""
+
+ encoding_index = self._unsigned()
+ if encoding_index not in self.encoding_definitions:
+ raise _MtefError("MTEF v5 FONT_DEF encoding reference is invalid")
+ name = self._cstring(max_bytes=4096)
+ if not name:
+ raise _MtefError("MTEF v5 font name is empty")
+ self.font_definitions.append(_FontDefinition(encoding_index, name))
+ return _Node("metadata")
+
+ def _parse_equation_preferences(self) -> _Node:
+ """读取 EQN_PREFS 的尺寸、间距和 style definition 数组。"""
+
+ if self._u8() != 0:
+ raise _MtefError("MTEF v5 equation preference options are invalid")
+ self._dimension_array()
+ self._dimension_array()
+ style_count = self._u8()
+ styles: list[_FontStyleDefinition | None] = []
+ for _ in range(style_count):
+ font_index = self._unsigned()
+ if font_index == 0:
+ styles.append(None)
+ continue
+ if font_index >= len(self.font_definitions):
+ raise _MtefError("MTEF v5 equation style reference is invalid")
+ style_bits = self._u8()
+ if style_bits & ~0x03:
+ raise _MtefError("MTEF v5 equation style bits are invalid")
+ styles.append(_FontStyleDefinition(font_index, style_bits))
+ self.equation_styles = styles
+ return _Node("metadata")
+
+ def _parse_encoding_definition(self) -> _Node:
+ """读取自定义 ENCODING_DEF 并按出现顺序从索引 5 编号。"""
+
+ name = self._cstring(max_bytes=4096)
+ if not name:
+ raise _MtefError("MTEF v5 encoding name is empty")
+ index = max(self.encoding_definitions) + 1
+ self.encoding_definitions[index] = name
+ return _Node("metadata")
+
+ def _character_style(self, typeface: int) -> int:
+ """从显式字体或 EQN_PREFS style 解析粗斜体位。"""
+
+ definition: _FontStyleDefinition | None = None
+ if typeface < 0:
+ index = -typeface
+ if 0 < index < len(self.font_style_definitions):
+ definition = self.font_style_definitions[index]
+ elif 0 < typeface <= len(self.equation_styles):
+ definition = self.equation_styles[typeface - 1]
+ return definition.style_bits if definition is not None else 0
+
+ def _character_encoding(self, typeface: int) -> str:
+ """解析无 MTCode 字符所引用的字体 encoding。"""
+
+ definition: _FontStyleDefinition | None = None
+ if typeface < 0:
+ index = -typeface
+ if 0 < index < len(self.font_style_definitions):
+ definition = self.font_style_definitions[index]
+ elif 0 < typeface <= len(self.equation_styles):
+ definition = self.equation_styles[typeface - 1]
+ if definition is not None:
+ font_definition = self.font_definitions[definition.font_definition_index]
+ if font_definition is not None:
+ return self.encoding_definitions[font_definition.encoding_index]
+ if typeface in {4, 5, 6}:
+ return "Symbol"
+ if typeface == 11:
+ return "MTExtra"
+ return "WinAllBasicCodePages"
+
+ @staticmethod
+ def _mtcode_character(code: int) -> int | str:
+ """把可验证的 MTCode 转为 Unicode/LaTeX,未知 PUA 整体回退。"""
+
+ if 0xD800 <= code <= 0xDFFF or code < 0x20:
+ raise _MtefError("MTEF v5 MTCode character is invalid")
+ if 0xE000 <= code <= 0xF8FF:
+ mapped = _MTCODE_PUA_TO_LATEX.get(code)
+ if mapped is not None:
+ return mapped
+ if 0xF000 <= code <= 0xF019:
+ return rf"\mathfrak{{{chr(ord('A') + code - 0xF000)}}}"
+ if 0xF01A <= code <= 0xF033:
+ return rf"\mathfrak{{{chr(ord('a') + code - 0xF01A)}}}"
+ if 0xF080 <= code <= 0xF099:
+ return rf"\mathbb{{{chr(ord('A') + code - 0xF080)}}}"
+ if 0xF100 <= code <= 0xF119:
+ return rf"\mathcal{{{chr(ord('A') + code - 0xF100)}}}"
+ raise _MtefError("MTEF v5 private MTCode is unsupported")
+ return code
+
+ @staticmethod
+ def _font_position_character(encoding: str, position: int) -> int | str:
+ """从已知 encoding 的 font position 恢复 Unicode/LaTeX。"""
+
+ normalized = encoding.strip().casefold()
+ if normalized == "mtcode":
+ return _MtefV5Reader._mtcode_character(position)
+ if normalized == "symbol":
+ character = _SYMBOL_FONT_POSITION_TO_UNICODE.get(position)
+ if character is None:
+ raise _MtefError("MTEF v5 Symbol font position is unsupported")
+ return character
+ if normalized == "mtextra":
+ character = _MTEXTRA_FONT_POSITION_TO_UNICODE.get(position)
+ if character is None:
+ raise _MtefError("MTEF v5 MTExtra font position is unsupported")
+ return character
+ if normalized in {
+ "winallbasiccodepages",
+ "windowsansi",
+ "windows-1252",
+ "cp1252",
+ "unicode",
+ }:
+ if position <= 0xFF:
+ value = bytes([position]).decode("cp1252")
+ return ord(value)
+ return _MtefV5Reader._mtcode_character(position)
+ raise _MtefError(f"unsupported MTEF v5 font encoding: {encoding}")
+
+ def _parse_embellishments(self) -> tuple[int, ...]:
+ """读取 CHAR 后以 END 终止的 EMBELL 列表。"""
+
+ values: list[int] = []
+ while True:
+ record_type = self._u8()
+ self._charge()
+ if record_type == 0:
+ return tuple(values)
+ if record_type != 6:
+ raise _MtefError("MTEF v5 embellishment list is invalid")
+ options = self._u8()
+ if options & ~_OPT_NUDGE:
+ raise _MtefError("MTEF v5 embellishment options are invalid")
+ if options & _OPT_NUDGE:
+ self._skip_nudge()
+ embellishment = self._u8()
+ if not 2 <= embellishment <= 37:
+ raise _MtefError("MTEF v5 embellishment type is invalid")
+ values.append(embellishment)
+
+ def _parse_character(self) -> _Node:
+ """读取 CHAR 的 typeface、MTCode/font position 和 embellishments。"""
+
+ options = self._u8()
+ allowed = (
+ _OPT_NUDGE
+ | _CHAR_EMBELL
+ | _CHAR_FUNC_START
+ | _CHAR_ENC_8
+ | _CHAR_ENC_16
+ | _CHAR_NO_MTCODE
+ )
+ if options & ~allowed or options & _CHAR_ENC_8 and options & _CHAR_ENC_16:
+ raise _MtefError("MTEF v5 CHAR options are invalid")
+ if options & _OPT_NUDGE:
+ self._skip_nudge()
+ typeface = self._signed()
+ if typeface < 0:
+ definition_index = -typeface
+ if not (
+ 0 < definition_index < len(self.font_style_definitions)
+ and self.font_style_definitions[definition_index] is not None
+ ):
+ raise _MtefError("MTEF v5 explicit typeface reference is invalid")
+ elif typeface not in _BUILTIN_TYPEFACES:
+ raise _MtefError("MTEF v5 typeface value is invalid")
+ mtcode = None if options & _CHAR_NO_MTCODE else self._u16()
+ font_position: int | None = None
+ if options & _CHAR_ENC_8:
+ font_position = self._u8()
+ elif options & _CHAR_ENC_16:
+ font_position = self._u16()
+ if mtcode is None and font_position is None:
+ raise _MtefError("MTEF v5 CHAR has no character value")
+ if mtcode is not None:
+ character = self._mtcode_character(mtcode)
+ else:
+ if font_position is None:
+ raise _MtefError("MTEF v5 CHAR font position is missing")
+ character = self._font_position_character(
+ self._character_encoding(typeface),
+ font_position,
+ )
+ embellishments = (
+ self._parse_embellishments() if options & _CHAR_EMBELL else ()
+ )
+ return _Node(
+ "character_v5",
+ (
+ character,
+ embellishments,
+ self._character_style(typeface),
+ typeface,
+ bool(options & _CHAR_FUNC_START),
+ ),
+ )
+
+ def _parse_line(self) -> _Node:
+ """读取 LINE options、可选 ruler 和内部 object list。"""
+
+ options = self._u8()
+ if options & ~(_OPT_NUDGE | _LINE_NULL | _LINE_RULER | _LINE_LSPACE):
+ raise _MtefError("MTEF v5 LINE options are invalid")
+ if options & _OPT_NUDGE:
+ self._skip_nudge()
+ if options & _LINE_LSPACE:
+ self._u16()
+ if options & _LINE_RULER:
+ if self._u8() != 7:
+ raise _MtefError("MTEF v5 LINE ruler tag is invalid")
+ self._charge()
+ self._skip_ruler()
+ if options & _LINE_NULL:
+ return _Node("sequence")
+ self._enter()
+ children = self._parse_list()
+ self._leave()
+ return _Node("sequence", children=children)
+
+ def _parse_pile(self) -> _Node:
+ """读取 PILE alignment、ruler 和逐行 object list。"""
+
+ options = self._u8()
+ if options & ~(_OPT_NUDGE | _PILE_RULER):
+ raise _MtefError("MTEF v5 PILE options are invalid")
+ if options & _OPT_NUDGE:
+ self._skip_nudge()
+ horizontal_alignment = self._u8()
+ vertical_alignment = self._u8()
+ if horizontal_alignment not in {1, 2, 3, 4, 5} or vertical_alignment > 4:
+ raise _MtefError("MTEF v5 PILE alignment is invalid")
+ if options & _PILE_RULER:
+ if self._u8() != 7:
+ raise _MtefError("MTEF v5 PILE ruler tag is invalid")
+ self._charge()
+ self._skip_ruler()
+ self._enter()
+ children = self._parse_list()
+ self._leave()
+ if any(child.kind != "sequence" for child in children):
+ raise _MtefError("MTEF v5 PILE contains a non-LINE object")
+ return _Node("pile", children=children)
+
+ def _parse_matrix(self) -> _Node:
+ """读取 MATRIX 维度、partition bits 和逐格 LINE。"""
+
+ options = self._u8()
+ if options & ~_OPT_NUDGE:
+ raise _MtefError("MTEF v5 MATRIX options are invalid")
+ if options & _OPT_NUDGE:
+ self._skip_nudge()
+ vertical_alignment = self._u8()
+ horizontal_justification = self._u8()
+ vertical_justification = self._u8()
+ if (
+ vertical_alignment > 4
+ or horizontal_justification not in {1, 2, 3, 4, 5}
+ or vertical_justification > 4
+ ):
+ raise _MtefError("MTEF v5 MATRIX alignment is invalid")
+ rows = self._u8()
+ cols = self._u8()
+ if rows == 0 or cols == 0 or rows * cols > 4096:
+ raise _MtefError("MTEF v5 matrix dimensions are invalid")
+ self._bytes((2 * (rows + 1) + 7) // 8)
+ self._bytes((2 * (cols + 1) + 7) // 8)
+ self._enter()
+ children = self._parse_list()
+ self._leave()
+ cells = tuple(child for child in children if child.kind == "sequence")
+ if len(cells) != rows * cols or len(cells) != len(children):
+ raise _MtefError("MTEF v5 matrix cell list is invalid")
+ return _Node("matrix", (rows, cols), cells)
+
+ def _parse_template(self) -> _Node:
+ """读取 TMPL selector、variation、options 并转换为语义 AST。"""
+
+ record_options = self._u8()
+ if record_options & ~_OPT_NUDGE:
+ raise _MtefError("MTEF v5 TMPL options are invalid")
+ if record_options & _OPT_NUDGE:
+ self._skip_nudge()
+ selector = self._u8()
+ variation = self._variation()
+ template_options = self._u8()
+ self._enter()
+ slots = self._parse_list()
+ self._leave()
+ return _semantic_template(selector, variation, template_options, slots)
+
+ def _parse_record(self, record_type: int) -> _Node:
+ """解析一条已读取 type 的 v5 record。"""
+
+ if record_type == 1:
+ return self._parse_line()
+ if record_type == 2:
+ return self._parse_character()
+ if record_type == 3:
+ return self._parse_template()
+ if record_type == 4:
+ return self._parse_pile()
+ if record_type == 5:
+ return self._parse_matrix()
+ if record_type == 6:
+ raise _MtefError("MTEF v5 EMBELL appears outside a CHAR list")
+ if record_type == 7:
+ self._skip_ruler()
+ return _Node("metadata")
+ if record_type == 8:
+ return self._parse_font_style_definition()
+ if record_type == 9:
+ self._skip_size()
+ return _Node("metadata")
+ if 10 <= record_type <= 14:
+ return _Node("metadata")
+ if record_type == 15:
+ color_index = self._unsigned()
+ if not 0 < color_index <= self.color_definition_count:
+ raise _MtefError("MTEF v5 COLOR reference is invalid")
+ return _Node("metadata")
+ if record_type == 16:
+ return self._parse_color_definition()
+ if record_type == 17:
+ return self._parse_font_definition()
+ if record_type == 18:
+ return self._parse_equation_preferences()
+ if record_type == 19:
+ return self._parse_encoding_definition()
+ if record_type >= 100:
+ self._bytes(self._unsigned())
+ return _Node("metadata")
+ raise _MtefError(f"unsupported MTEF v5 record type: {record_type}")
+
+ @staticmethod
+ def _group_character_runs(nodes: list[_Node]) -> tuple[_Node, ...]:
+ """把连续 TEXT 字符和 FUNC_START 函数字符折叠为语义节点。"""
+
+ grouped: list[_Node] = []
+ index = 0
+ while index < len(nodes):
+ node = nodes[index]
+ if node.kind != "character_v5":
+ grouped.append(node)
+ index += 1
+ continue
+ character, embellishments, style_bits, typeface, function_start = node.value # type: ignore[misc]
+ if (
+ isinstance(character, int)
+ and int(typeface) in {1, 12}
+ and not embellishments
+ and not style_bits
+ ):
+ characters = [chr(character)]
+ cursor = index + 1
+ while cursor < len(nodes):
+ candidate = nodes[cursor]
+ if candidate.kind != "character_v5":
+ break
+ c_char, c_embell, c_style, c_typeface, _c_start = candidate.value # type: ignore[misc]
+ if (
+ not isinstance(c_char, int)
+ or c_embell
+ or c_style
+ or int(c_typeface) != int(typeface)
+ ):
+ break
+ characters.append(chr(c_char))
+ cursor += 1
+ grouped.append(_Node("text", "".join(characters)))
+ index = cursor
+ continue
+ if (
+ not isinstance(character, int)
+ or not function_start
+ or int(typeface) != 2
+ or embellishments
+ or style_bits
+ ):
+ grouped.append(node)
+ index += 1
+ continue
+ characters = [chr(int(character))]
+ cursor = index + 1
+ while cursor < len(nodes):
+ candidate = nodes[cursor]
+ if candidate.kind != "character_v5":
+ break
+ c_char, c_embell, c_style, c_typeface, _c_start = candidate.value # type: ignore[misc]
+ if (
+ not isinstance(c_char, int)
+ or c_embell
+ or c_style
+ or int(c_typeface) != 2
+ ):
+ break
+ characters.append(chr(int(c_char)))
+ cursor += 1
+ grouped.append(_Node("function", "".join(characters)))
+ index = cursor
+ return tuple(grouped)
+
+ def _parse_list(self) -> tuple[_Node, ...]:
+ """解析以 END 终止的 v5 object list。"""
+
+ nodes: list[_Node] = []
+ while True:
+ record_type = self._u8()
+ self._charge()
+ if record_type == 0:
+ return self._group_character_runs(nodes)
+ node = self._parse_record(record_type)
+ if node.kind != "metadata":
+ nodes.append(node)
+
+ def parse(self) -> _Node:
+ """解析根 object list,要求完整消费且产生可见公式。"""
+
+ children = self._parse_list()
+ if self.pos != len(self.data):
+ raise _MtefError("MTEF v5 contains trailing bytes")
+ root = _Node("sequence", children=children)
+ if not _render_node(root).strip():
+ raise _MtefError("MTEF v5 formula contains no visible content")
+ return root
+
+
+def _slot_node(slots: tuple[_Node, ...], index: int) -> _Node:
+ """返回一个 template slot,不存在时补空 sequence。"""
+
+ return slots[index] if index < len(slots) else _Node("sequence")
+
+
+def _semantic_template(
+ selector: int,
+ variation: int,
+ options: int,
+ slots: tuple[_Node, ...],
+) -> _Node:
+ """把 MTEF v5 selector/variation 转换为版本无关语义节点。"""
+
+ if 0 <= selector <= 8:
+ if variation & ~0x03 or options not in {0, 1, 2}:
+ raise _MtefError("unsupported MTEF v5 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"),
+ 8: (r"\llbracket", r"\rrbracket"),
+ }
+ default_left, default_right = pairs[selector]
+ left = default_left if variation & 0x01 else "."
+ right = default_right if variation & 0x02 else "."
+ return _Node(
+ "fence_semantic",
+ (left, right),
+ (_slot_node(slots, 0), _slot_node(slots, 1), _slot_node(slots, 2)),
+ )
+ if selector == 9:
+ if variation & ~0x33 or options not in {0, 1, 2}:
+ raise _MtefError("unsupported MTEF v5 interval variation")
+ left = {0: "(", 1: ")", 2: "[", 3: "]"}[variation & 0x03]
+ right = {0: "(", 1: ")", 2: "[", 3: "]"}[(variation >> 4) & 0x03]
+ return _Node("fence_semantic", (left, right), (_slot_node(slots, 0),))
+ if selector == 10:
+ if variation not in {0, 1} or options != 0:
+ raise _MtefError("unsupported MTEF v5 root variation")
+ return _Node(
+ "root_semantic",
+ variation == 1,
+ (_slot_node(slots, 0), _slot_node(slots, 1)),
+ )
+ if selector == 11:
+ if variation & ~0x07 or options != 0:
+ raise _MtefError("unsupported MTEF v5 fraction variation")
+ return _Node(
+ "fraction_semantic",
+ bool(variation & 0x02),
+ (_slot_node(slots, 0), _slot_node(slots, 1)),
+ )
+ if selector in {12, 13}:
+ if variation & ~0x01 or options != 0:
+ raise _MtefError("unsupported MTEF v5 bar variation")
+ return _Node(
+ "bar_semantic",
+ (selector == 12, bool(variation & 0x01)),
+ (_slot_node(slots, 0),),
+ )
+ if selector == 14:
+ if variation & ~0x3F or options != 0:
+ raise _MtefError("unsupported MTEF v5 arrow variation")
+ return _Node("arrow_semantic", variation, slots)
+ if 15 <= selector <= 22:
+ if options not in {0, 1} or variation & ~0x01FF:
+ raise _MtefError("unsupported MTEF v5 big-operator variation")
+ defaults = {
+ 15: r"\int",
+ 16: r"\sum",
+ 17: r"\prod",
+ 18: r"\coprod",
+ 19: r"\bigcup",
+ 20: r"\bigcap",
+ 21: "",
+ 22: "",
+ }
+ return _Node(
+ "big_operator_semantic",
+ defaults[selector],
+ tuple(_slot_node(slots, index) for index in range(4)),
+ )
+ if selector == 23:
+ if variation not in {0, 1} or options != 0:
+ raise _MtefError("unsupported MTEF v5 limit variation")
+ return _Node(
+ "limit_semantic",
+ None,
+ tuple(_slot_node(slots, index) for index in range(3)),
+ )
+ if selector in {24, 25}:
+ if variation & ~0x01 or options != 0:
+ raise _MtefError("unsupported MTEF v5 horizontal-fence variation")
+ return _Node(
+ "horizontal_fence_semantic",
+ (selector == 24, bool(variation & 0x01)),
+ tuple(_slot_node(slots, index) for index in range(3)),
+ )
+ if selector == 26:
+ if variation & ~0x01 or options != 0:
+ raise _MtefError("unsupported MTEF v5 long-division variation")
+ return _Node(
+ "long_division_semantic",
+ bool(variation & 0x01),
+ (_slot_node(slots, 0), _slot_node(slots, 1)),
+ )
+ if selector in {27, 28, 29}:
+ if variation & ~0x01 or options != 0:
+ raise _MtefError("unsupported MTEF v5 script variation")
+ subscript = (
+ _slot_node(slots, 0)
+ if selector in {27, 29}
+ else _Node("sequence")
+ )
+ superscript = (
+ _slot_node(slots, 1)
+ if selector in {28, 29}
+ else _Node("sequence")
+ )
+ return _Node(
+ "scripts_semantic",
+ bool(variation & 0x01),
+ (subscript, superscript),
+ )
+ if selector == 30:
+ if variation & ~0x03 or options != 0:
+ raise _MtefError("unsupported MTEF v5 Dirac variation")
+ return _Node(
+ "dirac_semantic",
+ variation,
+ tuple(_slot_node(slots, index) for index in range(5)),
+ )
+ if selector == 31:
+ if variation & ~0x0F or options != 0 or variation & 0x08 and variation & 0x03 == 0x03:
+ raise _MtefError("unsupported MTEF v5 vector variation")
+ return _Node("vector_semantic", variation, (_slot_node(slots, 0),))
+ if selector in {32, 33, 34}:
+ if variation != 0 or options != 0:
+ raise _MtefError("unsupported MTEF v5 accent variation")
+ command = {32: "widetilde", 33: "widehat", 34: "overparen"}[selector]
+ return _Node("accent_semantic", command, (_slot_node(slots, 0),))
+ if selector == 35:
+ raise _MtefError("unsupported MTEF v5 joint-status template")
+ if selector == 36:
+ if variation & ~0x07 or variation == 0 or variation & 0x01 or options != 0:
+ raise _MtefError("unsupported MTEF v5 strike variation")
+ command = "xcancel" if variation & 0x06 == 0x06 else "cancel" if variation & 0x02 else "bcancel"
+ return _Node("strike_semantic", command, (_slot_node(slots, 0),))
+ if selector == 37:
+ if options != 0 or variation not in {0, 0x1E}:
+ raise _MtefError("unsupported MTEF v5 box variation")
+ return _Node("box_semantic", None, (_slot_node(slots, 0),))
+ raise _MtefError(f"unsupported MTEF v5 template selector: {selector}")
+
+
+def decode_mtef_v5(data: bytes) -> str | None:
+ """把 MTEF v5 字节流转换为 LaTeX,损坏或不支持时整体返回空。"""
+
+ try:
+ latex = _render_node(_MtefV5Reader(data).parse()).strip()
+ except LegacyOfficeResourceLimitError:
+ raise
+ except (
+ ArithmeticError,
+ IndexError,
+ struct.error,
+ UnicodeError,
+ _MtefError,
+ ValueError,
+ ):
+ return None
+ return latex or None
diff --git a/mineru/model/flash/office/image.py b/mineru/model/flash/office/image.py
index 62cd81f0..5f02fc75 100644
--- a/mineru/model/flash/office/image.py
+++ b/mineru/model/flash/office/image.py
@@ -32,6 +32,16 @@ STANDARD_VECTOR_PLACEHOLDER_LINES: Final = (
)
+def _is_wmf_payload(image_data: bytes) -> bool:
+ """根据 placeable 或标准 METAHEADER magic 判断原始载荷是否为 WMF。"""
+
+ return image_data.startswith(b"\xd7\xcd\xc6\x9a") or (
+ len(image_data) >= 4
+ and image_data[:2] in {b"\x01\x00", b"\x02\x00"}
+ and image_data[2:4] == b"\x09\x00"
+ )
+
+
def is_vector_image(pil_image: Image.Image) -> bool:
"""判断已由 Pillow 打开的图片是否属于 WMF/EMF 矢量格式。"""
return (getattr(pil_image, "format", None) or "").upper() in VECTOR_IMAGE_FORMATS
@@ -171,7 +181,11 @@ def serialize_office_image(
content_type: str | None = None,
) -> str | None:
"""识别并序列化 Office 图片,透明图保留 PNG,普通位图优先使用 JPEG。"""
- if is_vector_image_part(part_name, content_type):
+ is_wmf_payload = _is_wmf_payload(image_data)
+ if is_wmf_payload:
+ part_name = "image.wmf"
+ content_type = "image/wmf"
+ if is_wmf_payload or is_vector_image_part(part_name, content_type):
if not is_windows_environment():
return serialize_vector_part_with_placeholder(part_name, content_type)
diff --git a/mineru/model/flash/office/image_equation.py b/mineru/model/flash/office/image_equation.py
new file mode 100644
index 00000000..9424cec7
--- /dev/null
+++ b/mineru/model/flash/office/image_equation.py
@@ -0,0 +1,509 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+"""从 WMF/GIF 图片 comment 中安全恢复 MathType MTEF 公式。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import hashlib
+from pathlib import PurePosixPath
+import struct
+
+from loguru import logger
+
+from mineru.model.flash.legacy_office.errors import (
+ LegacyOfficeResourceLimitError,
+)
+from mineru.model.flash.legacy_office.limits import (
+ MAX_ASSET_TOTAL_BYTES,
+ MAX_ENTRY_BYTES,
+ MAX_PICTURE_RECORDS,
+)
+from mineru.model.flash.legacy_office.mtef import decode_mtef
+
+_PLACEABLE_WMF_MAGIC = b"\xd7\xcd\xc6\x9a"
+_META_ESCAPE = 0x0626
+_MFCOMMENT = 0x000F
+_APPS_MFCC_ID = b"AppsMFCC"
+_GIF_HEADERS = {b"GIF87a", b"GIF89a"}
+_HISTORICAL_APPS_SIGNATURES = {
+ "design science",
+ "design science, inc.",
+ "wiris",
+}
+
+
+class _ImageEquationError(ValueError):
+ """图片 comment 结构损坏、冲突或不受支持。"""
+
+
+@dataclass(frozen=True, slots=True)
+class _AppsChunk:
+ """一段已验证边界和 signature 的 AppsMFCC 数据。"""
+
+ key: tuple[str, ...]
+ total_length: int
+ data: bytes
+
+
+def _charge_picture_record(counter: list[int]) -> None:
+ """累计 WMF/GIF record 数并在超限时抛稳定资源错误。"""
+
+ counter[0] += 1
+ if counter[0] > MAX_PICTURE_RECORDS:
+ raise LegacyOfficeResourceLimitError(
+ "image equation records exceed "
+ f"max_picture_records={MAX_PICTURE_RECORDS}"
+ )
+
+
+def _signature_components(value: str) -> tuple[str, ...] | None:
+ """按 AppsMFCC 转义规则拆分 slash 分隔的 signature。"""
+
+ components: list[str] = []
+ current: list[str] = []
+ escaped = False
+ for character in value:
+ if escaped:
+ current.append(character)
+ escaped = False
+ elif character == "\\":
+ escaped = True
+ elif character == "/":
+ components.append("".join(current))
+ current = []
+ else:
+ current.append(character)
+ if escaped:
+ return None
+ components.append("".join(current))
+ if any(not component for component in components):
+ return None
+ return tuple(components)
+
+
+def _parse_apps_chunk(comment: bytes) -> _AppsChunk | None:
+ """解析一个 AppsMFCC comment,并仅接受规范或历史 MTEF signature。"""
+
+ if not comment.startswith(_APPS_MFCC_ID):
+ return None
+ if len(comment) > 0x7FFE:
+ raise _ImageEquationError("AppsMFCC comment exceeds WMF size limit")
+ if len(comment) < 19:
+ raise _ImageEquationError("AppsMFCC header is truncated")
+ version, total_length, data_length = struct.unpack_from("<HII", comment, 8)
+ if version != 1:
+ raise _ImageEquationError("AppsMFCC version is unsupported")
+ if (
+ total_length <= 0
+ or data_length <= 0
+ or data_length > total_length
+ or total_length > MAX_ENTRY_BYTES
+ ):
+ raise _ImageEquationError("AppsMFCC lengths are invalid")
+
+ signature_start = 18
+ signature_limit = min(len(comment), signature_start + 4097)
+ signature_end = comment.find(b"\x00", signature_start, signature_limit)
+ if signature_end < 0:
+ raise _ImageEquationError("AppsMFCC signature is not null-terminated")
+ try:
+ signature = comment[signature_start:signature_end].decode("ascii")
+ except UnicodeDecodeError as exc:
+ raise _ImageEquationError("AppsMFCC signature is not ASCII") from exc
+ components = _signature_components(signature)
+ if components is None:
+ raise _ImageEquationError("AppsMFCC signature is malformed")
+ normalized = tuple(component.strip().casefold() for component in components)
+ is_mtef = (
+ len(normalized) >= 2 and normalized[1] == "mtef"
+ ) or (
+ len(normalized) == 1
+ and normalized[0] in _HISTORICAL_APPS_SIGNATURES
+ )
+ if not is_mtef:
+ return None
+
+ data_start = signature_end + 1
+ data_end = data_start + int(data_length)
+ if data_end < data_start or data_end > len(comment):
+ raise _ImageEquationError("AppsMFCC chunk is truncated")
+ if any(comment[data_end:]):
+ raise _ImageEquationError("AppsMFCC comment has non-padding tail bytes")
+ key = (str(version), *normalized[:2])
+ return _AppsChunk(
+ key=key,
+ total_length=int(total_length),
+ data=comment[data_start:data_end],
+ )
+
+
+def _pre6_mtef_comment(comment: bytes) -> bytes | None:
+ """从 MathType 6.0b 前的单 comment 头提取 MTEF。"""
+
+ if not comment.startswith(b"MathType"):
+ return None
+ if len(comment) > 0x7FFE:
+ raise _ImageEquationError("pre-6 MathType comment exceeds WMF size limit")
+ if len(comment) < 12:
+ raise _ImageEquationError("pre-6 MathType comment is truncated")
+ magic, data_length = struct.unpack_from("<HH", comment, 8)
+ if magic != 0x5555:
+ # type=0 是 baseline comment,其他类型也不是 MTEF。
+ return None
+ data_start = 12
+ data_end = data_start + int(data_length)
+ if data_end < data_start or data_end > len(comment):
+ raise _ImageEquationError("pre-6 MathType comment length is invalid")
+ if any(comment[data_end:]):
+ raise _ImageEquationError("pre-6 MathType comment has non-padding tail bytes")
+ return comment[data_start:data_end]
+
+
+def _wmf_comments(image_data: bytes) -> tuple[list[bytes], bool]:
+ """有界遍历 WMF META_ESCAPE/MFCOMMENT 并返回 comment payloads。"""
+
+ cursor = 22 if image_data.startswith(_PLACEABLE_WMF_MAGIC) else 0
+ if cursor + 18 > len(image_data):
+ return [], False
+ metafile_type, header_words, _version, file_words = struct.unpack_from(
+ "<HHHI",
+ image_data,
+ cursor,
+ )
+ if metafile_type not in {1, 2} or header_words != 9:
+ return [], False
+ declared_end = cursor + int(file_words) * 2
+ if declared_end < cursor + 18 or declared_end > len(image_data):
+ raise _ImageEquationError("WMF declared file size is invalid")
+
+ comments: list[bytes] = []
+ counter = [0]
+ record_cursor = cursor + 18
+ saw_eof = False
+ while record_cursor < declared_end:
+ _charge_picture_record(counter)
+ if record_cursor + 6 > declared_end:
+ raise _ImageEquationError("WMF record header is truncated")
+ record_words, record_function = struct.unpack_from(
+ "<IH",
+ image_data,
+ record_cursor,
+ )
+ if record_words < 3:
+ raise _ImageEquationError("WMF record size is invalid")
+ record_end = record_cursor + int(record_words) * 2
+ if record_end <= record_cursor or record_end > declared_end:
+ raise _ImageEquationError("WMF record exceeds declared file size")
+ if record_function == 0:
+ saw_eof = True
+ record_cursor = record_end
+ break
+ if record_function == _META_ESCAPE:
+ if record_cursor + 10 > record_end:
+ raise _ImageEquationError("WMF META_ESCAPE record is truncated")
+ escape_function, byte_count = struct.unpack_from(
+ "<HH",
+ image_data,
+ record_cursor + 6,
+ )
+ data_start = record_cursor + 10
+ data_end = data_start + int(byte_count)
+ if data_end < data_start or data_end > record_end:
+ raise _ImageEquationError("WMF META_ESCAPE byte count is invalid")
+ if escape_function == _MFCOMMENT:
+ comments.append(image_data[data_start:data_end])
+ record_cursor = record_end
+
+ if not saw_eof or record_cursor != declared_end:
+ raise _ImageEquationError("WMF EOF record is missing or misplaced")
+ if any(image_data[declared_end:]):
+ raise _ImageEquationError("WMF contains non-padding bytes after declared end")
+ return comments, True
+
+
+def _wmf_mtef_candidates(image_data: bytes) -> tuple[list[bytes], bool]:
+ """从 WMF comments 提取 pre-6 与 AppsMFCC MTEF candidates。"""
+
+ comments, is_wmf = _wmf_comments(image_data)
+ if not is_wmf:
+ return [], False
+ candidates: list[bytes] = []
+ recognized = False
+ pending: _AppsChunk | None = None
+ pending_data = bytearray()
+
+ for comment in comments:
+ pre6 = _pre6_mtef_comment(comment)
+ if pre6 is not None:
+ recognized = True
+ candidates.append(pre6)
+ continue
+
+ is_apps = comment.startswith(_APPS_MFCC_ID)
+ try:
+ chunk = _parse_apps_chunk(comment)
+ except _ImageEquationError:
+ recognized = True
+ pending = None
+ pending_data.clear()
+ continue
+ if chunk is None:
+ if is_apps and pending is not None:
+ recognized = True
+ pending = None
+ pending_data.clear()
+ continue
+ recognized = True
+
+ if pending is None:
+ if len(chunk.data) == chunk.total_length:
+ candidates.append(chunk.data)
+ else:
+ pending = chunk
+ pending_data = bytearray(chunk.data)
+ continue
+
+ if (
+ chunk.key != pending.key
+ or chunk.total_length != pending.total_length
+ ):
+ pending = None
+ pending_data.clear()
+ if len(chunk.data) == chunk.total_length:
+ candidates.append(chunk.data)
+ elif len(chunk.data) < chunk.total_length:
+ pending = chunk
+ pending_data = bytearray(chunk.data)
+ continue
+ pending_data.extend(chunk.data)
+ if len(pending_data) == pending.total_length:
+ candidates.append(bytes(pending_data))
+ pending = None
+ pending_data.clear()
+ elif len(pending_data) > pending.total_length:
+ pending = None
+ pending_data.clear()
+
+ if pending is not None:
+ recognized = True
+ return candidates, recognized
+
+
+def _gif_subblocks(
+ image_data: bytes,
+ cursor: int,
+ counter: list[int],
+) -> tuple[bytes, int]:
+ """读取以零长度块终止的 GIF sub-block 序列。"""
+
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ _charge_picture_record(counter)
+ if cursor >= len(image_data):
+ raise _ImageEquationError("GIF sub-block length is truncated")
+ size = image_data[cursor]
+ cursor += 1
+ if size == 0:
+ return b"".join(chunks), cursor
+ end = cursor + size
+ if end < cursor or end > len(image_data):
+ raise _ImageEquationError("GIF sub-block data is truncated")
+ total += size
+ if total > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"GIF extension exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ chunks.append(image_data[cursor:end])
+ cursor = end
+
+
+def _gif_mtef_candidates(image_data: bytes) -> tuple[list[bytes], bool]:
+ """完整遍历 GIF blocks 并提取 MathType/001 Application Extension。"""
+
+ if len(image_data) < 13 or image_data[:6] not in _GIF_HEADERS:
+ return [], False
+ packed = image_data[10]
+ cursor = 13
+ if packed & 0x80:
+ cursor += 3 * (1 << ((packed & 0x07) + 1))
+ if cursor > len(image_data):
+ raise _ImageEquationError("GIF global color table is truncated")
+
+ candidates: list[bytes] = []
+ recognized = False
+ counter = [0]
+ saw_trailer = False
+ while cursor < len(image_data):
+ _charge_picture_record(counter)
+ marker = image_data[cursor]
+ cursor += 1
+ if marker == 0x3B:
+ saw_trailer = True
+ break
+ if marker == 0x2C:
+ if cursor + 9 > len(image_data):
+ raise _ImageEquationError("GIF image descriptor is truncated")
+ image_packed = image_data[cursor + 8]
+ cursor += 9
+ if image_packed & 0x80:
+ cursor += 3 * (1 << ((image_packed & 0x07) + 1))
+ if cursor >= len(image_data):
+ raise _ImageEquationError("GIF image data is truncated")
+ cursor += 1 # LZW minimum code size
+ _image_payload, cursor = _gif_subblocks(image_data, cursor, counter)
+ continue
+ if marker != 0x21:
+ raise _ImageEquationError("GIF block marker is invalid")
+ if cursor >= len(image_data):
+ raise _ImageEquationError("GIF extension label is truncated")
+ extension_label = image_data[cursor]
+ cursor += 1
+ if extension_label != 0xFF:
+ _payload, cursor = _gif_subblocks(image_data, cursor, counter)
+ continue
+ if cursor >= len(image_data):
+ raise _ImageEquationError("GIF application block size is truncated")
+ application_size = image_data[cursor]
+ cursor += 1
+ application_end = cursor + application_size
+ if application_end > len(image_data):
+ raise _ImageEquationError("GIF application identifier is truncated")
+ application = image_data[cursor:application_end]
+ cursor = application_end
+ payload, cursor = _gif_subblocks(image_data, cursor, counter)
+ if application_size != 11:
+ continue
+ application_id = application[:8]
+ authentication = application[8:11]
+ if application_id == b"MathType" and authentication == b"001":
+ recognized = True
+ candidates.append(payload)
+ # MathType/002 是 baseline,必须明确忽略。
+
+ if not saw_trailer:
+ raise _ImageEquationError("GIF trailer is missing")
+ if any(image_data[cursor:]):
+ raise _ImageEquationError("GIF contains non-padding bytes after trailer")
+ return candidates, recognized
+
+
+def _select_candidate_latex(candidates: list[bytes]) -> str | None:
+ """解码全部 candidates;仅返回唯一且完整一致的 LaTeX。"""
+
+ decoded = {
+ latex
+ for candidate in candidates
+ if (latex := decode_mtef(candidate)) is not None
+ }
+ return next(iter(decoded)) if len(decoded) == 1 else None
+
+
+def _format_hint(
+ image_data: bytes,
+ part_name: object | None,
+ content_type: str | None,
+) -> str | None:
+ """结合 magic、扩展名和内容类型确定 WMF/GIF decoder。"""
+
+ if image_data[:6] in _GIF_HEADERS:
+ return "gif"
+ if image_data.startswith(_PLACEABLE_WMF_MAGIC):
+ return "wmf"
+ if (
+ len(image_data) >= 4
+ and image_data[:2] in {b"\x01\x00", b"\x02\x00"}
+ and image_data[2:4] == b"\x09\x00"
+ ):
+ return "wmf"
+ suffix = PurePosixPath(str(part_name or "")).suffix.casefold()
+ normalized_content_type = (content_type or "").split(";", 1)[0].strip().casefold()
+ if suffix == ".gif" or normalized_content_type == "image/gif":
+ return "gif"
+ if suffix == ".wmf" or normalized_content_type in {
+ "image/wmf",
+ "image/x-wmf",
+ "application/x-msmetafile",
+ }:
+ return "wmf"
+ return None
+
+
+@dataclass(slots=True)
+class OfficeImageEquationDecoder:
+ """按共享资源上限缓存并解码 WMF/GIF 图片中的 MTEF。"""
+
+ total_bytes: int = 0
+ _cache: dict[tuple[str, bytes], str | None] = field(default_factory=dict)
+ _warned: set[tuple[str, bytes]] = field(default_factory=set)
+
+ def decode(
+ self,
+ image_data: object | None,
+ *,
+ part_name: object | None = None,
+ content_type: str | None = None,
+ ) -> str | None:
+ """识别图片格式、执行有界 comment 解包并返回完整 LaTeX。"""
+
+ if not isinstance(image_data, bytes):
+ return None
+ image_format = _format_hint(image_data, part_name, content_type)
+ if image_format is None:
+ return None
+ if len(image_data) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ "image equation payload exceeds "
+ f"max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ digest = hashlib.sha256(image_data).digest()
+ cache_key = (image_format, digest)
+ if cache_key in self._cache:
+ return self._cache[cache_key]
+ if self.total_bytes + len(image_data) > MAX_ASSET_TOTAL_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ "image equation payloads exceed "
+ f"max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
+ )
+ self.total_bytes += len(image_data)
+
+ recognized = False
+ try:
+ if image_format == "wmf":
+ candidates, recognized = _wmf_mtef_candidates(image_data)
+ else:
+ candidates, recognized = _gif_mtef_candidates(image_data)
+ latex = _select_candidate_latex(candidates)
+ except LegacyOfficeResourceLimitError:
+ raise
+ except (_ImageEquationError, ArithmeticError, IndexError, struct.error):
+ latex = None
+ recognized = (
+ b"MathType" in image_data
+ or _APPS_MFCC_ID in image_data
+ )
+ self._cache[cache_key] = latex
+ if recognized and latex is None and cache_key not in self._warned:
+ self._warned.add(cache_key)
+ logger.warning(
+ "OFFICE_IMAGE_MTEF_FALLBACK: format={}, payload_sha256={} is malformed, conflicting, or unsupported",
+ image_format,
+ digest.hex()[:16],
+ )
+ return latex
+
+
+def decode_image_embedded_equation(
+ image_data: bytes,
+ *,
+ part_name: object | None = None,
+ content_type: str | None = None,
+) -> str | None:
+ """使用一次性有界 decoder 从单张 WMF/GIF 中恢复 MTEF。"""
+
+ return OfficeImageEquationDecoder().decode(
+ image_data,
+ part_name=part_name,
+ content_type=content_type,
+ )
diff --git a/mineru/model/flash/office/ooxml_equation.py b/mineru/model/flash/office/ooxml_equation.py
index a772055a..34f9200c 100644
--- a/mineru/model/flash/office/ooxml_equation.py
+++ b/mineru/model/flash/office/ooxml_equation.py
@@ -1,6 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""现代 Office OOXML 包中的 Equation.3 OLE 公式解码适配器。"""
+"""现代 Office OOXML 包中的 MathType/Equation OLE 公式解码适配器。"""
from __future__ import annotations
@@ -15,18 +15,25 @@ from mineru.model.flash.legacy_office.limits import (
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"
+EQUATION_PROG_ID = "equation"
+EQUATION_PROG_ID_PREFIX = "equation."
-def is_equation_3_prog_id(prog_id: object | None) -> bool:
- """判断 OOXML OLE ProgID 是否精确指向 Equation.3。"""
+def is_mathtype_equation_prog_id(prog_id: object | None) -> bool:
+ """判断 OLE ProgID 是否为 Equation 或带非空版本后缀的 Equation.*。"""
- return isinstance(prog_id, str) and prog_id.strip().casefold() == EQUATION_3_PROG_ID
+ if not isinstance(prog_id, str):
+ return False
+ normalized = prog_id.strip().casefold()
+ return normalized == EQUATION_PROG_ID or (
+ normalized.startswith(EQUATION_PROG_ID_PREFIX)
+ and len(normalized) > len(EQUATION_PROG_ID_PREFIX)
+ )
@dataclass(slots=True)
class OoxmlEquationDecoder:
- """按共享资源上限缓存并解码 OOXML 中的 Equation.3 对象。"""
+ """按共享资源上限缓存并解码 OOXML 中的公式 OLE 对象。"""
total_bytes: int = 0
_cache: dict[bytes, str | None] = field(default_factory=dict)
@@ -38,15 +45,15 @@ class OoxmlEquationDecoder:
prog_id: object | None,
show_as_icon: bool = False,
) -> str | None:
- """校验 ProgID、图标模式、CFB 头和资源预算后返回 LaTeX。"""
+ """校验公式 ProgID、图标模式、CFB 头和资源预算后返回 LaTeX。"""
- if show_as_icon or not is_equation_3_prog_id(prog_id) or blob is None:
+ if show_as_icon or not is_mathtype_equation_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}"
+ f"OOXML equation object exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
)
if not blob.startswith(CFB_MAGIC):
return None
@@ -56,7 +63,7 @@ class OoxmlEquationDecoder:
return self._cache[digest]
if self.total_bytes + len(blob) > MAX_ASSET_TOTAL_BYTES:
raise LegacyOfficeResourceLimitError(
- "OOXML Equation.3 objects exceed "
+ "OOXML equation objects exceed "
f"max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"
)
diff --git a/mineru/model/flash/ppt/models.py b/mineru/model/flash/ppt/models.py
index f3155ce0..1bc44400 100644
--- a/mineru/model/flash/ppt/models.py
+++ b/mineru/model/flash/ppt/models.py
@@ -56,7 +56,7 @@ class PptImageElement:
@dataclass(frozen=True, slots=True)
class PptEquationElement:
- """已经从 Equation Editor 原生对象恢复的 LaTeX 公式。"""
+ """已经从原生对象或图片 comment 恢复的 LaTeX 公式。"""
latex: str
bbox: tuple[float, float, float, float]
diff --git a/mineru/model/flash/ppt/parser.py b/mineru/model/flash/ppt/parser.py
index 48ff1652..da36c8e3 100644
--- a/mineru/model/flash/ppt/parser.py
+++ b/mineru/model/flash/ppt/parser.py
@@ -32,6 +32,9 @@ from mineru.model.flash.legacy_office.officeart import (
decode_blip as decode_officeart_blip,
)
from mineru.model.flash.office.image import serialize_office_image
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
+)
from .models import (
PptEquationElement,
@@ -1445,9 +1448,10 @@ def _picture_map(
def _image_from_shape(
shape: _ShapeInfo,
image_map: dict[int, _ImagePayload],
+ equation_decoder: OfficeImageEquationDecoder,
budget: RecordBudget,
-) -> PptImageElement | None:
- """把 shape 的 pib 属性解析为可输出的 slide 图片。"""
+) -> PptImageElement | PptEquationElement | None:
+ """把 shape 的 pib 属性解析为图片或 comment 内公式。"""
reference = _shape_properties(shape.record, budget).get(FOPT_PIB)
if reference is None:
@@ -1458,6 +1462,18 @@ def _image_from_shape(
f"PPT_IMAGE_REFERENCE_MISSING: shape={shape.key}, pib={reference}"
)
return None
+ latex = equation_decoder.decode(
+ image.data,
+ part_name=f"picture.{image.extension}",
+ content_type=image.content_type,
+ )
+ if latex:
+ return PptEquationElement(
+ latex=latex,
+ bbox=shape.bbox,
+ order=shape.order,
+ shape_offset=shape.order,
+ )
data_uri = serialize_office_image(
image.data,
part_name=f"picture.{image.extension}",
@@ -1499,6 +1515,7 @@ def _slide_elements(
hyperlinks: dict[int, str],
image_map: dict[int, _ImagePayload],
equation_map: dict[int, str],
+ image_equation_decoder: OfficeImageEquationDecoder,
slide_width: int,
slide_height: int,
budget: RecordBudget,
@@ -1565,9 +1582,20 @@ def _slide_elements(
is_placeholder=_is_placeholder(shape.record, budget),
)
)
- image = _image_from_shape(shape, image_map, budget)
- if image is not None and not _is_small_picture(image.bbox, slide_width, slide_height):
- elements.append(image)
+ image_or_equation = _image_from_shape(
+ shape,
+ image_map,
+ image_equation_decoder,
+ budget,
+ )
+ if isinstance(image_or_equation, PptEquationElement):
+ elements.append(image_or_equation)
+ elif image_or_equation is not None and not _is_small_picture(
+ image_or_equation.bbox,
+ slide_width,
+ slide_height,
+ ):
+ elements.append(image_or_equation)
if not any(isinstance(element, PptTextElement) for element in elements):
# Handmade、早期生产器或恢复路径可能把文本直接放在 SlideContainer 中。
raw_contents = _parse_text_contents(
@@ -1758,6 +1786,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)
+ image_equation_decoder = OfficeImageEquationDecoder()
native_equations = _equation_map(layout, powerpoint_document, budget)
master_map, fallback_master = _collect_masters(
layout,
@@ -1821,6 +1850,7 @@ def parse_ppt_document(
hyperlinks,
image_map,
native_equations,
+ image_equation_decoder,
width,
height,
budget,
@@ -1846,6 +1876,7 @@ def parse_ppt_document(
hyperlinks,
image_map,
native_equations,
+ image_equation_decoder,
width,
height,
budget,
diff --git a/mineru/model/flash/pptx/pptx_converter.py b/mineru/model/flash/pptx/pptx_converter.py
index 77ef983d..7a0a58af 100644
--- a/mineru/model/flash/pptx/pptx_converter.py
+++ b/mineru/model/flash/pptx/pptx_converter.py
@@ -14,9 +14,12 @@ 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.image_equation import (
+ OfficeImageEquationDecoder,
+)
from mineru.model.flash.office.ooxml_equation import (
OoxmlEquationDecoder,
- is_equation_3_prog_id,
+ is_mathtype_equation_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
@@ -112,6 +115,7 @@ class PptxConverter:
] = {}
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
self._mtef_warned_shapes: set[tuple[str, int | None]] = set()
def convert(
@@ -142,6 +146,7 @@ class PptxConverter:
self.file_stream = None
self.pptx_obj = None
self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
self._mtef_warned_shapes = set()
@staticmethod
@@ -154,22 +159,22 @@ class PptxConverter:
return None
def _is_equation_ole_shape(self, shape: Any) -> bool:
- """判断 PPTX OLE shape 的 ProgID 是否为 Equation.3。"""
+ """判断 PPTX OLE shape 的 ProgID 是否为 MathType/Equation 公式。"""
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))
+ and is_mathtype_equation_prog_id(getattr(ole_format, "prog_id", None))
)
def _decode_pptx_ole_equation(self, shape: Any) -> str | None:
- """解码 PPTX 内嵌 Equation.3;链接、图标和坏对象返回空。"""
+ """解码 PPTX 内嵌公式 OLE;链接、图标和坏对象返回空。"""
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):
+ if not is_mathtype_equation_prog_id(prog_id):
return None
if bool(getattr(ole_format, "show_as_icon", False)):
return None
@@ -193,7 +198,7 @@ class PptxConverter:
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",
+ "PPTX_MTEF_FALLBACK: part={!r}, shape_id={!r} has an invalid or unsupported equation OLE object",
warning_key[0],
warning_key[1],
)
@@ -419,6 +424,15 @@ class PptxConverter:
self._handle_chart(shape)
if shape_type == MSO_SHAPE_TYPE.PICTURE:
+ image_latex = self._decode_pptx_shape_image_equation(shape)
+ if image_latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.EQUATION,
+ "content": image_latex,
+ }
+ )
+ return shape_blocks
later_shapes = linear_shapes[shape_index + 1 :]
if not self._should_skip_picture(
shape_entry,
@@ -687,8 +701,32 @@ class PptxConverter:
"content": self.equation_bookends.format(EQ=latex),
}
)
+ return
+ image_latex = self._decode_pptx_shape_image_equation(shape)
+ if image_latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": self.equation_bookends.format(
+ EQ=image_latex
+ ),
+ }
+ )
return
+ if shape_type == MSO_SHAPE_TYPE.PICTURE:
+ image_latex = self._decode_pptx_shape_image_equation(shape)
+ if image_latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": self.equation_bookends.format(
+ EQ=image_latex
+ ),
+ }
+ )
+ return
+
if self._should_skip_notes_shape(shape):
return
@@ -845,6 +883,19 @@ class PptxConverter:
image_bytes, content_type = image_data
+ latex = self._image_equation_decoder.decode(
+ image_bytes,
+ content_type=content_type,
+ )
+ if latex:
+ self.cur_page.append(
+ {
+ "type": BlockType.EQUATION,
+ "content": latex,
+ }
+ )
+ return
+
if content_type == "image/svg+xml":
image_block = {
"type": BlockType.IMAGE,
@@ -864,6 +915,18 @@ class PptxConverter:
self.cur_page.append(image_block)
return
+ def _decode_pptx_shape_image_equation(self, shape: Any) -> str | None:
+ """从普通 picture 或 OLE preview 的 WMF/GIF comment 恢复公式。"""
+
+ image_data = self._get_shape_image_data(shape)
+ if image_data is None:
+ return None
+ image_bytes, content_type = image_data
+ return self._image_equation_decoder.decode(
+ image_bytes,
+ content_type=content_type,
+ )
+
@classmethod
def _serialize_picture_image_best_effort(cls, image_bytes: bytes) -> Optional[str]:
"""尽量序列化图片;损坏图片失败时降级跳过,避免中断整份 PPTX。"""
diff --git a/mineru/model/flash/xls/models.py b/mineru/model/flash/xls/models.py
index 5f4d9a31..f1247bc4 100644
--- a/mineru/model/flash/xls/models.py
+++ b/mineru/model/flash/xls/models.py
@@ -57,7 +57,7 @@ class XlsImage:
@dataclass(frozen=True, slots=True)
class XlsEquation:
- """绑定到工作表 cell anchor 的 Equation Editor 原生公式。"""
+ """绑定到工作表 cell anchor 的原生或图片 comment 公式。"""
row: int
col: int
diff --git a/mineru/model/flash/xls/parser.py b/mineru/model/flash/xls/parser.py
index b1785166..a6b730d9 100644
--- a/mineru/model/flash/xls/parser.py
+++ b/mineru/model/flash/xls/parser.py
@@ -22,6 +22,9 @@ from mineru.model.flash.legacy_office.officeart import (
extract_excel_shapes,
)
from mineru.model.flash.office.image import serialize_office_image
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
+)
from .chart import chart_source_axes
from .models import (
@@ -464,7 +467,7 @@ def _pict_embedding_storage(payload: bytes, picture_flags: int | None) -> str |
if picture_flags is None:
return None
- # DDE、ActiveX、controls stream 与 camera picture 都不是内嵌 Equation.3 对象。
+ # DDE、ActiveX、controls stream 与 camera picture 都不是内嵌公式 OLE 对象。
if picture_flags & (0x0002 | 0x0010 | 0x0020 | 0x0080):
return None
if len(payload) < 10:
@@ -676,6 +679,7 @@ def _bind_objects(
globals_: _Globals,
sheet_index: int,
native_equations: dict[str, str],
+ image_equation_decoder: OfficeImageEquationDecoder,
budget: RecordBudget,
) -> None:
"""按 drawing/OBJ 顺序绑定文本框、复选框、图片与嵌入图表。"""
@@ -707,6 +711,21 @@ def _bind_objects(
if equation:
sheet.equations.append(XlsEquation(row=row, col=col, latex=equation))
continue
+ if (
+ object_.object_type == OBJ_PICTURE
+ and shape.pib is not None
+ and (payload := globals_.images.get(int(shape.pib))) is not None
+ ):
+ image_latex = image_equation_decoder.decode(
+ payload.data,
+ part_name=f"picture.{payload.extension}",
+ content_type=payload.content_type,
+ )
+ if image_latex:
+ sheet.equations.append(
+ XlsEquation(row=row, col=col, latex=image_latex)
+ )
+ 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:
@@ -778,6 +797,7 @@ def _read_sheet(
sheet_index: int,
recovered: bool,
native_equations: dict[str, str],
+ image_equation_decoder: OfficeImageEquationDecoder,
budget: RecordBudget,
) -> XlsSheet | None:
"""解析一个 worksheet substream 并绑定其 drawing/chart 对象。"""
@@ -1019,6 +1039,7 @@ def _read_sheet(
globals_=globals_,
sheet_index=sheet_index,
native_equations=native_equations,
+ image_equation_decoder=image_equation_decoder,
budget=budget,
)
return sheet
@@ -1059,6 +1080,7 @@ def parse_xls_workbook(
storage.casefold(): latex
for storage, latex in (native_equations or {}).items()
}
+ image_equation_decoder = OfficeImageEquationDecoder()
globals_ = _read_globals(data, budget)
candidates = _worksheet_bof_offsets(data)
used_offsets: set[int] = set()
@@ -1119,6 +1141,7 @@ def parse_xls_workbook(
sheet_index=sheet_index,
recovered=recovered,
native_equations=normalized_equations,
+ image_equation_decoder=image_equation_decoder,
budget=budget,
)
if parsed is None:
diff --git a/mineru/model/flash/xlsx/ooxml_ole.py b/mineru/model/flash/xlsx/ooxml_ole.py
index 866b9be7..6159bcd5 100644
--- a/mineru/model/flash/xlsx/ooxml_ole.py
+++ b/mineru/model/flash/xlsx/ooxml_ole.py
@@ -1,6 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
-"""读取 XLSX worksheet 中的 Equation.3 OLE 对象、anchor 与预览。"""
+"""读取 XLSX worksheet 中的 MathType/Equation OLE 对象、anchor 与预览。"""
from __future__ import annotations
@@ -15,9 +15,12 @@ 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.image_equation import (
+ OfficeImageEquationDecoder,
+)
from mineru.model.flash.office.ooxml_equation import (
OoxmlEquationDecoder,
- is_equation_3_prog_id,
+ is_mathtype_equation_prog_id,
)
WORKBOOK_PART = "xl/workbook.xml"
@@ -26,7 +29,7 @@ RELATIONSHIP_NS_SUFFIX = "/relationships"
@dataclass(frozen=True, slots=True)
class XlsxOleEquationArtifact:
- """一个已绑定 worksheet anchor 的 Equation.3 公式或预览。"""
+ """一个已绑定 worksheet anchor 的公式 OLE 结果或预览。"""
row: int | None
col: int | None
@@ -36,6 +39,17 @@ class XlsxOleEquationArtifact:
shape_id: str | None
+@dataclass(frozen=True, slots=True)
+class XlsxImageArtifact:
+ """一个从原始 worksheet drawing 读取的图片和 cell anchor。"""
+
+ row: int | None
+ col: int | None
+ payload: bytes
+ part_name: str
+ order: int
+
+
@dataclass(frozen=True, slots=True)
class _Relationship:
"""一个经过安全路径规范化的 OPC relationship。"""
@@ -304,6 +318,76 @@ def _drawing_shape_info(
return None, None
+def read_sheet_image_artifacts(
+ source: ZipFile,
+ worksheet_part: str,
+) -> list[XlsxImageArtifact]:
+ """从原始 worksheet DrawingML 读取未经过 openpyxl 转码的图片。"""
+
+ worksheet_relationships = _relationships(source, worksheet_part)
+ drawing_parts = [
+ relationship.target
+ for relationship in worksheet_relationships.values()
+ if not relationship.external
+ and relationship.target is not None
+ and relationship.reltype.rstrip("/").casefold().endswith("/drawing")
+ ]
+ artifacts: list[XlsxImageArtifact] = []
+ order = 0
+ for drawing_part in drawing_parts:
+ root = _read_xml(source, drawing_part)
+ if root is None:
+ continue
+ relationships = _relationships(source, drawing_part)
+ for anchor in root:
+ if _local_name(anchor.tag) not in {
+ "oneCellAnchor",
+ "twoCellAnchor",
+ "absoluteAnchor",
+ }:
+ 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 None
+ or relationship.external
+ or relationship.target is None
+ ):
+ continue
+ payload = _read_member_bounded(source, relationship.target)
+ if payload is None:
+ continue
+ artifacts.append(
+ XlsxImageArtifact(
+ row=coordinate[0] if coordinate is not None else None,
+ col=coordinate[1] if coordinate is not None else None,
+ payload=payload,
+ part_name=relationship.target,
+ order=order,
+ )
+ )
+ order += 1
+ return artifacts
+
+
def _vml_shape_info(
source: ZipFile,
drawing_part: str,
@@ -392,25 +476,13 @@ def _shape_anchor_and_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,
+ image_decoder: OfficeImageEquationDecoder,
) -> list[XlsxOleEquationArtifact]:
- """读取一个 worksheet 的 Equation.3 对象并绑定公式或图片回退。"""
+ """读取一个 worksheet 的公式 OLE 对象并绑定公式或图片回退。"""
worksheet = _read_xml(source, worksheet_part)
if worksheet is None:
@@ -421,7 +493,7 @@ def read_sheet_equation_artifacts(
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):
+ if not is_mathtype_equation_prog_id(prog_id):
continue
relationship = relationships.get(_relationship_id(ole_object) or "")
is_linked = bool(ole_object.get("link")) or (
@@ -443,12 +515,6 @@ def read_sheet_equation_artifacts(
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(
@@ -466,7 +532,27 @@ def read_sheet_equation_artifacts(
)
coordinate = coordinate or shape_coordinate
preview_part = preview_part or shape_preview
- preview = _preview_data_uri(source, preview_part)
+ preview_payload = _read_member_bounded(source, preview_part)
+ if latex is None and not show_as_icon and preview_payload is not None:
+ latex = image_decoder.decode(
+ preview_payload,
+ part_name=preview_part,
+ )
+ if latex is None and not show_as_icon and not is_linked:
+ logger.warning(
+ "XLSX_MTEF_FALLBACK: worksheet={!r}, relationship={!r} has no recoverable native or image-comment equation",
+ worksheet_part,
+ _relationship_id(ole_object),
+ )
+ preview = (
+ serialize_office_image(
+ preview_payload,
+ part_name=preview_part,
+ content_type=None,
+ )
+ if preview_payload is not None
+ else None
+ )
if latex is None and preview is None:
continue
diff --git a/mineru/model/flash/xlsx/xlsx_converter.py b/mineru/model/flash/xlsx/xlsx_converter.py
index 88e0aa59..49f431ed 100644
--- a/mineru/model/flash/xlsx/xlsx_converter.py
+++ b/mineru/model/flash/xlsx/xlsx_converter.py
@@ -1,5 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
import collections
+import hashlib
import html
import posixpath
import re
@@ -20,7 +21,13 @@ 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.image import serialize_office_image
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
+)
from mineru.model.flash.office.ooxml_equation import OoxmlEquationDecoder
+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.limits import MAX_ENTRY_BYTES
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 (
@@ -30,6 +37,7 @@ from mineru.model.flash.xlsx.package_normalizer import (
from mineru.model.flash.xlsx.ooxml_ole import (
XlsxOleEquationArtifact,
package_has_sheet_ole_objects,
+ read_sheet_image_artifacts,
read_sheet_equation_artifacts,
workbook_sheet_parts,
)
@@ -183,6 +191,7 @@ class XlsxConverter:
tuple[tuple[int, int], str]
] = set()
self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
self._merged_cell_lookup_cache = {}
self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式
@@ -224,6 +233,7 @@ class XlsxConverter:
self._omml_artifacts = []
self._suppressed_ole_previews = set()
self._ooxml_equation_decoder = OoxmlEquationDecoder()
+ self._image_equation_decoder = OfficeImageEquationDecoder()
self._merged_cell_lookup_cache = {}
def _convert_package_bytes(self, file_bytes: bytes) -> None:
@@ -359,7 +369,14 @@ class XlsxConverter:
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"]}" />')
+ if image_info.get("latex"):
+ self.table_image_map[anchor].append(
+ self.equation_bookends.format(EQ=image_info["latex"])
+ )
+ elif image_info.get("base64"):
+ self.table_image_map[anchor].append(
+ f'<img src="{image_info["base64"]}" />'
+ )
for artifact in self._ole_artifacts:
if (
artifact.latex is not None
@@ -377,6 +394,9 @@ class XlsxConverter:
visual_artifacts.extend(
self._find_equation_artifacts_in_sheet(used_cells)
)
+ visual_artifacts.extend(
+ self._find_image_equation_artifacts_in_sheet(used_cells)
+ )
for _, _, block in sorted(
visual_artifacts,
key=lambda item: (item[0][0], item[0][1], item[1]),
@@ -388,7 +408,7 @@ class XlsxConverter:
self,
sheet: Worksheet,
) -> list[XlsxOleEquationArtifact]:
- """从当前 worksheet part 读取 Equation.3 公式和预览。"""
+ """从当前 worksheet part 读取 MathType/Equation 公式和预览。"""
if self.zf is None:
return []
@@ -399,6 +419,7 @@ class XlsxConverter:
self.zf,
worksheet_part,
self._ooxml_equation_decoder,
+ self._image_equation_decoder,
)
def _find_equation_artifacts_in_sheet(
@@ -447,29 +468,154 @@ class XlsxConverter:
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]
- if is_vector_image(pil_image):
- return serialize_vector_image_with_placeholder(pil_image)
+ def _find_image_equation_artifacts_in_sheet(
+ self,
+ used_cells: set[tuple[int, int]],
+ ) -> list[tuple[tuple[int, int], int, dict]]:
+ """按原始 drawing anchor 输出未被表格吸收的图片 comment 公式。"""
+
+ artifacts: list[tuple[tuple[int, int], int, dict]] = []
+ for image_info in self.sheet_images:
+ latex = image_info.get("latex")
+ if not latex:
+ continue
+ row, col = image_info["anchor"]
+ if (
+ row is not None
+ and col is not None
+ and (row, col) in used_cells
+ ):
+ continue
+ coordinate = (
+ row if row is not None else 10**9,
+ col if col is not None else 10**9,
+ )
+ artifacts.append(
+ (
+ coordinate,
+ 25_000 + int(image_info.get("order", 0)),
+ {"type": BlockType.EQUATION, "content": latex},
+ )
+ )
+ return artifacts
+
+ def _read_xlsx_image_member(self, part_name: str) -> bytes | None:
+ """从原始 XLSX ZIP 有界读取 media member。"""
- if pil_image.mode != "RGB":
- return image_to_b64str(pil_image, image_format="PNG")
+ if self.zf is None:
+ return None
+ normalized = posixpath.normpath(part_name.lstrip("/"))
+ if normalized.startswith("../") or normalized not in self.zf.namelist():
+ return None
+ info = self.zf.getinfo(normalized)
+ if info.file_size > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"XLSX image exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ with self.zf.open(info) as stream:
+ payload = stream.read(MAX_ENTRY_BYTES + 1)
+ if len(payload) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"XLSX image exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ return payload
- return image_to_b64str(pil_image, image_format="JPEG")
+ def _raw_sheet_image(
+ self,
+ image: XlsImage,
+ ) -> tuple[bytes, str | None, str | None] | None:
+ """优先从原 ZIP 读取 openpyxl 图片的未转码原始字节。"""
+
+ part_name = str(getattr(image, "path", "") or "") or None
+ payload = (
+ self._read_xlsx_image_member(part_name)
+ if part_name is not None
+ else None
+ )
+ if payload is None:
+ try:
+ payload = image._data() # type: ignore[attr-defined]
+ except Exception:
+ return None
+ if len(payload) > MAX_ENTRY_BYTES:
+ raise LegacyOfficeResourceLimitError(
+ f"XLSX image exceeds max_entry_bytes={MAX_ENTRY_BYTES}"
+ )
+ image_format = str(getattr(image, "format", "") or "").casefold()
+ content_type = f"image/{image_format}" if image_format else None
+ return payload, part_name, content_type
def _collect_sheet_images(self, sheet: Worksheet) -> list[dict]:
images = []
if self.workbook is None:
return images
- for item in getattr(sheet, "_images", []): # type: ignore[attr-defined]
+ seen: set[tuple[tuple[int | None, int | None], bytes]] = set()
+ worksheet_part = self._sheet_part_by_title.get(sheet.title)
+ if self.zf is not None and worksheet_part is not None:
+ for artifact in read_sheet_image_artifacts(
+ self.zf,
+ worksheet_part,
+ ):
+ anchor = (artifact.row, artifact.col)
+ digest = hashlib.sha256(artifact.payload).digest()
+ key = (anchor, digest)
+ if key in seen:
+ continue
+ seen.add(key)
+ latex = self._image_equation_decoder.decode(
+ artifact.payload,
+ part_name=artifact.part_name,
+ )
+ image_base64 = serialize_office_image(
+ artifact.payload,
+ part_name=artifact.part_name,
+ content_type=None,
+ )
+ if latex is None and image_base64 is None:
+ continue
+ images.append(
+ {
+ "anchor": anchor,
+ "base64": image_base64,
+ "latex": latex,
+ "order": artifact.order,
+ }
+ )
+
+ for image_order, item in enumerate(
+ getattr(sheet, "_images", []), # type: ignore[attr-defined]
+ start=10_000,
+ ):
try:
image: XlsImage = cast(XlsImage, item)
+ raw_image = self._raw_sheet_image(image)
+ if raw_image is None:
+ continue
+ payload, part_name, content_type = raw_image
+ anchor = self._get_anchor_pos(item.anchor)
+ key = (anchor, hashlib.sha256(payload).digest())
+ if key in seen:
+ continue
+ seen.add(key)
+ latex = self._image_equation_decoder.decode(
+ payload,
+ part_name=part_name,
+ content_type=content_type,
+ )
+ image_base64 = serialize_office_image(
+ payload,
+ part_name=part_name,
+ content_type=content_type,
+ )
+ if latex is None and image_base64 is None:
+ continue
images.append(
{
- "anchor": self._get_anchor_pos(item.anchor),
- "base64": self._serialize_sheet_image(image),
+ "anchor": anchor,
+ "base64": image_base64,
+ "latex": latex,
+ "order": image_order,
}
)
except Exception as e:
@@ -1140,12 +1286,15 @@ class XlsxConverter:
if used_cells and r is not None and c is not None and (r, c) in used_cells:
continue
- self.cur_page.append(
- {
- "type": BlockType.IMAGE,
- "image_base64": image_info["base64"],
- }
- )
+ if image_info.get("latex"):
+ continue
+ if image_info.get("base64"):
+ self.cur_page.append(
+ {
+ "type": BlockType.IMAGE,
+ "image_base64": image_info["base64"],
+ }
+ )
return
@@ -1403,7 +1552,16 @@ class XlsxConverter:
return ""
try:
- with self.zf.open(zip_target_path) as image_file:
+ image_payload = self._read_xlsx_image_member(zip_target_path)
+ if image_payload is None:
+ return ""
+ latex = self._image_equation_decoder.decode(
+ image_payload,
+ part_name=zip_target_path,
+ )
+ if latex:
+ return self.equation_bookends.format(EQ=latex)
+ with BytesIO(image_payload) as image_file:
pil_image = Image.open(image_file)
if is_vector_image(pil_image):
img_base64 = serialize_vector_image_with_placeholder(pil_image)
diff --git a/tests/unittest/_docx_equationxml_test_utils.py b/tests/unittest/_docx_equationxml_test_utils.py
new file mode 100644
index 00000000..bddcbfb0
--- /dev/null
+++ b/tests/unittest/_docx_equationxml_test_utils.py
@@ -0,0 +1,210 @@
+"""构造带 VML ``equationxml`` 公式的确定性 DOCX 测试包。"""
+
+from __future__ import annotations
+
+from io import BytesIO
+from zipfile import ZipFile
+
+from lxml import etree # type: ignore[reportAttributeAccessIssue]
+
+from _mtef_test_utils import _TINY_PNG
+from _ooxml_mtef_test_utils import (
+ M_NS,
+ O_NS,
+ V_NS,
+ W_NS,
+ _rewrite_zip,
+ build_equation_docx,
+)
+
+WORD_2003_NS = "http://schemas.microsoft.com/office/word/2003/wordml"
+
+
+def _wrap_word_2003_equation(equation: etree._Element) -> str:
+ """把一个 OMML ``oMath`` 包装为规范要求的完整 Word 2003 XML 文档。"""
+
+ root = etree.Element(
+ f"{{{WORD_2003_NS}}}wordDocument",
+ nsmap={"w": WORD_2003_NS, "m": M_NS},
+ )
+ body = etree.SubElement(root, f"{{{WORD_2003_NS}}}body")
+ paragraph = etree.SubElement(body, f"{{{WORD_2003_NS}}}p")
+ math_paragraph = etree.SubElement(paragraph, f"{{{M_NS}}}oMathPara")
+ math_paragraph.append(equation)
+ return etree.tostring(root, encoding="unicode")
+
+
+def build_word_2003_equation_xml(text: str = "x+y") -> str:
+ """构造只含一个普通数学 run 的规范 Equation XML 属性值。"""
+
+ equation = etree.Element(f"{{{M_NS}}}oMath")
+ run = etree.SubElement(equation, f"{{{M_NS}}}r")
+ etree.SubElement(run, f"{{{M_NS}}}t").text = text
+ return _wrap_word_2003_equation(equation)
+
+
+def build_word_2003_equation_xml_from_omml(
+ equation: etree._Element,
+) -> str:
+ """把测试生成的 OMML ``oMath`` 节点包装为 Equation XML 属性值。"""
+
+ if equation.tag != f"{{{M_NS}}}oMath":
+ raise ValueError("Equation XML fixture requires an m:oMath element")
+ return _wrap_word_2003_equation(equation)
+
+
+def build_word_2003_fraction_equation_xml(
+ numerator: str = "a",
+ denominator: str = "b",
+) -> str:
+ """构造包含分式对象的规范 Equation XML 属性值。"""
+
+ equation = etree.Element(f"{{{M_NS}}}oMath")
+ fraction = etree.SubElement(equation, f"{{{M_NS}}}f")
+ for tag_name, text in (("num", numerator), ("den", denominator)):
+ argument = etree.SubElement(fraction, f"{{{M_NS}}}{tag_name}")
+ run = etree.SubElement(argument, f"{{{M_NS}}}r")
+ etree.SubElement(run, f"{{{M_NS}}}t").text = text
+ return _wrap_word_2003_equation(equation)
+
+
+def _set_paragraph_style(shape: etree._Element, style_id: str) -> None:
+ """给承载 Equation XML shape 的最近段落设置 Word 段落样式。"""
+
+ paragraphs = shape.xpath("ancestor::w:p[1]", namespaces={"w": W_NS})
+ if not paragraphs:
+ return
+ paragraph = paragraphs[0]
+ paragraph_properties = paragraph.find(f"{{{W_NS}}}pPr")
+ if paragraph_properties is None:
+ paragraph_properties = etree.Element(f"{{{W_NS}}}pPr")
+ paragraph.insert(0, paragraph_properties)
+ style = paragraph_properties.find(f"{{{W_NS}}}pStyle")
+ if style is None:
+ style = etree.SubElement(paragraph_properties, f"{{{W_NS}}}pStyle")
+ style.set(f"{{{W_NS}}}val", style_id)
+
+
+def _patch_equationxml_part(
+ payload: bytes,
+ equation_xml_values: list[str],
+ *,
+ keep_mtef: bool,
+ paragraph_style: str | None,
+ share_preview: bool,
+) -> tuple[bytes, int]:
+ """向一个 Word XML part 的公式 shape 写入属性并可移除 OLE 语义对象。"""
+
+ root = etree.fromstring(payload)
+ shapes = [
+ shape
+ for shape in root.findall(f".//{{{V_NS}}}shape")
+ if shape.find(f"{{{V_NS}}}imagedata") is not None
+ ]
+ for shape, equation_xml in zip(shapes, equation_xml_values, strict=False):
+ shape.set("equationxml", equation_xml)
+ if paragraph_style:
+ _set_paragraph_style(shape, paragraph_style)
+ if keep_mtef:
+ continue
+ container = shape.getparent()
+ if container is None or container.tag != f"{{{W_NS}}}object":
+ continue
+ for ole_object in container.findall(f"{{{O_NS}}}OLEObject"):
+ container.remove(ole_object)
+ container.tag = f"{{{W_NS}}}pict"
+ if share_preview and len(shapes) > 1:
+ first_image = shapes[0].find(f"{{{V_NS}}}imagedata")
+ first_rel_id = (
+ first_image.get(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
+ )
+ if first_image is not None
+ else None
+ )
+ if first_rel_id:
+ for shape in shapes[1:]:
+ image = shape.find(f"{{{V_NS}}}imagedata")
+ if image is not None:
+ image.set(
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id",
+ first_rel_id,
+ )
+ return (
+ etree.tostring(
+ root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ ),
+ len(shapes),
+ )
+
+
+def build_equationxml_docx(
+ equation_xml_values: list[str],
+ *,
+ inline: bool = False,
+ table: bool = False,
+ header_footer: bool = False,
+ alternate_omml: bool = False,
+ textbox: bool = False,
+ paragraph_style: str | None = None,
+ keep_mtef: bool = False,
+ mtef_payloads: list[bytes] | None = None,
+ share_preview: bool = False,
+ prog_id: str = "Equation.3",
+ preview_image: bytes | None = None,
+) -> bytes:
+ """基于现有 OOXML fixture 构造 Equation XML 正文及兼容分支。"""
+
+ if not equation_xml_values:
+ raise ValueError("Equation XML fixture requires at least one formula")
+ payloads = mtef_payloads or [b"invalid MTEF"] * len(equation_xml_values)
+ if len(payloads) != len(equation_xml_values):
+ raise ValueError("Equation XML and MTEF fixture counts must match")
+
+ package = build_equation_docx(
+ payloads,
+ inline=inline,
+ table=table,
+ header_footer=header_footer,
+ alternate_omml=alternate_omml,
+ textbox=textbox,
+ prog_id=prog_id,
+ preview_image=preview_image or _TINY_PNG,
+ )
+ replacements: dict[str, bytes] = {}
+ consumed = 0
+ with ZipFile(BytesIO(package)) as source:
+ part_names = [
+ name
+ for name in source.namelist()
+ if name.startswith("word/")
+ and name.endswith(".xml")
+ and "/_rels/" not in name
+ ]
+ if header_footer:
+ part_names.sort(
+ key=lambda name: (
+ 0 if "/header" in name else 1 if "/footer" in name else 2,
+ name,
+ )
+ )
+ for part_name in part_names:
+ remaining = equation_xml_values[consumed:]
+ if not remaining:
+ break
+ patched, shape_count = _patch_equationxml_part(
+ source.read(part_name),
+ remaining,
+ keep_mtef=keep_mtef,
+ paragraph_style=paragraph_style,
+ share_preview=share_preview,
+ )
+ if shape_count:
+ replacements[part_name] = patched
+ consumed += min(shape_count, len(remaining))
+ if consumed != len(equation_xml_values):
+ raise ValueError("Equation XML fixture could not locate every VML shape")
+ return _rewrite_zip(package, replacements, {})
diff --git a/tests/unittest/_image_mtef_test_utils.py b/tests/unittest/_image_mtef_test_utils.py
new file mode 100644
index 00000000..4d8eef42
--- /dev/null
+++ b/tests/unittest/_image_mtef_test_utils.py
@@ -0,0 +1,196 @@
+"""构造携带 MathType MTEF comment 的确定性 WMF/GIF 图片。"""
+
+from __future__ import annotations
+
+import base64
+import struct
+
+_TINY_GIF = base64.b64decode(
+ "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
+)
+
+
+def _wmf_record(function: int, payload: bytes = b"") -> bytes:
+ """构造按 WORD 对齐并声明正确 record size 的 WMF record。"""
+
+ padded = payload + b"\x00" * (len(payload) % 2)
+ return struct.pack("<IH", (6 + len(padded)) // 2, function) + padded
+
+
+def _wmf_comment_record(comment: bytes) -> bytes:
+ """把 comment 包装为 META_ESCAPE/MFCOMMENT record。"""
+
+ payload = struct.pack("<HH", 0x000F, len(comment)) + comment
+ return _wmf_record(0x0626, payload)
+
+
+def build_wmf(
+ comments: list[bytes],
+ *,
+ placeable: bool = False,
+) -> bytes:
+ """构造仅含 comment records 与 EOF 的标准 WMF。"""
+
+ records = [_wmf_comment_record(comment) for comment in comments]
+ records.append(_wmf_record(0))
+ file_words = (18 + sum(len(record) for record in records)) // 2
+ max_record_words = max(len(record) // 2 for record in records)
+ header = struct.pack(
+ "<HHHIHIH",
+ 1,
+ 9,
+ 0x0300,
+ file_words,
+ 0,
+ max_record_words,
+ 0,
+ )
+ metafile = header + b"".join(records)
+ if not placeable:
+ return metafile
+ placeable_header = struct.pack(
+ "<IHhhhhHIH",
+ 0x9AC6CDD7,
+ 0,
+ 0,
+ 0,
+ 100,
+ 100,
+ 1440,
+ 0,
+ 0,
+ )
+ return placeable_header + metafile
+
+
+def pre6_wmf_comment(mtef: bytes) -> bytes:
+ """构造 MathType 6.0b 前的单 comment MTEF 头。"""
+
+ if len(mtef) > 0xFFFF:
+ raise ValueError("pre-6 WMF fixture MTEF is too large")
+ return b"MathType" + struct.pack("<HH", 0x5555, len(mtef)) + mtef
+
+
+def baseline_wmf_comment(delta: int = 0) -> bytes:
+ """构造必须被忽略的 MathType baseline comment。"""
+
+ return b"MathType" + struct.pack("<HH", 0, delta & 0xFFFF)
+
+
+def apps_mfcc_comment(
+ chunk: bytes,
+ *,
+ total_length: int,
+ signature: str = "Design Science, Inc./MTEF",
+) -> bytes:
+ """构造一个 AppsMFCC v1 chunk。"""
+
+ return (
+ b"AppsMFCC"
+ + struct.pack("<HII", 1, total_length, len(chunk))
+ + signature.encode("ascii")
+ + b"\x00"
+ + chunk
+ )
+
+
+def apps_mfcc_comments(
+ mtef: bytes,
+ *,
+ chunk_size: int,
+ signature: str = "Design Science, Inc./MTEF",
+) -> list[bytes]:
+ """把 MTEF 切成多个连续 AppsMFCC comments。"""
+
+ if chunk_size <= 0:
+ raise ValueError("AppsMFCC fixture chunk_size must be positive")
+ return [
+ apps_mfcc_comment(
+ mtef[start : start + chunk_size],
+ total_length=len(mtef),
+ signature=signature,
+ )
+ for start in range(0, len(mtef), chunk_size)
+ ]
+
+
+def _gif_application_extension(
+ payload: bytes,
+ *,
+ authentication: bytes,
+ chunk_size: int,
+) -> bytes:
+ """构造 MathType GIF Application Extension 与 sub-blocks。"""
+
+ if len(authentication) != 3 or not 0 < chunk_size <= 255:
+ raise ValueError("GIF application fixture parameters are invalid")
+ subblocks = b"".join(
+ bytes([len(payload[start : start + chunk_size])])
+ + payload[start : start + chunk_size]
+ for start in range(0, len(payload), chunk_size)
+ )
+ return b"\x21\xff\x0bMathType" + authentication + subblocks + b"\x00"
+
+
+def build_gif_with_extensions(extensions: list[bytes]) -> bytes:
+ """把 extensions 插入有效 1×1 GIF 的首个图像块之前。"""
+
+ image_separator = _TINY_GIF.find(b"\x2c")
+ if image_separator < 0:
+ raise ValueError("tiny GIF fixture has no image descriptor")
+ return (
+ _TINY_GIF[:image_separator]
+ + b"".join(extensions)
+ + _TINY_GIF[image_separator:]
+ )
+
+
+def gif_mtef_extension(
+ mtef: bytes,
+ *,
+ chunk_size: int = 255,
+) -> bytes:
+ """构造可组合到同一 GIF 中的 MathType/001 extension。"""
+
+ return _gif_application_extension(
+ mtef,
+ authentication=b"001",
+ chunk_size=chunk_size,
+ )
+
+
+def build_gif_with_mtef(
+ mtef: bytes,
+ *,
+ chunk_size: int = 255,
+ include_baseline: bool = False,
+) -> bytes:
+ """构造带 MathType/001 MTEF 及可选 002 baseline 的有效 GIF。"""
+
+ extensions = [
+ gif_mtef_extension(mtef, chunk_size=chunk_size)
+ ]
+ if include_baseline:
+ extensions.insert(
+ 0,
+ _gif_application_extension(
+ b"baseline",
+ authentication=b"002",
+ chunk_size=255,
+ ),
+ )
+ return build_gif_with_extensions(extensions)
+
+
+def build_baseline_only_gif() -> bytes:
+ """构造只有 MathType/002 baseline、没有公式的有效 GIF。"""
+
+ return build_gif_with_extensions(
+ [
+ _gif_application_extension(
+ b"baseline",
+ authentication=b"002",
+ chunk_size=255,
+ )
+ ]
+ )
diff --git a/tests/unittest/_legacy_ppt_test_utils.py b/tests/unittest/_legacy_ppt_test_utils.py
index 32a696ba..ce66cd37 100644
--- a/tests/unittest/_legacy_ppt_test_utils.py
+++ b/tests/unittest/_legacy_ppt_test_utils.py
@@ -32,10 +32,21 @@ def _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)
+def _equation_preview_bse(preview_payload: bytes | None = None) -> bytes:
+ """构造一个内嵌 PNG 或 WMF 的 OfficeArt BSE。"""
+
+ if preview_payload is None:
+ blip = _officeart_record(0xF01E, b"\x00" * 17 + _TINY_PNG)
+ else:
+ compressed = zlib.compress(preview_payload)
+ metafile_header = bytearray(34)
+ struct.pack_into("<I", metafile_header, 0, len(preview_payload))
+ struct.pack_into("<I", metafile_header, 28, len(compressed))
+ metafile_header[32] = 0
+ blip = _officeart_record(
+ 0xF01B,
+ b"\x00" * 16 + bytes(metafile_header) + compressed,
+ )
return _officeart_record(0xF007, b"\x00" * 36 + blip, version=2)
@@ -79,6 +90,8 @@ def build_equation_ppt(
preview: bool = True,
compressed: bool = True,
declared_size: int | None = None,
+ prog_id: str = "Equation.3",
+ preview_payload: bytes | None = None,
) -> bytes:
"""构造每页一个 Equation Editor OLE 对象的 PPT persist fixture。"""
@@ -114,15 +127,27 @@ def build_equation_ppt(
0x0FC3,
struct.pack("<6I", 1, 0, index, 6, storage_id, 0),
)
- prog_id = _ppt_record(2 << 4, 0x0FBA, "Equation.3".encode("utf-16le"))
+ prog_id_record = _ppt_record(
+ 2 << 4,
+ 0x0FBA,
+ prog_id.encode("utf-16le"),
+ )
external_objects.append(
- _ppt_container(0, 0x0FCC, embed_atom + object_atom + prog_id)
+ _ppt_container(
+ 0,
+ 0x0FCC,
+ embed_atom + object_atom + prog_id_record,
+ )
)
object_list = _ppt_container(0, 0x0409, b"".join(external_objects))
drawing_group = (
_officeart_record(
0xF000,
- _officeart_record(0xF001, _equation_preview_bse(), version=0xF),
+ _officeart_record(
+ 0xF001,
+ _equation_preview_bse(preview_payload),
+ version=0xF,
+ ),
version=0xF,
)
if preview
diff --git a/tests/unittest/_legacy_xls_test_utils.py b/tests/unittest/_legacy_xls_test_utils.py
index 96dbd0ee..772bd153 100644
--- a/tests/unittest/_legacy_xls_test_utils.py
+++ b/tests/unittest/_legacy_xls_test_utils.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from dataclasses import dataclass
import struct
import uuid
+import zlib
from _mtef_test_utils import _TINY_PNG, _build_nested_cfb, equation_native
from _legacy_ppt_test_utils import _build_cfb
@@ -107,15 +108,31 @@ def _equation_obj(location: int, object_id: int) -> bytes:
return biff_record(0x005D, payload)
-def _preview_bstore() -> bytes:
- """构造一个可由 XLS/PPT 共用解码器读取的内嵌 PNG BStore。"""
-
- blip = _officeart_record(0xF01E, b"\x00" * 17 + _TINY_PNG)
+def _preview_bstore(preview_payload: bytes | None = None) -> bytes:
+ """构造一个可由 XLS/PPT 共用解码器读取的 PNG/WMF BStore。"""
+
+ if preview_payload is None:
+ blip = _officeart_record(0xF01E, b"\x00" * 17 + _TINY_PNG)
+ else:
+ compressed = zlib.compress(preview_payload)
+ metafile_header = bytearray(34)
+ struct.pack_into("<I", metafile_header, 0, len(preview_payload))
+ struct.pack_into("<I", metafile_header, 28, len(compressed))
+ metafile_header[32] = 0
+ blip = _officeart_record(
+ 0xF01B,
+ b"\x00" * 16 + bytes(metafile_header) + compressed,
+ )
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:
+def _build_xls_with_embeddings(
+ workbook: bytes,
+ equations: dict[int, bytes],
+ *,
+ prog_id: str,
+) -> bytes:
"""把 Workbook 与多个 MBD Equation Native storage 写入同一 CFB。"""
none = 0xFFFF_FFFF
@@ -145,7 +162,7 @@ def _build_xls_with_embeddings(workbook: bytes, equations: dict[int, bytes]) ->
"name": "\x01CompObj",
"kind": 2,
"right": storage_index + 3,
- "data": b"Equation.3\x00",
+ "data": prog_id.encode("ascii") + b"\x00",
},
{
"name": "\x03ObjInfo",
@@ -305,6 +322,7 @@ def build_xls(
corrupt_first_offset: bool = False,
encrypted: bool = False,
equations: dict[int, bytes] | None = None,
+ equation_prog_id: str = "Equation.3",
) -> bytes:
"""构造含 Workbook Globals 与多个 worksheet substreams 的 OLE 文件。"""
@@ -340,7 +358,11 @@ def build_xls(
)
workbook = prefix + directory + biff_record(0x000A) + b"".join(sheet_streams)
if equations:
- return _build_xls_with_embeddings(workbook, equations)
+ return _build_xls_with_embeddings(
+ workbook,
+ equations,
+ prog_id=equation_prog_id,
+ )
return _build_cfb([("Workbook", workbook)])
@@ -349,8 +371,10 @@ def build_equation_xls(
*,
cell_records: bytes = b"",
preview: bool = True,
+ prog_id: str = "Equation.3",
+ preview_payload: bytes | None = None,
) -> bytes:
- """构造带 Equation.3 picture OBJ、MBD storages 和可选预览的 XLS。"""
+ """构造带公式 picture OBJ、MBD storages 和可选预览的 XLS。"""
drawing_records = b""
for index, (location, _mtef) in enumerate(formulas, start=1):
@@ -360,7 +384,7 @@ def build_equation_xls(
)
drawing_records += _equation_obj(location, index)
globals_records = (
- biff_record(0x00EB, _preview_bstore())
+ biff_record(0x00EB, _preview_bstore(preview_payload))
if preview
else b""
)
@@ -368,6 +392,7 @@ def build_equation_xls(
[SheetFixture("Equations", cell_records + drawing_records)],
globals_records=globals_records,
equations=dict(formulas),
+ equation_prog_id=prog_id,
)
diff --git a/tests/unittest/_mtef_test_utils.py b/tests/unittest/_mtef_test_utils.py
index 90ed28b5..b4e12536 100644
--- a/tests/unittest/_mtef_test_utils.py
+++ b/tests/unittest/_mtef_test_utils.py
@@ -273,14 +273,23 @@ def _build_nested_cfb(entries: list[dict[str, object]]) -> bytes:
return header + b"".join(sectors)
-def build_equation_object(mtef: bytes) -> bytes:
- """构造含 Equation Native 的独立 Equation.3 OLE 对象。"""
+def build_equation_object(
+ mtef: bytes,
+ *,
+ prog_id: str = "Equation.3",
+) -> bytes:
+ """构造含 Equation Native 和指定 ProgID 的独立公式 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": "\x01CompObj",
+ "kind": 2,
+ "right": 2,
+ "data": prog_id.encode("ascii") + b"\x00",
+ },
{"name": "\x03ObjInfo", "kind": 2, "right": 3, "data": b"\x00" * 6},
{"name": "Equation Native", "kind": 2, "right": none, "data": equation_native(mtef)},
]
@@ -349,26 +358,49 @@ def _png_picf(png: bytes) -> bytes:
return bytes(header) + blip
+def _raw_picf(payload: bytes) -> bytes:
+ """把可由 magic fallback 识别的原始图片放入最小 PICF。"""
+
+ header_size = 68
+ header = bytearray(header_size)
+ struct.pack_into(
+ "<IH",
+ header,
+ 0,
+ header_size + len(payload),
+ header_size,
+ )
+ return bytes(header) + payload
+
+
def build_equation_doc(
formulas: list[tuple[int, bytes]],
*,
preview_storage_ids: set[int] | None = None,
+ preview_payloads: dict[int, bytes] | None = None,
+ prog_id: str = "Equation.3",
) -> bytes:
- """构造多个 ObjectPool Equation.3 字段的最小 DOC 集成 fixture。"""
+ """构造多个 ObjectPool 公式字段的最小 DOC 集成 fixture。"""
text_parts: list[str] = []
anchors: list[tuple[int, int, bool]] = []
data_stream = bytearray()
previews = preview_storage_ids or set()
+ custom_previews = preview_payloads or {}
cp_cursor = 0
for storage_id, _mtef in formulas:
- prefix = "\x13 EMBED Equation.3 "
+ prefix = f"\x13 EMBED {prog_id} "
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))
+ preview_payload = custom_previews.get(storage_id)
+ data_stream.extend(
+ _raw_picf(preview_payload)
+ if preview_payload is not None
+ else _png_picf(_TINY_PNG)
+ )
anchors.append((separator_cp + 1, preview_offset, False))
text_parts.append(field)
cp_cursor += len(field)
@@ -437,7 +469,7 @@ def build_equation_doc(
"name": "\x01CompObj",
"kind": 2,
"right": storage_index + 3,
- "data": b"Equation.3\x00",
+ "data": prog_id.encode("ascii") + b"\x00",
},
{
"name": "\x03ObjInfo",
diff --git a/tests/unittest/_mtef_v5_test_utils.py b/tests/unittest/_mtef_v5_test_utils.py
new file mode 100644
index 00000000..462df91d
--- /dev/null
+++ b/tests/unittest/_mtef_v5_test_utils.py
@@ -0,0 +1,335 @@
+"""构造结果已知的 MathType MTEF v5 测试字节流。"""
+
+from __future__ import annotations
+
+import struct
+
+
+def v5_signed(value: int) -> bytes:
+ """按 MTEF v5 紧凑格式编码一个有符号整数。"""
+
+ if not -0x8000 <= value <= 0x7FFF:
+ raise ValueError("MTEF v5 signed fixture is out of range")
+ if -128 <= value < 127:
+ return bytes([value + 128])
+ return b"\xff" + struct.pack("<H", value + 0x8000)
+
+
+def v5_unsigned(value: int) -> bytes:
+ """按 MTEF v5 紧凑格式编码一个无符号整数。"""
+
+ if not 0 <= value <= 0xFFFF:
+ raise ValueError("MTEF v5 unsigned fixture is out of range")
+ return bytes([value]) if value < 0xFF else b"\xff" + struct.pack("<H", value)
+
+
+def v5_variation(value: int) -> bytes:
+ """按 MTEF v5 一或两字节格式编码 template variation。"""
+
+ if not 0 <= value <= 0x7FFF:
+ raise ValueError("MTEF v5 variation fixture is out of range")
+ if value < 0x80:
+ return bytes([value])
+ return bytes([0x80 | (value & 0x7F), value >> 8])
+
+
+def v5_char(
+ value: str,
+ *,
+ typeface: int = 3,
+ embellishments: tuple[int, ...] = (),
+ function_start: bool = False,
+ font_position: int | None = None,
+ omit_mtcode: bool = False,
+) -> bytes:
+ """构造一个带可选字体位置、函数起点和 embellishments 的 CHAR。"""
+
+ if len(value) != 1 or ord(value) > 0xFFFF:
+ raise ValueError("MTEF v5 CHAR fixture requires one BMP character")
+ options = 0
+ if embellishments:
+ options |= 0x01
+ if function_start:
+ options |= 0x02
+ if font_position is not None:
+ options |= 0x04 if font_position <= 0xFF else 0x10
+ if omit_mtcode:
+ options |= 0x20
+ payload = bytes([2, options]) + v5_signed(typeface)
+ if not omit_mtcode:
+ payload += struct.pack("<H", ord(value))
+ if font_position is not None:
+ payload += (
+ bytes([font_position])
+ if font_position <= 0xFF
+ else struct.pack("<H", font_position)
+ )
+ if embellishments:
+ payload += b"".join(bytes([6, 0, item]) for item in embellishments)
+ payload += b"\x00"
+ return payload
+
+
+def v5_text(value: str, *, typeface: int = 3) -> bytes:
+ """把 BMP 字符串编码为连续 MTEF v5 CHAR records。"""
+
+ return b"".join(v5_char(character, typeface=typeface) for character in value)
+
+
+def v5_line(*records: bytes, null: bool = False) -> bytes:
+ """构造一个普通或 NULL LINE。"""
+
+ if null:
+ if records:
+ raise ValueError("NULL LINE fixture cannot contain records")
+ return b"\x01\x01"
+ return b"\x01\x00" + b"".join(records) + b"\x00"
+
+
+def v5_template(
+ selector: int,
+ *slots: bytes,
+ variation: int = 0,
+ options: int = 0,
+) -> bytes:
+ """构造一个含完整 subobject list 的 MTEF v5 TMPL。"""
+
+ return (
+ bytes([3, 0, selector])
+ + v5_variation(variation)
+ + bytes([options])
+ + b"".join(slots)
+ + b"\x00"
+ )
+
+
+def v5_pile(*lines: bytes) -> bytes:
+ """构造居中的 MTEF v5 PILE。"""
+
+ return b"\x04\x00\x02\x00" + b"".join(lines) + b"\x00"
+
+
+def v5_matrix(rows: list[list[bytes]]) -> bytes:
+ """构造无 partition lines 的 MTEF v5 MATRIX。"""
+
+ if not rows or not rows[0] or any(len(row) != len(rows[0]) for row in rows):
+ raise ValueError("MTEF v5 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(v5_line(cell) for row in rows for cell in row)
+ return (
+ bytes([5, 0, 0, 2, 0, row_count, col_count])
+ + row_parts
+ + col_parts
+ + cells
+ + b"\x00"
+ )
+
+
+def v5_encoding_definition(name: str) -> bytes:
+ """构造一个 ENCODING_DEF。"""
+
+ return b"\x13" + name.encode("ascii") + b"\x00"
+
+
+def v5_font_definition(encoding_index: int, name: str) -> bytes:
+ """构造一个 FONT_DEF。"""
+
+ return b"\x11" + v5_unsigned(encoding_index) + name.encode("ascii") + b"\x00"
+
+
+def v5_font_style_definition(font_index: int, style_bits: int) -> bytes:
+ """构造一个 FONT_STYLE_DEF。"""
+
+ return b"\x08" + v5_unsigned(font_index) + bytes([style_bits])
+
+
+def v5_equation_preferences(
+ styles: list[tuple[int, int] | None],
+) -> bytes:
+ """构造尺寸和间距为空、仅含 style definitions 的 EQN_PREFS。"""
+
+ payload = bytearray([18, 0, 0, 0, len(styles)])
+ for style in styles:
+ if style is None:
+ payload.extend(v5_unsigned(0))
+ else:
+ font_index, style_bits = style
+ payload.extend(v5_unsigned(font_index))
+ payload.append(style_bits)
+ return bytes(payload)
+
+
+def v5_future_record(payload: bytes) -> bytes:
+ """构造可由旧 reader 按显式长度跳过的 future record。"""
+
+ return b"\x64" + v5_unsigned(len(payload)) + payload
+
+
+def v5_equation(
+ *records: bytes,
+ definitions: tuple[bytes, ...] = (),
+ application_key: str = "DSMT7",
+ inline: bool = False,
+) -> bytes:
+ """构造完整 v5 header、定义记录、初始 SIZE、根 LINE 和 END。"""
+
+ header = bytes([5, 1, 0, 7, 0])
+ header += application_key.encode("ascii") + b"\x00" + bytes([1 if inline else 0])
+ return header + b"".join(definitions) + b"\x0a" + v5_line(*records) + b"\x00"
+
+
+def v5_formula_corpus() -> list[tuple[str, bytes, str]]:
+ """返回覆盖常见 v5 CHAR、TMPL、PILE 与 MATRIX 的公式语料。"""
+
+ fraction = v5_template(
+ 11,
+ v5_line(v5_text("a+b")),
+ v5_line(v5_char("c")),
+ )
+ square_root = v5_template(
+ 10,
+ v5_line(
+ v5_char("x"),
+ v5_template(
+ 28,
+ v5_line(null=True),
+ v5_line(v5_char("2")),
+ ),
+ v5_text("+1"),
+ ),
+ v5_line(null=True),
+ )
+ nth_root = v5_template(
+ 10,
+ v5_line(v5_char("x")),
+ v5_line(v5_char("3")),
+ variation=1,
+ )
+ scripts = v5_char("x") + v5_template(
+ 29,
+ v5_line(v5_char("i")),
+ v5_line(v5_char("2")),
+ )
+ fenced_fraction = v5_template(
+ 1,
+ v5_line(fraction),
+ variation=3,
+ )
+ summation = v5_template(
+ 16,
+ v5_line(v5_char("i")),
+ v5_line(v5_char("n")),
+ v5_line(v5_text("i=1")),
+ v5_char("∑", typeface=6),
+ variation=0x43,
+ )
+ integral = v5_template(
+ 15,
+ v5_line(v5_char("x")),
+ v5_line(v5_char("1")),
+ v5_line(v5_char("0")),
+ v5_char("∫", typeface=6),
+ variation=3,
+ )
+ matrix = v5_matrix(
+ [
+ [v5_char("a"), v5_char("b")],
+ [v5_char("c"), v5_char("d")],
+ ]
+ )
+ return [
+ ("linear", v5_equation(v5_text("x+y")), "x+y"),
+ ("fraction", v5_equation(fraction), r"\frac{a+b}{c}"),
+ ("square_root", v5_equation(square_root), r"\sqrt{x^{2}+1}"),
+ ("nth_root", v5_equation(nth_root), r"\sqrt[3]{x}"),
+ ("sub_sup", v5_equation(scripts), r"x_{i}^{2}"),
+ ("fence", v5_equation(fenced_fraction), r"\left(\frac{a+b}{c}\right)"),
+ ("summation", v5_equation(summation), r"\sum_{i=1}^{n}{i}"),
+ ("integral", v5_equation(integral), r"\int_{0}^{1}{x}"),
+ ("matrix", v5_equation(matrix), r"\begin{matrix}a&b\\c&d\end{matrix}"),
+ ("pile", v5_equation(v5_pile(v5_line(v5_char("x")), v5_line(v5_char("y")))), r"\begin{gathered}x\\y\end{gathered}"),
+ ("embellishment", v5_equation(v5_char("x", embellishments=(9,))), r"\widehat{x}"),
+ ("greek_relation", v5_equation(v5_char("α"), v5_char("≤"), v5_char("β")), r"\alpha \leq \beta"),
+ ("interval", v5_equation(v5_template(9, v5_line(v5_char("x")), variation=0x10)), r"\left(x\right)"),
+ ("vector", v5_equation(v5_template(31, v5_line(v5_char("x")), variation=2)), r"\overrightarrow{x}"),
+ (
+ "dirac",
+ v5_equation(
+ v5_template(
+ 30,
+ v5_line(v5_char("a")),
+ v5_line(v5_char("b")),
+ variation=3,
+ )
+ ),
+ r"\left\langle a\middle|b\right\rangle",
+ ),
+ ("box", v5_equation(v5_template(37, v5_line(v5_char("x")))), r"\boxed{x}"),
+ ("future", v5_equation(v5_future_record(b"future"), v5_char("x")), "x"),
+ ]
+
+
+def v5_template_corpus() -> list[tuple[str, bytes, str]]:
+ """返回覆盖 v5 各类标准 template selector 的精确语料。"""
+
+ line_x = v5_line(v5_char("x"))
+ line_a = v5_line(v5_char("a"))
+ line_b = v5_line(v5_char("b"))
+ line_i = v5_line(v5_char("i"))
+ line_n = v5_line(v5_char("n"))
+ null_line = v5_line(null=True)
+ cases = [
+ ("angle", v5_template(0, line_x, variation=3), r"\left\langle x\right\rangle"),
+ ("parenthesis", v5_template(1, line_x, variation=3), r"\left(x\right)"),
+ ("brace", v5_template(2, line_x, variation=3), r"\left\{x\right\}"),
+ ("bracket", v5_template(3, line_x, variation=3), r"\left[x\right]"),
+ ("bar", v5_template(4, line_x, variation=3), r"\left|x\right|"),
+ ("double_bar", v5_template(5, line_x, variation=3), r"\left\|x\right\|"),
+ ("floor", v5_template(6, line_x, variation=3), r"\left\lfloor x\right\rfloor"),
+ ("ceiling", v5_template(7, line_x, variation=3), r"\left\lceil x\right\rceil"),
+ ("white_bracket", v5_template(8, line_x, variation=3), r"\left\llbracket x\right\rrbracket"),
+ ("slash_fraction", v5_template(11, line_a, line_b, variation=2), r"{a}/{b}"),
+ ("double_underbar", v5_template(12, line_x, variation=1), r"\underline{\underline{x}}"),
+ ("overbar", v5_template(13, line_x), r"\overline{x}"),
+ ("arrow", v5_template(14, line_a, variation=0x20), r"\overset{a}{\rightarrow}"),
+ ("product", v5_template(17, line_x, line_n, line_i, v5_char("∏"), variation=3), r"\prod_{i}^{n}{x}"),
+ ("coproduct", v5_template(18, line_x, line_n, line_i, v5_char("∐"), variation=3), r"\coprod_{i}^{n}{x}"),
+ ("union", v5_template(19, line_x, line_n, line_i, v5_char("∪"), variation=3), r"\bigcup_{i}^{n}{x}"),
+ ("intersection", v5_template(20, line_x, line_n, line_i, v5_char("∩"), variation=3), r"\bigcap_{i}^{n}{x}"),
+ ("custom_bigop", v5_template(21, line_x, line_n, line_i, v5_char("∫"), variation=3), r"\int_{i}^{n}{x}"),
+ ("sum_style_bigop", v5_template(22, line_x, line_n, line_i, v5_char("∑"), variation=0x43), r"\sum_{i}^{n}{x}"),
+ (
+ "two_byte_variation",
+ v5_template(
+ 15,
+ line_x,
+ null_line,
+ null_line,
+ v5_char("∫"),
+ variation=0x100,
+ ),
+ r"\int{x}",
+ ),
+ ("limit", v5_template(23, line_x, v5_line(v5_char("0")), v5_line(v5_char("1"))), r"\lim_{0}^{1}{x}"),
+ ("overbrace", v5_template(24, line_x, line_n, variation=1), r"\overbrace{x}^{n}"),
+ ("underbracket", v5_template(25, line_x, line_n), r"\underbracket{x}_{n}"),
+ ("long_division", v5_template(26, line_x, v5_line(v5_char("q")), variation=1), r"\overline{q}\smash{\big) x}"),
+ ("subscript", v5_template(27, line_i, null_line), r"_{i}"),
+ ("superscript", v5_template(28, null_line, v5_line(v5_char("2"))), r"^{2}"),
+ ("prescripts", v5_template(29, line_i, v5_line(v5_char("2")), variation=1), r"{}_{i}^{2}"),
+ ("under_vector", v5_template(31, line_x, variation=0x05), r"\underleftarrow{x}"),
+ ("tilde", v5_template(32, line_x), r"\widetilde{x}"),
+ ("hat", v5_template(33, line_x), r"\widehat{x}"),
+ ("arc", v5_template(34, line_x), r"\overparen{x}"),
+ ("cancel", v5_template(36, line_x, variation=2), r"\cancel{x}"),
+ ("back_cancel", v5_template(36, line_x, variation=4), r"\bcancel{x}"),
+ ("cross_cancel", v5_template(36, line_x, variation=6), r"\xcancel{x}"),
+ ("box", v5_template(37, line_x, variation=0x1E), r"\boxed{x}"),
+ ]
+ return [
+ (name, v5_equation(template), expected)
+ for name, template, expected in cases
+ ]
diff --git a/tests/unittest/_office_image_mtef_test_utils.py b/tests/unittest/_office_image_mtef_test_utils.py
new file mode 100644
index 00000000..e332ac5e
--- /dev/null
+++ b/tests/unittest/_office_image_mtef_test_utils.py
@@ -0,0 +1,202 @@
+"""把带 MTEF comment 的图片注入确定性 DOCX/PPTX/XLSX。"""
+
+from __future__ import annotations
+
+import base64
+from io import BytesIO
+from zipfile import ZipFile
+
+from docx import Document
+from openpyxl import Workbook
+from openpyxl.drawing.image import Image as XlsxImage
+from pptx import Presentation
+from pptx.util import Inches
+from lxml import etree # type: ignore[reportAttributeAccessIssue]
+
+from _ooxml_mtef_test_utils import (
+ IMAGE_REL_TYPE,
+ PACKAGE_RELS_NS,
+ REL_NS,
+ _rewrite_zip,
+)
+
+_VALID_TINY_PNG = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/"
+ "x8AAusB9Wl2l9sAAAAASUVORK5CYII="
+)
+
+
+def _replace_media_parts(
+ package: bytes,
+ *,
+ prefix: str,
+ payload: bytes,
+) -> bytes:
+ """把指定 OOXML media 目录下的图片成员替换为原始测试载荷。"""
+
+ with ZipFile(BytesIO(package)) as source:
+ replacements = {
+ name: payload
+ for name in source.namelist()
+ if name.startswith(prefix)
+ }
+ if not replacements:
+ raise ValueError(f"OOXML image fixture has no media under {prefix}")
+ return _rewrite_zip(package, replacements, {})
+
+
+def build_image_docx(
+ image_payload: bytes,
+ *,
+ inline: bool = False,
+ table: bool = False,
+ header: bool = False,
+ paragraph_style: str | None = None,
+) -> bytes:
+ """构造正文、表格或页眉含单张图片的 DOCX。"""
+
+ document = Document()
+ if table:
+ paragraph = document.add_table(rows=1, cols=1).cell(0, 0).paragraphs[0]
+ elif header:
+ paragraph = document.sections[0].header.paragraphs[0]
+ else:
+ paragraph = document.add_paragraph()
+ if paragraph_style is not None:
+ paragraph.style = paragraph_style
+ if inline:
+ paragraph.add_run("before ")
+ paragraph.add_run().add_picture(BytesIO(_VALID_TINY_PNG))
+ if inline:
+ paragraph.add_run(" after")
+ buffer = BytesIO()
+ document.save(buffer)
+ return _replace_media_parts(
+ buffer.getvalue(),
+ prefix="word/media/",
+ payload=image_payload,
+ )
+
+
+def _move_pptx_picture_to_notes(package: bytes) -> bytes:
+ """把单页 PPTX 的 picture shape 移到 notesSlide 并重绑图片关系。"""
+
+ replacements: dict[str, bytes] = {}
+ with ZipFile(BytesIO(package)) as source:
+ slide_root = etree.fromstring(source.read("ppt/slides/slide1.xml"))
+ notes_root = etree.fromstring(
+ source.read("ppt/notesSlides/notesSlide1.xml")
+ )
+ pictures = slide_root.xpath(".//*[local-name()='pic']")
+ note_trees = notes_root.xpath(".//*[local-name()='spTree']")
+ if not pictures or not note_trees:
+ raise ValueError("PPTX notes image fixture cannot locate picture trees")
+ picture = pictures[0]
+ parent = picture.getparent()
+ parent.remove(picture)
+ note_trees[0].append(picture)
+
+ blips = picture.xpath(".//*[local-name()='blip']")
+ if not blips:
+ raise ValueError("PPTX notes image fixture has no blip")
+ relationship_id = blips[0].get(f"{{{REL_NS}}}embed")
+ slide_rels = etree.fromstring(
+ source.read("ppt/slides/_rels/slide1.xml.rels")
+ )
+ target = next(
+ (
+ rel.get("Target")
+ for rel in slide_rels
+ if rel.get("Id") == relationship_id
+ ),
+ None,
+ )
+ if not target:
+ raise ValueError("PPTX notes image relationship is missing")
+ notes_rels_name = "ppt/notesSlides/_rels/notesSlide1.xml.rels"
+ notes_rels = etree.fromstring(source.read(notes_rels_name))
+ new_relationship_id = "rIdImageMtef"
+ etree.SubElement(
+ notes_rels,
+ f"{{{PACKAGE_RELS_NS}}}Relationship",
+ Id=new_relationship_id,
+ Type=IMAGE_REL_TYPE,
+ Target=target,
+ )
+ blips[0].set(f"{{{REL_NS}}}embed", new_relationship_id)
+ replacements = {
+ "ppt/slides/slide1.xml": etree.tostring(
+ slide_root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ ),
+ "ppt/notesSlides/notesSlide1.xml": etree.tostring(
+ notes_root,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ ),
+ notes_rels_name: etree.tostring(
+ notes_rels,
+ xml_declaration=True,
+ encoding="UTF-8",
+ standalone=True,
+ ),
+ }
+ return _rewrite_zip(package, replacements, {})
+
+
+def build_image_pptx(
+ image_payload: bytes,
+ *,
+ notes: bool = False,
+) -> bytes:
+ """构造一页含单张图片 shape 或 notes 图片的 PPTX。"""
+
+ presentation = Presentation()
+ slide = presentation.slides.add_slide(presentation.slide_layouts[6])
+ slide.shapes.add_picture(
+ BytesIO(_VALID_TINY_PNG),
+ Inches(1),
+ Inches(1),
+ Inches(4),
+ Inches(1.5),
+ )
+ if notes:
+ _ = slide.notes_slide
+ buffer = BytesIO()
+ presentation.save(buffer)
+ package = buffer.getvalue()
+ if notes:
+ package = _move_pptx_picture_to_notes(package)
+ return _replace_media_parts(
+ package,
+ prefix="ppt/media/",
+ payload=image_payload,
+ )
+
+
+def build_image_xlsx(
+ image_payload: bytes,
+ *,
+ cell_value: str | None = None,
+) -> bytes:
+ """构造 A1 anchor 图片及可选单元格内容的 XLSX。"""
+
+ workbook = Workbook()
+ worksheet = workbook.active
+ if worksheet is None:
+ raise ValueError("XLSX image fixture has no active worksheet")
+ worksheet.title = "Images"
+ if cell_value is not None:
+ worksheet["A1"] = cell_value
+ image = XlsxImage(BytesIO(_VALID_TINY_PNG))
+ worksheet.add_image(image, "A1")
+ buffer = BytesIO()
+ workbook.save(buffer)
+ return _replace_media_parts(
+ buffer.getvalue(),
+ prefix="xl/media/",
+ payload=image_payload,
+ )
diff --git a/tests/unittest/_ooxml_mtef_test_utils.py b/tests/unittest/_ooxml_mtef_test_utils.py
index 303a7f52..bf3f2837 100644
--- a/tests/unittest/_ooxml_mtef_test_utils.py
+++ b/tests/unittest/_ooxml_mtef_test_utils.py
@@ -1,4 +1,4 @@
-"""构造带 Equation.3 OLE 对象的确定性 DOCX/PPTX/XLSX 测试包。"""
+"""构造带 MathType/Equation OLE 对象的确定性 DOCX/PPTX/XLSX 测试包。"""
from __future__ import annotations
@@ -57,7 +57,7 @@ def _rewrite_zip(
def _content_types_with_ole(content_types: bytes) -> bytes:
- """为 .bin Equation.3 persistence part 添加默认内容类型。"""
+ """为 .bin 公式 OLE persistence part 添加默认内容类型。"""
root = etree.fromstring(content_types)
if not any(
@@ -119,6 +119,7 @@ def _word_ole_run(
object_index: int,
ole_relationship_id: str,
image_relationship_id: str,
+ prog_id: str,
) -> etree._Element:
"""构造包含 VML 预览和 o:OLEObject 的 Word run。"""
@@ -141,7 +142,7 @@ def _word_ole_run(
f"{{{O_NS}}}OLEObject",
{
"Type": "Embed",
- "ProgID": "Equation.3",
+ "ProgID": prog_id,
"ShapeID": shape_id,
"DrawAspect": "Content",
"ObjectID": f"_{1200000000 + object_index}",
@@ -178,8 +179,10 @@ def _patch_word_part(
part_name: str,
formulas: list[tuple[str, bytes, bool]],
additions: dict[str, bytes],
+ prog_id: str,
+ preview_image: bytes,
) -> tuple[bytes, bytes]:
- """向一个 Word XML part 及其 relationships 注入多个 Equation.3 对象。"""
+ """向一个 Word XML part 及其 relationships 注入多个公式 OLE 对象。"""
root = etree.fromstring(source.read(part_name))
directory, basename = part_name.rsplit("/", 1)
@@ -207,9 +210,12 @@ def _patch_word_part(
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)
+ additions[object_part] = build_equation_object(
+ mtef,
+ prog_id=prog_id,
+ )
+ additions[image_part] = preview_image
+ ole_run = _word_ole_run(index, ole_rid, image_rid, prog_id)
if alternate_omml:
alternate = etree.Element(f"{{{MC_NS}}}AlternateContent")
choice = etree.SubElement(
@@ -286,8 +292,10 @@ def build_equation_docx(
alternate_omml: bool = False,
textbox: bool = False,
show_as_icon: bool = False,
+ prog_id: str = "Equation.3",
+ preview_image: bytes = _TINY_PNG,
) -> bytes:
- """构造正文、表格或页眉页脚中含 Equation.3 对象的 DOCX。"""
+ """构造正文、表格或页眉页脚中含公式 OLE 对象的 DOCX。"""
document = Document()
target_part = "word/document.xml"
@@ -340,7 +348,14 @@ def build_equation_docx(
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)
+ xml, rels = _patch_word_part(
+ source,
+ part,
+ entries,
+ additions,
+ prog_id,
+ preview_image,
+ )
replacements[part] = xml
directory, basename = part.rsplit("/", 1)
rels_name = f"{directory}/_rels/{basename}.rels"
@@ -359,7 +374,14 @@ def build_equation_docx(
zip(placeholders, formulas, strict=True)
)
]
- xml, rels = _patch_word_part(source, target_part, entries, additions)
+ xml, rels = _patch_word_part(
+ source,
+ target_part,
+ entries,
+ additions,
+ prog_id,
+ preview_image,
+ )
if textbox:
xml = _wrap_word_equations_in_textboxes(xml)
if show_as_icon:
@@ -378,8 +400,10 @@ def build_equation_pptx(
show_as_icon: bool = False,
notes: bool = False,
alternate_omml: bool = False,
+ prog_id: str = "Equation.3",
+ preview_image: bytes = _TINY_PNG,
) -> bytes:
- """使用 python-pptx 生成每页一个 Equation.3 OLE 对象的 PPTX。"""
+ """使用 python-pptx 生成每页一个公式 OLE 对象的 PPTX。"""
presentation = Presentation()
presentation.slides.add_slide(presentation.slide_layouts[6])
@@ -390,8 +414,8 @@ def build_equation_pptx(
else presentation.slides.add_slide(presentation.slide_layouts[6])
)
slide.shapes.add_ole_object(
- BytesIO(build_equation_object(mtef)),
- "Equation.3",
+ BytesIO(build_equation_object(mtef, prog_id=prog_id)),
+ prog_id,
Inches(1),
Inches(1),
Inches(4),
@@ -403,6 +427,15 @@ def build_equation_pptx(
buffer = BytesIO()
presentation.save(buffer)
package = buffer.getvalue()
+ if preview_image != _TINY_PNG:
+ replacements = {}
+ with ZipFile(BytesIO(package)) as source:
+ replacements = {
+ name: preview_image
+ for name in source.namelist()
+ if name.startswith("ppt/media/")
+ }
+ package = _rewrite_zip(package, replacements, {})
if notes:
return _move_pptx_equations_to_notes(
package,
@@ -615,8 +648,10 @@ def build_equation_xlsx(
linked: bool = False,
show_as_icon: bool = False,
alternate_omml: bool = False,
+ prog_id: str = "Equation.3",
+ preview_image: bytes = _TINY_PNG,
) -> bytes:
- """构造使用 objectPr、DrawingML 或 VML anchor 的 Equation.3 XLSX。"""
+ """构造使用 objectPr、DrawingML 或 VML anchor 的公式 OLE XLSX。"""
workbook = Workbook()
worksheet = workbook.active
@@ -648,7 +683,7 @@ def build_equation_xlsx(
ole_objects,
f"{{{X_NS}}}oleObject",
{
- "progId": "Equation.3",
+ "progId": prog_id,
"shapeId": str(shape_id),
f"{{{REL_NS}}}id": ole_rid,
},
@@ -677,7 +712,12 @@ def build_equation_xlsx(
if linked:
ole_object.set("link", "https://example.test/equation.bin")
else:
- additions[f"xl/embeddings/oleObjectMtef{index}.bin"] = build_equation_object(mtef)
+ additions[
+ f"xl/embeddings/oleObjectMtef{index}.bin"
+ ] = build_equation_object(
+ mtef,
+ prog_id=prog_id,
+ )
if anchor_mode == "drawing":
etree.SubElement(root, f"{{{X_NS}}}drawing", {f"{{{REL_NS}}}id": "rIdMtefDrawing"})
@@ -709,7 +749,7 @@ def build_equation_xlsx(
elif anchor_mode not in {"objectPr", "none"}:
raise ValueError(f"unsupported XLSX equation anchor fixture: {anchor_mode}")
- additions["xl/media/equationMtef.png"] = _TINY_PNG
+ additions["xl/media/equationMtef.png"] = preview_image
replacements[worksheet_part] = etree.tostring(
root,
xml_declaration=True,
diff --git a/tests/unittest/test_flash_docx_equationxml.py b/tests/unittest/test_flash_docx_equationxml.py
new file mode 100644
index 00000000..f34758d9
--- /dev/null
+++ b/tests/unittest/test_flash_docx_equationxml.py
@@ -0,0 +1,406 @@
+from __future__ import annotations
+
+import asyncio
+from io import BytesIO
+from pathlib import Path
+
+from lxml import etree # type: ignore[reportAttributeAccessIssue]
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.model.flash import DocxModel
+from mineru.model.flash.docx.docx_converter import DocxConverter
+from mineru.model.flash.docx.equationxml import DocxEquationXmlDecoder
+from mineru.model.flash.legacy_office.errors import (
+ LegacyOfficeResourceLimitError,
+)
+from mineru.render._internal.docx.math import latex_to_omml
+from mineru.types import BlockType, MiddleJson, ModelJson
+
+import mineru.model.flash.docx.equationxml as equationxml_module
+from _docx_equationxml_test_utils import (
+ M_NS,
+ WORD_2003_NS,
+ build_equationxml_docx,
+ build_word_2003_equation_xml,
+ build_word_2003_equation_xml_from_omml,
+ build_word_2003_fraction_equation_xml,
+)
+from _mtef_test_utils import formula_corpus
+
+
+def _equation_contents(pages: list[list[dict]]) -> list[str]:
+ """按分页顺序提取独立公式 block 的 LaTeX 内容。"""
+
+ return [
+ block["content"]
+ for page in pages
+ for block in page
+ if block["type"] == BlockType.EQUATION
+ ]
+
+
+def _invalid_equationxml_with_multiple_math() -> str:
+ """构造包含两个 ``m:oMath`` 的非规范 Equation XML。"""
+
+ root = etree.fromstring(build_word_2003_equation_xml("x").encode())
+ math_paragraph = root.find(
+ f".//{{{M_NS}}}oMathPara"
+ )
+ assert math_paragraph is not None
+ second = etree.SubElement(math_paragraph, f"{{{M_NS}}}oMath")
+ run = etree.SubElement(second, f"{{{M_NS}}}r")
+ etree.SubElement(run, f"{{{M_NS}}}t").text = "y"
+ return etree.tostring(root, encoding="unicode")
+
+
+def _doctype_equationxml() -> str:
+ """构造带外部实体声明的 Equation XML,验证解析器不会读取实体。"""
+
+ return (
+ '<!DOCTYPE w:wordDocument [<!ENTITY probe SYSTEM "file:///etc/passwd">]>'
+ f'<w:wordDocument xmlns:w="{WORD_2003_NS}" xmlns:m="{M_NS}">'
+ "<w:body><w:p><m:oMathPara><m:oMath><m:r><m:t>&probe;</m:t>"
+ "</m:r></m:oMath></m:oMathPara></w:p></w:body></w:wordDocument>"
+ )
+
+
+def _equationxml_with_forbidden_pict() -> str:
+ """构造包含 Word 2003 ``pict`` 的不可恢复 Equation XML。"""
+
+ root = etree.fromstring(build_word_2003_equation_xml("x").encode())
+ run = root.find(f".//{{{M_NS}}}r")
+ assert run is not None
+ etree.SubElement(run, f"{{{WORD_2003_NS}}}pict")
+ return etree.tostring(root, encoding="unicode")
+
+
+def test_equationxml_decoder_converts_spec_document_and_fraction() -> None:
+ """验证规范 Word 2003 XML 包装可复用现有 OMML 转换器。"""
+
+ decoder = DocxEquationXmlDecoder()
+
+ assert decoder.decode(build_word_2003_equation_xml()) == "x+y"
+ assert (
+ decoder.decode(build_word_2003_fraction_equation_xml())
+ == r"\frac{a}{b}"
+ )
+
+
+ ("source_latex", "expected_latex"),
+ [
+ (r"\sqrt{x}", r"\sqrt{x}"),
+ (r"x^2", r"x^{2}"),
+ (r"\int_0^1 x", r"\int_{0}^{1}x"),
+ (r"\left(x\right)", r"\left(x\right)"),
+ (
+ r"\begin{matrix}a&b\\c&d\end{matrix}",
+ r"\begin{matrix}a&b\\c&d\end{matrix}",
+ ),
+ ("α+β", r"\alpha +\beta"),
+ ],
+)
+def test_equationxml_decoder_reuses_omml_formula_coverage(
+ source_latex: str,
+ expected_latex: str,
+) -> None:
+ """验证根式、脚本、积分、定界符、矩阵和 Unicode 沿用 OMML 能力。"""
+
+ equation = latex_to_omml(source_latex, display=False)
+ equation_xml = build_word_2003_equation_xml_from_omml(equation)
+
+ assert DocxEquationXmlDecoder().decode(equation_xml) == expected_latex
+
+
+ "payload",
+ [
+ "<broken",
+ "<m:oMath xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math'/>",
+ _invalid_equationxml_with_multiple_math(),
+ _doctype_equationxml(),
+ _equationxml_with_forbidden_pict(),
+ "<!--comment-->" + build_word_2003_equation_xml("x"),
+ ],
+)
+def test_equationxml_decoder_rejects_malformed_or_unsafe_documents(
+ payload: str,
+) -> None:
+ """验证损坏、裸 OMML、多公式和实体文档整体回退。"""
+
+ assert DocxEquationXmlDecoder().decode(payload) is None
+
+
+def test_equationxml_decoder_enforces_entry_total_and_cache_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证单属性、累计资源限制及相同 payload 缓存不重复计费。"""
+
+ first = build_word_2003_equation_xml("x")
+ second = build_word_2003_equation_xml("y")
+ monkeypatch.setattr(equationxml_module, "MAX_ENTRY_BYTES", len(first.encode()) + 10)
+ monkeypatch.setattr(equationxml_module, "MAX_ASSET_TOTAL_BYTES", len(first.encode()) + 1)
+ decoder = DocxEquationXmlDecoder()
+
+ assert decoder.decode(first) == "x"
+ assert decoder.decode(first) == "x"
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):
+ decoder.decode(second)
+
+ monkeypatch.setattr(equationxml_module, "MAX_ENTRY_BYTES", 8)
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_entry_bytes"):
+ DocxEquationXmlDecoder().decode(first)
+
+
+def test_docx_equationxml_standalone_inline_table_and_textbox_flows() -> None:
+ """验证正文独立、行内、表格和文本框 Equation XML 输出语义。"""
+
+ equation_xml = build_word_2003_equation_xml()
+ standalone = DocxModel().predict(
+ BytesIO(build_equationxml_docx([equation_xml]))
+ )
+ inline = DocxModel().predict(
+ BytesIO(build_equationxml_docx([equation_xml], inline=True))
+ )
+ table = DocxModel().predict(
+ BytesIO(build_equationxml_docx([equation_xml], table=True))
+ )
+ textbox = DocxModel().predict(
+ BytesIO(build_equationxml_docx([equation_xml], textbox=True))
+ )
+
+ assert standalone == [
+ [{"type": BlockType.EQUATION, "content": "x+y"}]
+ ]
+ 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 "<img" not in table[0][0]["content"]
+ assert textbox == [
+ [{"type": BlockType.EQUATION, "content": "x+y"}]
+ ]
+
+
+def test_docx_equationxml_title_list_header_and_footer_flows() -> None:
+ """验证标题、列表及页眉页脚沿用现有公式内容重建路径。"""
+
+ first = build_word_2003_equation_xml("x")
+ second = build_word_2003_fraction_equation_xml()
+ title = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [first],
+ inline=True,
+ paragraph_style="Title",
+ )
+ )
+ )
+ bullet = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [first],
+ inline=True,
+ paragraph_style="ListBullet",
+ )
+ )
+ )
+ header_footer = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [first, second],
+ header_footer=True,
+ )
+ )
+ )
+
+ assert title[0][0] == {
+ "type": BlockType.DOC_TITLE,
+ "level": 1,
+ "content": "before <eq>x</eq> after",
+ }
+ assert bullet == [
+ [
+ {
+ "type": BlockType.LIST,
+ "attribute": "unordered",
+ "content": [
+ {
+ "type": BlockType.TEXT,
+ "content": "before <eq>x</eq> after",
+ }
+ ],
+ "ilevel": 0,
+ }
+ ]
+ ]
+ assert header_footer == [
+ [
+ {"type": BlockType.HEADER, "content": "<eq>x</eq>"},
+ {
+ "type": BlockType.FOOTER,
+ "content": r"<eq>\frac{a}{b}</eq>",
+ },
+ ]
+ ]
+
+
+def test_docx_equationxml_precedence_and_preview_fallback() -> None:
+ """验证 OMML、Equation XML、MTEF 和预览图片的确定优先级。"""
+
+ equation_xml = build_word_2003_equation_xml("x")
+ _name, mtef, mtef_latex = formula_corpus()[1]
+ native_omml = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [equation_xml],
+ alternate_omml=True,
+ keep_mtef=True,
+ mtef_payloads=[mtef],
+ )
+ )
+ )
+ equationxml_over_mtef = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [equation_xml],
+ keep_mtef=True,
+ mtef_payloads=[mtef],
+ )
+ )
+ )
+ mtef_over_bad_equationxml = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ ["<broken"],
+ keep_mtef=True,
+ mtef_payloads=[mtef],
+ )
+ )
+ )
+ preview = DocxModel().predict(
+ BytesIO(build_equationxml_docx(["<broken"]))
+ )
+
+ assert native_omml == [
+ [{"type": BlockType.EQUATION, "content": "z"}]
+ ]
+ assert equationxml_over_mtef == [
+ [{"type": BlockType.EQUATION, "content": "x"}]
+ ]
+ assert mtef_over_bad_equationxml == [
+ [{"type": BlockType.EQUATION, "content": mtef_latex}]
+ ]
+ assert len(preview[0]) == 1
+ assert preview[0][0]["type"] == BlockType.IMAGE
+
+
+def test_docx_equationxml_same_payload_is_not_semantically_deduplicated() -> None:
+ """验证缓存只减少解码成本,不合并两个独立公式 shape。"""
+
+ equation_xml = build_word_2003_equation_xml("x")
+ pages = DocxModel().predict(
+ BytesIO(build_equationxml_docx([equation_xml, equation_xml]))
+ )
+
+ assert _equation_contents(pages) == ["x", "x"]
+
+
+def test_docx_equationxml_shared_preview_is_suppressed_per_shape() -> None:
+ """验证共享图片关系只抑制有效公式所属 shape,不全局删除图片。"""
+
+ pages = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [build_word_2003_equation_xml("x"), "<broken"],
+ share_preview=True,
+ )
+ )
+ )
+
+ assert [block["type"] for block in pages[0]] == [
+ BlockType.EQUATION,
+ BlockType.IMAGE,
+ ]
+ assert pages[0][0]["content"] == "x"
+
+
+def test_docx_equationxml_attribute_is_unescaped_exactly_once() -> None:
+ """验证外层属性和内层 XML 实体各解码一次,不发生二次展开。"""
+
+ pages = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [build_word_2003_equation_xml("x&y")]
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == [r"x\&y"]
+
+
+def test_docx_equationxml_analyze_lifecycle_and_strict_contracts() -> None:
+ """验证 Equation XML 贯穿同步异步 Analyze 且调用方流保持打开。"""
+
+ file_bytes = build_equationxml_docx(
+ [build_word_2003_fraction_equation_xml()]
+ )
+ stream = BytesIO(file_bytes)
+ pages = DocxModel().predict(stream)
+ middle, model = doc_analyze(file_bytes, file_suffix="docx")
+ async_middle, async_model = asyncio.run(
+ aio_doc_analyze(file_bytes, file_suffix="docx")
+ )
+
+ assert not stream.closed
+ assert _equation_contents(pages) == [r"\frac{a}{b}"]
+ assert isinstance(model, ModelJson)
+ assert isinstance(middle, MiddleJson)
+ assert model.file_suffix == middle.file_suffix == "docx"
+ assert middle.pages[0].blocks[0].type == BlockType.EQUATION
+ assert middle.pages[0].blocks[0].content == r"\frac{a}{b}"
+ assert async_model == model
+ assert async_middle == middle
+
+
+def test_docx_equationxml_converter_reuse_resets_decoder_state() -> None:
+ """验证 converter 复用时页、缓存、资源预算和告警状态均重置。"""
+
+ converter = DocxConverter()
+ converter.convert(
+ BytesIO(
+ build_equationxml_docx([build_word_2003_equation_xml("x")])
+ )
+ )
+ assert _equation_contents(converter.pages) == ["x"]
+
+ converter.convert(
+ BytesIO(
+ build_equationxml_docx([build_word_2003_equation_xml("y")])
+ )
+ )
+ assert _equation_contents(converter.pages) == ["y"]
+
+
+def test_invalid_docx_equationxml_preview_exports_to_sidecar(
+ tmp_path: Path,
+) -> None:
+ """验证坏 Equation XML 的图片回退导出后无 base64 JSON 残留。"""
+
+ middle, _model = doc_analyze(
+ build_equationxml_docx(["<broken"]),
+ file_suffix="docx",
+ )
+
+ result = middle.export(tmp_path / "docx-equationxml")
+
+ 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")
diff --git a/tests/unittest/test_flash_image_mtef.py b/tests/unittest/test_flash_image_mtef.py
new file mode 100644
index 00000000..2b8f5be7
--- /dev/null
+++ b/tests/unittest/test_flash_image_mtef.py
@@ -0,0 +1,251 @@
+from __future__ import annotations
+
+import pytest
+
+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
+from mineru.model.flash.office import image_equation as image_equation_module
+from mineru.model.flash.office.image_equation import (
+ OfficeImageEquationDecoder,
+ decode_image_embedded_equation,
+)
+
+from _image_mtef_test_utils import (
+ apps_mfcc_comment,
+ apps_mfcc_comments,
+ baseline_wmf_comment,
+ build_baseline_only_gif,
+ build_gif_with_extensions,
+ build_gif_with_mtef,
+ build_wmf,
+ gif_mtef_extension,
+ pre6_wmf_comment,
+)
+from _mtef_test_utils import formula_corpus
+from _mtef_v5_test_utils import v5_equation, v5_formula_corpus, v5_text
+
+
+ ("mtef", "expected"),
+ [
+ (formula_corpus()[1][1], formula_corpus()[1][2]),
+ (v5_formula_corpus()[1][1], v5_formula_corpus()[1][2]),
+ ],
+ ids=["v3", "v5"],
+)
+def test_pre6_wmf_comment_decodes_mtef_versions(
+ mtef: bytes,
+ expected: str,
+) -> None:
+ """验证带/不带 placeable header 的 pre-6 WMF 可恢复 v3/v5。"""
+
+ comment = pre6_wmf_comment(mtef)
+
+ assert decode_image_embedded_equation(
+ build_wmf([comment]),
+ part_name="image.wmf",
+ ) == expected
+ assert decode_image_embedded_equation(
+ build_wmf([comment], placeable=True),
+ content_type="image/x-wmf",
+ ) == expected
+
+
+ "signature",
+ [
+ "Design Science, Inc./MTEF",
+ "Wiris/MTEF/MathType7",
+ "Acme/MTEF",
+ "Design Science, Inc.",
+ "Wiris",
+ ],
+)
+def test_apps_mfcc_single_and_multi_chunk_signatures(signature: str) -> None:
+ """验证规范及历史 signature 的单/多 chunk AppsMFCC。"""
+
+ _name, mtef, expected = v5_formula_corpus()[2]
+
+ single = build_wmf(
+ apps_mfcc_comments(
+ mtef,
+ chunk_size=len(mtef),
+ signature=signature,
+ )
+ )
+ multiple = build_wmf(
+ apps_mfcc_comments(
+ mtef,
+ chunk_size=7,
+ signature=signature,
+ )
+ )
+
+ assert decode_image_embedded_equation(single) == expected
+ assert decode_image_embedded_equation(multiple) == expected
+
+
+def test_apps_mfcc_reassembles_mtef_larger_than_32k() -> None:
+ """验证 AppsMFCC 可跨 WMF 单 comment 上限重组大型 MTEF。"""
+
+ mtef = v5_equation(v5_text("x" * 7000))
+ assert len(mtef) > 0x7FFE
+ image = build_wmf(
+ apps_mfcc_comments(
+ mtef,
+ chunk_size=30_000,
+ )
+ )
+
+ assert decode_image_embedded_equation(image) == "x" * 7000
+
+
+ ("mtef", "expected"),
+ [
+ (formula_corpus()[0][1], formula_corpus()[0][2]),
+ (v5_formula_corpus()[0][1], v5_formula_corpus()[0][2]),
+ ],
+ ids=["v3", "v5"],
+)
+def test_gif_mathtype_001_decodes_across_subblocks(
+ mtef: bytes,
+ expected: str,
+) -> None:
+ """验证 GIF MathType/001 跨 sub-block 恢复 v3/v5。"""
+
+ image = build_gif_with_mtef(
+ mtef,
+ chunk_size=5,
+ include_baseline=True,
+ )
+
+ assert decode_image_embedded_equation(image) == expected
+
+
+def test_wmf_gif_decode_full_v3_v5_formula_corpora() -> None:
+ """验证两种图片载体复用全部既有 v3/v5 公式语料。"""
+
+ for _name, mtef, expected in formula_corpus():
+ assert decode_image_embedded_equation(
+ build_wmf([pre6_wmf_comment(mtef)])
+ ) == expected
+ assert decode_image_embedded_equation(
+ build_gif_with_mtef(mtef, chunk_size=5)
+ ) == expected
+ for _name, mtef, expected in v5_formula_corpus():
+ assert decode_image_embedded_equation(
+ build_wmf(apps_mfcc_comments(mtef, chunk_size=7))
+ ) == expected
+ assert decode_image_embedded_equation(
+ build_gif_with_mtef(mtef, chunk_size=5)
+ ) == expected
+
+
+def test_baseline_comments_and_ordinary_images_are_ignored() -> None:
+ """验证 WMF baseline、GIF/002 和普通图片不被误判为公式。"""
+
+ assert decode_image_embedded_equation(
+ build_wmf([baseline_wmf_comment(12)])
+ ) is None
+ assert decode_image_embedded_equation(build_baseline_only_gif()) is None
+ assert decode_image_embedded_equation(b"\x89PNG\r\n\x1a\n") is None
+
+
+def test_conflicting_wmf_and_gif_candidates_fail_closed() -> None:
+ """验证同一图片中互相冲突的公式 candidates 整体回退。"""
+
+ v3 = formula_corpus()[0][1]
+ v5 = v5_formula_corpus()[1][1]
+ wmf = build_wmf(
+ [
+ pre6_wmf_comment(v3),
+ apps_mfcc_comment(v5, total_length=len(v5)),
+ ]
+ )
+ gif = build_gif_with_extensions(
+ [
+ gif_mtef_extension(v3),
+ gif_mtef_extension(v5),
+ ]
+ )
+
+ assert decode_image_embedded_equation(wmf) is None
+ assert decode_image_embedded_equation(gif) is None
+
+
+ "image",
+ [
+ build_wmf([pre6_wmf_comment(bytes([4, 1, 0, 3, 5, 0]))]),
+ build_wmf(
+ [
+ apps_mfcc_comment(
+ b"truncated",
+ total_length=100,
+ )
+ ]
+ ),
+ build_gif_with_mtef(bytes([4, 1, 0, 3, 5, 0])),
+ build_gif_with_mtef(v5_formula_corpus()[0][1])[:-1],
+ ],
+)
+def test_unsupported_or_truncated_image_comments_fail_closed(
+ image: bytes,
+) -> None:
+ """验证 v4、缺 chunk 和截断 GIF 不输出部分公式。"""
+
+ assert decode_image_embedded_equation(image) is None
+
+
+def test_reordered_apps_chunks_and_strict_image_prefixes_fail_closed() -> None:
+ """验证 AppsMFCC 乱序及任意 WMF/GIF 截断不会输出部分公式。"""
+
+ mtef = v5_formula_corpus()[1][1]
+ comments = apps_mfcc_comments(mtef, chunk_size=7)
+ reordered = build_wmf(list(reversed(comments)))
+ valid_wmf = build_wmf(comments)
+ valid_gif = build_gif_with_mtef(mtef, chunk_size=5)
+
+ assert decode_image_embedded_equation(reordered) is None
+ assert all(
+ decode_image_embedded_equation(valid_wmf[:end]) is None
+ for end in range(len(valid_wmf))
+ )
+ assert all(
+ decode_image_embedded_equation(valid_gif[:end]) is None
+ for end in range(len(valid_gif))
+ )
+
+
+def test_image_equation_decoder_cache_and_total_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证相同图片缓存不重复计费,唯一图片受累计预算限制。"""
+
+ first_mtef = v5_formula_corpus()[0][1]
+ second_mtef = v5_formula_corpus()[1][1]
+ first = build_gif_with_mtef(first_mtef)
+ second = build_gif_with_mtef(second_mtef)
+ monkeypatch.setattr(
+ image_equation_module,
+ "MAX_ASSET_TOTAL_BYTES",
+ len(first) + 1,
+ )
+ decoder = OfficeImageEquationDecoder()
+
+ assert decoder.decode(first) == v5_formula_corpus()[0][2]
+ assert decoder.decode(first) == v5_formula_corpus()[0][2]
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_asset_total_bytes"):
+ decoder.decode(second)
+
+
+def test_image_equation_record_limit_raises_stable_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 WMF/GIF record 超限抛稳定 resource-limit 错误。"""
+
+ monkeypatch.setattr(image_equation_module, "MAX_PICTURE_RECORDS", 1)
+ image = build_gif_with_mtef(v5_formula_corpus()[0][1], chunk_size=1)
+
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_picture_records"):
+ decode_image_embedded_equation(image)
diff --git a/tests/unittest/test_flash_mtef_v5.py b/tests/unittest/test_flash_mtef_v5.py
new file mode 100644
index 00000000..44d2f102
--- /dev/null
+++ b/tests/unittest/test_flash_mtef_v5.py
@@ -0,0 +1,328 @@
+from __future__ import annotations
+
+import struct
+
+import pytest
+
+from mineru.model.flash.legacy_office import mtef_v5 as mtef_v5_module
+from mineru.model.flash.legacy_office import mtef as mtef_module
+from mineru.model.flash.legacy_office.errors import LegacyOfficeResourceLimitError
+from mineru.model.flash.legacy_office.mtef import (
+ decode_equation_native,
+ decode_equation_object,
+ decode_mtef,
+ decode_mtef_v3,
+ decode_mtef_v5,
+)
+
+from _mtef_test_utils import build_equation_object, equation_native, formula_corpus
+from _mtef_v5_test_utils import (
+ v5_char,
+ v5_encoding_definition,
+ v5_equation,
+ v5_equation_preferences,
+ v5_font_definition,
+ v5_font_style_definition,
+ v5_formula_corpus,
+ v5_future_record,
+ v5_line,
+ v5_template,
+ v5_template_corpus,
+ v5_text,
+)
+
+# WIRIS MTEF v5 页面公布的 MathType 7 二次公式字节表。原网页第 133 行
+# 被帮助文本覆盖,按 dimension nibble padding 归一化为 0;第 255 行误插入
+# 的 HTML “&” 字节不属于 CHAR record,构造 golden 时予以移除。
+_WIRIS_QUADRATIC_MTEF = bytes.fromhex(
+ "050100070044534d543700001357696e416c6c4261736963436f646550616765"
+ "7300110554696d6573204e657720526f6d616e00110353796d626f6c00110543"
+ "6f7572696572204e65770011044d5420457874726100120008212f458f442f41"
+ "50f4100f475f4150f21f1e4150f4150f4100f445f425f48f425f4100f4100f43"
+ "5f4100f21f00a5f20a25f48f41f4100f4000f40f48f417f48f4000f21a5f445f"
+ "45f45f45f45f410f0c0100010001020202020002000101010003000100040000"
+ "0a010003000b0000010002048612222d0200836200020486b100b103000a0000"
+ "0100020083620003001c00000b01010100020088320000000a02048612222d02"
+ "0088340002008361000200836300000b010100000a0100020088320002008361"
+ "0000000000"
+)
+
+
+ ("name", "mtef", "expected"),
+ v5_formula_corpus(),
+ ids=[name for name, _mtef, _expected in v5_formula_corpus()],
+)
+def test_mtef_v5_corpus_decodes_to_exact_latex(
+ name: str,
+ mtef: bytes,
+ expected: str,
+) -> None:
+ """验证常见 MTEF v5 字符、模板、PILE 和 MATRIX 精确输出。"""
+
+ assert name
+ assert decode_mtef_v5(mtef) == expected
+ assert decode_mtef(mtef) == expected
+
+
+ ("name", "mtef", "expected"),
+ v5_template_corpus(),
+ ids=[name for name, _mtef, _expected in v5_template_corpus()],
+)
+def test_mtef_v5_template_selectors_decode_to_exact_latex(
+ name: str,
+ mtef: bytes,
+ expected: str,
+) -> None:
+ """验证标准 fence、bar、big-op、script、vector 和 box templates。"""
+
+ assert name
+ assert decode_mtef_v5(mtef) == expected
+
+
+def test_mtef_dispatch_keeps_v3_and_rejects_v4() -> None:
+ """验证通用入口只按 header 分派 v3/v5,v3 输出保持不变。"""
+
+ _name, v3, expected = formula_corpus()[1]
+
+ assert decode_mtef(v3) == expected
+ assert decode_mtef_v3(v3) == expected
+ assert decode_mtef(bytes([4, 1, 0, 3, 5, 0])) is None
+
+
+def test_wiris_mathtype_7_quadratic_golden_decodes_exactly() -> None:
+ """验证 WIRIS 公布的真实 MathType 7 v5 字节流恢复二次公式。"""
+
+ assert decode_mtef_v5(_WIRIS_QUADRATIC_MTEF) == (
+ r"\frac{-\mathit{b}\pm \sqrt{\mathit{b}^{2}-4"
+ r"\mathit{a}\mathit{c}}}{2\mathit{a}}"
+ )
+
+
+def test_equation_native_and_ole_object_decode_mtef_v5() -> None:
+ """验证 EQNOLEFILEHDR 与独立 OLE 对象均按首字节解码 v5。"""
+
+ _name, mtef, expected = v5_formula_corpus()[1]
+
+ assert decode_equation_native(equation_native(mtef)) == expected
+ assert decode_equation_object(build_equation_object(mtef)) == expected
+
+
+def test_mtef_v5_known_symbol_font_position_and_style_definitions() -> None:
+ """验证无 MTCode 的 Symbol position 及显式 FONT_STYLE_DEF 粗体。"""
+
+ symbol = v5_char(
+ "x",
+ typeface=6,
+ font_position=0x61,
+ omit_mtcode=True,
+ )
+ definitions = (
+ v5_encoding_definition("WinAllBasicCodePages"),
+ v5_font_definition(5, "Times New Roman"),
+ v5_font_style_definition(1, 1),
+ )
+ bold = v5_char("x", typeface=-1)
+ mt_extra = v5_char(
+ "x",
+ typeface=11,
+ font_position=0x68,
+ omit_mtcode=True,
+ )
+
+ assert decode_mtef_v5(v5_equation(symbol)) == r"\alpha"
+ assert decode_mtef_v5(v5_equation(bold, definitions=definitions)) == r"\mathbf{x}"
+ assert decode_mtef_v5(v5_equation(mt_extra)) == r"\hbar"
+
+
+ ("mtcode", "expected"),
+ [
+ (0xE930, r"\leqslant"),
+ (0xF000, r"\mathfrak{A}"),
+ (0xF01A, r"\mathfrak{a}"),
+ (0xF080, r"\mathbb{A}"),
+ (0xF100, r"\mathcal{A}"),
+ ],
+)
+def test_mtef_v5_common_private_mtcode_mapping(
+ mtcode: int,
+ expected: str,
+) -> None:
+ """验证常见 MathType PUA 关系符和数学字母可稳定映射。"""
+
+ record = b"\x02\x00\x83" + struct.pack("<H", mtcode)
+
+ assert decode_mtef_v5(v5_equation(record)) == expected
+
+
+ ("embellishment", "expected"),
+ [
+ (7, "{}'x"),
+ (14, r"\overrightharpoon{x}"),
+ (15, r"\overleftharpoon{x}"),
+ (21, r"\xcancel{x}"),
+ (29, r"\underline{x}"),
+ (33, r"\underrightarrow{x}"),
+ ],
+)
+def test_mtef_v5_extended_embellishment_mapping(
+ embellishment: int,
+ expected: str,
+) -> None:
+ """验证 v5 新增的反向 prime、harpoon、strike 和下方修饰符。"""
+
+ assert decode_mtef_v5(
+ v5_equation(v5_char("x", embellishments=(embellishment,)))
+ ) == expected
+
+
+def test_mtef_v5_16bit_font_position_and_large_future_record() -> None:
+ """验证 16 位 font position 和三字节 future length 保持同步。"""
+
+ definitions = (
+ v5_font_definition(1, "MTCode Font"),
+ v5_font_style_definition(1, 0),
+ )
+ alpha = v5_char(
+ "x",
+ typeface=-1,
+ font_position=0x03B1,
+ omit_mtcode=True,
+ )
+ mtef = v5_equation(
+ v5_future_record(b"x" * 300),
+ alpha,
+ definitions=definitions,
+ )
+
+ assert decode_mtef_v5(mtef) == r"\alpha"
+
+
+def test_mtef_v5_color_and_size_metadata_stays_synchronized() -> None:
+ """验证 COLOR_DEF、COLOR 和 SIZE 只校验结构而不改变公式内容。"""
+
+ color_definition = b"\x10\x00" + struct.pack("<HHH", 0, 0, 0)
+ color_reference = b"\x0f\x01"
+ size = b"\x09\x00\x80"
+
+ assert decode_mtef_v5(
+ v5_equation(
+ v5_char("x"),
+ definitions=(color_definition, color_reference, size),
+ )
+ ) == "x"
+ assert decode_mtef_v5(
+ v5_equation(v5_char("x"), definitions=(color_reference,))
+ ) is None
+
+
+def test_mtef_v5_function_start_groups_function_style_characters() -> None:
+ """验证 FUNC_START 将连续 FUNCTION 字符恢复为 LaTeX operator。"""
+
+ function = (
+ v5_char("s", typeface=2, function_start=True)
+ + v5_char("i", typeface=2)
+ + v5_char("n", typeface=2)
+ + v5_char("x")
+ )
+
+ assert decode_mtef_v5(v5_equation(function)) == r"\sin x"
+
+
+def test_mtef_v5_text_style_groups_and_escapes_visible_text() -> None:
+ """验证 TEXT/TEXT_FE 连续字符使用单一 text 节点并安全转义。"""
+
+ assert decode_mtef_v5(
+ v5_equation(v5_text("rate_1 & rate_2", typeface=1))
+ ) == r"\text{rate\_1 \& rate\_2}"
+
+
+ "payload",
+ [
+ b"",
+ b"\x05\x01\x00\x07\x00unterminated",
+ v5_equation(v5_template(35, v5_line(v5_char("x")))),
+ v5_equation(v5_template(37, v5_line(v5_char("x")), variation=1)),
+ v5_equation(v5_char("\ue000")),
+ v5_equation(v5_char("x", font_position=1, omit_mtcode=True, typeface=11)),
+ v5_equation(b"\x14"),
+ v5_equation(b"\x64\xff\xff\xff"),
+ v5_equation(b"\x02\x14\x83\x78\x00\x01\x00"),
+ v5_equation(b"\x02\x00\x80\x78\x00"),
+ v5_equation(b"\x06\x00\x02"),
+ v5_equation(b"\x05\x00\x00\x02\x00\x00\x01"),
+ v5_equation(v5_char("x")) + b"\x00",
+ ],
+)
+def test_mtef_v5_invalid_or_unsupported_payload_fails_closed(
+ payload: bytes,
+) -> None:
+ """验证坏 header、未知语义、PUA、MTExtra 和尾随字节不生成残缺 LaTeX。"""
+
+ assert decode_mtef_v5(payload) is None
+
+
+def test_every_strict_prefix_of_mtef_v5_fails_closed() -> None:
+ """验证任意位置截断的 v5 对象都不会输出部分公式。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[1]
+
+ assert all(decode_mtef_v5(mtef[:end]) is None for end in range(len(mtef)))
+
+
+def test_mtef_v5_invalid_equation_native_lengths_fail_closed() -> None:
+ """验证 v5 仍受 EQNOLEFILEHDR 对象边界约束。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ native = bytearray(equation_native(mtef))
+ struct.pack_into("<I", native, 8, len(mtef) + 1)
+
+ assert decode_equation_native(bytes(native)) is None
+
+
+def test_mtef_v5_record_and_depth_limits_raise_stable_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 v5 record/depth 超限抛稳定 resource-limit 错误。"""
+
+ monkeypatch.setattr(mtef_v5_module, "MAX_RECORDS", 2)
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):
+ decode_mtef_v5(v5_equation(v5_char("x")))
+
+ monkeypatch.setattr(mtef_v5_module, "MAX_RECORDS", 100)
+ monkeypatch.setattr(mtef_v5_module, "MAX_RECORD_DEPTH", 1)
+ nested = v5_equation(
+ v5_template(11, v5_line(v5_char("a")), v5_line(v5_char("b")))
+ )
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):
+ decode_mtef_v5(nested)
+
+
+def test_mtef_v3_record_and_depth_limits_also_raise_stable_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证共享资源超限语义同时覆盖原有 v3 reader。"""
+
+ _name, mtef, _expected = formula_corpus()[1]
+ monkeypatch.setattr(mtef_module, "MAX_RECORDS", 2)
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_records"):
+ decode_mtef_v3(mtef)
+
+ monkeypatch.setattr(mtef_module, "MAX_RECORDS", 100)
+ monkeypatch.setattr(mtef_module, "MAX_RECORD_DEPTH", 0)
+ with pytest.raises(LegacyOfficeResourceLimitError, match="max_record_depth"):
+ decode_mtef_v3(mtef)
+
+
+def test_mtef_v5_equation_preferences_style_reference_is_validated() -> None:
+ """验证 EQN_PREFS style 引用不存在的 FONT_DEF 时整体回退。"""
+
+ invalid_preferences = v5_equation_preferences([(1, 0)])
+
+ assert decode_mtef_v5(
+ v5_equation(v5_char("x"), definitions=(invalid_preferences,))
+ ) is None
diff --git a/tests/unittest/test_flash_office_image_mtef.py b/tests/unittest/test_flash_office_image_mtef.py
new file mode 100644
index 00000000..37d87116
--- /dev/null
+++ b/tests/unittest/test_flash_office_image_mtef.py
@@ -0,0 +1,634 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+from io import BytesIO
+from pathlib import Path
+from zipfile import ZIP_DEFLATED, ZipFile
+
+import pytest
+
+from mineru.backend.analyze import aio_doc_analyze, doc_analyze
+from mineru.model.flash import (
+ DocModel,
+ DocxModel,
+ PptModel,
+ PptxModel,
+ XlsModel,
+ XlsxModel,
+)
+from mineru.model.flash.doc.doc_converter import DocConverter
+from mineru.model.flash.docx.docx_converter import DocxConverter
+from mineru.model.flash.doc.models import (
+ DocImage,
+ DocImagePayload,
+ DocParagraph,
+ DocTable,
+ DocTableCell,
+ DocTableRow,
+)
+from mineru.model.flash.xlsx.xlsx_converter import XlsxConverter
+from mineru.model.flash.pptx.pptx_converter import PptxConverter
+from mineru.types import BlockType, MiddleJson, ModelJson
+
+from _docx_equationxml_test_utils import (
+ build_equationxml_docx,
+ build_word_2003_equation_xml,
+)
+from _image_mtef_test_utils import (
+ apps_mfcc_comments,
+ baseline_wmf_comment,
+ build_baseline_only_gif,
+ build_gif_with_mtef,
+ build_wmf,
+)
+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 build_equation_doc, formula_corpus
+from _mtef_v5_test_utils import v5_formula_corpus
+from _office_image_mtef_test_utils import (
+ build_image_docx,
+ build_image_pptx,
+ build_image_xlsx,
+)
+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 _has_image(pages: list[list[dict]]) -> bool:
+ """判断 model-list 是否至少保留一个图片 block。"""
+
+ return any(
+ block.get("type") == BlockType.IMAGE
+ for page in pages
+ for block in page
+ )
+
+
+def _wmf_formula(mtef: bytes) -> bytes:
+ """把 MTEF 包装为跨 chunk AppsMFCC WMF。"""
+
+ return build_wmf(
+ apps_mfcc_comments(
+ mtef,
+ chunk_size=7,
+ ),
+ placeable=True,
+ )
+
+
+def test_legacy_doc_ppt_xls_recover_wmf_comment_after_bad_native() -> None:
+ """验证旧三格式 Native 失败后用同一预览 WMF comment 恢复公式。"""
+
+ _name, mtef, expected = v5_formula_corpus()[1]
+ preview = _wmf_formula(mtef)
+ invalid = b"invalid native"
+ cases = [
+ (
+ DocModel(),
+ build_equation_doc(
+ [(1, invalid)],
+ preview_storage_ids={1},
+ preview_payloads={1: preview},
+ ),
+ ),
+ (
+ PptModel(),
+ build_equation_ppt(
+ [invalid],
+ preview_payload=preview,
+ ),
+ ),
+ (
+ XlsModel(),
+ build_equation_xls(
+ [(1, invalid)],
+ preview_payload=preview,
+ ),
+ ),
+ ]
+
+ for model, file_bytes in cases:
+ pages = model.predict(BytesIO(file_bytes))
+ assert _equation_contents(pages) == [expected]
+ assert not _has_image(pages)
+
+
+def test_legacy_doc_direct_gif_comment_recovers_after_bad_native() -> None:
+ """验证 DOC PICF magic fallback 保留并解析原始 GIF/001。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ image = build_gif_with_mtef(mtef, chunk_size=3)
+ pages = DocModel().predict(
+ BytesIO(
+ build_equation_doc(
+ [(1, b"invalid native")],
+ preview_storage_ids={1},
+ preview_payloads={1: image},
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == [expected]
+ assert not _has_image(pages)
+
+
+def test_legacy_native_mtef_precedes_conflicting_wmf_comment() -> None:
+ """验证旧三格式有效 Native 优先于内容不同的 WMF comment。"""
+
+ _native_name, native, expected = formula_corpus()[0]
+ _image_name, image_mtef, _image_expected = v5_formula_corpus()[1]
+ preview = _wmf_formula(image_mtef)
+ cases = [
+ (
+ DocModel(),
+ build_equation_doc(
+ [(1, native)],
+ preview_storage_ids={1},
+ preview_payloads={1: preview},
+ ),
+ ),
+ (
+ PptModel(),
+ build_equation_ppt([native], preview_payload=preview),
+ ),
+ (
+ XlsModel(),
+ build_equation_xls([(1, native)], preview_payload=preview),
+ ),
+ ]
+
+ for model, file_bytes in cases:
+ assert _equation_contents(model.predict(BytesIO(file_bytes))) == [expected]
+
+
+def test_xls_wmf_comment_equation_enters_table_cell() -> None:
+ """验证 XLS 图片 comment 公式进入 cell HTML 且不重复输出。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ pages = XlsModel().predict(
+ BytesIO(
+ build_equation_xls(
+ [(1, b"invalid native")],
+ preview_payload=_wmf_formula(mtef),
+ cell_records=label_cell(0, 0, "value"),
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == []
+ assert len(pages[0]) == 1
+ assert pages[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{expected}</eq>" in pages[0][0]["content"]
+
+
+def test_doc_image_comment_equation_enters_nested_table_html() -> None:
+ """验证 DOC 段落图片与独立图片在嵌套表格中都写入 eq。"""
+
+ payload = DocImagePayload(
+ data=b"",
+ extension="wmf",
+ content_type="image/wmf",
+ equation_latex="x+y",
+ )
+ paragraph = DocParagraph(
+ cp_start=0,
+ cp_end=1,
+ images=[payload],
+ )
+ nested = DocTable(
+ cp_start=1,
+ cp_end=2,
+ rows=[
+ DocTableRow(
+ cells=[
+ DocTableCell(
+ blocks=[DocImage(cp=1, payload=payload)]
+ )
+ ]
+ )
+ ],
+ )
+ table = DocTable(
+ cp_start=0,
+ cp_end=2,
+ rows=[
+ DocTableRow(
+ cells=[DocTableCell(blocks=[paragraph, nested])]
+ )
+ ],
+ )
+
+ html = DocConverter._table_html(table)
+
+ assert html.count("<eq>x+y</eq>") == 2
+ assert "<img" not in html
+
+
+def test_docx_picture_comment_flows_inline_table_header_and_standalone() -> None:
+ """验证 DOCX 普通 WMF/GIF 图片进入统一公式 token 重建链路。"""
+
+ first = v5_formula_corpus()[0]
+ second = v5_formula_corpus()[1]
+ wmf = _wmf_formula(first[1])
+ gif = build_gif_with_mtef(second[1], chunk_size=5)
+ standalone = DocxModel().predict(BytesIO(build_image_docx(wmf)))
+ inline = DocxModel().predict(
+ BytesIO(build_image_docx(gif, inline=True))
+ )
+ table = DocxModel().predict(
+ BytesIO(build_image_docx(gif, table=True))
+ )
+ header = DocxModel().predict(
+ BytesIO(build_image_docx(gif, header=True))
+ )
+
+ assert standalone == [
+ [{"type": BlockType.EQUATION, "content": first[2]}]
+ ]
+ assert inline == [
+ [
+ {
+ "type": BlockType.TEXT,
+ "content": f"before <eq>{second[2]}</eq> after",
+ }
+ ]
+ ]
+ assert table[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{second[2]}</eq>" in table[0][0]["content"]
+ assert "<img" not in table[0][0]["content"]
+ assert header == [
+ [
+ {
+ "type": BlockType.HEADER,
+ "content": f"<eq>{second[2]}</eq>",
+ }
+ ]
+ ]
+
+
+def test_docx_picture_comment_flows_title_and_list() -> None:
+ """验证 DOCX 图片公式在标题和列表中保持 eq 行内语义。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ image = build_gif_with_mtef(mtef)
+ title = DocxModel().predict(
+ BytesIO(
+ build_image_docx(
+ image,
+ inline=True,
+ paragraph_style="Title",
+ )
+ )
+ )
+ bullet = DocxModel().predict(
+ BytesIO(
+ build_image_docx(
+ image,
+ inline=True,
+ paragraph_style="List Bullet",
+ )
+ )
+ )
+
+ assert title[0][0] == {
+ "type": BlockType.DOC_TITLE,
+ "level": 1,
+ "content": f"before <eq>{expected}</eq> after",
+ }
+ assert bullet[0][0]["type"] == BlockType.LIST
+ assert bullet[0][0]["content"][0]["content"] == (
+ f"before <eq>{expected}</eq> after"
+ )
+
+
[email protected]("carrier", ["wmf", "gif"])
+def test_pptx_picture_comment_equation_keeps_shape_order(carrier: str) -> None:
+ """验证 PPTX 普通图片 comment 以原 shape 顺序输出 equation。"""
+
+ _name, mtef, expected = v5_formula_corpus()[2]
+ image = (
+ _wmf_formula(mtef)
+ if carrier == "wmf"
+ else build_gif_with_mtef(mtef, chunk_size=7)
+ )
+
+ pages = PptxModel().predict(BytesIO(build_image_pptx(image)))
+
+ assert _equation_contents(pages) == [expected]
+ assert not _has_image(pages)
+
+
[email protected]("carrier", ["wmf", "gif"])
+def test_pptx_notes_picture_comment_becomes_page_footnote(
+ carrier: str,
+) -> None:
+ """验证 PPTX notes 中的 WMF/GIF 图片公式输出 page_footnote。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ image = (
+ _wmf_formula(mtef)
+ if carrier == "wmf"
+ else build_gif_with_mtef(mtef)
+ )
+ pages = PptxModel().predict(
+ BytesIO(
+ build_image_pptx(
+ image,
+ notes=True,
+ )
+ )
+ )
+
+ assert pages == [
+ [
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": f"<eq>{expected}</eq>",
+ }
+ ]
+ ]
+
+
+def test_pptx_notes_bad_ole_native_uses_wmf_preview_comment() -> None:
+ """验证 notes 中 OLE Native 失败时继续解析同对象 WMF preview。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ pages = PptxModel().predict(
+ BytesIO(
+ build_equation_pptx(
+ [b"invalid native"],
+ notes=True,
+ preview_image=_wmf_formula(mtef),
+ )
+ )
+ )
+
+ assert pages == [
+ [
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": f"<eq>{expected}</eq>",
+ }
+ ]
+ ]
+
+
[email protected]("carrier", ["wmf", "gif"])
+def test_xlsx_image_comment_equation_enters_visual_and_table_paths(
+ carrier: str,
+) -> None:
+ """验证 XLSX 普通 WMF/GIF comment 按 anchor 输出或进入表格 cell。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ image = (
+ _wmf_formula(mtef)
+ if carrier == "wmf"
+ else build_gif_with_mtef(mtef, chunk_size=3)
+ )
+ standalone = XlsxModel().predict(
+ BytesIO(build_image_xlsx(image))
+ )
+ table = XlsxModel().predict(
+ BytesIO(build_image_xlsx(image, cell_value="value"))
+ )
+
+ assert _equation_contents(standalone) == [expected]
+ assert _equation_contents(table) == []
+ assert table[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{expected}</eq>" in table[0][0]["content"]
+
+
+def test_xlsx_cell_image_comment_returns_eq_html() -> None:
+ """验证 XLSX cellimages media 在返回 img 前尝试 comment 公式。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ image = build_gif_with_mtef(mtef)
+ package = BytesIO()
+ with ZipFile(package, "w", ZIP_DEFLATED) as archive:
+ archive.writestr("xl/media/image1.gif", image)
+ converter = XlsxConverter()
+ converter.zf = ZipFile(BytesIO(package.getvalue()))
+ converter.cell_image_map = {"image-id": "media/image1.gif"}
+ try:
+ html = converter._get_cell_image('DISPIMG("image-id")')
+ finally:
+ converter.zf.close()
+
+ assert html == f"<eq>{expected}</eq>"
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_equation_docx),
+ (PptxModel(), build_equation_pptx),
+ (XlsxModel(), build_equation_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_ooxml_bad_native_recovers_from_wmf_preview_comment(
+ model: DocxModel | PptxModel | XlsxModel,
+ builder: Callable[..., bytes],
+) -> None:
+ """验证现代三格式 OLE Native 失败后升级有效 WMF preview。"""
+
+ _name, mtef, expected = v5_formula_corpus()[1]
+ pages = model.predict(
+ BytesIO(
+ builder(
+ [b"invalid native"],
+ prog_id="Equation.DSMT4",
+ preview_image=_wmf_formula(mtef),
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == [expected]
+ assert not _has_image(pages)
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_equation_docx),
+ (PptxModel(), build_equation_pptx),
+ (XlsxModel(), build_equation_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_ooxml_native_precedes_conflicting_wmf_preview_comment(
+ model: DocxModel | PptxModel | XlsxModel,
+ builder: Callable[..., bytes],
+) -> None:
+ """验证现代三格式有效 OLE Native 优先于图片 comment。"""
+
+ _native_name, native, expected = formula_corpus()[0]
+ _image_name, image_mtef, _image_expected = v5_formula_corpus()[1]
+ pages = model.predict(
+ BytesIO(
+ builder(
+ [native],
+ prog_id="Equation.DSMT4",
+ preview_image=_wmf_formula(image_mtef),
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == [expected]
+
+
+def test_docx_equationxml_and_ooxml_omml_precede_image_comment() -> None:
+ """验证 equationxml/OMML 继续高于同对象图片 comment。"""
+
+ _name, image_mtef, _expected = v5_formula_corpus()[0]
+ preview = _wmf_formula(image_mtef)
+ docx = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [build_word_2003_equation_xml("x")],
+ keep_mtef=True,
+ mtef_payloads=[b"invalid native"],
+ preview_image=preview,
+ )
+ )
+ )
+ pptx = PptxModel().predict(
+ BytesIO(
+ build_equation_pptx(
+ [b"invalid native"],
+ alternate_omml=True,
+ preview_image=preview,
+ )
+ )
+ )
+ xlsx = XlsxModel().predict(
+ BytesIO(
+ build_equation_xlsx(
+ [b"invalid native"],
+ anchor_mode="drawing",
+ alternate_omml=True,
+ preview_image=preview,
+ )
+ )
+ )
+
+ assert _equation_contents(docx) == ["x"]
+ assert _equation_contents(pptx) == ["z"]
+ assert _equation_contents(xlsx) == ["z"]
+
+
+def test_bad_image_comment_keeps_original_picture_or_placeholder() -> None:
+ """验证 baseline-only WMF 不升级公式并继续输出图片。"""
+
+ image = build_wmf([baseline_wmf_comment(0)], placeable=True)
+ cases = [
+ (DocxModel(), build_image_docx(image)),
+ (PptxModel(), build_image_pptx(image)),
+ ]
+
+ for model, file_bytes in cases:
+ pages = model.predict(BytesIO(file_bytes))
+ assert _equation_contents(pages) == []
+ assert _has_image(pages)
+
+
+def test_bad_image_comment_preview_exports_to_sidecar(tmp_path: Path) -> None:
+ """验证未升级的图片导出后 sidecar 完整且 JSON 不残留 base64。"""
+
+ middle, _model = doc_analyze(
+ build_image_docx(build_baseline_only_gif()),
+ file_suffix="docx",
+ )
+
+ result = middle.export(tmp_path / "image-mtef-fallback")
+
+ 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")
+
+
+ "file_suffix",
+ ["doc", "docx", "ppt", "pptx", "xls", "xlsx"],
+)
+def test_image_comment_mtef_runs_through_sync_async_analyze(
+ file_suffix: str,
+) -> None:
+ """验证图片 comment 公式贯穿六格式同步/异步严格 Analyze。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ wmf = _wmf_formula(mtef)
+ gif = build_gif_with_mtef(mtef)
+ builders = {
+ "doc": lambda: build_equation_doc(
+ [(1, b"invalid")],
+ preview_storage_ids={1},
+ preview_payloads={1: wmf},
+ ),
+ "docx": lambda: build_image_docx(gif),
+ "ppt": lambda: build_equation_ppt(
+ [b"invalid"],
+ preview_payload=wmf,
+ ),
+ "pptx": lambda: build_image_pptx(gif),
+ "xls": lambda: build_equation_xls(
+ [(1, b"invalid")],
+ preview_payload=wmf,
+ ),
+ "xlsx": lambda: build_image_xlsx(gif),
+ }
+ file_bytes = builders[file_suffix]()
+ 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 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_modern_converter_reuse_resets_image_comment_decoder() -> None:
+ """验证现代 converter 复用时图片公式缓存和资源预算不会串文档。"""
+
+ first = v5_formula_corpus()[0]
+ second = v5_formula_corpus()[1]
+ cases = [
+ (DocxConverter(), build_image_docx),
+ (PptxConverter(), build_image_pptx),
+ (XlsxConverter(), build_image_xlsx),
+ ]
+
+ for converter, builder in cases:
+ converter.convert(
+ BytesIO(builder(build_gif_with_mtef(first[1])))
+ )
+ assert _equation_contents(converter.pages) == [first[2]]
+ converter.convert(
+ BytesIO(builder(build_gif_with_mtef(second[1])))
+ )
+ assert _equation_contents(converter.pages) == [second[2]]
diff --git a/tests/unittest/test_flash_office_mtef_v5.py b/tests/unittest/test_flash_office_mtef_v5.py
new file mode 100644
index 00000000..754a43fb
--- /dev/null
+++ b/tests/unittest/test_flash_office_mtef_v5.py
@@ -0,0 +1,461 @@
+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 (
+ DocModel,
+ DocxModel,
+ PptModel,
+ PptxModel,
+ XlsModel,
+ XlsxModel,
+)
+from mineru.model.flash.docx.docx_converter import DocxConverter
+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 _docx_equationxml_test_utils import (
+ build_equationxml_docx,
+ build_word_2003_equation_xml,
+)
+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 build_equation_doc, formula_corpus
+from _mtef_v5_test_utils import v5_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]:
+ """按分页和 block 顺序收集独立公式内容。"""
+
+ return [
+ block["content"]
+ for page in pages
+ for block in page
+ if block.get("type") == BlockType.EQUATION
+ ]
+
+
+def _has_preview_image(pages: list[list[dict]]) -> bool:
+ """判断 model-list 是否至少保留一个图片回退。"""
+
+ return any(
+ block.get("type") == BlockType.IMAGE
+ for page in pages
+ for block in page
+ )
+
+
+def test_six_office_models_decode_the_full_mtef_v5_corpus() -> None:
+ """验证 DOC/DOCX/PPT/PPTX/XLS/XLSX 对完整 v5 语料输出一致。"""
+
+ corpus = v5_formula_corpus()
+ formulas = [mtef for _name, mtef, _expected in corpus]
+ expected = [latex for _name, _mtef, latex in corpus]
+ prog_id = "Equation.DSMT4"
+ cases = [
+ (
+ DocModel(),
+ build_equation_doc(
+ [(1000 + index, mtef) for index, mtef in enumerate(formulas)],
+ prog_id=prog_id,
+ ),
+ ),
+ (
+ DocxModel(),
+ build_equation_docx(formulas, prog_id=prog_id),
+ ),
+ (
+ PptModel(),
+ build_equation_ppt(formulas, preview=False, prog_id=prog_id),
+ ),
+ (
+ PptxModel(),
+ build_equation_pptx(formulas, prog_id=prog_id),
+ ),
+ (
+ XlsModel(),
+ build_equation_xls(
+ [(2000 + index, mtef) for index, mtef in enumerate(formulas)],
+ preview=False,
+ prog_id=prog_id,
+ ),
+ ),
+ (
+ XlsxModel(),
+ build_equation_xlsx(formulas, prog_id=prog_id),
+ ),
+ ]
+
+ for model, file_bytes in cases:
+ assert _equation_contents(model.predict(BytesIO(file_bytes))) == expected
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_equation_docx),
+ (PptxModel(), build_equation_pptx),
+ (XlsxModel(), build_equation_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_ooxml_prog_id_and_mtef_version_are_orthogonal(
+ model: DocxModel | PptxModel | XlsxModel,
+ builder: Callable[..., bytes],
+) -> None:
+ """验证 Equation.3 可承载 v5,DSMT4/Equation 也可承载 v3。"""
+
+ _v5_name, v5, v5_expected = v5_formula_corpus()[1]
+ _v3_name, v3, v3_expected = formula_corpus()[1]
+
+ assert _equation_contents(
+ model.predict(BytesIO(builder([v5], prog_id="Equation.3")))
+ ) == [v5_expected]
+ assert _equation_contents(
+ model.predict(BytesIO(builder([v3], prog_id="Equation.DSMT4")))
+ ) == [v3_expected]
+ assert _equation_contents(
+ model.predict(BytesIO(builder([v5], prog_id="Equation")))
+ ) == [v5_expected]
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_equation_docx),
+ (PptxModel(), build_equation_pptx),
+ (XlsxModel(), build_equation_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_non_equation_ooxml_prog_id_is_not_probed(
+ model: DocxModel | PptxModel | XlsxModel,
+ builder: Callable[..., bytes],
+) -> None:
+ """验证非公式或空后缀 ProgID 不探测有效 v5 OLE 内容。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ for prog_id in ("Package", "Equation."):
+ pages = model.predict(BytesIO(builder([mtef], prog_id=prog_id)))
+ assert _equation_contents(pages) == []
+
+
+ ("model", "builder"),
+ [
+ (DocxModel(), build_equation_docx),
+ (PptxModel(), build_equation_pptx),
+ (XlsxModel(), build_equation_xlsx),
+ ],
+ ids=["docx", "pptx", "xlsx"],
+)
+def test_mtef_v5_icon_mode_keeps_icon_preview(
+ model: DocxModel | PptxModel | XlsxModel,
+ builder: Callable[..., bytes],
+) -> None:
+ """验证图标模式不展开有效 v5,只保留原图标预览。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ pages = model.predict(
+ BytesIO(
+ builder(
+ [mtef],
+ prog_id="Equation.DSMT4",
+ show_as_icon=True,
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == []
+ assert _has_preview_image(pages)
+
+
+def test_xlsx_linked_mtef_v5_object_never_loads_external_target() -> None:
+ """验证 XLSX 外链 MathType 对象只保留包内预览,不访问目标。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ pages = XlsxModel().predict(
+ BytesIO(
+ build_equation_xlsx(
+ [mtef],
+ prog_id="Equation.DSMT4",
+ linked=True,
+ )
+ )
+ )
+
+ assert _equation_contents(pages) == []
+ assert _has_preview_image(pages)
+
+
+ ("model", "file_bytes"),
+ [
+ (
+ DocModel(),
+ build_equation_doc(
+ [(1, bytes([4, 1, 0, 3, 5, 0]))],
+ preview_storage_ids={1},
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ (
+ DocxModel(),
+ build_equation_docx(
+ [bytes([4, 1, 0, 3, 5, 0])],
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ (
+ PptModel(),
+ build_equation_ppt(
+ [bytes([4, 1, 0, 3, 5, 0])],
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ (
+ PptxModel(),
+ build_equation_pptx(
+ [bytes([4, 1, 0, 3, 5, 0])],
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ (
+ XlsModel(),
+ build_equation_xls(
+ [(1, bytes([4, 1, 0, 3, 5, 0]))],
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ (
+ XlsxModel(),
+ build_equation_xlsx(
+ [bytes([4, 1, 0, 3, 5, 0])],
+ prog_id="Equation.DSMT4",
+ ),
+ ),
+ ],
+ ids=["doc", "docx", "ppt", "pptx", "xls", "xlsx"],
+)
+def test_mtef_v4_keeps_preview_in_all_six_formats(
+ model: DocModel | DocxModel | PptModel | PptxModel | XlsModel | XlsxModel,
+ file_bytes: bytes,
+) -> None:
+ """验证六格式遇到 v4 均不猜测解析并保留缓存预览。"""
+
+ pages = model.predict(BytesIO(file_bytes))
+
+ assert _equation_contents(pages) == []
+ assert _has_preview_image(pages)
+
+
+ "file_suffix",
+ ["doc", "docx", "ppt", "pptx", "xls", "xlsx"],
+)
+def test_mtef_v5_runs_through_sync_async_analyze(
+ file_suffix: str,
+) -> None:
+ """验证 v5 贯穿六格式同步/异步严格 Analyze 契约。"""
+
+ _name, mtef, expected = v5_formula_corpus()[3]
+ prog_id = "Equation.DSMT4"
+ builders: dict[str, Callable[[], bytes]] = {
+ "doc": lambda: build_equation_doc([(10, mtef)], prog_id=prog_id),
+ "docx": lambda: build_equation_docx([mtef], prog_id=prog_id),
+ "ppt": lambda: build_equation_ppt([mtef], preview=False, prog_id=prog_id),
+ "pptx": lambda: build_equation_pptx([mtef], prog_id=prog_id),
+ "xls": lambda: build_equation_xls([(10, mtef)], preview=False, prog_id=prog_id),
+ "xlsx": lambda: build_equation_xlsx([mtef], prog_id=prog_id),
+ }
+ file_bytes = builders[file_suffix]()
+ 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_mtef_v5_enters_docx_xls_xlsx_table_cells() -> None:
+ """验证三种文档/表格格式的 v5 公式进入 cell HTML 且不重复输出。"""
+
+ _name, mtef, expected = v5_formula_corpus()[0]
+ docx = DocxModel().predict(
+ BytesIO(
+ build_equation_docx(
+ [mtef],
+ table=True,
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+ xls = XlsModel().predict(
+ BytesIO(
+ build_equation_xls(
+ [(10, mtef)],
+ cell_records=label_cell(0, 0, "value"),
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+ xlsx = XlsxModel().predict(
+ BytesIO(
+ build_equation_xlsx(
+ [mtef],
+ cell_value="value",
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+
+ for pages in (docx, xls, xlsx):
+ assert _equation_contents(pages) == []
+ assert pages[0][0]["type"] == BlockType.TABLE
+ assert f"<eq>{expected}</eq>" in pages[0][0]["content"]
+
+
+def test_docx_equationxml_and_ooxml_omml_precede_mtef_v5() -> None:
+ """验证 DOCX equationxml 以及 PPTX/XLSX OMML 都优先于有效 v5。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ docx = DocxModel().predict(
+ BytesIO(
+ build_equationxml_docx(
+ [build_word_2003_equation_xml("x")],
+ keep_mtef=True,
+ mtef_payloads=[mtef],
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+ pptx = PptxModel().predict(
+ BytesIO(
+ build_equation_pptx(
+ [mtef],
+ alternate_omml=True,
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+ xlsx = XlsxModel().predict(
+ BytesIO(
+ build_equation_xlsx(
+ [mtef],
+ anchor_mode="drawing",
+ alternate_omml=True,
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+
+ assert _equation_contents(docx) == ["x"]
+ assert _equation_contents(pptx) == ["z"]
+ assert _equation_contents(xlsx) == ["z"]
+
+
+def test_docx_header_footer_and_pptx_notes_accept_mtef_v5() -> None:
+ """验证 v5 在 DOCX 页眉页脚和 PPTX notes 中保持归属。"""
+
+ corpus = v5_formula_corpus()
+ first = corpus[0]
+ second = corpus[1]
+ docx = DocxModel().predict(
+ BytesIO(
+ build_equation_docx(
+ [first[1], second[1]],
+ header_footer=True,
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+ pptx = PptxModel().predict(
+ BytesIO(
+ build_equation_pptx(
+ [first[1]],
+ notes=True,
+ prog_id="Equation.DSMT4",
+ )
+ )
+ )
+
+ assert docx == [
+ [
+ {"type": BlockType.HEADER, "content": f"<eq>{first[2]}</eq>"},
+ {"type": BlockType.FOOTER, "content": f"<eq>{second[2]}</eq>"},
+ ]
+ ]
+ assert pptx == [
+ [
+ {
+ "type": BlockType.PAGE_FOOTNOTE,
+ "content": f"<eq>{first[2]}</eq>",
+ }
+ ]
+ ]
+
+
+def test_mtef_v5_model_streams_remain_open_in_all_six_formats() -> None:
+ """验证六种 Model 的 v5 路径均不关闭调用方输入流。"""
+
+ _name, mtef, _expected = v5_formula_corpus()[0]
+ prog_id = "Equation.DSMT4"
+ cases = [
+ (DocModel(), build_equation_doc([(1, mtef)], prog_id=prog_id)),
+ (DocxModel(), build_equation_docx([mtef], prog_id=prog_id)),
+ (PptModel(), build_equation_ppt([mtef], prog_id=prog_id)),
+ (PptxModel(), build_equation_pptx([mtef], prog_id=prog_id)),
+ (XlsModel(), build_equation_xls([(1, mtef)], prog_id=prog_id)),
+ (XlsxModel(), build_equation_xlsx([mtef], prog_id=prog_id)),
+ ]
+
+ for model, file_bytes in cases:
+ stream = BytesIO(file_bytes)
+ model.predict(stream)
+ assert not stream.closed
+
+
+def test_modern_office_converter_reuse_resets_v5_state() -> None:
+ """验证现代 Office converter 复用时 v5 缓存和分页状态不会串文档。"""
+
+ first = v5_formula_corpus()[0]
+ second = v5_formula_corpus()[1]
+ prog_id = "Equation.DSMT4"
+ cases = [
+ (DocxConverter(), build_equation_docx),
+ (PptxConverter(), build_equation_pptx),
+ (XlsxConverter(), build_equation_xlsx),
+ ]
+
+ for converter, builder in cases:
+ converter.convert(
+ BytesIO(builder([first[1]], prog_id=prog_id))
+ )
+ assert _equation_contents(converter.pages) == [first[2]]
+ converter.convert(
+ BytesIO(builder([second[1]], prog_id=prog_id))
+ )
+ assert _equation_contents(converter.pages) == [second[2]]
diff --git a/tests/unittest/test_flash_ooxml_mtef.py b/tests/unittest/test_flash_ooxml_mtef.py
index 4d7144c5..3f9b80a5 100644
--- a/tests/unittest/test_flash_ooxml_mtef.py
+++ b/tests/unittest/test_flash_ooxml_mtef.py
@@ -13,7 +13,10 @@ 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.office.ooxml_equation import (
+ OoxmlEquationDecoder,
+ is_mathtype_equation_prog_id,
+)
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
@@ -38,7 +41,7 @@ def _equation_contents(pages: list[list[dict]]) -> list[str]:
def test_ooxml_equation_decoder_enforces_scope_icon_and_total_budget() -> None:
- """验证共享入口只接受 Equation.3、非图标及预算内的 CFB。"""
+ """验证共享入口只接受公式 ProgID、非图标及预算内的 CFB。"""
_name, mtef, expected = formula_corpus()[0]
blob = build_equation_object(mtef)
@@ -46,7 +49,10 @@ def test_ooxml_equation_decoder_enforces_scope_icon_and_total_budget() -> None:
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.DSMT4") == expected
+ assert decoder.decode(blob, prog_id="Equation") == expected
+ assert decoder.decode(blob, prog_id="Equation.") is None
+ assert decoder.decode(blob, prog_id="Package") 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
@@ -55,6 +61,28 @@ def test_ooxml_equation_decoder_enforces_scope_icon_and_total_budget() -> None:
exhausted.decode(blob, prog_id="Equation.3")
+ ("prog_id", "expected"),
+ [
+ ("Equation", True),
+ ("equation.3", True),
+ ("EQUATION.DSMT4", True),
+ (" Equation.Custom ", True),
+ ("Equation.", False),
+ ("EquationXML", False),
+ ("Package", False),
+ (None, False),
+ ],
+)
+def test_mathtype_equation_prog_id_matching(
+ prog_id: object | None,
+ expected: bool,
+) -> None:
+ """验证 OLE1 Equation 和 OLE2 Equation.* 的大小写无关匹配。"""
+
+ assert is_mathtype_equation_prog_id(prog_id) is expected
+
+
def test_docx_pptx_xlsx_decode_the_full_mtef_corpus_exactly() -> None:
"""验证三种 OOXML Model 对11类MTEF公式给出完全一致的LaTeX。"""