Skip to content

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

feat: add PPTX package normalization to handle common compatibility issues

myhlolic839c8f51290
diff --git a/mineru/model/pptx/package_normalizer.py b/mineru/model/pptx/package_normalizer.py
new file mode 100644
index 00000000..ffc0b6e5
--- /dev/null
+++ b/mineru/model/pptx/package_normalizer.py
@@ -0,0 +1,242 @@
+# Copyright (c) Opendatalab. All rights reserved.
+import re
+from io import BytesIO
+from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile, ZipInfo
+
+from loguru import logger
+from lxml import etree
+
+LEGACY_PPT_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
+
+WORDPROCESSINGML_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+MARKUP_COMPATIBILITY_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+PRESENTATIONML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
+
+CONTENT_PART_TAG = f"{{{PRESENTATIONML_NS}}}contentPart"
+PPTX_SHAPE_TAGS = {
+ f"{{{PRESENTATIONML_NS}}}sp",
+ f"{{{PRESENTATIONML_NS}}}grpSp",
+ f"{{{PRESENTATIONML_NS}}}graphicFrame",
+ f"{{{PRESENTATIONML_NS}}}cxnSp",
+ f"{{{PRESENTATIONML_NS}}}pic",
+}
+
+ROOT_TAG_PATTERN = re.compile(
+ br"<(?![?!])(?:[A-Za-z_][\w.-]*:)?[A-Za-z_][\w.-]*(?=\s|/?>)"
+)
+
+STRICT_OOXML_REPLACEMENTS = (
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/relationships/metadata/thumbnail",
+ b"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/relationships/customProperties",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/relationships/extendedProperties",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/relationships",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/relationships",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/drawingml/main",
+ b"http://schemas.openxmlformats.org/drawingml/2006/main",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/drawingml/chart",
+ b"http://schemas.openxmlformats.org/drawingml/2006/chart",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/presentationml/main",
+ b"http://schemas.openxmlformats.org/presentationml/2006/main",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/math",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/math",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/customProperties",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/extendedProperties",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/docPropsVTypes",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes",
+ ),
+ (
+ b"http://purl.oclc.org/ooxml/officeDocument/oleObject",
+ b"http://schemas.openxmlformats.org/officeDocument/2006/oleObject",
+ ),
+)
+
+KNOWN_NAMESPACE_DECLARATIONS = {
+ b"w": f'xmlns:w="{WORDPROCESSINGML_NS}"'.encode("utf-8"),
+}
+
+
+def normalize_pptx_package(file_bytes: bytes) -> bytes:
+ """在进入 python-pptx 前修复常见包级兼容问题,避免修复逻辑散落到形状解析阶段。"""
+ if file_bytes.startswith(LEGACY_PPT_MAGIC):
+ raise ValueError(
+ "Legacy binary PPT files are not supported; convert the file to PPTX before parsing."
+ )
+
+ try:
+ with ZipFile(BytesIO(file_bytes)) as source:
+ rewritten_members: list[tuple[ZipInfo, bytes]] = []
+ changed = False
+
+ for info in source.infolist():
+ member_data = _read_member_best_effort(source, info)
+ if member_data is None:
+ changed = True
+ continue
+
+ normalized_data = _normalize_member_xml(info.filename, member_data)
+ if normalized_data != member_data:
+ changed = True
+ rewritten_members.append((info, normalized_data))
+ except BadZipFile as exc:
+ raise ValueError("Invalid PPTX package: file is not a ZIP archive.") from exc
+
+ if not changed:
+ return file_bytes
+
+ return _write_package(rewritten_members)
+
+
+def _read_member_best_effort(source: ZipFile, info: ZipInfo) -> bytes | None:
+ """读取 ZIP 成员;损坏的媒体资源可跳过,关键 XML/关系文件仍保持失败。"""
+ try:
+ return source.read(info.filename)
+ except BadZipFile as exc:
+ if _is_skippable_corrupt_member(info.filename):
+ logger.warning(
+ f"Skipping corrupt non-critical PPTX media member {info.filename}: {exc}"
+ )
+ return None
+ raise
+
+
+def _is_skippable_corrupt_member(filename: str) -> bool:
+ """判断损坏成员是否属于可降级丢弃的媒体资源。"""
+ return filename.startswith("ppt/media/")
+
+
+def _normalize_member_xml(filename: str, member_data: bytes) -> bytes:
+ """仅对 XML/关系成员做文本级和结构级规范化,二进制资源保持原样。"""
+ if not (filename.endswith(".xml") or filename.endswith(".rels")):
+ return member_data
+
+ normalized = _translate_strict_ooxml_uris(member_data)
+ if filename.endswith(".xml"):
+ normalized = _add_missing_known_namespaces(normalized)
+ normalized = _replace_content_part_alternate_content_with_fallback(normalized)
+ return normalized
+
+
+def _translate_strict_ooxml_uris(xml_bytes: bytes) -> bytes:
+ """把 Strict OOXML URI 转为 python-pptx 能识别的 Transitional URI。"""
+ normalized = xml_bytes
+ for strict_uri, transitional_uri in STRICT_OOXML_REPLACEMENTS:
+ normalized = normalized.replace(strict_uri, transitional_uri)
+ return normalized
+
+
+def _add_missing_known_namespaces(xml_bytes: bytes) -> bytes:
+ """为实际使用但未声明的已知前缀补齐命名空间,修复轻微损坏的 XML。"""
+ declarations = []
+ for prefix, declaration in KNOWN_NAMESPACE_DECLARATIONS.items():
+ if prefix + b":" in xml_bytes and b"xmlns:" + prefix + b"=" not in xml_bytes:
+ declarations.append(declaration)
+
+ if not declarations:
+ return xml_bytes
+
+ root_match = ROOT_TAG_PATTERN.search(xml_bytes)
+ if root_match is None:
+ return xml_bytes
+
+ close_index = xml_bytes.find(b">", root_match.end())
+ if close_index < 0:
+ return xml_bytes
+
+ insert_at = close_index
+ if insert_at > 0 and xml_bytes[insert_at - 1 : insert_at] == b"/":
+ insert_at -= 1
+
+ namespace_attrs = b" " + b" ".join(declarations)
+ return xml_bytes[:insert_at] + namespace_attrs + xml_bytes[insert_at:]
+
+
+def _replace_content_part_alternate_content_with_fallback(xml_bytes: bytes) -> bytes:
+ """将 python-pptx 不支持的 p:contentPart 优先分支替换为可解析的 fallback 图形。"""
+ if b"AlternateContent" not in xml_bytes or b"contentPart" not in xml_bytes:
+ return xml_bytes
+
+ try:
+ parser = etree.XMLParser(resolve_entities=False, remove_blank_text=False)
+ root = etree.fromstring(xml_bytes, parser)
+ except etree.XMLSyntaxError:
+ return xml_bytes
+
+ replaced_count = 0
+ alternate_content_nodes = root.findall(
+ f".//{{{MARKUP_COMPATIBILITY_NS}}}AlternateContent"
+ )
+ for alternate_content in alternate_content_nodes:
+ if _replace_single_alternate_content(alternate_content):
+ replaced_count += 1
+
+ if replaced_count == 0:
+ return xml_bytes
+
+ return etree.tostring(
+ root,
+ xml_declaration=xml_bytes.lstrip().startswith(b"<?xml"),
+ encoding="UTF-8",
+ standalone=True,
+ )
+
+
+def _replace_single_alternate_content(alternate_content: etree._Element) -> bool:
+ """替换单个 AlternateContent 节点,优先保留 fallback 中的可见图形。"""
+ choice = alternate_content.find(f"{{{MARKUP_COMPATIBILITY_NS}}}Choice")
+ fallback = alternate_content.find(f"{{{MARKUP_COMPATIBILITY_NS}}}Fallback")
+ if choice is None or fallback is None:
+ return False
+
+ if not any(child.tag == CONTENT_PART_TAG for child in choice):
+ return False
+
+ fallback_shapes = [child for child in list(fallback) if child.tag in PPTX_SHAPE_TAGS]
+ if not fallback_shapes:
+ return False
+
+ parent = alternate_content.getparent()
+ if parent is None:
+ return False
+
+ insert_index = parent.index(alternate_content)
+ parent.remove(alternate_content)
+ for fallback_shape in fallback_shapes:
+ fallback.remove(fallback_shape)
+ parent.insert(insert_index, fallback_shape)
+ insert_index += 1
+ return True
+
+
+def _write_package(members: list[tuple[ZipInfo, bytes]]) -> bytes:
+ """把规范化后的成员重新写成 PPTX ZIP 包,并重新计算 CRC。"""
+ output = BytesIO()
+ with ZipFile(output, "w", ZIP_DEFLATED) as target:
+ for info, member_data in members:
+ target.writestr(info, member_data)
+ return output.getvalue()
diff --git a/mineru/model/pptx/pptx_converter.py b/mineru/model/pptx/pptx_converter.py
index cf348849..ab2da947 100644
--- a/mineru/model/pptx/pptx_converter.py
+++ b/mineru/model/pptx/pptx_converter.py
@@ -10,7 +10,7 @@ from pptx import Presentation, presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER
from pptx.oxml.text import CT_TextLineBreak
from loguru import logger
-from PIL import Image, UnidentifiedImageError
+from PIL import Image, ImageFile, UnidentifiedImageError
from mineru.utils.enum_class import BlockType
from mineru.backend.utils.office_image import (
@@ -19,6 +19,7 @@ from mineru.backend.utils.office_image import (
)
from mineru.model.docx.tools.math.omml import oMath2Latex
from mineru.backend.utils.office_chart import extract_chart_html_from_ooxml
+from mineru.model.pptx.package_normalizer import normalize_pptx_package
from mineru.model.pptx.xycut_pp_sorter import sort_entries
from mineru.utils.pdf_reader import image_to_b64str
@@ -102,11 +103,29 @@ class PptxConverter:
self,
file_stream: BinaryIO,
):
+ file_bytes = file_stream.read()
+ try:
+ self._convert_package_bytes(file_bytes)
+ except Exception as exc:
+ normalized_bytes = normalize_pptx_package(file_bytes)
+ if normalized_bytes == file_bytes:
+ raise
+ logger.warning(f"Retrying PPTX parsing after package normalization: {exc}")
+ self._convert_package_bytes(normalized_bytes)
+
+ def _reset_state(self) -> None:
+ """重置解析状态,确保失败重试时不会残留上一次半解析结果。"""
self.pages = []
self.cur_page = []
self.list_block_stack = []
self._shape_type_cache = {}
- self.file_stream = file_stream
+ self.file_stream = None
+ self.pptx_obj = None
+
+ def _convert_package_bytes(self, file_bytes: bytes) -> None:
+ """用独立字节流解析 PPTX 包,便于原始包失败后用规范化包重试。"""
+ self._reset_state()
+ self.file_stream = BytesIO(file_bytes)
self.pptx_obj = Presentation(self.file_stream)
self.pages.append(self.cur_page)
if self.pptx_obj:
@@ -683,25 +702,51 @@ class PptxConverter:
self.cur_page.append(image_block)
return
- # 使用PIL打开图像
+ img_base64 = self._serialize_picture_image_best_effort(image_bytes)
+ if img_base64 is None:
+ return
+
+ image_block = {
+ "type": BlockType.IMAGE,
+ "content": img_base64,
+ }
+ self.cur_page.append(image_block)
+ return
+
+ @classmethod
+ def _serialize_picture_image_best_effort(cls, image_bytes: bytes) -> Optional[str]:
+ """尽量序列化图片;损坏图片失败时降级跳过,避免中断整份 PPTX。"""
try:
- pil_image = Image.open(BytesIO(image_bytes))
+ return cls._serialize_picture_image(image_bytes)
+ except (UnidentifiedImageError, OSError, SyntaxError) as exc:
+ logger.warning(
+ f"Warning: image cannot be loaded by Pillow, retrying with truncated-image mode: {exc}"
+ )
- if is_vector_image(pil_image):
- img_base64 = serialize_vector_image_with_placeholder(pil_image)
- else:
- if pil_image.mode != "RGB":
- pil_image = pil_image.convert("RGB")
- img_base64 = image_to_b64str(pil_image)
- image_block = {
- "type": BlockType.IMAGE,
- "content": img_base64,
- }
- self.cur_page.append(image_block)
+ previous_truncated_setting = ImageFile.LOAD_TRUNCATED_IMAGES
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
+ try:
+ return cls._serialize_picture_image(image_bytes)
+ except (UnidentifiedImageError, OSError, SyntaxError) as exc:
+ logger.warning(f"Warning: image cannot be loaded by Pillow: {exc}")
+ return None
+ finally:
+ ImageFile.LOAD_TRUNCATED_IMAGES = previous_truncated_setting
- except (UnidentifiedImageError, OSError) as e:
- logger.warning(f"Warning: image cannot be loaded by Pillow: {e}")
- return
+ @staticmethod
+ def _serialize_picture_image(image_bytes: bytes) -> str:
+ """将单张 Pillow 支持的图片转为 Markdown 可用的 base64 字符串。"""
+ pil_image = Image.open(BytesIO(image_bytes))
+
+ if is_vector_image(pil_image):
+ return serialize_vector_image_with_placeholder(pil_image)
+
+ if pil_image.mode != "RGB":
+ pil_image = pil_image.convert("RGB")
+ else:
+ pil_image.load()
+
+ return image_to_b64str(pil_image)
@staticmethod
def _bytes_to_data_uri(image_bytes: bytes, content_type: str) -> str: