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-search): halve originals above Pillow's decompression-warning size

hugohe3481e057ecd9f
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
index 19dafdf5..463aa375 100644
--- a/skills/ppt-master/scripts/docs/image.md
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -299,7 +299,7 @@ python3 scripts/image_search.py "abstract gradient" \
Suitability & manual replacement (a web top hit is metadata-relevant, not guaranteed visually right):
-- By default only the best match is downloaded, plus a downscaled review copy at `images/.review/<stem>.jpg` (the placed asset stays full-resolution). A downloaded camera multi-picture JPEG (MPO, common among Commons originals) is rewritten as its primary frame before validation so every later consumer sees a single-frame JPEG.
+- By default only the best match is downloaded, plus a downscaled review copy at `images/.review/<stem>.jpg` (the placed asset stays full-resolution). A downloaded camera multi-picture JPEG (MPO, common among Commons originals) is rewritten as its primary frame before validation so every later consumer sees a single-frame JPEG. An original above Pillow's decompression-warning size (about 89.5 megapixels) is first reduced by the smallest power of two that fits, keeping format, EXIF, and ICC data, so later readers neither warn nor decode hundreds of megabytes.
- For exact subjects (landmarks, people, companies, products), use `--require-terms` or batch `required_terms` so visually plausible but wrong metadata is rejected before ranking. Example: `--require-terms Chongqing --require-terms "Jiefangbei|Liberation Monument"`. Keep proper-name / geography anchors; do not broaden to generic terms like `canyon`, `stone pillar`, or `ancient town` just to improve coverage.
- When the current Generate agent can inspect images, use `--save-candidates`. The tool saves only the first ranked page of review-eligible provider previews (**8 by default**), writes `candidates/<stem>/review_sheet.jpg`, and leaves the target image and `image_sources.json` untouched. Standalone CLI use remains best-only unless this flag is explicit.
- Compare the thumbnail set against the active Reference/Crop Policy. Only after one passes, run `--promote candidate_03.jpg --filename <name>.jpg`; this downloads and validates exactly that original. In batch mode, pass the same `--batch images/image_queries.json` so `Needs-Selection` becomes `Sourced`.
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index 3a66ca42..5f13c056 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -48,6 +48,7 @@ import shutil
import sys
import tempfile
import threading
+import warnings
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from pathlib import Path
@@ -487,6 +488,55 @@ def _normalize_multi_frame_jpeg(path: Path) -> bool:
return True
+def _fit_pixel_budget(path: Path) -> Optional[tuple[tuple[int, int], tuple[int, int]]]:
+ """Halve in place an original above Pillow's decompression-warning size.
+
+ Wikimedia and similar hosts serve 100+ megapixel originals. Every later
+ Pillow reader (checker, finalizer, exporter) would warn and decode hundreds
+ of megabytes for a picture no slide shows at that size. The saved copy is
+ reduced by the smallest power of two that fits — decoded at that scale for
+ JPEG — keeping its format, EXIF, and ICC data. Returns the old and new sizes
+ when the file was rewritten.
+ """
+ try:
+ from PIL import Image # type: ignore
+ except ImportError:
+ return None
+ limit = Image.MAX_IMAGE_PIXELS
+ if not limit:
+ return None
+ try:
+ with Image.open(path) as source:
+ width, height = source.size
+ if width * height <= limit:
+ return None
+ factor = 2
+ while (width // factor) * (height // factor) > limit:
+ factor *= 2
+ fmt = source.format or "JPEG"
+ save_kwargs: dict[str, object] = {"quality": 90} if fmt in ("JPEG", "WEBP") else {}
+ for key in ("exif", "icc_profile"):
+ value = source.info.get(key)
+ if value:
+ save_kwargs[key] = value
+ source.draft(source.mode, (width // factor, height // factor))
+ reduced = source.reduce(max(1, source.size[0] // (width // factor)))
+ except (OSError, ValueError, SyntaxError):
+ return None
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}.fit.", suffix=path.suffix, dir=str(path.parent))
+ os.close(fd)
+ temp_path = Path(temp_name)
+ try:
+ reduced.save(temp_path, fmt, **save_kwargs)
+ os.replace(temp_path, path)
+ except (OSError, ValueError):
+ temp_path.unlink(missing_ok=True)
+ return None
+ finally:
+ reduced.close()
+ return (width, height), reduced.size
+
+
def _stage_and_validate_image(
output_path: Path,
materialize: Callable[[Path], object],
@@ -508,6 +558,17 @@ def _stage_and_validate_image(
keep_temp = False
try:
materialize(temp_path)
+ with warnings.catch_warnings():
+ # The oversized original is exactly what the next call removes.
+ warnings.filterwarnings("ignore", message=r"Image size \(\d+ pixels\) exceeds limit")
+ fitted = _fit_pixel_budget(temp_path)
+ if fitted is not None:
+ (old_w, old_h), (new_w, new_h) = fitted
+ print(
+ f" downscaled a {old_w}x{old_h} original to {new_w}x{new_h}: "
+ "above Pillow's decompression-warning size",
+ file=sys.stderr,
+ )
if _normalize_multi_frame_jpeg(temp_path):
print(
" normalized a multi-frame camera JPEG (MPO) to its primary frame",
diff --git a/skills/ppt-master/scripts/tests/test_image_search.py b/skills/ppt-master/scripts/tests/test_image_search.py
index f98111d3..bc1bd0f9 100644
--- a/skills/ppt-master/scripts/tests/test_image_search.py
+++ b/skills/ppt-master/scripts/tests/test_image_search.py
@@ -183,6 +183,33 @@ class CandidatePoolContinuationTests(unittest.TestCase):
self.assertGreater(image.getpixel((3, 3))[0], 150)
self.assertFalse(image_search._normalize_multi_frame_jpeg(path))
+ def test_original_above_pillow_warning_size_is_halved_quietly(self) -> None:
+ import warnings
+
+ from PIL import Image
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ target = Path(temp_dir) / "takin.jpg"
+
+ def materialize(path: Path) -> None:
+ Image.new("RGB", (200, 150), (120, 90, 60)).save(path, "JPEG")
+
+ with patch.object(Image, "MAX_IMAGE_PIXELS", 20_000), \
+ warnings.catch_warnings(record=True) as caught, \
+ redirect_stderr(io.StringIO()) as stderr:
+ warnings.simplefilter("always")
+ staged, size = image_search._stage_and_validate_image(
+ target, materialize, min_width=0, min_height=0,
+ enforce_thumbnail_floor=False,
+ )
+
+ self.assertEqual(size, (100, 75))
+ self.assertIn("downscaled a 200x150 original to 100x75", stderr.getvalue())
+ self.assertFalse(
+ [w for w in caught if issubclass(w.category, Image.DecompressionBombWarning)]
+ )
+ staged.unlink()
+
def test_multi_frame_camera_jpeg_bakes_exif_orientation(self) -> None:
from PIL import Image