Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(image): prevent png/jpeg mime mismatches in generation pipeline

hugohe33701cbd93d67
diff --git a/skills/ppt-master/scripts/image_backends/backend_common.py b/skills/ppt-master/scripts/image_backends/backend_common.py
index f3ba4f2a..5148f198 100644
--- a/skills/ppt-master/scripts/image_backends/backend_common.py
+++ b/skills/ppt-master/scripts/image_backends/backend_common.py
@@ -3,6 +3,7 @@
Shared helpers for image generation backends.
"""
+import io
import os
import time
@@ -37,6 +38,103 @@ def resolve_output_path(prompt: str, output_dir: str = None,
return full_name
+CONTENT_TYPE_TO_EXT = {
+ "image/png": ".png",
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ "image/webp": ".webp",
+ "image/gif": ".gif",
+ "image/bmp": ".bmp",
+ "image/tiff": ".tiff",
+}
+
+EXT_TO_PIL_FORMAT = {
+ ".png": "PNG",
+ ".jpg": "JPEG",
+ ".jpeg": "JPEG",
+ ".webp": "WEBP",
+ ".gif": "GIF",
+ ".bmp": "BMP",
+ ".tiff": "TIFF",
+ ".tif": "TIFF",
+}
+
+
+def detect_image_extension(image_bytes: bytes, content_type: str = None) -> str | None:
+ """Best-effort detection of the real image format."""
+ if content_type:
+ clean_type = content_type.split(";", 1)[0].strip().lower()
+ if clean_type in CONTENT_TYPE_TO_EXT:
+ return CONTENT_TYPE_TO_EXT[clean_type]
+
+ if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
+ return ".png"
+ if image_bytes.startswith(b"\xff\xd8\xff"):
+ return ".jpg"
+ if image_bytes.startswith(b"GIF87a") or image_bytes.startswith(b"GIF89a"):
+ return ".gif"
+ if image_bytes.startswith(b"RIFF") and image_bytes[8:12] == b"WEBP":
+ return ".webp"
+ if image_bytes.startswith(b"BM"):
+ return ".bmp"
+ if image_bytes.startswith((b"II*\x00", b"MM\x00*")):
+ return ".tiff"
+ return None
+
+
+def _normalize_extension(ext: str) -> str:
+ ext = ext.lower()
+ if ext == ".jpeg":
+ return ".jpg"
+ if ext == ".tif":
+ return ".tiff"
+ return ext
+
+
+def save_image_bytes(image_bytes: bytes, path: str, content_type: str = None) -> str:
+ """
+ Save image bytes to disk while keeping the file extension and the real bytes aligned.
+
+ If the target extension differs from the actual bytes, transcode through Pillow when
+ available. Otherwise fail loudly instead of writing a misleading file.
+ """
+ target_ext = _normalize_extension(os.path.splitext(path)[1])
+ actual_ext = _normalize_extension(detect_image_extension(image_bytes, content_type) or "")
+
+ if not target_ext:
+ raise ValueError(f"Output path must include an image extension: {path}")
+
+ if actual_ext and target_ext == actual_ext:
+ with open(path, "wb") as f:
+ f.write(image_bytes)
+ print(f" File saved to: {path}")
+ report_resolution(path)
+ return path
+
+ if not HAS_PIL:
+ actual_label = actual_ext or "unknown"
+ raise RuntimeError(
+ f"Image format mismatch for {path}: target extension is {target_ext}, "
+ f"but the actual image bytes are {actual_label}. "
+ "Install Pillow to enable automatic format conversion."
+ )
+
+ target_format = EXT_TO_PIL_FORMAT.get(target_ext)
+ if not target_format:
+ raise ValueError(f"Unsupported output image extension: {target_ext}")
+
+ image = PILImage.open(io.BytesIO(image_bytes))
+ if target_format == "JPEG" and image.mode in ("RGBA", "LA", "P"):
+ image = image.convert("RGB")
+ image.save(path, format=target_format)
+
+ if actual_ext and actual_ext != target_ext:
+ print(f" Converted: {actual_ext} -> {target_ext}")
+ print(f" File saved to: {path}")
+ report_resolution(path)
+ return path
+
+
def report_resolution(path: str):
"""Try to report image resolution using PIL."""
if HAS_PIL:
@@ -80,11 +178,11 @@ def download_image(url: str, path: str, headers: dict = None, timeout: int = 180
"""Download an image URL and save it to disk."""
response = requests.get(url, headers=headers or {}, timeout=timeout)
response.raise_for_status()
- with open(path, "wb") as f:
- f.write(response.content)
- print(f" File saved to: {path}")
- report_resolution(path)
- return path
+ return save_image_bytes(
+ response.content,
+ path,
+ content_type=response.headers.get("Content-Type"),
+ )
def require_api_key(*candidates: str, message: str):
diff --git a/skills/ppt-master/scripts/image_backends/backend_gemini.py b/skills/ppt-master/scripts/image_backends/backend_gemini.py
index 055082fc..bc4108b6 100644
--- a/skills/ppt-master/scripts/image_backends/backend_gemini.py
+++ b/skills/ppt-master/scripts/image_backends/backend_gemini.py
@@ -23,9 +23,9 @@ from image_backends.backend_common import (
MAX_RETRIES,
is_rate_limit_error,
normalize_image_size,
- report_resolution,
resolve_output_path,
retry_delay,
+ save_image_bytes,
)
@@ -142,12 +142,12 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
if last_image_data is not None and last_image_data.inline_data is not None:
if chunk_count > 1:
print(f" Keeping the final chunk (highest quality).")
- image = last_image_data.as_image()
path = resolve_output_path(prompt, output_dir, filename, ".png")
- image.save(path)
- print(f"File saved to: {path}")
- report_resolution(path)
- return path
+ return save_image_bytes(
+ last_image_data.inline_data.data,
+ path,
+ content_type=getattr(last_image_data.inline_data, "mime_type", None),
+ )
raise RuntimeError("No image was generated. The server may have refused the request.")
diff --git a/skills/ppt-master/scripts/image_backends/backend_openai.py b/skills/ppt-master/scripts/image_backends/backend_openai.py
index 9d5f80f9..8c07f016 100644
--- a/skills/ppt-master/scripts/image_backends/backend_openai.py
+++ b/skills/ppt-master/scripts/image_backends/backend_openai.py
@@ -22,18 +22,13 @@ import threading
from openai import OpenAI
from image_backends.backend_common import (
MAX_RETRIES,
- HAS_PIL,
is_rate_limit_error,
normalize_image_size,
- report_resolution,
resolve_output_path,
retry_delay,
+ save_image_bytes,
)
-if HAS_PIL:
- import io
- from PIL import Image as PILImage
-
# ╔══════════════════════════════════════════════════════════════════╗
# ║ Constants ║
@@ -140,17 +135,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
if resp is not None and resp.data:
path = resolve_output_path(prompt, output_dir, filename, ".png")
image_data = base64.b64decode(resp.data[0].b64_json)
-
- if HAS_PIL:
- image = PILImage.open(io.BytesIO(image_data))
- image.save(path)
- else:
- with open(path, "wb") as f:
- f.write(image_data)
-
- print(f" File saved to: {path}")
- report_resolution(path)
- return path
+ return save_image_bytes(image_data, path)
raise RuntimeError("No image was generated. The server may have refused the request.")
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_images.py b/skills/ppt-master/scripts/svg_finalize/embed_images.py
index e07270bd..b3bb88c5 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_images.py
@@ -18,8 +18,21 @@ import re
import sys
import argparse
-def get_mime_type(filename):
- """Return the MIME type based on file extension."""
+
+def get_mime_type(filename, file_bytes=None):
+ """Return the MIME type based on file bytes first, then extension as fallback."""
+ if file_bytes:
+ if file_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
+ return 'image/png'
+ if file_bytes.startswith(b"\xff\xd8\xff"):
+ return 'image/jpeg'
+ if file_bytes.startswith((b"GIF87a", b"GIF89a")):
+ return 'image/gif'
+ if file_bytes.startswith(b"RIFF") and file_bytes[8:12] == b"WEBP":
+ return 'image/webp'
+ if file_bytes.lstrip().startswith(b"<svg"):
+ return 'image/svg+xml'
+
ext = filename.lower().split('.')[-1]
mime_map = {
'png': 'image/png',
@@ -90,9 +103,10 @@ def embed_images_in_svg(svg_path, dry_run=False):
return match.group(0)
with open(full_path, 'rb') as img_file:
- b64_data = base64.b64encode(img_file.read()).decode('utf-8')
-
- mime_type = get_mime_type(img_path)
+ img_bytes = img_file.read()
+ b64_data = base64.b64encode(img_bytes).decode('utf-8')
+
+ mime_type = get_mime_type(img_path, img_bytes)
images_embedded += 1
images_found.append((img_path, "EMBEDDED", img_size))