Python tool for converting files and office documents to Markdown.
fix: handle PPTX SVG images without a rasterized fallback (#2233)
Guoyu Wang2e42a01c4046
diff --git a/packages/markitdown/src/markitdown/converters/_pptx_converter.py b/packages/markitdown/src/markitdown/converters/_pptx_converter.pyindex 52f7553e..21a12dc8 100644--- a/packages/markitdown/src/markitdown/converters/_pptx_converter.py+++ b/packages/markitdown/src/markitdown/converters/_pptx_converter.py@@ -98,22 +98,33 @@ class PptxConverter(DocumentConverter):llm_description = ""alt_text = ""+ # Resolve the image blob, handling SVG images that lack a+ # rasterized fallback (shape.image raises in that case).+ (+ image_blob,+ image_content_type,+ image_filename,+ ) = self._get_image_info(shape)+# Potentially generate a description using an LLMllm_client = kwargs.get("llm_client")llm_model = kwargs.get("llm_model")- if llm_client is not None and llm_model is not None:+ if (+ llm_client is not None+ and llm_model is not None+ and image_blob is not None+ ):# Prepare a file_stream and stream_info for the image data- image_filename = shape.image.filenameimage_extension = Noneif image_filename:image_extension = os.path.splitext(image_filename)[1]image_stream_info = StreamInfo(- mimetype=shape.image.content_type,+ mimetype=image_content_type,extension=image_extension,filename=image_filename,)- image_stream = io.BytesIO(shape.image.blob)+ image_stream = io.BytesIO(image_blob)# Caption the imagetry:@@ -141,10 +152,9 @@ class PptxConverter(DocumentConverter):alt_text = re.sub(r"\s+", " ", alt_text).strip()# If keep_data_uris is True, use base64 encoding for images- if kwargs.get("keep_data_uris", False):- blob = shape.image.blob- content_type = shape.image.content_type or "image/png"- b64_string = base64.b64encode(blob).decode("utf-8")+ if kwargs.get("keep_data_uris", False) and image_blob is not None:+ content_type = image_content_type or "image/png"+ b64_string = base64.b64encode(image_blob).decode("utf-8")md_content += f"\n\n"else:# A placeholder name@@ -199,12 +209,69 @@ class PptxConverter(DocumentConverter):return DocumentConverterResult(markdown=md_content.strip())+ def _find_svg_blip_part(self, shape):+ """Return the image part referenced by an ``<asvg:svgBlip>``, if any.++ PowerPoint stores SVG pictures as a blip whose main ``r:embed`` points+ to a rasterized PNG fallback, plus an ``<asvg:svgBlip>`` extension+ pointing to the SVG. When there is no raster fallback the ``<a:blip>``+ has no ``r:embed`` at all, so python-pptx's ``shape.image`` fails. This+ resolves the SVG part directly from the ``svgBlip`` extension.+ """+ try:+ nsmap = {+ "asvg": "http://schemas.microsoft.com/office/drawing/2016/SVG/main",+ }+ r_embed = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"+ for svg_blip in shape._element.findall(".//asvg:svgBlip", nsmap):+ embed_rid = svg_blip.get(r_embed)+ if not embed_rid:+ continue+ return shape.part.related_part(embed_rid)+ except Exception:+ pass+ return None++ def _get_image_info(self, shape):+ """Return (blob, content_type, filename) for a picture shape.++ Handles SVG images that lack a rasterized fallback. In that case+ ``shape.image`` raises ``ValueError("no embedded image")`` because the+ ``<a:blip>`` has no ``r:embed`` attribute (only an ``<asvg:svgBlip>``+ extension). We fall back to resolving the SVG blip directly.+ """+ try:+ image = shape.image+ return image.blob, image.content_type, image.filename+ except Exception:+ pass++ # Fall back to an embedded SVG blip (image without a raster fallback)+ part = self._find_svg_blip_part(shape)+ if part is not None:+ try:+ filename = os.path.basename(getattr(part, "partname", "") or "") or None+ return part.blob, "image/svg+xml", filename+ except Exception:+ pass++ return None, None, None+def _is_picture(self, shape):if shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.PICTURE:return Trueif shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.PLACEHOLDER:- if hasattr(shape, "image"):- return True+ # ``shape.image`` can raise (e.g. ValueError "no embedded image")+ # for SVG placeholders without a raster fallback, so guard against+ # any exception rather than relying on hasattr (which only swallows+ # AttributeError).+ try:+ if shape.image is not None:+ return True+ except Exception:+ # Still a picture if it carries an embedded SVG blip.+ if self._find_svg_blip_part(shape) is not None:+ return Truereturn Falsedef _is_table(self, shape):diff --git a/packages/markitdown/tests/test_files/test_svg_no_fallback.pptx b/packages/markitdown/tests/test_files/test_svg_no_fallback.pptxnew file mode 100644index 00000000..01bdb7b7Binary files /dev/null and b/packages/markitdown/tests/test_files/test_svg_no_fallback.pptx differdiff --git a/packages/markitdown/tests/test_pptx_svg.py b/packages/markitdown/tests/test_pptx_svg.pynew file mode 100644index 00000000..8bb0d163--- /dev/null+++ b/packages/markitdown/tests/test_pptx_svg.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3 -m pytest+"""Tests for PPTX SVG images that lack a rasterized fallback.++PowerPoint stores an SVG picture as an ``<a:blip>`` whose ``r:embed`` points to+a rasterized PNG fallback, plus an ``<asvg:svgBlip>`` extension that points to+the SVG. When a picture has no raster fallback the ``<a:blip>`` has no+``r:embed`` at all, so python-pptx's ``shape.image`` raises+``ValueError("no embedded image")``. The converter must handle this gracefully+(resolving the SVG blip directly) instead of failing the whole conversion.+"""+import os++from lxml import etree+from pptx import Presentation+from pptx.enum.shapes import MSO_SHAPE_TYPE++from markitdown import MarkItDown+from markitdown.converters._pptx_converter import PptxConverter++TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "test_files")++# A tiny synthetic PPTX whose only picture is an SVG without a rasterized+# fallback: the <a:blip> has no r:embed, only an <asvg:svgBlip> extension+# pointing to an embedded SVG. Its alt text is "Red square SVG".+SVG_NO_FALLBACK_PPTX = os.path.join(TEST_FILES_DIR, "test_svg_no_fallback.pptx")++_SVG_NS = "http://schemas.microsoft.com/office/drawing/2016/SVG/main"+++def _first_picture_shape(pptx_path):+ presentation = Presentation(pptx_path)+ converter = PptxConverter()+ for slide in presentation.slides:+ for shape in slide.shapes:+ if converter._is_picture(shape):+ return converter, shape+ raise AssertionError(f"No picture shape found in {pptx_path}")+++def test_pptx_svg_without_raster_fallback() -> None:+ md = MarkItDown()++ # Default conversion should not raise and should emit the image alt text.+ result = md.convert(SVG_NO_FALLBACK_PPTX)+ assert "Red square SVG" in result.markdown++ # keep_data_uris used to crash with ValueError("no embedded image"). It+ # should now embed the SVG as a data URI.+ result = md.convert(SVG_NO_FALLBACK_PPTX, keep_data_uris=True)+ assert "data:image/svg+xml;base64," in result.markdown+++def test_get_image_info_resolves_svg_blip_without_fallback() -> None:+ # Unit-level check: _get_image_info must resolve the raw SVG blob directly+ # from the <asvg:svgBlip> extension when shape.image raises because there is+ # no rasterized fallback (no r:embed on the <a:blip>).+ converter, shape = _first_picture_shape(SVG_NO_FALLBACK_PPTX)++ blob, content_type, _filename = converter._get_image_info(shape)++ assert blob is not None and len(blob) > 0+ assert content_type == "image/svg+xml"+ assert b"<svg" in blob[:512].lower()+++class _FakePart:+ """Minimal part whose related_part always resolves to a truthy object."""++ def related_part(self, rid):+ return object()+++class _FakeSvgPlaceholderShape:+ """A placeholder shape whose ``image`` raises like an SVG-only placeholder.++ ``_is_picture`` used to rely on ``hasattr(shape, "image")`` which only+ swallows ``AttributeError`` and let this ``ValueError`` propagate, failing+ even the default conversion.+ """++ shape_type = MSO_SHAPE_TYPE.PLACEHOLDER++ def __init__(self):+ xml = (+ '<p:pic xmlns:p="http://schemas.openxmlformats.org/'+ 'presentationml/2006/main" xmlns:a="http://schemas.'+ 'openxmlformats.org/drawingml/2006/main" xmlns:r="http://'+ 'schemas.openxmlformats.org/officeDocument/2006/relationships" '+ 'xmlns:asvg="%s"><a:blip><a:extLst><a:ext uri="{96DAC541-7B7A-'+ '43D3-8B79-37D633B846F1}"><asvg:svgBlip r:embed="rId9"/></a:ext>'+ "</a:extLst></a:blip></p:pic>" % _SVG_NS+ )+ self._element = etree.fromstring(xml)+ self.part = _FakePart()++ @property+ def image(self):+ raise ValueError("no embedded image")+++def test_is_picture_true_for_svg_placeholder() -> None:+ # _is_picture must not let shape.image's ValueError propagate for SVG+ # placeholders lacking a raster fallback; it should still report a picture+ # because an embedded SVG blip is present.+ converter = PptxConverter()+ assert converter._is_picture(_FakeSvgPlaceholderShape()) is True+++if __name__ == "__main__":+ test_pptx_svg_without_raster_fallback()+ test_get_image_info_resolves_svg_blip_without_fallback()+ test_is_picture_true_for_svg_placeholder()+ print("All tests passed!")