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

perf(svg_to_pptx): parallelize and cache SVG→PNG fallback rendering

hugohe364bef3544ff9
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 1659b838..83224215 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -75,6 +75,12 @@ Behavior:
- `--animation-duration` controls per-element entrance length (default `0.4`); `--animation-stagger` adds gap between elements in `after-previous` mode (default `0.5`)
- Optional object-level overrides live in `<project>/animations.json` or a path passed via `--animation-config`; build and validate them with `animation_config.py scaffold|validate`
+Performance (legacy `_svg.pptx` PNG fallback):
+- SVG→PNG is pre-rendered in a process pool before the main loop. Default workers = `min(cpu, pages, 8)`; override with `--workers N` (set `1` for sequential, `0` is treated as sequential).
+- Results are cached at `<project>/.cache/svg_png/` keyed by SVG content hash + size + active renderer (`cairosvg` vs `svglib`). Switching renderers naturally invalidates the cache; nothing to clean by hand.
+- `--cache-dir <path>` relocates the cache; `--no-cache` forces re-render without writing/reading the cache (handy when debugging rendering).
+- Native mode (`--only native`) is unaffected — that path embeds DrawingML shapes and never touches PNG.
+
Dependency:
```bash
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
index 313b5182..e0417c8c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
@@ -4,10 +4,12 @@ from __future__ import annotations
import hashlib
import mimetypes
+import os
import re
import shutil
import tempfile
import zipfile
+from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Any
@@ -22,7 +24,7 @@ from .pptx_dimensions import (
)
from .pptx_media import (
PNG_RENDERER,
- get_png_renderer_info, convert_svg_to_png,
+ get_png_renderer_info, convert_svg_to_png, convert_svg_to_png_cached,
)
from .pptx_notes import (
markdown_to_plain_text,
@@ -226,6 +228,61 @@ def _build_sequence_targets(
return seq_targets, mixed_count
+def _prerender_legacy_pngs(
+ svg_files: list[Path],
+ media_dir: Path,
+ pixel_width: int,
+ pixel_height: int,
+ cache_dir: Path | None,
+ workers: int,
+ verbose: bool,
+) -> dict[int, bool]:
+ """Render every SVG→PNG into media_dir in parallel.
+
+ Returns {1-based slide index: success}. Falls back to sequential when
+ workers<=1 or len(svg_files)<=2.
+ """
+ results: dict[int, bool] = {}
+ targets: list[tuple[int, Path, Path]] = [
+ (i, svg, media_dir / f'image{i}.png')
+ for i, svg in enumerate(svg_files, 1)
+ ]
+
+ if workers <= 1 or len(targets) <= 2:
+ for i, svg, png in targets:
+ ok = convert_svg_to_png_cached(svg, png, pixel_width, pixel_height, cache_dir)
+ results[i] = ok
+ if verbose:
+ tag = 'cached/ok' if ok else 'failed'
+ print(f" [PNG {i}/{len(targets)}] {svg.name} - {tag}")
+ return results
+
+ with ProcessPoolExecutor(max_workers=workers) as pool:
+ future_map = {
+ pool.submit(
+ convert_svg_to_png_cached,
+ svg, png, pixel_width, pixel_height, cache_dir,
+ ): (i, svg)
+ for i, svg, png in targets
+ }
+ done = 0
+ for future in as_completed(future_map):
+ i, svg = future_map[future]
+ try:
+ ok = future.result()
+ except Exception as exc:
+ ok = False
+ if verbose:
+ print(f" [PNG] {svg.name} - worker error: {exc}")
+ results[i] = ok
+ done += 1
+ if verbose:
+ tag = 'cached/ok' if ok else 'failed'
+ print(f" [PNG {done}/{len(targets)}] {svg.name} - {tag}")
+
+ return results
+
+
def create_pptx_with_native_svg(
svg_files: list[Path],
output_path: Path,
@@ -247,6 +304,8 @@ def create_pptx_with_native_svg(
narration_audio: dict[str, Path] | None = None,
use_narration_timings: bool = False,
narration_padding: float = 0.5,
+ cache_dir: Path | None = None,
+ workers: int | None = None,
) -> bool:
"""Create a PPTX file with native SVG.
@@ -361,6 +420,23 @@ def create_pptx_with_native_svg(
media_dir = extract_dir / 'ppt' / 'media'
media_dir.mkdir(exist_ok=True)
+ prerender_results: dict[int, bool] | None = None
+ if not use_native_shapes and use_compat_mode and PNG_RENDERER is not None:
+ if workers is None:
+ resolved_workers = min(os.cpu_count() or 2, len(svg_files), 8)
+ else:
+ resolved_workers = max(0, workers)
+ if verbose:
+ cache_label = str(cache_dir) if cache_dir else 'disabled'
+ mode = f'parallel x{resolved_workers}' if resolved_workers > 1 else 'sequential'
+ print(f" Pre-rendering PNGs ({mode}, cache: {cache_label})")
+ prerender_results = _prerender_legacy_pngs(
+ svg_files, media_dir, pixel_width, pixel_height,
+ cache_dir, resolved_workers, verbose,
+ )
+ if verbose:
+ print()
+
success_count = 0
has_any_image = False
media_cache: dict[tuple[str, str], str] = {}
@@ -520,11 +596,14 @@ def create_pptx_with_native_svg(
slide_has_png = False
if use_compat_mode:
- png_path = media_dir / png_filename
- png_success = convert_svg_to_png(
- svg_path, png_path,
- width=pixel_width, height=pixel_height,
- )
+ if prerender_results is not None:
+ png_success = prerender_results.get(i, False)
+ else:
+ png_path = media_dir / png_filename
+ png_success = convert_svg_to_png(
+ svg_path, png_path,
+ width=pixel_width, height=pixel_height,
+ )
if png_success:
slide_has_png = True
has_any_image = True
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
index 1182b4cd..d8a6bab9 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
@@ -200,6 +200,16 @@ Recorded narration:
parser.add_argument('--narration-padding', type=float, default=0.5,
help='Seconds to add after each narration before auto-advance (default: 0.5)')
+ parser.add_argument('--cache-dir', type=str, default=None,
+ help='Cache directory for SVG→PNG renders (default: '
+ '<project>/.cache/svg_png). Cache key uses SVG content '
+ 'hash + size + renderer; safe across renderer switches.')
+ parser.add_argument('--no-cache', action='store_true',
+ help='Disable the SVG→PNG cache for this run (still parallel).')
+ parser.add_argument('--workers', type=int, default=None,
+ help='Parallel workers for SVG→PNG pre-rendering. '
+ 'Default: min(cpu, pages, 8). Set 1 for sequential.')
+
args = parser.parse_args()
project_path = Path(args.project_path)
@@ -427,6 +437,15 @@ Recorded narration:
print(f" ... and {len(on_click_slides) - 20} more", file=sys.stderr)
sys.exit(1)
+ if args.no_cache:
+ cache_dir: Path | None = None
+ elif args.cache_dir:
+ cache_dir = Path(args.cache_dir)
+ if not cache_dir.is_absolute():
+ cache_dir = project_path / cache_dir
+ else:
+ cache_dir = project_path / '.cache' / 'svg_png'
+
# svg_files is per-product (native vs legacy may now read different
# directories); everything else is shared.
shared_kwargs = dict(
@@ -447,6 +466,8 @@ Recorded narration:
narration_audio=narration_audio,
use_narration_timings=use_narration_timings,
narration_padding=args.narration_padding,
+ cache_dir=cache_dir,
+ workers=args.workers,
)
success = True
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_media.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_media.py
index e016763c..e54c6a43 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_media.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_media.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+import hashlib
+import shutil
+import tempfile
from pathlib import Path
# SVG to PNG library detection
@@ -84,3 +87,74 @@ def convert_svg_to_png(
return False
return False
+
+
+def _cache_key(svg_path: Path, width: int | None, height: int | None) -> str:
+ h = hashlib.sha256()
+ with open(svg_path, 'rb') as f:
+ for chunk in iter(lambda: f.read(65536), b''):
+ h.update(chunk)
+ return f"{h.hexdigest()}_{width or 0}x{height or 0}_{PNG_RENDERER or 'none'}"
+
+
+def convert_svg_to_png_cached(
+ svg_path: Path,
+ png_path: Path,
+ width: int | None = None,
+ height: int | None = None,
+ cache_dir: Path | None = None,
+) -> bool:
+ """Cache-aware SVG→PNG conversion.
+
+ Returns True on success (cache hit or fresh render). Cache key bakes in
+ SVG content hash + size + renderer name; switching renderers invalidates
+ naturally. Failures are never cached.
+ """
+ if cache_dir is None:
+ return convert_svg_to_png(svg_path, png_path, width, height)
+
+ if PNG_RENDERER is None:
+ return False
+
+ try:
+ key = _cache_key(svg_path, width, height)
+ except OSError as e:
+ print(f" Warning: Failed to hash SVG ({svg_path.name}): {e}")
+ return convert_svg_to_png(svg_path, png_path, width, height)
+
+ cached = cache_dir / f"{key}.png"
+ if cached.is_file():
+ try:
+ shutil.copy(cached, png_path)
+ return True
+ except OSError as e:
+ print(f" Warning: Cache copy failed, re-rendering ({svg_path.name}): {e}")
+
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ tmp_fd, tmp_name = tempfile.mkstemp(suffix='.png', dir=str(cache_dir))
+ tmp_path = Path(tmp_name)
+ import os
+ os.close(tmp_fd)
+
+ ok = convert_svg_to_png(svg_path, tmp_path, width, height)
+ if not ok:
+ try:
+ tmp_path.unlink()
+ except OSError:
+ pass
+ return False
+
+ try:
+ os.replace(tmp_path, cached)
+ except OSError:
+ try:
+ tmp_path.unlink()
+ except OSError:
+ pass
+
+ try:
+ shutil.copy(cached, png_path)
+ return True
+ except OSError as e:
+ print(f" Warning: Cache copy failed ({svg_path.name}): {e}")
+ return False