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

feat(svg_to_pptx): add recorded narration export

hugohe3e776e4686553
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index be4b5e7f..18e1d0ce 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -311,6 +311,16 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path> -s final
- `--animation-trigger {on-click,with-previous,after-previous}` — Start mode (matches PowerPoint's animation-pane Start dropdown). Default `after-previous` (click-free cascade; pace via `--animation-stagger`). Use `on-click` for presenter-paced reveals, or `with-previous` for all-at-once.
- `--auto-advance <seconds>` — kiosk-style auto-play.
+**Optional recorded narration** (only when the user asks for narrated/video export):
+```bash
+python3 ${SKILL_DIR}/scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural
+python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path> -s final --recorded-narration audio
+```
+
+- `notes_to_audio.py` reads split `notes/*.md` files and writes one MP3 per slide to `audio/`.
+- `--recorded-narration audio` embeds the matching audio files, keeps speaker notes, and uses audio duration for slide auto-advance timings.
+- Use this for PowerPoint video export with recorded timings and narrations.
+
Full effect list, anchor logic, and limits: [`references/animations.md`](references/animations.md).
> ❌ **NEVER** substitute `cp` for `finalize_svg.py` — finalize performs multiple critical processing steps
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 32f48b89..8c9168d2 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -314,6 +314,16 @@ python3 scripts/svg_to_pptx.py <project_path> -s final
- `--animation-trigger {on-click,with-previous,after-previous}` — Start mode matching PowerPoint's animation-pane Start dropdown. Default `after-previous` (cascade on slide entry; pace via `--animation-stagger <seconds>`); `on-click` advances per click; `with-previous` plays all groups together.
- `--auto-advance <seconds>` — kiosk-style auto-play
+**Optional recorded narration** (only when the user asks for narrated/video export):
+
+```bash
+python3 scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural
+python3 scripts/svg_to_pptx.py <project_path> -s final --recorded-narration audio
+```
+
+- `notes_to_audio.py` reads split `notes/*.md` files and writes one MP3 per slide to `audio/`.
+- `--recorded-narration audio` embeds matching audio, keeps speaker notes, and sets slide timings from audio duration.
+
Full reference: [`animations.md`](animations.md).
**Prohibited**:
diff --git a/skills/ppt-master/requirements.txt b/skills/ppt-master/requirements.txt
index 7268947f..83fde5bc 100644
--- a/skills/ppt-master/requirements.txt
+++ b/skills/ppt-master/requirements.txt
@@ -16,6 +16,11 @@
# 默认使用 Office 兼容模式(PNG + SVG 双格式),支持所有 Office 版本
python-pptx>=0.6.21
+# Recorded narration / 录制计时和旁白
+# notes_to_audio.py generates per-slide narration audio on macOS/Linux/Windows.
+# notes_to_audio.py 用于在 macOS/Linux/Windows 上生成逐页旁白音频。
+edge-tts>=7.2.8
+
# Office compatibility dependencies (choose one, CairoSVG preferred)
# Office 兼容模式依赖(二选一,优先使用 cairosvg)
# Converts SVG to PNG fallback images for Office LTSC 2021 etc.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 855f7e8e..c2c0f66d 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -1,6 +1,6 @@
# PPT Master Toolset
-This directory contains user-facing scripts for conversion, project setup, SVG processing, export, and image generation.
+This directory contains user-facing scripts for conversion, project setup, SVG processing, export, recorded narration, and image generation.
## Directory Layout
@@ -40,7 +40,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `source_to_md/web_to_md.cjs` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
+| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
| Image tools | `image_gen.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |
| Repo maintenance | `update_repo.py` | README install/update section |
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 85a0e182..a50c3a34 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -1,6 +1,6 @@
# SVG Pipeline Tools
-These tools cover post-processing, SVG validation, speaker notes, and PPTX export.
+These tools cover post-processing, SVG validation, speaker notes, recorded narration, and PPTX export.
## Recommended Pipeline
@@ -36,6 +36,8 @@ python3 scripts/svg_to_pptx.py <project_path> -s final --no-notes
python3 scripts/svg_to_pptx.py <project_path> -t none
python3 scripts/svg_to_pptx.py <project_path> -s final --auto-advance 3
python3 scripts/svg_to_pptx.py <project_path> -s final --animation mixed --animation-duration 0.8
+python3 scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural
+python3 scripts/svg_to_pptx.py <project_path> -s final --recorded-narration audio
```
Behavior:
@@ -46,6 +48,12 @@ Behavior:
- Explicit `-o/--output` keeps the legacy side-by-side `_svg.pptx` next to the chosen path and skips `backup/`
- Recommended source directory: `svg_final/`
- Speaker notes are embedded automatically unless `--no-notes` is used
+- Recorded narration is opt-in:
+ - `notes_to_audio.py` uses the cross-platform Python package `edge-tts` and generates one MP3 file per slide into `audio/`
+ - Narration text is read strictly from the matching `notes/*.md` file; the script only skips Markdown heading lines (`# ...`) and does not summarize, rewrite, or filter delivery notes
+ - `--recorded-narration audio` keeps speaker notes, embeds each matching audio file, and writes slide auto-advance timings from audio duration
+ - This is intended for PowerPoint's video export option "Use recorded timings and narrations"
+ - Voice choices can be listed with `python3 scripts/notes_to_audio.py --list-common-voices` or `python3 scripts/notes_to_audio.py --list-voices --locale zh-CN`
- Page transitions are controlled by `-t/--transition`; per-element entrance animations are controlled by `-a/--animation`
- Per-element animation applies to top-level SVG `<g id="...">` groups in z-order; aim for 3–8 content groups per slide. Page chrome (background / header / footer / decorations / watermark / page number, by id token) is skipped automatically
- Start mode is set by `--animation-trigger`, mirroring PowerPoint's Start dropdown: `after-previous` (default, cascade with `--animation-stagger` spacing on slide entry), `on-click` (presenter-paced), `with-previous` (all together on slide entry)
diff --git a/skills/ppt-master/scripts/docs/troubleshooting.md b/skills/ppt-master/scripts/docs/troubleshooting.md
index 125cba96..d06ce174 100644
--- a/skills/ppt-master/scripts/docs/troubleshooting.md
+++ b/skills/ppt-master/scripts/docs/troubleshooting.md
@@ -46,6 +46,18 @@ python3 scripts/svg_to_pptx.py <project_path> -s final
Do not export directly from `svg_output/` when `svg_final/` exists.
+## Recorded Narration Missing
+
+1. Generate audio after `total_md_split.py`, so filenames in `audio/` can match split `notes/*.md` files.
+2. Export with the project-relative audio directory:
+
+```bash
+python3 scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural
+python3 scripts/svg_to_pptx.py <project_path> -s final --recorded-narration audio
+```
+
+If slide timings do not follow the narration, confirm `ffprobe` is available; without it, audio can still embed, but duration-based auto-advance is skipped.
+
## Dependency Checklist
Most tools use the standard library. Install extra dependencies only when needed:
@@ -56,6 +68,7 @@ pip install -r requirements.txt
Important optional packages:
- `python-pptx` for PPTX export
+- `edge-tts` for `notes_to_audio.py` recorded narration audio
- `Pillow` for image utilities
- `numpy` for watermark removal
- `PyMuPDF` for PDF conversion
diff --git a/skills/ppt-master/scripts/notes_to_audio.py b/skills/ppt-master/scripts/notes_to_audio.py
new file mode 100644
index 00000000..f143df37
--- /dev/null
+++ b/skills/ppt-master/scripts/notes_to_audio.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python3
+"""Generate per-slide narration audio from PPT Master notes.
+
+This script uses `edge-tts` for the same cross-platform behavior on macOS,
+Linux, and Windows.
+
+Usage:
+ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path>
+ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural
+ python3 skills/ppt-master/scripts/notes_to_audio.py --list-common-voices
+ python3 skills/ppt-master/scripts/notes_to_audio.py --list-voices --locale zh-CN
+
+Dependency:
+ python3 -m pip install edge-tts
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import re
+import sys
+from pathlib import Path
+
+
+COMMON_VOICES = [
+ ("zh-CN", "zh-CN-XiaoxiaoNeural", "女声,普通话,清晰自然,默认推荐"),
+ ("zh-CN", "zh-CN-XiaoyiNeural", "女声,普通话,明亮"),
+ ("zh-CN", "zh-CN-YunjianNeural", "男声,普通话,稳重"),
+ ("zh-CN", "zh-CN-YunxiNeural", "男声,普通话,年轻"),
+ ("zh-CN", "zh-CN-YunxiaNeural", "男声,普通话,少年感"),
+ ("zh-CN", "zh-CN-YunyangNeural", "男声,普通话,播报感"),
+ ("zh-HK", "zh-HK-HiuGaaiNeural", "女声,粤语"),
+ ("zh-HK", "zh-HK-WanLungNeural", "男声,粤语"),
+ ("zh-TW", "zh-TW-HsiaoChenNeural", "女声,台湾普通话"),
+ ("zh-TW", "zh-TW-YunJheNeural", "男声,台湾普通话"),
+ ("en-US", "en-US-JennyNeural", "女声,美式英语"),
+ ("en-US", "en-US-GuyNeural", "男声,美式英语"),
+ ("en-GB", "en-GB-SoniaNeural", "女声,英式英语"),
+ ("en-GB", "en-GB-RyanNeural", "男声,英式英语"),
+]
+
+
+def spoken_text(markdown: str) -> str:
+ """Return narration text exactly from notes, except Markdown headings."""
+ lines: list[str] = []
+ for raw in markdown.splitlines():
+ if raw.lstrip().startswith("#"):
+ continue
+ line = raw.rstrip()
+ if not line.strip():
+ if lines and lines[-1] != "":
+ lines.append("")
+ continue
+ lines.append(line)
+ return "\n".join(lines).strip()
+
+
+def _edge_rate(rate: str) -> str:
+ """Normalize a user-provided rate into edge-tts format."""
+ value = rate.strip()
+ if not value:
+ return "+0%"
+ if value.endswith("%"):
+ if value[0] not in "+-":
+ return f"+{value}"
+ return value
+ if re.fullmatch(r"[+-]?\d+", value):
+ number = int(value)
+ return f"{number:+d}%"
+ return value
+
+
+async def run_edge_tts(text: str, output_path: Path, *, voice: str, rate: str) -> None:
+ try:
+ import edge_tts
+ except ImportError as exc:
+ raise RuntimeError(
+ "Missing dependency `edge-tts`. Install it with: "
+ "python3 -m pip install edge-tts"
+ ) from exc
+
+ communicate = edge_tts.Communicate(text, voice=voice, rate=_edge_rate(rate))
+ await communicate.save(str(output_path))
+
+
+def print_common_voices() -> None:
+ print("Common edge-tts voices:")
+ print("Locale Voice Notes")
+ print("------ ---------------------------- ----------------")
+ for locale, voice, notes in COMMON_VOICES:
+ print(f"{locale:<8} {voice:<29} {notes}")
+
+
+async def print_edge_voices(locale: str | None = None) -> None:
+ try:
+ import edge_tts
+ except ImportError as exc:
+ raise RuntimeError(
+ "Missing dependency `edge-tts`. Install it with: "
+ "python3 -m pip install edge-tts"
+ ) from exc
+
+ manager = await edge_tts.VoicesManager.create()
+ voices = manager.voices
+ if locale:
+ voices = [voice for voice in voices if voice.get("Locale") == locale]
+ for voice in sorted(voices, key=lambda item: (item.get("Locale", ""), item.get("ShortName", ""))):
+ short_name = voice.get("ShortName", "")
+ voice_locale = voice.get("Locale", "")
+ gender = voice.get("Gender", "")
+ friendly = voice.get("FriendlyName", "")
+ print(f"{voice_locale:<8} {short_name:<34} {gender:<8} {friendly}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("project_path", type=Path, nargs="?")
+ parser.add_argument("-o", "--output", type=Path, default=None)
+ parser.add_argument(
+ "--voice",
+ default="zh-CN-XiaoxiaoNeural",
+ help="edge-tts voice name (default: zh-CN-XiaoxiaoNeural)",
+ )
+ parser.add_argument(
+ "--rate",
+ default="+0%",
+ help='edge-tts speaking rate, e.g. "+0%%", "-10%%", "+15%%" (default: +0%%)',
+ )
+ parser.add_argument("--list-common-voices", action="store_true", help="print a curated voice list and exit")
+ parser.add_argument("--list-voices", action="store_true", help="query edge-tts voices and exit")
+ parser.add_argument("--locale", default=None, help='filter --list-voices by locale, e.g. "zh-CN"')
+ args = parser.parse_args()
+
+ if args.list_common_voices:
+ print_common_voices()
+ return 0
+
+ if args.list_voices:
+ try:
+ asyncio.run(print_edge_voices(args.locale))
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ return 0
+
+ if args.project_path is None:
+ parser.error("project_path is required unless --list-voices or --list-common-voices is used")
+
+ project = args.project_path
+ notes_dir = project / "notes"
+ output_dir = args.output or (project / "audio")
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ note_files = [
+ path for path in sorted(notes_dir.glob("*.md"))
+ if path.name != "total.md"
+ ]
+ if not note_files:
+ print(f"error: no per-slide notes found in {notes_dir}", file=sys.stderr)
+ return 2
+
+ generated = 0
+ for note_path in note_files:
+ text = spoken_text(note_path.read_text(encoding="utf-8"))
+ if not text:
+ print(f"[skip] {note_path.name}: empty spoken text")
+ continue
+ output_path = output_dir / f"{note_path.stem}.mp3"
+ try:
+ asyncio.run(run_edge_tts(text, output_path, voice=args.voice, rate=args.rate))
+ except Exception as exc:
+ print(f"error: failed to generate {output_path}: {exc}", file=sys.stderr)
+ return 1
+ generated += 1
+ print(f"[OK] {output_path}")
+
+ print(f"[Done] Generated {generated}/{len(note_files)} audio file(s): {output_dir}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
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 ed341c11..467bd049 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
@@ -27,6 +27,17 @@ from .pptx_notes import (
markdown_to_plain_text,
create_notes_slide_xml, create_notes_slide_rels_xml,
)
+from .pptx_narration import (
+ AUDIO_CONTENT_TYPES,
+ AUDIO_REL_TYPE,
+ IMAGE_REL_TYPE,
+ MEDIA_REL_TYPE,
+ TRANSPARENT_PNG_BYTES,
+ apply_recorded_timing,
+ inject_narration,
+ next_shape_id,
+ probe_audio_duration,
+)
from .pptx_slide_xml import (
ANIMATIONS_AVAILABLE, TRANSITIONS,
create_slide_xml_with_svg, create_slide_rels_xml,
@@ -70,6 +81,15 @@ def _append_relationship(
return next_rid
+def _add_default_content_type(content_types: str, extension: str, content_type: str) -> str:
+ """Add a Default content type if it is not already present."""
+ ext = extension.lstrip(".")
+ if f'Extension="{ext}"' in content_types:
+ return content_types
+ entry = f' <Default Extension="{ext}" ContentType="{content_type}"/>'
+ return content_types.replace('</Types>', entry + '\n</Types>')
+
+
def _expand_anim_targets_to_group_children(
slide_xml: str,
anim_targets: list[tuple[int, str]],
@@ -137,6 +157,9 @@ def create_pptx_with_native_svg(
animation_duration: float = 0.4,
animation_stagger: float = 0.5,
animation_trigger: str = 'after-previous',
+ narration_audio: dict[str, Path] | None = None,
+ use_narration_timings: bool = False,
+ narration_padding: float = 0.5,
) -> bool:
"""Create a PPTX file with native SVG.
@@ -159,6 +182,9 @@ def create_pptx_with_native_svg(
trigger mode (seconds). Ignored otherwise.
animation_trigger: PowerPoint Start mode — ``'after-previous'`` (default),
``'on-click'``, or ``'with-previous'``.
+ narration_audio: Optional dict mapping SVG stem to narration audio file.
+ use_narration_timings: Whether to set slide auto-advance from audio duration.
+ narration_padding: Extra seconds added after each narration before advancing.
Returns:
Whether all slides were successfully created.
@@ -248,6 +274,8 @@ def create_pptx_with_native_svg(
has_any_image = False
media_cache: dict[tuple[str, str], str] = {}
notes_slides_created: set[int] = set()
+ narration_slides_created: set[int] = set()
+ audio_exts_used: set[str] = set()
mixed_animation_offset = 0
for i, svg_path in enumerate(svg_files, 1):
@@ -433,6 +461,63 @@ def create_pptx_with_native_svg(
)
notes_slides_created.add(slide_num)
+ # --- Process narration audio (shared between native and legacy mode) ---
+ svg_stem = svg_path.stem
+ audio_path = narration_audio.get(svg_stem) if narration_audio else None
+ if audio_path:
+ slide_xml_path = extract_dir / 'ppt' / 'slides' / f'slide{slide_num}.xml'
+ rels_path = extract_dir / 'ppt' / 'slides' / '_rels' / f'slide{slide_num}.xml.rels'
+
+ ext = audio_path.suffix.lower()
+ media_name = f'narration{slide_num}{ext}'
+ shutil.copy2(audio_path, media_dir / media_name)
+ audio_exts_used.add(ext)
+
+ poster_name = 'narration_poster.png'
+ poster_path = media_dir / poster_name
+ if not poster_path.exists():
+ poster_path.write_bytes(TRANSPARENT_PNG_BYTES)
+ has_any_image = True
+
+ media_rid = _append_relationship(
+ rels_path,
+ MEDIA_REL_TYPE,
+ f'../media/{media_name}',
+ )
+ audio_rid = _append_relationship(
+ rels_path,
+ AUDIO_REL_TYPE,
+ f'../media/{media_name}',
+ )
+ poster_rid = _append_relationship(
+ rels_path,
+ IMAGE_REL_TYPE,
+ f'../media/{poster_name}',
+ )
+
+ slide_xml = slide_xml_path.read_text(encoding='utf-8')
+ narration_shape_id = next_shape_id(slide_xml)
+ slide_xml = inject_narration(
+ slide_xml,
+ shape_id=narration_shape_id,
+ shape_name=media_name,
+ audio_rid=audio_rid,
+ media_rid=media_rid,
+ poster_rid=poster_rid,
+ )
+
+ if use_narration_timings:
+ duration = probe_audio_duration(audio_path)
+ if duration:
+ slide_xml = apply_recorded_timing(
+ slide_xml,
+ advance_after=duration + narration_padding,
+ transition_duration=transition_duration,
+ transition_effect=transition or 'fade',
+ )
+ slide_xml_path.write_text(slide_xml, encoding='utf-8')
+ narration_slides_created.add(slide_num)
+
if verbose:
if use_native_shapes:
mode_str = " (Native)"
@@ -442,7 +527,8 @@ def create_pptx_with_native_svg(
mode_str = " (SVG)"
has_notes = slide_num in notes_slides_created
notes_str = " +notes" if has_notes else ""
- print(f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}{notes_str}")
+ narration_str = " +narration" if slide_num in narration_slides_created else ""
+ print(f" [{i}/{len(svg_files)}] {svg_path.name}{mode_str}{notes_str}{narration_str}")
success_count += 1
@@ -473,6 +559,16 @@ def create_pptx_with_native_svg(
with open(content_types_path, 'w', encoding='utf-8') as f:
f.write(content_types)
+ if audio_exts_used:
+ for ext in sorted(audio_exts_used):
+ content_type = AUDIO_CONTENT_TYPES.get(ext)
+ if content_type:
+ content_types = _add_default_content_type(content_types, ext, content_type)
+ if 'Extension="png"' not in content_types:
+ content_types = _add_default_content_type(content_types, 'png', 'image/png')
+ with open(content_types_path, 'w', encoding='utf-8') as f:
+ f.write(content_types)
+
# Add notesSlides content types
if enable_notes and notes_slides_created:
for i in sorted(notes_slides_created):
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 b50929e6..f5f94b52 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
@@ -11,6 +11,7 @@ from pathlib import Path
from .pptx_dimensions import CANVAS_FORMATS, get_project_info
from .pptx_discovery import find_svg_files, find_notes_files
from .pptx_builder import create_pptx_with_native_svg
+from .pptx_narration import find_narration_files
from .pptx_slide_xml import TRANSITIONS
try:
@@ -79,6 +80,13 @@ Speaker notes (enabled by default):
1. Match by filename (recommended): 01_cover.md corresponds to 01_cover.svg
2. Match by index: slide01.md corresponds to the 1st SVG (backward compatible)
- Use --no-notes to disable
+
+Recorded narration:
+ %(prog)s examples/ppt169_demo -s final --recorded-narration audio
+ - Keeps speaker notes when enabled
+ - Embeds per-slide audio matched by SVG filename / slide number
+ - Sets slide auto-advance from audio duration so video export can use
+ "recorded timings and narrations"
''',
)
@@ -127,6 +135,14 @@ Speaker notes (enabled by default):
parser.add_argument('--no-notes', action='store_true',
help='Disable speaker notes embedding (enabled by default)')
+ parser.add_argument('--narration-audio-dir', type=str, default=None,
+ help='Embed per-slide narration audio from this directory')
+ parser.add_argument('--use-narration-timings', action='store_true',
+ help='Set slide auto-advance timings from narration audio durations')
+ parser.add_argument('--recorded-narration', type=str, default=None,
+ help='Shortcut: embed narration audio and use its durations as recorded timings')
+ parser.add_argument('--narration-padding', type=float, default=0.5,
+ help='Seconds to add after each narration before auto-advance (default: 0.5)')
args = parser.parse_args()
@@ -189,6 +205,18 @@ Speaker notes (enabled by default):
if enable_notes:
notes = find_notes_files(project_path, svg_files)
+ narration_audio: dict[str, Path] = {}
+ narration_audio_dir_arg = args.recorded_narration or args.narration_audio_dir
+ use_narration_timings = args.use_narration_timings or bool(args.recorded_narration)
+ if narration_audio_dir_arg:
+ narration_audio_dir = Path(narration_audio_dir_arg)
+ if not narration_audio_dir.is_absolute():
+ narration_audio_dir = project_path / narration_audio_dir
+ narration_audio = find_narration_files(narration_audio_dir, svg_files)
+ if verbose:
+ print(f" Narration audio directory: {narration_audio_dir}")
+ print(f" Narration audio matched: {len(narration_audio)}/{len(svg_files)} slide(s)")
+
transition = args.transition if args.transition != 'none' else None
animation = args.animation if args.animation != 'none' else None
@@ -206,6 +234,9 @@ Speaker notes (enabled by default):
animation_duration=args.animation_duration,
animation_stagger=args.animation_stagger,
animation_trigger=args.animation_trigger,
+ narration_audio=narration_audio,
+ use_narration_timings=use_narration_timings,
+ narration_padding=args.narration_padding,
)
success = True
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_narration.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_narration.py
new file mode 100644
index 00000000..7ec45cec
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_narration.py
@@ -0,0 +1,224 @@
+"""Narration audio discovery and PPTX XML helpers."""
+
+from __future__ import annotations
+
+import base64
+import json
+import re
+import subprocess
+from pathlib import Path
+
+
+MEDIA_REL_TYPE = "http://schemas.microsoft.com/office/2007/relationships/media"
+AUDIO_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"
+IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
+
+AUDIO_CONTENT_TYPES = {
+ ".m4a": "audio/mp4",
+ ".mp4": "audio/mp4",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".aif": "audio/aiff",
+ ".aiff": "audio/aiff",
+}
+
+NARRATION_EXTENSIONS = tuple(AUDIO_CONTENT_TYPES.keys())
+
+TRANSPARENT_PNG_BYTES = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/"
+ "lBf7WQAAAABJRU5ErkJggg=="
+)
+
+
+def _normalize_title(title: str) -> str:
+ text = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]+", "_", title.strip())
+ return re.sub(r"_+", "_", text).strip("_").lower()
+
+
+def _leading_number(text: str) -> int | None:
+ match = re.match(r"^(\d{1,3})", text.strip())
+ return int(match.group(1)) if match else None
+
+
+def find_narration_files(audio_dir: Path, svg_files: list[Path]) -> dict[str, Path]:
+ """Return `{svg_stem: audio_path}` matched by exact stem, normalized stem, or index."""
+ if not audio_dir.exists() or not audio_dir.is_dir():
+ return {}
+
+ audio_files = [
+ path for path in sorted(audio_dir.iterdir())
+ if path.is_file() and path.suffix.lower() in NARRATION_EXTENSIONS
+ ]
+ exact = {path.stem: path for path in audio_files}
+ normalized: dict[str, Path] = {}
+ numbered: dict[int, Path] = {}
+ for path in audio_files:
+ normalized.setdefault(_normalize_title(path.stem), path)
+ number = _leading_number(path.stem)
+ if number is not None:
+ numbered.setdefault(number, path)
+
+ matched: dict[str, Path] = {}
+ for index, svg in enumerate(svg_files, 1):
+ stem = svg.stem
+ if stem in exact:
+ matched[stem] = exact[stem]
+ continue
+ norm = _normalize_title(stem)
+ if norm in normalized:
+ matched[stem] = normalized[norm]
+ continue
+ if index in numbered:
+ matched[stem] = numbered[index]
+ return matched
+
+
+def probe_audio_duration(audio_path: Path) -> float | None:
+ """Return duration in seconds using ffprobe when available."""
+ try:
+ result = subprocess.run(
+ [
+ "ffprobe", "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "json",
+ str(audio_path),
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ )
+ data = json.loads(result.stdout or "{}")
+ duration = float(data.get("format", {}).get("duration", 0))
+ return duration if duration > 0 else None
+ except Exception:
+ return None
+
+
+def next_shape_id(slide_xml: str) -> int:
+ ids = [int(value) for value in re.findall(r'<p:cNvPr[^>]*\sid="(\d+)"', slide_xml)]
+ return max(ids, default=1) + 1
+
+
+def create_audio_pic_xml(
+ shape_id: int,
+ shape_name: str,
+ audio_rid: str,
+ media_rid: str,
+ poster_rid: str,
+) -> str:
+ """Create a tiny audio picture shape carrying narration media."""
+ return f'''<p:pic>
+ <p:nvPicPr>
+ <p:cNvPr id="{shape_id}" name="{shape_name}">
+ <a:hlinkClick r:id="" action="ppaction://media"/>
+ </p:cNvPr>
+ <p:cNvPicPr>
+ <a:picLocks noChangeAspect="1"/>
+ </p:cNvPicPr>
+ <p:nvPr>
+ <a:audioFile r:link="{audio_rid}"/>
+ <p:extLst>
+ <p:ext uri="{{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}}">
+ <p14:media xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" r:embed="{media_rid}"/>
+ </p:ext>
+ </p:extLst>
+ </p:nvPr>
+ </p:nvPicPr>
+ <p:blipFill>
+ <a:blip r:embed="{poster_rid}"/>
+ <a:stretch><a:fillRect/></a:stretch>
+ </p:blipFill>
+ <p:spPr>
+ <a:xfrm>
+ <a:off x="0" y="0"/>
+ <a:ext cx="1" cy="1"/>
+ </a:xfrm>
+ <a:prstGeom prst="rect"><a:avLst/></a:prstGeom>
+ </p:spPr>
+ </p:pic>'''
+
+
+def _next_timing_id(slide_xml: str) -> int:
+ ids = [int(value) for value in re.findall(r'<p:cTn[^>]*\sid="(\d+)"', slide_xml)]
+ return max(ids, default=1) + 1
+
+
+def _create_audio_timing_xml(shape_id: int, ctn_id: int) -> str:
+ return f'''<p:audio>
+ <p:cMediaNode vol="80000">
+ <p:cTn id="{ctn_id}" fill="hold" display="0">
+ <p:stCondLst><p:cond delay="0"/></p:stCondLst>
+ </p:cTn>
+ <p:tgtEl><p:spTgt spid="{shape_id}"/></p:tgtEl>
+ </p:cMediaNode>
+ </p:audio>'''
+
+
+def inject_narration(
+ slide_xml: str,
+ *,
+ shape_id: int,
+ shape_name: str,
+ audio_rid: str,
+ media_rid: str,
+ poster_rid: str,
+) -> str:
+ """Inject a hidden narration media shape and slide-entry autoplay timing."""
+ audio_pic_xml = create_audio_pic_xml(
+ shape_id=shape_id,
+ shape_name=shape_name,
+ audio_rid=audio_rid,
+ media_rid=media_rid,
+ poster_rid=poster_rid,
+ )
+ slide_xml = slide_xml.replace("</p:spTree>", audio_pic_xml + "\n </p:spTree>", 1)
+
+ audio_timing_xml = _create_audio_timing_xml(shape_id, _next_timing_id(slide_xml))
+ if "<p:timing>" not in slide_xml:
+ timing_xml = f''' <p:timing>
+ <p:tnLst>
+ <p:par>
+ <p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot">
+ <p:childTnLst>
+ {audio_timing_xml}
+ </p:childTnLst>
+ </p:cTn>
+ </p:par>
+ </p:tnLst>
+ </p:timing>'''
+ return slide_xml.replace("</p:sld>", timing_xml + "\n</p:sld>", 1)
+
+ pattern = re.compile(r'(<p:cTn\s+id="1"[^>]*>\s*<p:childTnLst>)', re.S)
+ if pattern.search(slide_xml):
+ return pattern.sub(r"\1\n " + audio_timing_xml, slide_xml, count=1)
+ return slide_xml.replace("</p:tnLst>", audio_timing_xml + "\n </p:tnLst>", 1)
+
+
+def apply_recorded_timing(
+ slide_xml: str,
+ *,
+ advance_after: float,
+ transition_duration: float,
+ transition_effect: str | None = "fade",
+) -> str:
+ """Set slide auto-advance timing so exported video follows narration length."""
+ adv_ms = max(1, int(advance_after * 1000))
+ dur_ms = max(1, int(transition_duration * 1000))
+
+ transition_match = re.search(r"<p:transition\b[^>]*>", slide_xml)
+ if transition_match:
+ tag = transition_match.group(0)
+ if "advTm=" in tag:
+ new_tag = re.sub(r'\sadvTm="[^"]*"', f' advTm="{adv_ms}"', tag, count=1)
+ else:
+ new_tag = tag[:-1] + f' advTm="{adv_ms}">'
+ return slide_xml[:transition_match.start()] + new_tag + slide_xml[transition_match.end():]
+
+ effect = transition_effect or "fade"
+ transition_xml = f''' <p:transition p14:dur="{dur_ms}" xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" advTm="{adv_ms}">
+ <p:{effect}/>
+ </p:transition>'''
+ if "<p:timing>" in slide_xml:
+ return slide_xml.replace("<p:timing>", transition_xml + "\n <p:timing>", 1)
+ return slide_xml.replace("</p:sld>", transition_xml + "\n</p:sld>", 1)