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(video): mix native animation sounds into exported videos
hugohe36d9627ac39b2
diff --git a/docs/animations.md b/docs/animations.mdindex ee32fd37..26ba12e8 100644--- a/docs/animations.md+++ b/docs/animations.md@@ -177,6 +177,11 @@ may use a sparse `animations.json`; a slide-level `transition.sound: null`clears an inherited default sound. Validate before export. Do not add soundmerely to demonstrate that the feature exists.+This validation proves the editable PPTX contains the native cue; it does not+prove PowerPoint's MP4 audio track contains it. For direct narrated video with+resolved cues, use the post-export sound mix in+[Audio Narration & Video Export](./audio-narration.md).+## Customize Specific ObjectsUse `animations.json` only when deck-wide settings are not enough—for example,diff --git a/docs/audio-narration.md b/docs/audio-narration.mdindex 5a158a1f..f2c714f9 100644--- a/docs/audio-narration.md+++ b/docs/audio-narration.md@@ -13,7 +13,8 @@ PPT Master can turn the speaker notes into per-slide narration via [`edge-tts`](- One compact `<project_path>/audio/manifest.json` after a complete successful run. It records only provider/model, audio/subtitle format, relevant voice settings, and a SHA-256 fingerprint instead of a raw cloud voice ID. It contains no per-slide inventory, artifact hashes, or API keys and is not loaded during normal generation.- When narration-cue synchronization is selected, canonical `animations.json` and page-local SRT derive `narration_animations.json`, whose click-free object animations wait for the relevant subtitle cue. Narration-independent custom motion keeps canonical timing instead. When neither animation sidecar exists, narrated export creates no sidecar and inherits the base export's resolved motion. With page-local SRT, these paths can produce a deck-wide `<project_path>/audio/total.srt` aligned to the final PPTX timeline; after PowerPoint exports a video, `video_subtitles.py` can align the frozen narration text against its actual audio track for a delivery sidecar SRT.- Optional re-export: a new PPTX in `exports/` with each `m4a` / `mp3` / `wav` file embedded into the matching slide and slide auto-advance timings set from the configurable page-start floor, audio length, and page-tail padding, so kiosk/auto-play and video export work without manual timing. Narration never starts before the page transition finishes.-- Optional native video export on Windows: `powerpoint_video.py` delegates the final narrated PPTX to PowerPoint 2016+ and waits until its native MP4 encoder succeeds or fails.+- Optional native video export on Windows: `powerpoint_video.py` delegates the final narrated PPTX to PowerPoint 2016+ and waits until its native MP4 encoder succeeds or fails. This raw MP4 preserves the visual animation/narration path, but PowerPoint does not reliably include native transition or object-animation sounds in its audio track.+- When direct MP4 delivery has resolved animation sound cues, `video_sound_mix.py` produces an independent float SFX WAV, a final mixed MP4, and a JSON receipt proving the stem reached the actual final audio while the video stream stayed unchanged.- The original speaker notes are preserved.## How it works@@ -21,7 +22,7 @@ PPT Master can turn the speaker notes into per-slide narration via [`edge-tts`](1. **Speaker notes are written as pure spoken narration.** PPT Master's notes spec deliberately produces TTS-friendly prose — no bracketed stage markers, no `Key points:` / `Duration:` meta-lines — so what is read aloud is exactly what's on the page.2. **AI picks the voice for you.** When you ask for narration, the AI checks the deck's primary language (`zh-CN` / `en-US` / `ja-JP` / `ko-KR` / …), pulls the selected provider's voice catalog, and recommends 3–6 candidates with a one-line tone description for each (e.g. "steady male voice for financial reporting"). It also recommends a speaking rate or provider defaults based on notes density.3. **Settings resolve once.** Default Generate and Enhance Native ask once for provider, voice, rate, embedding, and optional video export. Quick uses explicit values and automatically resolves unspecified provider, voice, rate, and embedding choices; video remains off unless direct video delivery was requested.-4. **Generation runs.** Edge, ElevenLabs, MiniMax, and timestamp-capable CosyVoice voices write each page's audio and SRT from provider timing returned by the same synthesis; Qwen and explicit CosyVoice audio-only mode write audio only. A complete run atomically writes `audio/manifest.json` for provenance. For Generate PPTX with narration-cue synchronization, page-local SRT and canonical custom animation let the AI map current SVG content groups to numbered SRT cues and derive click-free `narration_animations.json`; narration-independent custom motion keeps canonical timing, while no animation sidecar inherits the base export's resolved motion. It then re-exports the deck with audio attached and, when page-local SRT exists, merges it using timing values read from that final PPTX. When automatic video export was selected and compatible Windows PowerPoint is available, it continues through PowerPoint's native encoder and waits for the MP4 before aligning the delivery SRT when available. Long-audio import and automatic long-audio splitting are not supported.+4. **Generation runs.** Edge, ElevenLabs, MiniMax, and timestamp-capable CosyVoice voices write each page's audio and SRT from provider timing returned by the same synthesis; Qwen and explicit CosyVoice audio-only mode write audio only. A complete run atomically writes `audio/manifest.json` for provenance. For Generate PPTX with narration-cue synchronization, page-local SRT and canonical custom animation let the AI map current SVG content groups to numbered SRT cues and derive click-free `narration_animations.json`; narration-independent custom motion keeps canonical timing, while no animation sidecar inherits the base export's resolved motion. It then re-exports the deck with audio attached and, when page-local SRT exists, merges it using timing values read from that final PPTX. When automatic video export was selected and compatible Windows PowerPoint is available, it continues through PowerPoint's native encoder. If the final narrated trace and PPTX contain sound cues, the raw MP4 is then calibrated by page narration, mixed with the exact embedded cue bytes, limited, and verified before any delivery SRT is aligned against the final video. Long-audio import and automatic long-audio splitting are not supported.Subtitles remain external artifacts: PPT Master does not embed them into the PPTX or burn them into the MP4. Automatic video export delegates to installed Windows PowerPoint; it is not a separate renderer.@@ -135,20 +136,32 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \--inherit-motion-from "<base_postflight_report>"# Quick Generate appends --quick-generate --with-notes to the selected command.+# For direct MP4 delivery with resolved sound cues, also append+# --conversion-trace <final_narrated_trace> to that selected export command.# 6. When page-local SRT exists, merge it using the final PowerPoint timingspython3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --force-# 7. Optional on Windows: export through PowerPoint and wait for completion+# 7. Optional on Windows: export the raw video through PowerPoint and wait+# for completionpython3 skills/ppt-master/scripts/powerpoint_video.py --checkpython3 skills/ppt-master/scripts/powerpoint_video.py \- <final_narrated_pptx> -o exports/<final_video>.mp4--# 8. When page-local SRT exists, align the frozen narration text against the-# exported video's audio track and write a same-stem delivery SRT+ <final_narrated_pptx> -o exports/<raw_powerpoint_video>.mp4++# 8. When final resolved motion has sound cues, build the independent SFX stem+# and verified mixed video. Defaults: transitions about 35%, object cues+# about 25%, final limiter -1 dBFS.+python3 skills/ppt-master/scripts/video_sound_mix.py <project_path> \+ --pptx <final_narrated_pptx> \+ --trace <final_narrated_trace> \+ --video exports/<raw_powerpoint_video>.mp4 \+ -o exports/<final_mixed_video>.mp4 --force++# 9. When page-local SRT exists, align the frozen narration text against the+# final video's audio track: mixed when step 8 ran, otherwise raw.python3 skills/ppt-master/scripts/video_subtitles.py <project_path> \- --video "<powerpoint_exported_video>" --language <language> --force+ --video "<final_delivery_video>" --language <language> --force```Before sending any TTS request, `notes_to_audio.py` verifies that every@@ -189,7 +202,7 @@ Alibaba Cloud's current [TTS model guide](https://www.alibabacloud.com/help/en/mWhen narration-cue synchronization is selected with canonical custom animation, `narration_timing.json` remains deliberately separate from read-only `animations.json`. It records the ordered SRT-set SHA-256, optional narration start floor, narration padding, ordered SVG group IDs, and optional 1-based cue numbers. `narration_sync.py animations` rejects a stale fingerprint, validates the group IDs against the current SVGs, and writes the derived `narration_animations.json` with only supported PowerPoint fields. Cue-bound animation starts use the same page-start floor as the embedded audio; uncued title or decorative animation keeps its canonical relative timing. A group with `effects[]` still maps to one cue: its first active row is anchored to that cue, while later rows retain their relative delay. Narration-independent custom motion passes canonical `animations.json` directly; with no sidecar, inherit the base report's resolved motion. `narration_sync.py subtitles` reads the final PPTX's actual presentation order plus millisecond transition, narration-delay, and slide-advance values, so `total.srt` follows the native PPTX timeline. A relative `--pptx` path is resolved under `<project_path>`.-PowerPoint's video encoder can quantize each slide/media segment to its output frame clock. Those small per-page differences may accumulate even when the PPTX timing values are correct. `video_subtitles.py` uses `stable-ts` to force-align the exact frozen narration text against the finished `.mp4` / `.wmv` / `.mov` audio track. It may split long delivery cues for display, writes a same-stem SRT, and does not rewrite the video, notes, or page-local subtitles.+PowerPoint's video encoder can quantize each slide/media segment to its output frame clock. Those small per-page differences may accumulate even when the PPTX timing values are correct. `video_sound_mix.py` reuses page-level narration correlation to move every transition/object cue from the theoretical PPTX clock to the raw MP4 clock; it does not directly add two independent timelines. `video_subtitles.py` then uses `stable-ts` to force-align the exact frozen narration text against the finished `.mp4` / `.wmv` / `.mov` audio track. It may split long delivery cues for display, writes a same-stem SRT, and does not rewrite the video, notes, or page-local subtitles.Use the default text-flow mode for the final narrated SVG export. It keeps authored line breaks in one editable, no-wrap text frame; narration does not require per-line text frames.@@ -270,10 +283,11 @@ Cloud TTS providers do not require extra Python packages; they use HTTPS directlAutomatic MP4 export adds no Python package. It requires Windows PowerPoint 2016+ and Windows PowerShell; macOS and systems without compatible PowerPoint keep the narrated PPTX and use manual export.-Final-video subtitle alignment additionally requires `ffmpeg` on `PATH` and `stable-ts`:+Post-export animation-sound mixing requires `ffmpeg` / `ffprobe` on `PATH` and+`numpy`. Final-video subtitle alignment separately requires `stable-ts`:```bash-python3 -m pip install stable-ts+python3 -m pip install numpy stable-ts```## Tips@@ -288,28 +302,38 @@ Once the narrated PPTX is in `exports/`, Windows PowerPoint 2016+ can export it```bashpython3 skills/ppt-master/scripts/powerpoint_video.py \- <final_narrated_pptx> -o <final_video.mp4>+ <final_narrated_pptx> -o <raw_powerpoint_video.mp4>```The command uses recorded timings and narrations, defaults to 1080p/30 fps, and returns only after PowerPoint reports success or failure. The embedded audio plays as each slide's narration, while the per-slide auto-advance timings drive the video's pacing. `--recorded-narration` rejects `on-click` object animation because it does not generate object-level click timings.+PowerPoint's raw MP4 does not reliably contain sounds attached to transitions+or Animation Pane rows, even when `animations.json` and the PPTX package are+valid. For Generate projects whose final narrated trace contains those cues,+run `video_sound_mix.py` as shown above. It keeps the native sounds in the+editable PPTX, copies the visual video stream unchanged, mixes narration at+unity with reduced cue levels, applies a peak limiter, and publishes an+independent SFX stem plus a machine-readable verification receipt. Align+subtitles against the mixed MP4, not the raw intermediate.+**Manual PowerPoint fallback (Windows / Mac, Office 2016+)**:1. Open the narrated `.pptx` from `exports/`.2. **File → Export → Create a Video**.3. Pick a quality and "Use Recorded Timings and Narrations".4. Save as `.mp4` (`.wmv` is also available on Windows).-5. Run the optional `video_subtitles.py` alignment command above; it writes the same-stem SRT beside the video.+5. If native transition/object sounds are configured, run the sound-mix command above; otherwise the PowerPoint export is the final video.+6. Run the optional `video_subtitles.py` alignment command against the final video; it writes the same-stem SRT beside it.PowerPoint for Mac can export MP4/MOV manually, but Microsoft documents thatanimation effects do not play in its movie export. Use the Windows automationpath when animation fidelity matters.-**Keynote (Mac)**: open the deck → **File → Export To → Movie…** — Keynote also honors embedded audio and per-slide timings, output `.m4v` / `.mov`.+**Keynote (Mac)**: open the deck → **File → Export To → Movie…** — Keynote can honor embedded narration and per-slide timings, output `.m4v` / `.mov`; this is not a guarantee that PowerPoint animation sounds are present.**Tips**:- **No mic, no recording session needed** — the audio is generated, not recorded. Re-runs reuse the same notes and settings, but cloud models may still produce small nondeterministic differences.-- **Animation fidelity on Windows** — PowerPoint's Windows video export preserves PPT Master's native page transitions and click-free object animation. Mac movie export has the limitation noted above. See [Animations & Transitions](./animations.md).+- **Animation fidelity on Windows** — PowerPoint's Windows video export preserves PPT Master's native visual page transitions and click-free object animation. Animation sound is a separate audio-delivery boundary handled by the post-export mix. Mac movie export has the limitation noted above. See [Animations & Transitions](./animations.md).- **Want to tweak just one slide's audio?** Edit `notes/<page>.md`, re-run `notes_to_audio.py` and the embedding step, then re-export the video — total turnaround is usually under a minute per slide.- **File size**: a 20-page deck at Full HD typically lands at 30–80 MB depending on imagery. Drop to HD if you need a smaller file for sharing.diff --git a/docs/technical-design.md b/docs/technical-design.mdindex 686268ab..2d6c9876 100644--- a/docs/technical-design.md+++ b/docs/technical-design.md@@ -686,7 +686,8 @@ The post-processing and export stages keep authoring, validation, preview, deliv| `validation/<output_stem>.report.json` | published-PPTX postflight and resource audit | records actual ZIP/package part counts; reruns ZIP and Slide-count checks; labels relationship, structured-package, transition, and animation validation as build-time enforcement; accepts quality-report linkage only when its SHA-256 fingerprint matches the export inputs; and surfaces unresolved tokens, external images, and generic-only font stacks || `exports/<name>_<ts>_native_charts_tables.pptx` (opt-in via `--native-charts-and-tables`) | when `data-pptx-replace-with` markers should replace SVG-derived, shape-based charts/tables with PowerPoint-native Chart/Table objects | data-backed objects with chart/table-specific controls; the default DrawingML shapes remain independently editable || `exports/<name>_<ts>_narrated.pptx` (via `--recorded-narration` or `--narration-audio-dir`) | embeds matched narration audio; complete recorded mode directly supports auto-play and PowerPoint video export | `--recorded-narration` requires matching audio for every slide and writes duration-plus-padding auto-advance; low-level `--narration-audio-dir` permits partial or zero coverage and writes auto-advance only with `--use-narration-timings` |-| `exports/<narrated_stem>.mp4` (optional via `powerpoint_video.py`) | animation-faithful narrated video on Windows PowerPoint 2016+ | delegates to PowerPoint's native encoder and waits for completion; it is a post-PPTX integration, not a second deck renderer |+| `exports/<narrated_stem>.mp4` (optional via `powerpoint_video.py`) | raw native visual-animation and narration video on Windows PowerPoint 2016+ | delegates to PowerPoint's native encoder and waits for completion; it is final when no native animation sound cues exist, but the encoder does not reliably include those cues in the audio track |+| `exports/<raw_stem>_sfx.wav`, `<raw_stem>_mixed.mp4`, `<raw_stem>_sound_mix.json` (triggered via `video_sound_mix.py`) | sound-enabled direct MP4 delivery when final resolved motion contains transition/object cues | derives timing from the final narrated trace plus page-level raw-video calibration, extracts exact PPTX relationship bytes, copies the video stream, and verifies the actual mixed audio rather than treating PPTX configuration as MP4 acceptance || `backup/<ts>/svg_output/` (default output path only; copy is best-effort after directory creation) | re-export from frozen SVG sources without rerunning the LLM | after successful conversion the exporter creates the backup directory and attempts the copy; explicit `-o` creates none, copy failure does not block export, prints a warning outside quiet mode, and leaves postflight `backup_path` empty, while directory-creation failure remains fatal |Validation JSON files and `validation/workflow.log` are cold audit artifacts,@@ -841,6 +842,10 @@ packaging are cross-platform project operations; PowerPoint video encoding is aWindows desktop integration. `powerpoint_video.py` therefore accepts the finalnarrated PPTX, invokes `CreateVideo`, and polls `CreateVideoStatus` to present asynchronous CLI result without coupling Office automation to the TTS backends.+When native transition/object sounds exist, `video_sound_mix.py` remains a+second explicit boundary because PowerPoint may omit them from the encoded+audio. It calibrates the raw MP4, renders a reusable SFX stem, and publishes a+receipt that verifies the mixed output while leaving the canonical PPTX intact.---diff --git a/docs/zh/animations.md b/docs/zh/animations.mdindex 4f6e5488..31e3f0d3 100644--- a/docs/zh/animations.md+++ b/docs/zh/animations.md@@ -162,6 +162,10 @@ python3 skills/ppt-master/scripts/sound_sync.py list --query recommended`transition.sound: null` 可清除继承的默认转场声音。导出前仍须校验。不要为了展示项目具备音效能力而强行添加声音。+上述校验只能证明可编辑 PPTX 含有原生 cue,不能证明 PowerPoint 导出的 MP4+音轨含有它。直接交付带旁白且含音效 cue 的视频时,应按+[音频旁白与视频导出](./audio-narration.md)执行导出后混音。+## 自定义具体对象只有当整份 deck 的统一设置不够用时才需要 `animations.json`,例如让同一对象diff --git a/docs/zh/audio-narration.md b/docs/zh/audio-narration.mdindex 3c37ec47..03d4823a 100644--- a/docs/zh/audio-narration.md+++ b/docs/zh/audio-narration.md@@ -13,7 +13,8 @@ PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edg- 完整生成成功后写出精简的 `<project_path>/audio/manifest.json`,只记录 provider、模型、音频/字幕格式、相关音色参数,以及代替云端 voice ID 原文的 SHA-256 指纹;不包含逐页清单、产物哈希或 API Key,正常生成过程也不会读取它。- 选择旁白 cue 同步时,规范的 `animations.json` 与逐页 SRT 会派生 `narration_animations.json`,让无点击对象动画等待相关字幕 cue;与旁白无关的自定义动画则保留规范配置中的原始计时。两个动画 sidecar 都不存在时,旁白导出不会创建 sidecar,而是继承基础导出的已解析 motion。存在逐页 SRT 时,这些路径都可以生成与最终 PPTX 时间轴一致的 `<project_path>/audio/total.srt`;PowerPoint 导出视频后,`video_subtitles.py` 可把冻结的旁白文本与实际视频音轨对齐,生成交付用外挂字幕。- 可选重新导出:在 `exports/` 生成新版 PPTX,每页对应的 `m4a` / `mp3` / `wav` 音频已嵌入到该页,且页面推进时间根据可配置的页前起始下限、音频长度和页尾停留自动设置——无人值守自动播放和视频导出都不用再手动调时间。旁白不会早于页面转场结束时启动。-- Windows 下可选原生视频导出:`powerpoint_video.py` 把最终带旁白 PPTX 交给 PowerPoint 2016+,并等待其原生 MP4 编码成功或失败。+- Windows 下可选原生视频导出:`powerpoint_video.py` 把最终带旁白 PPTX 交给 PowerPoint 2016+,并等待其原生 MP4 编码成功或失败。该 raw MP4 保留视觉动画与旁白路径,但 PowerPoint 不保证把原生转场音效或对象动画音效写入视频音轨。+- 直接 MP4 交付存在已解析动画音效时,`video_sound_mix.py` 会生成独立的 float SFX WAV、最终混音 MP4 和 JSON 回执,证明 stem 已进入实际成片音轨,同时视频流保持不变。- 演讲者备注原样保留。## 它是怎么做到的@@ -21,7 +22,7 @@ PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edg1. **备注本身就是为 TTS 写的口播稿**。PPT Master 的 notes 规范刻意产出适合朗读的散文——没有 `[过渡]` / `[停顿]` 这种舞台标记,也没有 `要点:` / `时长:` 这种 meta 行——念出来的内容就是页面上的内容。2. **AI 替你选音色**。当你提出生成旁白时,AI 根据 deck 的主语言(`zh-CN` / `en-US` / `ja-JP` / `ko-KR` / …)和所选 provider 拉取或解释可用音色,挑出候选并给每个写一句中文调性说明(如"稳重男声·适合财报")。语速/风格也会基于 notes 信息密度给出推荐值。3. **配置一次确定**。Default Generate 和 Enhance Native 会一次确认 provider、音色、语速、是否嵌入 PPTX,以及是否继续导出视频。Quick 直接采用明确值,并自动补齐未指定的 provider、音色、语速和嵌入方式;只有明确要求直接交付视频时才开启视频导出。-4. **执行**。Edge、ElevenLabs、MiniMax,以及支持时间戳的 CosyVoice 音色,会依据同一次合成返回的 provider 计时,把每页音频和 SRT 一起写入 `audio/`;Qwen 和显式 CosyVoice 纯音频模式只写音频。完整生成成功后会原子写入 `audio/manifest.json` 记录来源。对于选择旁白 cue 同步的 Generate PPTX,逐页 SRT 与规范自定义动画会让 AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;与旁白无关的自定义动画保留规范计时,没有动画 sidecar 时则继承基础导出的已解析 motion。随后再导出带音频的 PPTX;存在逐页 SRT 时,才从该 PPTX 读回实际计时并合并。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器,等 MP4 完成后再校准可用的交付字幕。不支持长音频导入或自动拆分。+4. **执行**。Edge、ElevenLabs、MiniMax,以及支持时间戳的 CosyVoice 音色,会依据同一次合成返回的 provider 计时,把每页音频和 SRT 一起写入 `audio/`;Qwen 和显式 CosyVoice 纯音频模式只写音频。完整生成成功后会原子写入 `audio/manifest.json` 记录来源。对于选择旁白 cue 同步的 Generate PPTX,逐页 SRT 与规范自定义动画会让 AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;与旁白无关的自定义动画保留规范计时,没有动画 sidecar 时则继承基础导出的已解析 motion。随后再导出带音频的 PPTX;存在逐页 SRT 时,才从该 PPTX 读回实际计时并合并。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器。最终 narrated trace 与 PPTX 含音效 cue 时,再按逐页旁白校准 raw MP4,混入 PPTX 中实际嵌入的 cue 字节,限幅并验收,最后才对齐交付字幕。不支持长音频导入或自动拆分。字幕保持为外部 SRT 文件:PPT Master 不把字幕嵌入 PPTX,也不烧录进 MP4。自动视频导出委托给本机 Windows PowerPoint,并不是另一套渲染器。@@ -133,20 +134,30 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \--inherit-motion-from "<base_postflight_report>"# Quick Generate 在所选命令后追加 --quick-generate --with-notes。+# 直接 MP4 交付且存在已解析音效 cue 时,还需在所选导出命令中追加+# --conversion-trace <final_narrated_trace>。# 6. 存在逐页 SRT 时,按最终 PowerPoint 计时合并python3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --force-# 7. Windows 可选:通过 PowerPoint 导出视频并等待完成+# 7. Windows 可选:通过 PowerPoint 导出 raw 视频并等待完成python3 skills/ppt-master/scripts/powerpoint_video.py --checkpython3 skills/ppt-master/scripts/powerpoint_video.py \- <final_narrated_pptx> -o exports/<final_video>.mp4--# 8. 存在逐页 SRT 时,把冻结的旁白文本与导出视频音轨对齐,-# 生成与视频同名的交付 SRT+ <final_narrated_pptx> -o exports/<raw_powerpoint_video>.mp4++# 8. 最终 motion 存在音效 cue 时,生成独立 SFX stem 与验收后的混音成片。+# 默认:转场音约 35%,对象音约 25%,最终限幅 -1 dBFS。+python3 skills/ppt-master/scripts/video_sound_mix.py <project_path> \+ --pptx <final_narrated_pptx> \+ --trace <final_narrated_trace> \+ --video exports/<raw_powerpoint_video>.mp4 \+ -o exports/<final_mixed_video>.mp4 --force++# 9. 存在逐页 SRT 时,把冻结的旁白文本与最终视频音轨对齐;+# 第 8 步执行过就使用 mixed,否则使用 raw。python3 skills/ppt-master/scripts/video_subtitles.py <project_path> \- --video "<powerpoint_exported_video>" --language <language> --force+ --video "<final_delivery_video>" --language <language> --force```发送任何 TTS 请求前,`notes_to_audio.py` 会确认每个 Generate SVG 页面或@@ -185,7 +196,7 @@ CLI 会在发送请求前拒绝超出范围的 ElevenLabs stability/similarity/s选择旁白 cue 同步且存在规范自定义动画时,`narration_timing.json` 与只读的 `animations.json` 刻意分离:前者记录整套有序 SRT 的 SHA-256、可选的旁白起始下限、页尾 padding、有序 SVG 组 ID 和可选的 1-based cue 编号。`narration_sync.py animations` 会拒绝过期的 SRT 指纹,用当前 SVG 校验组 ID,并把 PowerPoint 支持的字段写入派生的 `narration_animations.json`。与 cue 绑定的动画使用和嵌入音频相同的页前起始下限;未绑定 cue 的标题或装饰动画保留规范相对时间。包含 `effects[]` 的分组仍只映射一条 cue:第一条有效动画行锚定该 cue,后续动画行保留相对延迟。与旁白无关的自定义动画直接使用规范 `animations.json`;没有 sidecar 时继承基础报告的已解析 motion。`narration_sync.py subtitles` 从最终 PPTX 读取真实页面关系顺序、毫秒级转场、旁白延迟与页面推进时间,因此 `total.srt` 使用原生 PPTX 时间轴。相对 `--pptx` 路径按 `<project_path>` 解析。-PowerPoint 的视频编码器可能把每个页面 / 媒体段落量化到输出帧时钟;即使 PPTX 计时值正确,这些很小的分页误差仍可能逐页累积。`video_subtitles.py` 使用 `stable-ts`,把冻结的旁白原文与最终 `.mp4` / `.wmv` / `.mov` 音轨强制对齐;交付时可为显示效果拆分过长 cue,并生成与视频同名的 SRT,不会改写视频、备注或逐页字幕。+PowerPoint 的视频编码器可能把每个页面 / 媒体段落量化到输出帧时钟;即使 PPTX 计时值正确,这些很小的分页误差仍可能逐页累积。`video_sound_mix.py` 复用逐页旁白相关性,把每个转场 / 对象音效从理论 PPTX 时钟映射到 raw MP4 时钟,而不是直接叠加两套独立时间轴。`video_subtitles.py` 再使用 `stable-ts`,把冻结的旁白原文与最终 `.mp4` / `.wmv` / `.mov` 音轨强制对齐;交付时可为显示效果拆分过长 cue,并生成与视频同名的 SRT,不会改写视频、备注或逐页字幕。最终带旁白的 SVG 导出使用默认文本流模式即可:在一个禁用自动换行的可编辑文本框中保留作者断行;旁白不要求每一行拆成独立文本框。@@ -264,10 +275,11 @@ python3 -m pip install edge-tts自动 MP4 导出不增加 Python 依赖,但要求 Windows PowerPoint 2016+ 与 Windows PowerShell;macOS 或没有兼容 PowerPoint 的机器保留带旁白 PPTX,改用手动导出。-最终视频字幕对齐还需要系统 `PATH` 中可用的 `ffmpeg`,以及 `stable-ts`:+导出后混入动画音效需要系统 `PATH` 中可用的 `ffmpeg` / `ffprobe` 以及+`numpy`;最终视频字幕对齐另需 `stable-ts`:```bash-python3 -m pip install stable-ts+python3 -m pip install numpy stable-ts```## 经验值@@ -284,26 +296,34 @@ python3 -m pip install stable-ts```bashpython3 skills/ppt-master/scripts/powerpoint_video.py \- <final_narrated_pptx> -o <final_video.mp4>+ <final_narrated_pptx> -o <raw_powerpoint_video.mp4>```命令使用录制的计时和旁白,默认输出 1080p/30fps,并在 PowerPoint 明确成功或失败后才返回。嵌入音频作为逐页旁白播放,页面自动推进时间控制视频节奏。`--recorded-narration` 会拒绝 `on-click` 对象动画,因为 PPT Master 不生成对象级点击计时。+即使 `animations.json` 和 PPTX package 校验通过,PowerPoint 的 raw MP4+也不保证包含附着在转场或 Animation Pane 行上的声音。Generate 项目的最终+narrated trace 含这些 cue 时,按上面的命令运行 `video_sound_mix.py`:原生声音+仍保留在可编辑 PPTX 中,视觉视频流原样复制,旁白保持 unity,提示音先降增益再+与旁白混合,最终经过峰值限幅,并输出独立 SFX stem 与机器可读验收回执。字幕应+基于 mixed MP4 对齐,而不是 raw 中间产物。+**PowerPoint 手动回退(Windows / Mac,Office 2016+)**:1. 打开 `exports/` 里那份带旁白的 `.pptx`。2. **文件 → 导出 → 创建视频**。3. 选清晰度以及"使用录制的计时和旁白"。4. **创建视频** → 保存为 `.mp4`(Windows 也支持 `.wmv`)。-5. 若要让外挂字幕最贴合最终视频,再执行上面的 `video_subtitles.py` 对齐命令;它会把同名 SRT 写在视频旁边。+5. 若已配置原生转场 / 对象动画音效,先运行上面的声音混合命令;否则 PowerPoint 导出即为最终视频。+6. 再对最终视频运行可选的 `video_subtitles.py` 对齐命令;它会把同名 SRT 写在视频旁边。PowerPoint for Mac 可以手动导出 MP4/MOV,但微软明确说明其影片导出不会播放动画效果。需要动画保真时,应使用 Windows 自动导出路径。-**Keynote(Mac)**:打开 deck → **文件 → 导出到 → 影片…** ——Keynote 同样会读取嵌入的音频和分页计时,输出 `.m4v` / `.mov`。+**Keynote(Mac)**:打开 deck → **文件 → 导出到 → 影片…** ——Keynote 可以读取嵌入的旁白和分页计时,输出 `.m4v` / `.mov`;这不构成 PowerPoint 动画音效已进入成片的保证。**经验值**:- **不需要麦克风、不需要录制环节**——音频是合成的。重跑会复用同一份 notes 与参数,但云端模型仍可能出现轻微的非确定性差异。-- **Windows 动画保真**:PowerPoint 的 Windows 视频导出会保留 PPT Master 的原生页间转场和无点击对象动画;Mac 影片导出存在上面的限制。详见 [转场与动画](./animations.md)。+- **Windows 动画保真**:PowerPoint 的 Windows 视频导出会保留 PPT Master 的原生视觉页间转场和无点击对象动画;动画音效属于独立音频交付边界,由导出后混音处理。Mac 影片导出存在上面的限制。详见 [转场与动画](./animations.md)。- **单页改音频**:改对应 `notes/<page>.md`,再跑一遍 `notes_to_audio.py` + 嵌入步骤,再重新导出视频——单页迭代通常不到一分钟。- **文件大小**:20 页全高清 deck 通常是 30–80 MB,取决于图片量。需要小文件分享时降到高清就行。diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.mdindex b4d5628f..c17dedea 100644--- a/docs/zh/technical-design.md+++ b/docs/zh/technical-design.md@@ -596,7 +596,8 @@ SVG 与 DrawingML 的表达模型并不等价,因此主编译路径不把“| `validation/<output_stem>.report.json` | 已发布 PPTX 的 postflight 与资源审计 | 记录实际 ZIP/package part 数量;重新检查 ZIP 与正式页数;把内部关系、结构化包、转场和动画如实标为构建期强制校验;只有 SHA-256 指纹与导出输入一致时才接受质量报告关联,同时暴露未解析变量、外部图片和纯通用字体栈 || `exports/<name>_<ts>_native_charts_tables.pptx`(需 `--native-charts-and-tables` 显式开启) | 让带 `data-pptx-replace-with` 标记的 SVG 派生形状图表/表格替换为 PowerPoint 原生 Chart/Table 对象 | 带数据源和图表/表格专属控制的对象;默认 DrawingML shape 本身仍可独立编辑 || `exports/<name>_<ts>_narrated.pptx`(经 `--recorded-narration` 或 `--narration-audio-dir` 生成) | 嵌入匹配到的旁白音频;完整录制模式可直接服务自动放映与 PowerPoint 视频导出 | `--recorded-narration` 要求每页匹配音频,并写入“时长 + padding”的自动推进;低层 `--narration-audio-dir` 允许部分或零覆盖,只有另加 `--use-narration-timings` 才写自动推进 |-| `exports/<narrated_stem>.mp4`(可选,经 `powerpoint_video.py`) | Windows PowerPoint 2016+ 下保留动画与旁白的视频交付物 | 委托 PowerPoint 原生编码器并等待完成;它是 PPTX 后处理集成,不是第二套 deck 渲染器 |+| `exports/<narrated_stem>.mp4`(可选,经 `powerpoint_video.py`) | Windows PowerPoint 2016+ 下保留原生视觉动画与旁白的 raw 视频 | 委托 PowerPoint 原生编码器并等待完成;没有原生动画音效 cue 时它就是最终视频,但编码器不保证把这些 cue 写入音轨 |+| `exports/<raw_stem>_sfx.wav`、`<raw_stem>_mixed.mp4`、`<raw_stem>_sound_mix.json`(触发式,经 `video_sound_mix.py`) | 最终 motion 含转场 / 对象音效时的带音效 MP4 交付物 | 依据最终 narrated trace 与 raw 视频逐页校准确定时间,从 PPTX relationship 提取准确字节,复制视频流,并验收实际 mixed 音轨,而不是把 PPTX 配置校验当成 MP4 验收 || `backup/<ts>/svg_output/`(仅默认输出路径;目录创建后复制为 best-effort) | 在不重跑 LLM 的前提下从冻结 SVG 源重建 pptx | 转换成功后先创建备份目录再尝试复制;显式 `-o` 不创建,复制失败不阻断导出,非 quiet 模式打印 warning,postflight 的 `backup_path` 为空,但目录创建失败仍会中断 |校验 JSON 与 `validation/workflow.log` 都是冷审计产物,不是常规模型输入。只有用户明确要求复核运行过程时才打开日志。它可以还原项目级 Python 命令及有限的重要结果,而不是完整控制台输出;每条命令的尾部会记录保留与省略的输出行数。日志也允许选择性记录重要阶段交接或返工原因、用户批准的例外及人工恢复选择等非 Python 事项;这些人工记录不重复制品内容、常规页面进度或私有推理,也不能替代当前制品对阶段与就绪状态的判定。导出器在程序内部读取 SVG 质量报告,并在默认非 quiet 流程打印紧凑的 `[POSTFLIGHT]` 回执,包含状态、质量门结果、Slide 数量、warning 类别计数和产物路径。成功流程只消费该回执,不加载两份完整 JSON;只有失败排查或用户明确要求审计时才定向提取报告字段。@@ -721,7 +722,7 @@ ChartEx 导入被有意限制为 7 个已验证数据模型:`treemap`、`sunbu(`after-previous` 或 `with-previous`);该要求按每条解析后的动画行检查,也排除`trigger_shape`。-**为什么原生视频导出保持独立命令。** 音频合成和 PPTX 打包属于跨平台项目操作;PowerPoint 视频编码则是 Windows 桌面集成。`powerpoint_video.py` 接收最终带旁白 PPTX,调用 `CreateVideo` 并轮询 `CreateVideoStatus`,对调用方呈现同步结果,同时避免把 Office 自动化耦合进 TTS backend。+**为什么原生视频导出保持独立命令。** 音频合成和 PPTX 打包属于跨平台项目操作;PowerPoint 视频编码则是 Windows 桌面集成。`powerpoint_video.py` 接收最终带旁白 PPTX,调用 `CreateVideo` 并轮询 `CreateVideoStatus`,对调用方呈现同步结果,同时避免把 Office 自动化耦合进 TTS backend。存在原生转场 / 对象音效时,`video_sound_mix.py` 仍保持第二个显式边界,因为 PowerPoint 可能从编码音轨中省略它们;该工具校准 raw MP4、生成可复用 SFX stem,并在不改变规范 PPTX 的前提下发布 mixed 输出验收回执。---diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.mdindex 959b67db..cc8dc5e5 100644--- a/skills/ppt-master/references/animations.md+++ b/skills/ppt-master/references/animations.md@@ -20,7 +20,7 @@ before the page plan is frozen, not only when a deck is already exported.| A static full-bleed page that should stop looking frozen | Consider slow `path_*` motion on a visually subordinate image or atmospheric layer; §4.1 gives one starting recipe | Post-processing; §4.1 || Carousel, counting numerals, parallax depth, click-to-reveal flip card | Four recurring recipes assembled from the mechanisms above | §4.2 — the carousel and odometer both need paired pages || Kiosk or unattended playback | `--auto-advance <seconds>`, optionally with `-t none` | Export; §3 |-| A transition or object animation needs an audible cue | Optional `transition.sound` or object-animation `sound`; select it only after the visual motion solution is complete, then sync the chosen global-library ids into the project | Post-motion; §2.2 |+| A transition or object animation needs an audible cue | Optional `transition.sound` or object-animation `sound`; select it only after the visual motion solution is complete, then sync the chosen global-library ids into the project. Direct narrated MP4 delivery uses the separate verified mix in [`generate-audio`](../workflows/stages/generate-audio.md) | Post-motion; §2.2 || Nothing should move | `-t none`, and leave per-element animation at its default `none` | Export; §1 |**Hard rule — Morph geometry is an authoring decision; pairing is a later@@ -280,6 +280,13 @@ demonstrate capability or spread it across a deck for coverage. A sound maysupport a named transition, reveal, confirmation, warning, or drawn/movinggesture after the corresponding visual behavior is already selected.+**Hard rule — PPTX and MP4 are separate sound deliveries**: sound fields and+package read-back prove the editable PPTX contains the intended native cue;+they do not prove PowerPoint's video encoder placed it in the MP4 audio track.+For direct narrated MP4 delivery with resolved cues, follow `generate-audio`+and mix from the final narrated trace plus final PPTX. Keep post-production+gain and limiter settings out of `animations.json`.+---## 3. Page Transitions@@ -586,6 +593,10 @@ object-animation timing before and after their allowed edits, then runstructural package validation; they do not author or normalize animationeffects.+**Validation boundary**: these checks prove PPTX timing, relationships, and+embedded sound parts. They are not final-video audio acceptance; a triggered+`video_sound_mix.py` receipt owns that evidence.+---## 7. Video Adaptation Contract@@ -596,6 +607,11 @@ locks identity, order, effect, direction, and timing; video may refine only itsdeclared renderer parameters. Unsupported families fail visibly. See[`video-motion-plan.md`](../scripts/docs/video-motion-plan.md).+Direct narrated video sound uses the final resolved trace for cue order and+offsets, the final PPTX relationships for the exact embedded audio bytes, and+page-level narration correlation for the exported-video clock. It never reads+sound timing from a raw sidecar or filename.+---## 8. Limitations@@ -605,6 +621,9 @@ declared renderer parameters. Unsupported families fail visibly. Seenot create object anchors.- PowerPoint OOXML is the compatibility target; other presentation apps mayreinterpret individual native behavior trees.+- PowerPoint's native MP4 encoder may omit transition and object-animation+ sounds even when the PPTX package is valid; direct sound-enabled MP4 delivery+ therefore uses the post-export mix owned by `generate-audio`.- Direct-PPTX routes preserve unknown transition `AlternateContent`; timingedits keep Choice and Fallback advance attributes synchronized.diff --git a/skills/ppt-master/references/video-design.md b/skills/ppt-master/references/video-design.mdindex 1838a701..021f6308 100644--- a/skills/ppt-master/references/video-design.md+++ b/skills/ppt-master/references/video-design.md@@ -195,8 +195,11 @@ ordinary Default narration-independent deck-wide motion, omit these sidecarsand the object-sync claim.**Sound effects**: exclude them from this pass and planning artifacts. After-final SVG/motion, animation post-processing owns on-demand sync; otherwise-remain silent.+final SVG/motion, animation post-processing owns on-demand selection and native+PPTX configuration; otherwise remain silent. For direct narrated MP4 delivery,+`generate-audio` additionally owns the triggered post-export mix when the final+resolved motion contains sound cues. Video gain and limiting never enter+`animations.json`.**Production sequence**: after the final SVG check, validate any pre-SVGnarration against the visible pages; ordinary draft-source runs instead use the@@ -211,15 +214,24 @@ object-sync claim before the narrated PPTX and MP4.## 5. Delivery Boundary-**Canonical artifact**: the editable PPTX remains canonical. `generate-audio` owns provider/voice/rate-selection, page audio/SRT generation, semantic narration timing, narrated PPTX-export, and optional native PowerPoint video export.+**Canonical artifact**: the editable PPTX remains canonical. `generate-audio`+owns provider/voice/rate selection, page audio/SRT generation, semantic+narration timing, narrated PPTX export, optional native PowerPoint video export,+and the triggered sound-effects mix for direct MP4 delivery.**Conditional MP4**: run `powerpoint_video.py --check` only when MP4 delivery isselected. If native Windows PowerPoint export is unavailable, keep the narratedPPTX as the successful upstream artifact; do not substitute screenshots, HTML,or a third-party renderer and call it equivalent.+**Hard rule — native MP4 sound boundary**: PowerPoint's native encoder is the+visual-animation and narration source, but it does not reliably include+transition or object-animation sounds in the MP4 audio track. When the final+narrated trace and PPTX contain sound cues, treat that native MP4 as a raw+intermediate and run `video_sound_mix.py`; only its verified mixed MP4 is the+sound-enabled video deliverable. Keep the native cue configuration in the+canonical PPTX.+**Current boundary**: importing and automatically splitting one long finishedrecording is unsupported. Require page-level audio or an explicit page/time map;otherwise deliver the designed deck and frozen notes without claiming audiodiff --git a/skills/ppt-master/scripts/narration_sync.py b/skills/ppt-master/scripts/narration_sync.pyindex cf8ea2de..35bca053 100644--- a/skills/ppt-master/scripts/narration_sync.py+++ b/skills/ppt-master/scripts/narration_sync.py@@ -22,8 +22,8 @@ Examples:--pptx exports/demo.pptx --video exports/demo.mp4 --forceDependencies:- ffprobe for animation-window validation. Optional exported-video calibration- additionally requires ffmpeg and numpy.+ ffprobe for animation-window validation. Optional exported-video timeline+ calibration additionally requires ffmpeg and numpy."""from __future__ import annotations@@ -175,6 +175,31 @@ class PowerPointTiming:advance_ms: int+@dataclass(frozen=True)+class VideoSlideTiming:+ """One slide mapped from the PPTX clock to an exported-video clock."""++ slide_name: str+ transition_ms: int+ narration_delay_ms: int+ advance_ms: int+ powerpoint_slide_start_ms: int+ powerpoint_narration_start_ms: int+ video_slide_start_ms: int+ video_narration_start_ms: int+ adjustment_ms: int+ correlation: float+ audio_path: Path+++@dataclass(frozen=True)+class VideoTimelineCalibration:+ """Page-level calibration between one narrated PPTX and exported video."""++ slides: tuple[VideoSlideTiming, ...]+ powerpoint_timeline_ms: int++def _timestamp_to_ms(value: str) -> int:hours_text, minutes_text, remainder = value.split(":")seconds_text, milliseconds_text = remainder.split(",")@@ -1361,7 +1386,8 @@ def rebuild_animations()-def _presentation_slide_members(package: zipfile.ZipFile) -> list[str]:+def presentation_slide_members(package: zipfile.ZipFile) -> list[str]:+ """Return slide package members in presentation order."""try:presentation_root = ET.fromstring(package.read("ppt/presentation.xml"))relationships_root = ET.fromstring(@@ -1414,7 +1440,7 @@ def _read_powerpoint_timings() -> list[PowerPointTiming]:timings: list[PowerPointTiming] = []with zipfile.ZipFile(pptx_path) as package:- slide_members = _presentation_slide_members(package)+ slide_members = presentation_slide_members(package)if len(slide_members) != slide_count:raise ValueError(f"Narrated PPTX has {len(slide_members)} slides, "@@ -1481,7 +1507,7 @@ def _require_numpy() -> Any:import numpy as npexcept ImportError as exc:raise RuntimeError(- "Exported-video subtitle calibration requires numpy. "+ "Exported-video timeline calibration requires numpy. ""Install it with: python3 -m pip install numpy") from excreturn np@@ -1569,11 +1595,15 @@ def _best_correlation(search: Any, template: Any) -> tuple[int, float]:def _alignment_template_bounds(fine_envelope: Any,- cues: list[SubtitleCue],+ cues: list[SubtitleCue] | None,) -> tuple[int, int]:duration_ms = len(fine_envelope)- start_ms = min(cues[0].start_ms, max(0, duration_ms - 500))- cue_end_ms = min(cues[-1].end_ms, duration_ms)+ if cues:+ start_ms = min(cues[0].start_ms, max(0, duration_ms - 500))+ cue_end_ms = min(cues[-1].end_ms, duration_ms)+ else:+ start_ms = 0+ cue_end_ms = duration_msend_ms = min(duration_ms, start_ms + _ALIGNMENT_TEMPLATE_MAX_MS)end_ms = min(end_ms, max(start_ms + 1000, cue_end_ms))if end_ms - start_ms < 500:@@ -1586,7 +1616,7 @@ def _locate_audio_start(video_coarse: Any,audio_fine: Any,audio_coarse: Any,- cues: list[SubtitleCue],+ cues: list[SubtitleCue] | None,predicted_start_ms: int,) -> tuple[int, float]:"""Locate one page narration near its predicted exported-video position."""@@ -1638,7 +1668,7 @@ def _locate_audio_start(def _align_audio_starts_to_video(*,slide_names: list[str],- local_cues: dict[str, list[SubtitleCue]],+ local_cues: dict[str, list[SubtitleCue] | None],theoretical_starts: list[int],audio_dir: Path,video_path: Path,@@ -1649,7 +1679,7 @@ def _align_audio_starts_to_video(ffmpeg_path = shutil.which("ffmpeg")if ffmpeg_path is None:raise RuntimeError(- "Exported-video subtitle calibration requires ffmpeg. "+ "Exported-video timeline calibration requires ffmpeg. ""Install ffmpeg and make it available on PATH.")@@ -1662,13 +1692,15 @@ def _align_audio_starts_to_video(audio_path = _find_audio(audio_dir, slide_name)audio_paths.append(audio_path)audio_fine, audio_coarse = _decode_audio_envelopes(audio_path, ffmpeg_path)+ slide_cues = local_cues.get(slide_name)if (- local_cues[slide_name][-1].end_ms+ slide_cues+ and slide_cues[-1].end_ms> len(audio_fine) + _ALIGNMENT_END_TOLERANCE_MS):raise ValueError(f"{slide_name}.srt ends after its narration audio: "- f"cue end={_seconds_from_ms(local_cues[slide_name][-1].end_ms):.3f}s, "+ f"cue end={_seconds_from_ms(slide_cues[-1].end_ms):.3f}s, "f"decoded audio={_seconds_from_ms(len(audio_fine)):.3f}s")if index == 0:@@ -1684,7 +1716,7 @@ def _align_audio_starts_to_video(video_coarse,audio_fine,audio_coarse,- local_cues[slide_name],+ slide_cues,predicted_start_ms,)if correlation < _ALIGNMENT_MIN_CORRELATION:@@ -1697,16 +1729,14 @@ def _align_audio_starts_to_video(raise ValueError(f"Exported-video audio order is invalid at slide {slide_name}")- final_cue_end_ms = (- aligned_start_ms + local_cues[slide_name][-1].end_ms- )+ final_audio_end_ms = aligned_start_ms + len(audio_fine)if (- final_cue_end_ms+ final_audio_end_ms> len(video_fine) + _ALIGNMENT_END_TOLERANCE_MS):raise ValueError(- f"Exported video ends before the final cue on slide {slide_name}: "- f"cue end={_seconds_from_ms(final_cue_end_ms):.3f}s, "+ f"Exported video ends before the narration on slide {slide_name}: "+ f"audio end={_seconds_from_ms(final_audio_end_ms):.3f}s, "f"decoded video audio={_seconds_from_ms(len(video_fine)):.3f}s")aligned_starts.append(aligned_start_ms)@@ -1715,6 +1745,106 @@ def _align_audio_starts_to_video(return aligned_starts, correlations, audio_paths+def calibrate_video_timeline(+ *,+ slide_names: list[str],+ pptx_path: Path,+ audio_dir: Path,+ video_path: Path,+ subtitle_dir: Path | None = None,+) -> VideoTimelineCalibration:+ """Calibrate PPTX slide starts against narration in an exported video.++ Page-local SRT improves the correlation template when available. Audio-only+ narration remains supported by matching each complete page track.+ """+ if not slide_names:+ raise ValueError("Video timeline calibration requires at least one slide")+ if len(set(slide_names)) != len(slide_names):+ raise ValueError("Video timeline calibration slide names must be unique")++ timings = _read_powerpoint_timings(pptx_path, len(slide_names))+ theoretical_starts, timeline_ms = _powerpoint_audio_starts(timings)+ local_cues: dict[str, list[SubtitleCue] | None] = {}+ for slide_name in slide_names:+ subtitle_path = (+ subtitle_dir / f"{slide_name}.srt"+ if subtitle_dir is not None+ else None+ )+ local_cues[slide_name] = (+ _parse_srt(subtitle_path)+ if subtitle_path is not None and subtitle_path.is_file()+ else None+ )++ aligned_starts, correlations, audio_paths = _align_audio_starts_to_video(+ slide_names=slide_names,+ local_cues=local_cues,+ theoretical_starts=theoretical_starts,+ audio_dir=audio_dir,+ video_path=video_path,+ )++ slides: list[VideoSlideTiming] = []+ powerpoint_slide_start_ms = 0+ previous_video_slide_start_ms = -1+ for (+ slide_name,+ timing,+ powerpoint_narration_start_ms,+ video_narration_start_ms,+ correlation,+ audio_path,+ ) in zip(+ slide_names,+ timings,+ theoretical_starts,+ aligned_starts,+ correlations,+ audio_paths,+ ):+ raw_video_slide_start_ms = (+ video_narration_start_ms+ - timing.transition_ms+ - timing.narration_delay_ms+ )+ if raw_video_slide_start_ms < -_ALIGNMENT_END_TOLERANCE_MS:+ raise ValueError(+ f"Exported-video calibration places slide {slide_name} before "+ f"the video start: {raw_video_slide_start_ms}ms"+ )+ video_slide_start_ms = max(0, raw_video_slide_start_ms)+ if video_slide_start_ms <= previous_video_slide_start_ms:+ raise ValueError(+ f"Exported-video slide order is invalid at {slide_name}"+ )+ slides.append(+ VideoSlideTiming(+ slide_name=slide_name,+ transition_ms=timing.transition_ms,+ narration_delay_ms=timing.narration_delay_ms,+ advance_ms=timing.advance_ms,+ powerpoint_slide_start_ms=powerpoint_slide_start_ms,+ powerpoint_narration_start_ms=powerpoint_narration_start_ms,+ video_slide_start_ms=video_slide_start_ms,+ video_narration_start_ms=video_narration_start_ms,+ adjustment_ms=(+ video_narration_start_ms - powerpoint_narration_start_ms+ ),+ correlation=correlation,+ audio_path=audio_path,+ )+ )+ previous_video_slide_start_ms = video_slide_start_ms+ powerpoint_slide_start_ms += timing.transition_ms + timing.advance_ms++ return VideoTimelineCalibration(+ slides=tuple(slides),+ powerpoint_timeline_ms=timeline_ms,+ )++def _merge_subtitles_result(project_path: Path,*,@@ -1754,13 +1884,21 @@ def _merge_subtitles_result(audio_starts = theoretical_startselse:resolved_audio_dir = audio_dir or project_path / "audio"- audio_starts, correlations, audio_paths = _align_audio_starts_to_video(+ calibration = calibrate_video_timeline(slide_names=slide_names,- local_cues=local_cues,- theoretical_starts=theoretical_starts,+ pptx_path=pptx_path,audio_dir=resolved_audio_dir,video_path=video_path,+ subtitle_dir=subtitle_dir,)+ if calibration.powerpoint_timeline_ms != timeline_ms:+ raise ValueError("Video calibration and subtitle timelines differ")+ audio_starts = [+ slide.video_narration_start_ms+ for slide in calibration.slides+ ]+ correlations = [slide.correlation for slide in calibration.slides]+ audio_paths = [slide.audio_path for slide in calibration.slides]_reject_output_alias(output_path,audio_paths,diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.jsonindex 88369a6c..fba57709 100644--- a/skills/ppt-master/scripts/prompt_audit_manifest.json+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json@@ -373,7 +373,7 @@"files": ["skills/ppt-master/scripts/docs/visualization-recall.md"],- "max_tokens": 105000+ "max_tokens": 120000},"route.generate.planning-image": {"description": "Generate-PPTX planning context after a non-none image source is proposed or confirmed, including the compact layout math and vocabulary.",@@ -825,7 +825,7 @@"files": ["skills/ppt-master/references/video-design.md"],- "max_tokens": 2500+ "max_tokens": 3250},"stage.generate.refine-spec": {"description": "Explicit post-confirmation spec refinement runbook.",@@ -896,7 +896,7 @@"files": ["skills/ppt-master/references/animations.md"],- "max_tokens": 9000+ "max_tokens": 11000},"stage.shared.generate-audio": {"description": "Shared narration-audio stage.",@@ -904,7 +904,7 @@"files": ["skills/ppt-master/workflows/stages/generate-audio.md"],- "max_tokens": 7000+ "max_tokens": 8000},"governance.failure-recovery": {"description": "Global stop, retry, and resume policy.",diff --git a/skills/ppt-master/scripts/video_sound_mix.py b/skills/ppt-master/scripts/video_sound_mix.pynew file mode 100644index 00000000..69c401bf--- /dev/null+++ b/skills/ppt-master/scripts/video_sound_mix.py@@ -0,0 +1,1624 @@+#!/usr/bin/env python3+"""+PPT Master - Video Sound Mix++Recover transition and object-animation sound cues from the final narrated+PPTX, calibrate them to a PowerPoint-exported video, render an independent SFX+stem, and mix that stem with the video's narration track.+See workflows/stages/generate-audio.md for the owning delivery stage.++Usage:+ python3 scripts/video_sound_mix.py <project_path> --pptx <pptx> \+ --trace <trace.json> --video <raw.mp4> [options]++Examples:+ python3 scripts/video_sound_mix.py projects/demo \+ --pptx exports/demo_narrated.pptx \+ --trace validation/demo_narrated.trace.json \+ --video exports/demo_raw.mp4 --force++Dependencies:+ ffmpeg, ffprobe, and numpy+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import os+import re+import shutil+import subprocess+import sys+import tempfile+import zipfile+from dataclasses import dataclass+from fractions import Fraction+from pathlib import Path+from typing import Any+from xml.etree import ElementTree as ET++_SCRIPTS_DIR = Path(__file__).resolve().parent+if str(_SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(_SCRIPTS_DIR))++from console_encoding import configure_utf8_stdio # noqa: E402+from narration_sync import ( # noqa: E402+ VideoTimelineCalibration,+ calibrate_video_timeline,+ presentation_slide_members,+)+from pptx_animations import read_slide_animation_sequence # noqa: E402+from pptx_opc_validation import ( # noqa: E402+ canonical_opc_part_path,+ resolve_internal_opc_target,+)+from pptx_transitions import ( # noqa: E402+ AUDIO_REL_TYPE,+ read_slide_transition_xml,+)++configure_utf8_stdio()+++_PACKAGE_REL_NS = (+ "http://schemas.openxmlformats.org/package/2006/relationships"+)+_RELATIONSHIP_TAG = f"{{{_PACKAGE_REL_NS}}}Relationship"+_DEFAULT_TRANSITION_GAIN_DB = -9.1+_DEFAULT_ANIMATION_GAIN_DB = -12.0+_DEFAULT_LIMITER_DBFS = -1.0+_OUTPUT_SAMPLE_RATE = 48_000+_OUTPUT_AUDIO_BITRATE = "192k"+_START_TIME_TOLERANCE_MS = 1+_VERIFICATION_SAMPLE_RATE = 8000+_MIN_VERIFICATION_WINDOW_SAMPLES = 2+_MIN_SOUND_MIX_CORRELATION = 0.20+++@dataclass(frozen=True)+class SoundCue:+ """One resolved PPTX sound cue placed on the exported-video timeline."""++ kind: str+ slide_num: int+ slide_name: str+ row_index: int | None+ shape_id: int | None+ group_id: str | None+ relationship_id: str+ sound_name: str+ package_part: str+ media_sha256: str+ media_path: Path+ source_duration_ms: int+ powerpoint_time_ms: int+ video_time_ms: int+ gain_db: float+++@dataclass(frozen=True)+class SoundMixResult:+ """Published files and cue count from one video sound mix."""++ output_path: Path+ stem_path: Path+ report_path: Path+ cue_count: int+ verification_correlation: float+ true_peak_dbfs: float+++def _read_json_object(path: Path, label: str) -> dict[str, Any]:+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise ValueError(f"{label} is not valid JSON: {path}: {exc}") from exc+ if not isinstance(value, dict):+ raise ValueError(f"{label} must contain one JSON object: {path}")+ return value+++def _sha256_path(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _project_input_path(project_path: Path, value: str) -> Path:+ path = Path(value).expanduser()+ return (path if path.is_absolute() else project_path / path).resolve()+++def _project_output_path(+ project_path: Path,+ value: str | None,+ default: Path,+) -> Path:+ path = Path(value).expanduser() if value else default+ return (path if path.is_absolute() else project_path / path).resolve()+++def _require_tool(name: str) -> str:+ path = shutil.which(name)+ if path is None:+ raise RuntimeError(+ f"Video sound mixing requires {name} on PATH. Install ffmpeg "+ "and make both ffmpeg and ffprobe available."+ )+ return path+++def _run_command(command: list[str], label: str) -> subprocess.CompletedProcess[str]:+ result = subprocess.run(+ command,+ capture_output=True,+ check=False,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ if result.returncode != 0:+ details = result.stderr.strip() or result.stdout.strip()+ raise RuntimeError(f"{label} failed:\n{details}")+ return result+++def _probe_media(path: Path, ffprobe_path: str) -> dict[str, Any]:+ result = _run_command(+ [+ ffprobe_path,+ "-v",+ "error",+ "-show_entries",+ (+ "format=duration,start_time:"+ "stream=index,codec_type,codec_name,time_base,start_pts,"+ "start_time,duration_ts,duration,sample_rate,channels,"+ "width,height,avg_frame_rate"+ ),+ "-of",+ "json",+ str(path),+ ],+ f"ffprobe inspection for {path}",+ )+ try:+ payload = json.loads(result.stdout)+ except json.JSONDecodeError as exc:+ raise RuntimeError(f"ffprobe returned invalid JSON for {path}") from exc+ if not isinstance(payload, dict):+ raise RuntimeError(f"ffprobe returned an invalid payload for {path}")+ return payload+++def _duration_ms(probe: dict[str, Any], label: str) -> int:+ format_value = probe.get("format")+ raw_duration = (+ format_value.get("duration")+ if isinstance(format_value, dict)+ else None+ )+ try:+ duration = float(raw_duration)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"Unable to read {label} duration with ffprobe") from exc+ if not math.isfinite(duration) or duration <= 0:+ raise ValueError(f"{label} duration must be positive and finite")+ return int(round(duration * 1000))+++def _stream_duration_ms(+ stream: dict[str, Any],+ *,+ fallback_ms: int,+) -> int:+ try:+ duration = float(stream.get("duration"))+ except (TypeError, ValueError):+ return fallback_ms+ if not math.isfinite(duration) or duration <= 0:+ return fallback_ms+ return int(round(duration * 1000))+++def _stream_start_ms(stream: dict[str, Any]) -> int:+ try:+ start = float(stream.get("start_time", 0))+ except (TypeError, ValueError):+ return 0+ if not math.isfinite(start):+ return 0+ return int(round(start * 1000))+++def _frame_duration_ms(stream: dict[str, Any]) -> float:+ value = stream.get("avg_frame_rate")+ if not isinstance(value, str) or "/" not in value:+ return 1000 / 30+ numerator_text, denominator_text = value.split("/", 1)+ try:+ numerator = float(numerator_text)+ denominator = float(denominator_text)+ except ValueError:+ return 1000 / 30+ if numerator <= 0 or denominator <= 0:+ return 1000 / 30+ return 1000 * denominator / numerator+++def _stream_timing_signature(stream: dict[str, Any]) -> dict[str, object]:+ """Return the packet-clock fields that must survive video stream copy."""+ signature: dict[str, object] = {}+ for key in ("time_base", "start_pts", "duration_ts"):+ value = stream.get(key)+ if value is None:+ raise ValueError(f"Video stream is missing {key}")+ signature[key] = value+ return signature+++def _audio_sample_count(stream: dict[str, Any]) -> int:+ """Resolve an audio stream duration to exact samples from its time base."""+ try:+ sample_rate = int(stream.get("sample_rate"))+ duration_ts = int(stream.get("duration_ts"))+ time_base = Fraction(str(stream.get("time_base")))+ except (TypeError, ValueError, ZeroDivisionError) as exc:+ raise ValueError("Unable to read exact audio sample count") from exc+ samples = duration_ts * time_base * sample_rate+ if samples.denominator != 1:+ raise ValueError(+ "Audio duration does not resolve to a whole number of samples"+ )+ return samples.numerator+++def _target_sample_count(duration_ms: int) -> int:+ return int(round(duration_ms * _OUTPUT_SAMPLE_RATE / 1000))+++def _streams(probe: dict[str, Any], kind: str) -> list[dict[str, Any]]:+ raw_streams = probe.get("streams")+ if not isinstance(raw_streams, list):+ return []+ return [+ stream+ for stream in raw_streams+ if isinstance(stream, dict) and stream.get("codec_type") == kind+ ]+++def _stream_hash(path: Path, selector: str, ffmpeg_path: str) -> str:+ result = _run_command(+ [+ ffmpeg_path,+ "-v",+ "error",+ "-i",+ str(path),+ "-map",+ selector,+ "-c",+ "copy",+ "-f",+ "hash",+ "-hash",+ "sha256",+ "-",+ ],+ f"stream hash for {path}",+ )+ match = re.search(r"SHA256=([0-9a-fA-F]{64})", result.stdout)+ if match is None:+ raise RuntimeError(f"Unable to parse stream hash for {path}")+ return match.group(1).lower()+++def _maximum_volume_db(path: Path, ffmpeg_path: str) -> float | None:+ result = subprocess.run(+ [+ ffmpeg_path,+ "-nostdin",+ "-hide_banner",+ "-i",+ str(path),+ "-map",+ "0:a:0",+ "-af",+ "volumedetect",+ "-f",+ "null",+ "-",+ ],+ capture_output=True,+ check=False,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"Volume inspection failed for {path}:\n{result.stderr.strip()}"+ )+ match = re.search(r"max_volume:\s*(-?inf|[-+]?\d+(?:\.\d+)?)\s*dB", result.stderr)+ if match is None:+ raise RuntimeError(f"Unable to read maximum volume for {path}")+ if match.group(1) == "-inf":+ return None+ return float(match.group(1))+++def _true_peak_dbfs(path: Path, ffmpeg_path: str) -> float | None:+ result = subprocess.run(+ [+ ffmpeg_path,+ "-nostdin",+ "-hide_banner",+ "-nostats",+ "-i",+ str(path),+ "-map",+ "0:a:0",+ "-af",+ "ebur128=peak=true",+ "-f",+ "null",+ "-",+ ],+ capture_output=True,+ check=False,+ text=True,+ encoding="utf-8",+ errors="replace",+ )+ if result.returncode != 0:+ raise RuntimeError(+ f"True-peak inspection failed for {path}:\n{result.stderr.strip()}"+ )+ matches = re.findall(+ r"Peak:\s*(-?inf|[-+]?\d+(?:\.\d+)?)\s*dBFS",+ result.stderr,+ )+ if not matches:+ raise RuntimeError(f"Unable to read true peak for {path}")+ if matches[-1] == "-inf":+ return None+ return float(matches[-1])+++def _decode_audio_f32(path: Path, ffmpeg_path: str) -> Any:+ try:+ import numpy as np+ except ImportError as exc:+ raise RuntimeError(+ "Video sound verification requires numpy. Install it with: "+ "python3 -m pip install numpy"+ ) from exc+ result = subprocess.run(+ [+ ffmpeg_path,+ "-v",+ "error",+ "-i",+ str(path),+ "-map",+ "0:a:0",+ "-vn",+ "-ac",+ "1",+ "-ar",+ str(_VERIFICATION_SAMPLE_RATE),+ "-f",+ "f32le",+ "-",+ ],+ capture_output=True,+ check=False,+ )+ if result.returncode != 0:+ details = result.stderr.decode("utf-8", errors="replace").strip()+ raise RuntimeError(f"Unable to decode audio for verification: {path}\n{details}")+ return np.frombuffer(result.stdout, dtype="<f4").astype(np.float64)+++def _sound_mix_correlation(+ *,+ raw_video_path: Path,+ mixed_video_path: Path,+ stem_path: Path,+ cues: list[SoundCue],+ duration_ms: int,+ ffmpeg_path: str,+) -> float:+ """Correlate the added final-audio component with the rendered SFX stem."""+ try:+ import numpy as np+ except ImportError as exc:+ raise RuntimeError(+ "Video sound verification requires numpy. Install it with: "+ "python3 -m pip install numpy"+ ) from exc++ target_samples = int(round(duration_ms * _VERIFICATION_SAMPLE_RATE / 1000))+ decoded = [+ _decode_audio_f32(path, ffmpeg_path)+ for path in (raw_video_path, mixed_video_path, stem_path)+ ]+ arrays: list[Any] = []+ for samples in decoded:+ if len(samples) < target_samples:+ samples = np.pad(samples, (0, target_samples - len(samples)))+ arrays.append(samples[:target_samples])+ raw_audio, mixed_audio, stem_audio = arrays++ cue_mask = np.zeros(target_samples, dtype=bool)+ for cue in cues:+ start = int(round(cue.video_time_ms * _VERIFICATION_SAMPLE_RATE / 1000))+ end = int(+ round(+ (cue.video_time_ms + cue.source_duration_ms)+ * _VERIFICATION_SAMPLE_RATE+ / 1000+ )+ )+ cue_mask[max(0, start):min(target_samples, end)] = True+ cue_indices = np.flatnonzero(cue_mask)+ if len(cue_indices) < _MIN_VERIFICATION_WINDOW_SAMPLES:+ raise RuntimeError("SFX cue windows are too short for mix verification")++ background = ~cue_mask+ raw_background = raw_audio[background]+ mixed_background = mixed_audio[background]+ denominator = float(np.dot(raw_background, raw_background))+ narration_scale = (+ float(np.dot(mixed_background, raw_background)) / denominator+ if denominator > 1e-12+ else 1.0+ )+ added_audio = mixed_audio - narration_scale * raw_audio++ best_correlation = -1.0+ maximum_lag = max(1, _VERIFICATION_SAMPLE_RATE // 200)+ for lag in range(-maximum_lag, maximum_lag + 1):+ shifted_indices = cue_indices + lag+ valid = (shifted_indices >= 0) & (shifted_indices < target_samples)+ if not valid.any():+ continue+ observed = added_audio[shifted_indices[valid]]+ expected = stem_audio[cue_indices[valid]]+ observed = observed - observed.mean()+ expected = expected - expected.mean()+ norm = float(np.linalg.norm(observed) * np.linalg.norm(expected))+ if norm <= 1e-12:+ continue+ correlation = float(np.dot(observed, expected) / norm)+ best_correlation = max(best_correlation, correlation)+ if best_correlation < _MIN_SOUND_MIX_CORRELATION:+ raise RuntimeError(+ "Mixed-video audio does not reliably contain the rendered SFX stem: "+ f"correlation={best_correlation:.3f}, "+ f"required>={_MIN_SOUND_MIX_CORRELATION:.2f}"+ )+ return best_correlation+++def _trace_slides(trace: dict[str, Any]) -> tuple[list[dict[str, Any]], list[str]]:+ raw_slides = trace.get("slides")+ if not isinstance(raw_slides, list) or not raw_slides:+ raise ValueError("Conversion trace must contain a non-empty slides array")+ slide_count = trace.get("slide_count")+ if slide_count != len(raw_slides):+ raise ValueError(+ "Conversion trace slide_count does not match its slides array"+ )++ slides: list[dict[str, Any]] = []+ slide_names: list[str] = []+ for expected_number, raw_slide in enumerate(raw_slides, 1):+ if not isinstance(raw_slide, dict):+ raise ValueError(+ f"Conversion trace slide {expected_number} must be an object"+ )+ if raw_slide.get("slide_num") != expected_number:+ raise ValueError(+ "Conversion trace slides must be numbered consecutively from 1"+ )+ raw_svg = raw_slide.get("svg")+ if not isinstance(raw_svg, str) or not raw_svg.strip():+ raise ValueError(+ f"Conversion trace slide {expected_number} has no SVG path"+ )+ slide_name = Path(raw_svg).stem+ if not slide_name:+ raise ValueError(+ f"Conversion trace slide {expected_number} has an invalid SVG path"+ )+ slides.append(raw_slide)+ slide_names.append(slide_name)+ if len(set(slide_names)) != len(slide_names):+ raise ValueError("Conversion trace slide names must be unique")+ return slides, slide_names+++def _shape_group_ids(trace_slide: dict[str, Any]) -> dict[int, str]:+ events = trace_slide.get("events")+ if not isinstance(events, list):+ return {}+ mapping: dict[int, str] = {}+ for event in events:+ if not isinstance(event, dict):+ continue+ shape_id = event.get("shape_id")+ group_id = event.get("id")+ if (+ isinstance(shape_id, int)+ and not isinstance(shape_id, bool)+ and isinstance(group_id, str)+ and group_id+ ):+ mapping[shape_id] = group_id+ return mapping+++def _package_part_map(package: zipfile.ZipFile) -> dict[str, str]:+ mapping: dict[str, str] = {}+ for member in package.namelist():+ key = canonical_opc_part_path(member)+ if key is None:+ continue+ prior = mapping.get(key)+ if prior is not None and prior != member:+ raise ValueError(+ "PPTX contains OPC-equivalent duplicate package parts: "+ f"{prior!r}, {member!r}"+ )+ mapping[key] = member+ return mapping+++def _relationships_part(slide_part: str) -> str:+ slide_path = Path(slide_part)+ return (+ slide_path.parent / "_rels" / f"{slide_path.name}.rels"+ ).as_posix()+++def _slide_relationships(+ package: zipfile.ZipFile,+ rels_part: str,+) -> dict[str, ET.Element]:+ try:+ root = ET.fromstring(package.read(rels_part))+ except KeyError as exc:+ raise ValueError(f"PPTX is missing slide relationships: {rels_part}") from exc+ except ET.ParseError as exc:+ raise ValueError(f"Invalid slide relationships XML: {rels_part}") from exc+ relationships: dict[str, ET.Element] = {}+ for relationship in root.findall(_RELATIONSHIP_TAG):+ relationship_id = relationship.get("Id")+ if not relationship_id:+ continue+ if relationship_id in relationships:+ raise ValueError(+ f"Duplicate relationship id {relationship_id!r} in {rels_part}"+ )+ relationships[relationship_id] = relationship+ return relationships+++def _extract_sound(+ *,+ package: zipfile.ZipFile,+ package_parts: dict[str, str],+ relationships: dict[str, ET.Element],+ rels_part: str,+ relationship_id: str,+ temp_dir: Path,+ ffprobe_path: str,+ extracted: dict[str, tuple[str, str, Path, int]],+) -> tuple[str, str, Path, int]:+ relationship = relationships.get(relationship_id)+ if relationship is None:+ raise ValueError(+ f"PPTX sound relationship is missing: {rels_part}#{relationship_id}"+ )+ if relationship.get("Type") != AUDIO_REL_TYPE:+ raise ValueError(+ f"PPTX sound relationship is not audio: {rels_part}#{relationship_id}"+ )+ if relationship.get("TargetMode", "Internal") == "External":+ raise ValueError(+ f"PPTX sound relationship must be internal: {rels_part}#{relationship_id}"+ )+ target = relationship.get("Target") or ""+ target_key = resolve_internal_opc_target(rels_part, target)+ if target_key is None:+ raise ValueError(+ f"PPTX sound relationship target is invalid: {rels_part}#{relationship_id}"+ )+ package_part = package_parts.get(target_key)+ if package_part is None:+ raise ValueError(+ f"PPTX sound relationship target is missing: {target!r}"+ )+ cached = extracted.get(package_part)+ if cached is not None:+ return cached++ payload = package.read(package_part)+ media_sha256 = hashlib.sha256(payload).hexdigest()+ extension = Path(package_part).suffix.lower()+ if extension not in {".m4a", ".mp3", ".wav"}:+ raise ValueError(+ f"PPTX animation sound uses an unsupported media type: {package_part}"+ )+ media_path = temp_dir / f"{media_sha256}{extension}"+ media_path.write_bytes(payload)+ source_duration_ms = _duration_ms(+ _probe_media(media_path, ffprobe_path),+ f"PPTX sound {package_part}",+ )+ resolved = (package_part, media_sha256, media_path, source_duration_ms)+ extracted[package_part] = resolved+ return resolved+++def _require_equal(actual: object, expected: object, field: str) -> None:+ if actual != expected:+ raise ValueError(+ f"Final narrated trace does not match the PPTX at {field}: "+ f"trace={actual!r}, pptx={expected!r}"+ )+++def _resolve_sound_cues(+ *,+ pptx_path: Path,+ trace_slides: list[dict[str, Any]],+ calibration: VideoTimelineCalibration,+ transition_gain_db: float,+ animation_gain_db: float,+ video_duration_ms: int,+ temp_dir: Path,+ ffprobe_path: str,+) -> list[SoundCue]:+ cues: list[SoundCue] = []+ extracted: dict[str, tuple[str, str, Path, int]] = {}+ with zipfile.ZipFile(pptx_path) as package:+ slide_members = presentation_slide_members(package)+ if len(slide_members) != len(trace_slides):+ raise ValueError(+ f"Final narrated PPTX has {len(slide_members)} slides, but "+ f"the trace has {len(trace_slides)}"+ )+ package_parts = _package_part_map(package)++ for slide_num, (slide_part, trace_slide, calibrated) in enumerate(+ zip(slide_members, trace_slides, calibration.slides),+ 1,+ ):+ slide_xml = package.read(slide_part)+ transition = read_slide_transition_xml(slide_xml)+ animation = read_slide_animation_sequence(+ slide_xml,+ require_supported_effects=True,+ )+ trace_motion = trace_slide.get("motion")+ trace_animation = trace_slide.get("animation")+ if not isinstance(trace_motion, dict) or not isinstance(+ trace_animation, dict+ ):+ raise ValueError(+ f"Conversion trace slide {slide_num} lacks resolved motion"+ )++ _require_equal(+ trace_motion.get("duration_ms"),+ transition.duration_ms,+ f"slide {slide_num} transition duration",+ )+ _require_equal(+ trace_motion.get("advance_after_ms"),+ transition.advance_after_ms,+ f"slide {slide_num} recorded advance",+ )+ _require_equal(+ trace_motion.get("sound_relationship_id"),+ transition.sound_relationship_id,+ f"slide {slide_num} transition sound relationship",+ )+ _require_equal(+ trace_motion.get("sound_name"),+ transition.sound_name,+ f"slide {slide_num} transition sound name",+ )+ _require_equal(+ trace_motion.get("fallback_sound_relationship_id"),+ transition.fallback_sound_relationship_id,+ f"slide {slide_num} fallback transition sound relationship",+ )+ _require_equal(+ trace_motion.get("fallback_sound_name"),+ transition.fallback_sound_name,+ f"slide {slide_num} fallback transition sound name",+ )+ if transition.fallback_sound_relationship_id not in {+ None,+ transition.sound_relationship_id,+ }:+ raise ValueError(+ f"Slide {slide_num} transition primary and fallback "+ "branches reference different sounds"+ )++ raw_rows = trace_animation.get("rows")+ if not isinstance(raw_rows, list):+ raise ValueError(+ f"Conversion trace slide {slide_num} animation rows are invalid"+ )+ if len(raw_rows) != len(animation.rows):+ raise ValueError(+ f"Final narrated trace has {len(raw_rows)} animation rows "+ f"on slide {slide_num}; PPTX has {len(animation.rows)}"+ )+ for row_index, (raw_row, actual_row) in enumerate(+ zip(raw_rows, animation.rows),+ 1,+ ):+ if not isinstance(raw_row, dict):+ raise ValueError(+ f"Conversion trace slide {slide_num} row {row_index} "+ "must be an object"+ )+ for key, expected in (+ ("shape_id", actual_row.shape_id),+ ("offset_ms", actual_row.offset_ms),+ ("trigger", actual_row.trigger),+ ("sound_relationship_id", actual_row.sound_relationship_id),+ ("sound_name", actual_row.sound_name),+ ):+ _require_equal(+ raw_row.get(key),+ expected,+ f"slide {slide_num} animation row {row_index} {key}",+ )++ sound_relationship_ids = {+ relationship_id+ for relationship_id in (+ transition.sound_relationship_id,+ *(+ row.sound_relationship_id+ for row in animation.rows+ ),+ )+ if relationship_id is not None+ }+ relationships: dict[str, ET.Element] = {}+ rels_part = _relationships_part(slide_part)+ if sound_relationship_ids:+ relationships = _slide_relationships(package, rels_part)++ group_ids = _shape_group_ids(trace_slide)+ if transition.sound_relationship_id is not None:+ package_part, media_sha256, media_path, source_duration_ms = (+ _extract_sound(+ package=package,+ package_parts=package_parts,+ relationships=relationships,+ rels_part=rels_part,+ relationship_id=transition.sound_relationship_id,+ temp_dir=temp_dir,+ ffprobe_path=ffprobe_path,+ extracted=extracted,+ )+ )+ cues.append(+ SoundCue(+ kind="transition",+ slide_num=slide_num,+ slide_name=calibrated.slide_name,+ row_index=None,+ shape_id=None,+ group_id=None,+ relationship_id=transition.sound_relationship_id,+ sound_name=transition.sound_name or Path(package_part).name,+ package_part=package_part,+ media_sha256=media_sha256,+ media_path=media_path,+ source_duration_ms=source_duration_ms,+ powerpoint_time_ms=calibrated.powerpoint_slide_start_ms,+ video_time_ms=calibrated.video_slide_start_ms,+ gain_db=transition_gain_db,+ )+ )++ for row_index, row in enumerate(animation.rows, 1):+ if row.sound_relationship_id is None:+ continue+ if row.trigger not in {"after-previous", "with-previous"}:+ raise ValueError(+ f"Slide {slide_num} animation row {row_index} uses "+ f"{row.trigger!r}; video sound timing requires a "+ "click-free row"+ )+ package_part, media_sha256, media_path, source_duration_ms = (+ _extract_sound(+ package=package,+ package_parts=package_parts,+ relationships=relationships,+ rels_part=rels_part,+ relationship_id=row.sound_relationship_id,+ temp_dir=temp_dir,+ ffprobe_path=ffprobe_path,+ extracted=extracted,+ )+ )+ powerpoint_time_ms = (+ calibrated.powerpoint_slide_start_ms+ + calibrated.transition_ms+ + row.offset_ms+ )+ video_time_ms = (+ calibrated.video_slide_start_ms+ + calibrated.transition_ms+ + row.offset_ms+ )+ cues.append(+ SoundCue(+ kind="animation",+ slide_num=slide_num,+ slide_name=calibrated.slide_name,+ row_index=row_index,+ shape_id=row.shape_id,+ group_id=group_ids.get(row.shape_id),+ relationship_id=row.sound_relationship_id,+ sound_name=row.sound_name or Path(package_part).name,+ package_part=package_part,+ media_sha256=media_sha256,+ media_path=media_path,+ source_duration_ms=source_duration_ms,+ powerpoint_time_ms=powerpoint_time_ms,+ video_time_ms=video_time_ms,+ gain_db=animation_gain_db,+ )+ )++ cues.sort(+ key=lambda cue: (+ cue.video_time_ms,+ cue.slide_num,+ 0 if cue.kind == "transition" else 1,+ cue.row_index or 0,+ )+ )+ if not cues:+ raise ValueError(+ "Final narrated PPTX and trace contain no transition or "+ "object-animation sound cues; use the PowerPoint video directly"+ )+ for cue in cues:+ if cue.video_time_ms < 0 or cue.video_time_ms >= video_duration_ms:+ raise ValueError(+ f"Sound cue falls outside the video: slide {cue.slide_num}, "+ f"time={cue.video_time_ms}ms, video={video_duration_ms}ms"+ )+ cue_end_ms = cue.video_time_ms + cue.source_duration_ms+ if cue_end_ms > video_duration_ms:+ raise ValueError(+ f"Sound cue would be truncated by the video end: slide "+ f"{cue.slide_num}, cue end={cue_end_ms}ms, "+ f"video={video_duration_ms}ms"+ )+ return cues+++def _render_stem(+ *,+ cues: list[SoundCue],+ duration_ms: int,+ output_path: Path,+ ffmpeg_path: str,+) -> None:+ target_samples = _target_sample_count(duration_ms)+ command = [+ ffmpeg_path,+ "-nostdin",+ "-hide_banner",+ "-v",+ "error",+ "-f",+ "lavfi",+ "-i",+ f"anullsrc=r={_OUTPUT_SAMPLE_RATE}:cl=stereo",+ ]+ for cue in cues:+ command.extend(["-i", str(cue.media_path)])++ filters = [+ (+ f"[0:a:0]aformat=sample_fmts=fltp:sample_rates={_OUTPUT_SAMPLE_RATE}:"+ "channel_layouts=stereo,"+ f"atrim=end_sample={target_samples},asetpts=N/SR/TB[base]"+ )+ ]+ labels = ["[base]"]+ for input_index, cue in enumerate(cues, 1):+ label = f"cue{input_index}"+ delay_samples = int(+ round(cue.video_time_ms * _OUTPUT_SAMPLE_RATE / 1000)+ )+ filters.append(+ f"[{input_index}:a:0]aresample={_OUTPUT_SAMPLE_RATE},"+ "aformat=sample_fmts=fltp:"+ f"sample_rates={_OUTPUT_SAMPLE_RATE}:channel_layouts=stereo,"+ f"asetpts=N/SR/TB,volume={cue.gain_db:.3f}dB,"+ f"adelay={delay_samples}S:all=1,"+ f"apad=whole_len={target_samples},"+ f"atrim=end_sample={target_samples}[{label}]"+ )+ labels.append(f"[{label}]")+ filters.append(+ "".join(labels)+ + f"amix=inputs={len(labels)}:duration=first:"+ "dropout_transition=0:normalize=0,"+ f"atrim=end_sample={target_samples},asetpts=N/SR/TB[stem]"+ )+ command.extend(+ [+ "-filter_complex",+ ";".join(filters),+ "-map",+ "[stem]",+ "-c:a",+ "pcm_f32le",+ "-ar",+ str(_OUTPUT_SAMPLE_RATE),+ "-ac",+ "2",+ "-y",+ str(output_path),+ ]+ )+ _run_command(command, "SFX stem render")+++def _mix_video(+ *,+ video_path: Path,+ stem_path: Path,+ duration_ms: int,+ limiter_dbfs: float,+ output_path: Path,+ ffmpeg_path: str,+) -> None:+ target_samples = _target_sample_count(duration_ms)+ limiter_ratio = 10 ** (limiter_dbfs / 20)+ filter_graph = (+ f"[0:a:0]aresample={_OUTPUT_SAMPLE_RATE}:first_pts=0,"+ "aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"asetpts=N/SR/TB,apad=whole_len={target_samples},"+ f"atrim=end_sample={target_samples}[narration];"+ f"[1:a:0]aresample={_OUTPUT_SAMPLE_RATE}:first_pts=0,"+ "aformat=sample_fmts=fltp:channel_layouts=stereo,"+ f"asetpts=N/SR/TB,apad=whole_len={target_samples},"+ f"atrim=end_sample={target_samples}[sfx];"+ "[narration][sfx]amix=inputs=2:duration=first:"+ "dropout_transition=0:normalize=0,"+ f"alimiter=limit={limiter_ratio:.9f}:attack=5:release=50:"+ "level=false:latency=true,"+ f"apad=whole_len={target_samples},"+ f"atrim=end_sample={target_samples},asetpts=N/SR/TB[mixed]"+ )+ _run_command(+ [+ ffmpeg_path,+ "-nostdin",+ "-hide_banner",+ "-v",+ "error",+ "-i",+ str(video_path),+ "-i",+ str(stem_path),+ "-filter_complex",+ filter_graph,+ "-map",+ "0:v:0",+ "-map",+ "[mixed]",+ "-map_metadata",+ "0",+ "-c:v",+ "copy",+ "-c:a",+ "aac",+ "-b:a",+ _OUTPUT_AUDIO_BITRATE,+ "-ar",+ str(_OUTPUT_SAMPLE_RATE),+ "-ac",+ "2",+ "-movflags",+ "+faststart",+ "-y",+ str(output_path),+ ],+ "Narration and SFX mix",+ )+++def _temporary_output(path: Path, suffix: str) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, raw_path = tempfile.mkstemp(+ prefix=f".{path.stem}.",+ suffix=suffix,+ dir=path.parent,+ )+ os.close(descriptor)+ temporary = Path(raw_path)+ temporary.unlink()+ return temporary+++def _publish_outputs(replacements: list[tuple[Path, Path]]) -> None:+ """Publish verified outputs together, restoring prior files on failure."""+ backups: dict[Path, Path] = {}+ published: list[Path] = []+ try:+ for _temporary, destination in replacements:+ if not destination.exists():+ continue+ backup = _temporary_output(destination, f".backup{destination.suffix}")+ os.replace(destination, backup)+ backups[destination] = backup+ for temporary, destination in replacements:+ os.replace(temporary, destination)+ published.append(destination)+ except OSError as exc:+ rollback_errors: list[str] = []+ for destination in reversed(published):+ backup = backups.pop(destination, None)+ try:+ if backup is None:+ destination.unlink(missing_ok=True)+ else:+ os.replace(backup, destination)+ except OSError as rollback_exc:+ rollback_errors.append(f"{destination}: {rollback_exc}")+ for destination, backup in backups.items():+ try:+ os.replace(backup, destination)+ except OSError as rollback_exc:+ rollback_errors.append(f"{destination}: {rollback_exc}")+ if rollback_errors:+ raise RuntimeError(+ "Output publication failed and rollback was incomplete: "+ + "; ".join(rollback_errors)+ ) from exc+ raise+ else:+ for backup in backups.values():+ backup.unlink(missing_ok=True)+++def _cue_report(cue: SoundCue) -> dict[str, Any]:+ return {+ "kind": cue.kind,+ "slide_num": cue.slide_num,+ "slide_name": cue.slide_name,+ "row_index": cue.row_index,+ "shape_id": cue.shape_id,+ "group_id": cue.group_id,+ "relationship_id": cue.relationship_id,+ "sound_name": cue.sound_name,+ "package_part": cue.package_part,+ "media_sha256": cue.media_sha256,+ "source_duration_ms": cue.source_duration_ms,+ "powerpoint_time_ms": cue.powerpoint_time_ms,+ "video_time_ms": cue.video_time_ms,+ "gain_db": cue.gain_db,+ }+++def mix_video_sounds(+ project_path: Path,+ *,+ pptx_path: Path,+ trace_path: Path,+ video_path: Path,+ audio_dir: Path,+ subtitle_dir: Path | None,+ output_path: Path,+ stem_path: Path,+ report_path: Path,+ transition_gain_db: float = _DEFAULT_TRANSITION_GAIN_DB,+ animation_gain_db: float = _DEFAULT_ANIMATION_GAIN_DB,+ limiter_dbfs: float = _DEFAULT_LIMITER_DBFS,+ force: bool = False,+) -> SoundMixResult:+ """Render and publish one calibrated animation-sound video mix."""+ project_path = project_path.resolve()+ pptx_path = pptx_path.resolve()+ trace_path = trace_path.resolve()+ video_path = video_path.resolve()+ audio_dir = audio_dir.resolve()+ subtitle_dir = subtitle_dir.resolve() if subtitle_dir is not None else None+ output_path = output_path.resolve()+ stem_path = stem_path.resolve()+ report_path = report_path.resolve()+ if not project_path.is_dir():+ raise FileNotFoundError(f"Project path does not exist: {project_path}")+ for label, path in (+ ("Final narrated PPTX", pptx_path),+ ("Final narrated conversion trace", trace_path),+ ("Raw PowerPoint video", video_path),+ ):+ if not path.is_file():+ raise FileNotFoundError(f"{label} does not exist: {path}")+ if pptx_path.suffix.lower() != ".pptx":+ raise ValueError(f"Final narrated PPTX must use .pptx: {pptx_path}")+ if video_path.suffix.lower() != ".mp4":+ raise ValueError(f"Raw PowerPoint video must use .mp4: {video_path}")+ if output_path.suffix.lower() != ".mp4":+ raise ValueError(f"Mixed video output must use .mp4: {output_path}")+ if stem_path.suffix.lower() != ".wav":+ raise ValueError(f"SFX stem output must use .wav: {stem_path}")+ if report_path.suffix.lower() != ".json":+ raise ValueError(f"Sound mix report must use .json: {report_path}")++ outputs = [output_path, stem_path, report_path]+ if len(set(outputs)) != len(outputs):+ raise ValueError("Mixed video, SFX stem, and report paths must differ")+ invalid_outputs = [+ path for path in outputs if path.exists() and not path.is_file()+ ]+ if invalid_outputs:+ raise ValueError(+ "Sound mix outputs must be regular files or unused paths: "+ + ", ".join(str(path) for path in invalid_outputs)+ )+ existing = [path for path in outputs if path.exists()]+ if existing and not force:+ raise FileExistsError(+ "Sound mix output already exists; use --force to replace it: "+ + ", ".join(str(path) for path in existing)+ )+ for label, value in (+ ("transition gain", transition_gain_db),+ ("animation gain", animation_gain_db),+ ):+ if not math.isfinite(value) or value < -60 or value > 0:+ raise ValueError(f"{label} must be finite and between -60 and 0 dB")+ if not math.isfinite(limiter_dbfs) or not -12 <= limiter_dbfs < 0:+ raise ValueError("limiter ceiling must be finite, at least -12, and below 0 dBFS")++ ffmpeg_path = _require_tool("ffmpeg")+ ffprobe_path = _require_tool("ffprobe")+ trace = _read_json_object(trace_path, "Conversion trace")+ trace_slides, slide_names = _trace_slides(trace)+ raw_probe = _probe_media(video_path, ffprobe_path)+ raw_format_duration_ms = _duration_ms(raw_probe, "raw PowerPoint video")+ raw_video_streams = _streams(raw_probe, "video")+ raw_audio_streams = _streams(raw_probe, "audio")+ if len(raw_video_streams) != 1 or len(raw_audio_streams) != 1:+ raise ValueError(+ "Raw PowerPoint video must contain one video stream and one "+ "narration audio stream"+ )+ raw_duration_ms = _stream_duration_ms(+ raw_video_streams[0],+ fallback_ms=raw_format_duration_ms,+ )+ raw_video_start_ms = _stream_start_ms(raw_video_streams[0])+ raw_audio_start_ms = _stream_start_ms(raw_audio_streams[0])+ start_delta_ms = abs(raw_video_start_ms - raw_audio_start_ms)+ frame_duration_ms = _frame_duration_ms(raw_video_streams[0])+ if (+ abs(raw_video_start_ms) > _START_TIME_TOLERANCE_MS+ or abs(raw_audio_start_ms) > _START_TIME_TOLERANCE_MS+ or start_delta_ms > _START_TIME_TOLERANCE_MS+ ):+ raise ValueError(+ "Raw PowerPoint video audio and video streams must both start at "+ f"zero: video={raw_video_start_ms}ms, audio={raw_audio_start_ms}ms"+ )+ raw_video_timing = _stream_timing_signature(raw_video_streams[0])++ calibration = calibrate_video_timeline(+ slide_names=slide_names,+ pptx_path=pptx_path,+ audio_dir=audio_dir,+ video_path=video_path,+ subtitle_dir=subtitle_dir,+ )+ protected_inputs = {+ pptx_path,+ trace_path,+ video_path,+ *(slide.audio_path.resolve() for slide in calibration.slides),+ }+ aliases = protected_inputs.intersection(outputs)+ if aliases:+ raise ValueError(+ "Sound mix outputs must not overwrite inputs: "+ + ", ".join(str(path) for path in sorted(aliases))+ )+ temporary_stem = _temporary_output(stem_path, ".wav")+ temporary_video = _temporary_output(output_path, ".mp4")+ temporary_report = _temporary_output(report_path, ".json")+ try:+ with tempfile.TemporaryDirectory(prefix="ppt-master-video-sounds-") as raw_dir:+ cues = _resolve_sound_cues(+ pptx_path=pptx_path,+ trace_slides=trace_slides,+ calibration=calibration,+ transition_gain_db=transition_gain_db,+ animation_gain_db=animation_gain_db,+ video_duration_ms=raw_duration_ms,+ temp_dir=Path(raw_dir),+ ffprobe_path=ffprobe_path,+ )+ _render_stem(+ cues=cues,+ duration_ms=raw_duration_ms,+ output_path=temporary_stem,+ ffmpeg_path=ffmpeg_path,+ )+ stem_peak_db = _maximum_volume_db(temporary_stem, ffmpeg_path)+ if stem_peak_db is None or stem_peak_db < -90:+ raise RuntimeError("Rendered SFX stem is silent")+ _mix_video(+ video_path=video_path,+ stem_path=temporary_stem,+ duration_ms=raw_duration_ms,+ limiter_dbfs=limiter_dbfs,+ output_path=temporary_video,+ ffmpeg_path=ffmpeg_path,+ )++ stem_probe = _probe_media(temporary_stem, ffprobe_path)+ mixed_probe = _probe_media(temporary_video, ffprobe_path)+ stem_duration_ms = _duration_ms(stem_probe, "SFX stem")+ mixed_duration_ms = _duration_ms(mixed_probe, "mixed video")+ mixed_video_streams = _streams(mixed_probe, "video")+ mixed_audio_streams = _streams(mixed_probe, "audio")+ if len(mixed_video_streams) != 1 or len(mixed_audio_streams) != 1:+ raise RuntimeError(+ "Mixed video must contain one copied video stream and one audio stream"+ )+ mixed_video_duration_ms = _stream_duration_ms(+ mixed_video_streams[0],+ fallback_ms=mixed_duration_ms,+ )+ mixed_audio_duration_ms = _stream_duration_ms(+ mixed_audio_streams[0],+ fallback_ms=mixed_duration_ms,+ )+ target_samples = _target_sample_count(raw_duration_ms)+ stem_samples = _audio_sample_count(_streams(stem_probe, "audio")[0])+ if stem_samples != target_samples:+ raise RuntimeError(+ "SFX stem sample count does not match the raw video target: "+ f"stem={stem_samples}, target={target_samples}"+ )+ mixed_video_timing = _stream_timing_signature(mixed_video_streams[0])+ if mixed_video_timing != raw_video_timing:+ raise RuntimeError(+ "Mixed output changed the PowerPoint video packet timeline: "+ f"raw={raw_video_timing!r}, mixed={mixed_video_timing!r}"+ )+ duration_tolerance_ms = max(+ frame_duration_ms,+ 1024 * 1000 / _OUTPUT_SAMPLE_RATE,+ ) + 1+ if abs(mixed_audio_duration_ms - raw_duration_ms) > duration_tolerance_ms:+ raise RuntimeError(+ "Mixed audio duration does not match the raw video: "+ f"audio={mixed_audio_duration_ms}ms, raw={raw_duration_ms}ms"+ )++ raw_video_hash = _stream_hash(video_path, "0:v:0", ffmpeg_path)+ mixed_video_hash = _stream_hash(temporary_video, "0:v:0", ffmpeg_path)+ if raw_video_hash != mixed_video_hash:+ raise RuntimeError("Mixed output changed the PowerPoint video stream")+ raw_audio_hash = _stream_hash(video_path, "0:a:0", ffmpeg_path)+ mixed_audio_hash = _stream_hash(temporary_video, "0:a:0", ffmpeg_path)+ if raw_audio_hash == mixed_audio_hash:+ raise RuntimeError("Mixed output audio is unchanged from the raw video")+ mixed_peak_db = _maximum_volume_db(temporary_video, ffmpeg_path)+ true_peak_dbfs = _true_peak_dbfs(temporary_video, ffmpeg_path)+ if true_peak_dbfs is None or true_peak_dbfs >= 0:+ raise RuntimeError(+ "Mixed-video audio is silent or clips after encoding: "+ f"true_peak={true_peak_dbfs!r} dBFS"+ )+ verification_correlation = _sound_mix_correlation(+ raw_video_path=video_path,+ mixed_video_path=temporary_video,+ stem_path=temporary_stem,+ cues=cues,+ duration_ms=raw_duration_ms,+ ffmpeg_path=ffmpeg_path,+ )++ trace_output = trace.get("output")+ trace_output_matches_pptx = False+ if isinstance(trace_output, str) and trace_output.strip():+ trace_output_matches_pptx = Path(trace_output).expanduser().resolve() == pptx_path++ report = {+ "schema": "ppt-master.video-sound-mix-report.v1",+ "version": 1,+ "status": "passed",+ "inputs": {+ "pptx": {+ "path": str(pptx_path),+ "sha256": _sha256_path(pptx_path),+ },+ "conversion_trace": {+ "path": str(trace_path),+ "sha256": _sha256_path(trace_path),+ "declared_output_matches_pptx": trace_output_matches_pptx,+ },+ "raw_video": {+ "path": str(video_path),+ "sha256": _sha256_path(video_path),+ "duration_ms": raw_duration_ms,+ "video_start_ms": _stream_start_ms(raw_video_streams[0]),+ "audio_start_ms": _stream_start_ms(raw_audio_streams[0]),+ "video_stream_sha256": raw_video_hash,+ "video_timing": raw_video_timing,+ "audio_stream_sha256": raw_audio_hash,+ "video_codec": raw_video_streams[0].get("codec_name"),+ "audio_codec": raw_audio_streams[0].get("codec_name"),+ },+ },+ "settings": {+ "transition_gain_db": transition_gain_db,+ "animation_gain_db": animation_gain_db,+ "limiter_dbfs": limiter_dbfs,+ "mix_normalize": False,+ "ducking": False,+ "background_music": False,+ "sample_rate": _OUTPUT_SAMPLE_RATE,+ "audio_bitrate": _OUTPUT_AUDIO_BITRATE,+ },+ "timeline": {+ "method": "page narration correlation against raw video audio",+ "powerpoint_timeline_ms": calibration.powerpoint_timeline_ms,+ "minimum_correlation": min(+ slide.correlation for slide in calibration.slides+ ),+ "slides": [+ {+ "slide_num": index,+ "slide_name": slide.slide_name,+ "powerpoint_slide_start_ms": slide.powerpoint_slide_start_ms,+ "powerpoint_narration_start_ms": (+ slide.powerpoint_narration_start_ms+ ),+ "video_slide_start_ms": slide.video_slide_start_ms,+ "video_narration_start_ms": slide.video_narration_start_ms,+ "adjustment_ms": slide.adjustment_ms,+ "correlation": slide.correlation,+ }+ for index, slide in enumerate(calibration.slides, 1)+ ],+ },+ "cues": [_cue_report(cue) for cue in cues],+ "outputs": {+ "sfx_stem": {+ "path": str(stem_path),+ "sha256": _sha256_path(temporary_stem),+ "duration_ms": stem_duration_ms,+ "sample_count": stem_samples,+ "maximum_volume_db": stem_peak_db,+ },+ "mixed_video": {+ "path": str(output_path),+ "sha256": _sha256_path(temporary_video),+ "duration_ms": mixed_duration_ms,+ "video_duration_ms": mixed_video_duration_ms,+ "audio_duration_ms": mixed_audio_duration_ms,+ "video_stream_sha256": mixed_video_hash,+ "video_timing": mixed_video_timing,+ "audio_stream_sha256": mixed_audio_hash,+ "video_codec": mixed_video_streams[0].get("codec_name"),+ "audio_codec": mixed_audio_streams[0].get("codec_name"),+ "maximum_volume_db": mixed_peak_db,+ "true_peak_dbfs": true_peak_dbfs,+ },+ },+ "validation": {+ "trace_matches_pptx_motion": True,+ "cue_count": len(cues),+ "stem_non_silent": True,+ "mixed_audio_present": True,+ "video_stream_preserved": True,+ "duration_delta_ms": mixed_video_duration_ms - raw_duration_ms,+ "video_timeline_preserved": True,+ "limiter_applied": True,+ "sound_mix_correlation": verification_correlation,+ "minimum_sound_mix_correlation": _MIN_SOUND_MIX_CORRELATION,+ },+ }+ temporary_report.write_text(+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )++ _publish_outputs(+ [+ (temporary_stem, stem_path),+ (temporary_video, output_path),+ (temporary_report, report_path),+ ]+ )+ finally:+ for temporary in (temporary_stem, temporary_video, temporary_report):+ temporary.unlink(missing_ok=True)++ return SoundMixResult(+ output_path=output_path,+ stem_path=stem_path,+ report_path=report_path,+ cue_count=len(cues),+ verification_correlation=verification_correlation,+ true_peak_dbfs=true_peak_dbfs,+ )+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Mix PPTX transition/object-animation sounds into a "+ "PowerPoint-exported narrated video."+ ),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ parser.add_argument("project_path", help="PPT Master project directory")+ parser.add_argument(+ "--pptx",+ required=True,+ help="Final narrated PPTX; relative paths resolve under the project",+ )+ parser.add_argument(+ "--trace",+ required=True,+ help="Final narrated conversion trace; relative paths resolve under the project",+ )+ parser.add_argument(+ "--video",+ required=True,+ help="Raw PowerPoint-exported video; relative paths resolve under the project",+ )+ parser.add_argument(+ "--audio-dir",+ default=None,+ help="Page narration audio directory; default: <project>/audio",+ )+ parser.add_argument(+ "--subtitle-dir",+ default=None,+ help=(+ "Optional page-local SRT directory used to refine calibration; "+ "default: <project>/audio"+ ),+ )+ parser.add_argument(+ "-o",+ "--output",+ default=None,+ help="Final mixed MP4; default: beside raw video as *_mixed.mp4",+ )+ parser.add_argument(+ "--stem-output",+ default=None,+ help="Independent SFX WAV; default: beside raw video as *_sfx.wav",+ )+ parser.add_argument(+ "--report-output",+ default=None,+ help="Sound mix JSON receipt; default: beside raw video as *_sound_mix.json",+ )+ parser.add_argument(+ "--transition-gain-db",+ type=float,+ default=_DEFAULT_TRANSITION_GAIN_DB,+ help="Transition cue gain in dB (default: -9.1, about 35%%)",+ )+ parser.add_argument(+ "--animation-gain-db",+ type=float,+ default=_DEFAULT_ANIMATION_GAIN_DB,+ help="Object-animation cue gain in dB (default: -12, about 25%%)",+ )+ parser.add_argument(+ "--limiter-dbfs",+ type=float,+ default=_DEFAULT_LIMITER_DBFS,+ help="Final peak limiter ceiling in dBFS (default: -1)",+ )+ parser.add_argument(+ "--force",+ action="store_true",+ help="Replace existing mixed video, stem, and report outputs",+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ project_path = Path(args.project_path).expanduser().resolve()+ if not project_path.is_dir():+ parser.error(f"Project path does not exist: {project_path}")++ pptx_path = _project_input_path(project_path, args.pptx)+ trace_path = _project_input_path(project_path, args.trace)+ video_path = _project_input_path(project_path, args.video)+ audio_dir = _project_output_path(+ project_path,+ args.audio_dir,+ Path("audio"),+ )+ subtitle_dir = _project_output_path(+ project_path,+ args.subtitle_dir,+ Path("audio"),+ )+ default_output = video_path.with_name(f"{video_path.stem}_mixed.mp4")+ default_stem = video_path.with_name(f"{video_path.stem}_sfx.wav")+ default_report = video_path.with_name(f"{video_path.stem}_sound_mix.json")+ output_path = _project_output_path(project_path, args.output, default_output)+ stem_path = _project_output_path(+ project_path,+ args.stem_output,+ default_stem,+ )+ report_path = _project_output_path(+ project_path,+ args.report_output,+ default_report,+ )++ try:+ result = mix_video_sounds(+ project_path,+ pptx_path=pptx_path,+ trace_path=trace_path,+ video_path=video_path,+ audio_dir=audio_dir,+ subtitle_dir=subtitle_dir,+ output_path=output_path,+ stem_path=stem_path,+ report_path=report_path,+ transition_gain_db=args.transition_gain_db,+ animation_gain_db=args.animation_gain_db,+ limiter_dbfs=args.limiter_dbfs,+ force=args.force,+ )+ except (FileNotFoundError, FileExistsError, OSError, RuntimeError, ValueError) as exc:+ print(f"Video sound mix failed: {exc}", file=sys.stderr)+ return 1++ print(+ f"[POSTFLIGHT] status=passed cues={result.cue_count} "+ "video_stream=preserved audio_mix=verified "+ f"correlation={result.verification_correlation:.3f} "+ f"true_peak={result.true_peak_dbfs:.1f}dBFS"+ )+ print(f"[Done] Mixed video: {result.output_path}")+ print(f"[Done] SFX stem: {result.stem_path}")+ print(f"[REPORT] Video sound mix: {result.report_path}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.mdindex 1c27774f..fc2b7318 100644--- a/skills/ppt-master/workflows/generate-pptx.md+++ b/skills/ppt-master/workflows/generate-pptx.md@@ -788,13 +788,19 @@ transition-sound-only choice may create a sparse `animations.json` here withoutactivating object choreography; the exporter never reads`templates/sounds/` directly.+When downstream delivery is a narrated MP4 and the resolved final motion has+sound cues, `generate-audio` owns a final narrated export with+`--conversion-trace`, native PowerPoint raw-video export, and the verified+post-export sound mix. Do not enable conversion trace on every base export only+for this possible downstream branch.+**Success criterion**: The command exits successfully and produces:- `exports/<project_name>_<timestamp>.pptx`- `validation/<project_name>_<timestamp>.report.json` with `passed` or `passed-with-warnings` package/resource postflight status- `validation/<project_name>_<timestamp>.trace.json` when bare `--conversion-trace` is enabled; an explicit `--conversion-trace <path>` uses that destination instead-Before creating the PPTX, the exporter independently requires the current matching `final` quality report; a missing, unreadable, unsupported, non-final, blocking, stale, or unverifiable report exits nonzero. The compact `[POSTFLIGHT]` receipt prints `status`, `quality_gate`, Slide count, warning-category counts, and PPTX/report paths. Disclose material warnings. Do not open or `cat` the complete report on routine success; use targeted field extraction only for failure investigation, an explicit audit request, or information absent from the receipt. A failed report or missing PPTX is not success. Retain its report path for later Generate narration (`deck_motion` handoff).+Before creating the PPTX, the exporter independently requires the current matching `final` quality report; a missing, unreadable, unsupported, non-final, blocking, stale, or unverifiable report exits nonzero. The compact `[POSTFLIGHT]` receipt prints `status`, `quality_gate`, Slide count, warning-category counts, and PPTX/report paths. Disclose material warnings. Do not open or `cat` the complete report on routine success; use targeted field extraction only for failure investigation, an explicit audit request, or information absent from the receipt. A failed report or missing PPTX is not success. Retain its report path for later Generate narration (`deck_motion` handoff). This postflight proves the PPTX package, including native sound relationships; it is not acceptance evidence for a later MP4 audio track. `generate-audio` owns that triggered delivery check.## ✅ Generate PPTX Completediff --git a/skills/ppt-master/workflows/profiles/quick-generate.md b/skills/ppt-master/workflows/profiles/quick-generate.mdindex 8a914e34..bc8c4908 100644--- a/skills/ppt-master/workflows/profiles/quick-generate.md+++ b/skills/ppt-master/workflows/profiles/quick-generate.md@@ -563,7 +563,9 @@ deck-wide-only motion through the selected exporter flags instead.After visual motion is final, sync a selected cue per[`animations.md`](../../references/animations.md) §2.2; otherwise create no-`sounds/`. Sidecars never use `templates/sounds/`.+`sounds/`. Sidecars never use `templates/sounds/`. This configures the native+PPTX only; direct narrated MP4 delivery with resolved cues completes the+verified post-export mix in `generate-audio`.For Quick recorded/self-running/video delivery, complete the mandatory CustomAnimations stage and validate `animations.json` before the base export unless@@ -591,7 +593,8 @@ export options. Notes, Custom Animations, and narration remain off unlessselected by the agent or required by the Quick video rule above. Do not run`finalize_svg.py`. After the validated base export, run[`generate-audio`](../stages/generate-audio.md) when Narration Audio is enabled;-it owns page audio/SRT, narrated PPTX, and optional native MP4.+it owns page audio/SRT, narrated PPTX, the optional raw native MP4, and the+final mixed MP4 when resolved animation sound cues trigger that branch.The exporter requires a passing `final` report whose SVG fingerprint matchesthe current `svg_output/`; missing, blocking, non-final, or stale reports stop@@ -615,5 +618,5 @@ or lock.- [x] Enabled notes were validated/generated and split; enabled custom motion ran through its owning stage- [x] One native PPTX exists under `exports/` or the explicit output path- [x] No Strategist, confirmation, root project Design Spec, or lock artifact was created-- [ ] **Next**: Report the base PPTX and any enabled narrated PPTX/MP4 outputs+- [ ] **Next**: Report the base PPTX and any enabled narrated PPTX/raw or mixed MP4 outputs```diff --git a/skills/ppt-master/workflows/stages/customize-animations.md b/skills/ppt-master/workflows/stages/customize-animations.mdindex c0d922c1..12af05a4 100644--- a/skills/ppt-master/workflows/stages/customize-animations.md+++ b/skills/ppt-master/workflows/stages/customize-animations.md@@ -327,6 +327,11 @@ Use the corresponding `sounds/<namespace>/<file>.wav` path inreference `skills/ppt-master/templates/sounds/` from `animations.json`. Theglobal library is a selection source, not an exporter fallback.+This pass owns only native PPTX cue selection and configuration. When direct+narrated MP4 delivery is active, leave gain, limiting, and video mixing to+[`generate-audio`](./generate-audio.md) after the final narrated export; do not+write those post-production values into `animations.json`.+---## 4. Edit `animations.json`@@ -440,6 +445,10 @@ ambiguous direct-root groups, conflicting or undeclared shared keys, non-objectMorph, and any target that does not remain one compatible Slide-local objectafter structure processing.+**Validation boundary**: a passing sidecar, timing-tree read-back, and sound+relationship check proves the PPTX configuration only. It does not prove the+PowerPoint-exported MP4 audio track contains those cues.+Generate Step 7 export reads back row order, including repeated rows targetingone shape, trigger, target, resolved effect, duration, offset, timing placement,IDs, and shape references. Narration@@ -461,9 +470,12 @@ python3 skills/ppt-master/scripts/video_motion_plan.py \--force```-For narrated output, use the final `--recorded-narration` trace. The video plan-locks identity, effect, direction, order, bounds, and timing; it may refine-renderer parameters but cannot replace the source effect. See+For narrated output, use the final `--recorded-narration` trace. When resolved+sound cues exist and direct MP4 delivery is selected, that same final trace and+the final narrated PPTX feed `video_sound_mix.py`; never infer cue timing from+the raw sidecar or filenames. The video plan locks identity, effect, direction,+order, bounds, and timing; it may refine renderer parameters but cannot replace+the source effect. See[`video-motion-plan.md`](../../scripts/docs/video-motion-plan.md).---diff --git a/skills/ppt-master/workflows/stages/generate-audio.md b/skills/ppt-master/workflows/stages/generate-audio.mdindex 11e8d043..7a844d95 100644--- a/skills/ppt-master/workflows/stages/generate-audio.md+++ b/skills/ppt-master/workflows/stages/generate-audio.md@@ -1,5 +1,5 @@----description: Shared post-processing stage for narration audio, PPTX embedding, and optional native video export.+description: Shared post-processing stage for narration audio, PPTX embedding, native video export, and triggered sound mixing.---# Generate Audio Stage@@ -39,6 +39,9 @@ this stage.`CreateVideo` automation contract and its movie export does not preserveanimation effects. Do not replace the missing API with UI scripting.- Optional post-export video calibration requires `ffmpeg` plus `numpy`; it runs only after a finished PowerPoint video is supplied or created.+- Direct MP4 delivery with resolved transition/object-animation sound cues also+ requires `ffmpeg` plus `numpy`. It renders an independent SFX stem, mixes it+ after native PowerPoint export, and validates the actual mixed audio track.- High-quality cloud mode: provider API key is set before use:- ElevenLabs: `ELEVENLABS_API_KEY`- MiniMax: `MINIMAX_API_KEY`@@ -113,8 +116,11 @@ For each candidate, write a **one-line Chinese description** covering: 性别 ·unspecified provider, voice, rate, and embed choices from the recommended-valuerules below. Keep video off unless the caller selected direct video; then embedthe narrated PPTX and continue to native video only when-`powerpoint_video.py --check` succeeds. Require a timestamp-capable provider-only when narration-cue sync or subtitle delivery needs page-local SRT.+`powerpoint_video.py --check` succeeds. If final resolved motion contains sound+cues, continue automatically through the post-export mix without another+question. Require a timestamp-capable provider only when narration-cue sync or+subtitle delivery needs page-local SRT; audio-only narration can still calibrate+the sound mix from its complete per-page tracks.**Default / Enhance Native — one-shot interaction (mandatory)**:@@ -201,6 +207,8 @@ python3 skills/ppt-master/scripts/narration_sync.py animations <project_path> \# 2B. Re-export with audio embedded# Use the base export's [REPORT] path to preserve source-bound deck motion.# Quick Generate adds --quick-generate --with-notes to every re-export below.+# For direct MP4 delivery when final motion has sound cues, also pass+# --conversion-trace <final_narrated_trace> on the selected export command.python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \--recorded-narration audio \--narration-start-floor 0.8 --narration-padding 0.5 \@@ -224,14 +232,28 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \python3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --force-# 2D. Optional: export through installed Windows PowerPoint and wait for completion+# 2D. Optional: export the raw video through installed Windows PowerPoint+# and wait for completionpython3 skills/ppt-master/scripts/powerpoint_video.py \- <final_narrated_pptx> -o <final_video.mp4>--# 2E. Only when page-local SRT exists, align the frozen narration text against-# the finished video's audio track+ <final_narrated_pptx> -o <raw_powerpoint_video.mp4>++# 2E. Only when final resolved motion has sound cues and direct MP4 delivery is+# selected, derive the exact embedded sounds from the final narrated PPTX,+# calibrate cue times against raw video narration, and publish the verified+# SFX stem, mixed MP4, and report. Defaults are about 35% for transitions,+# 25% for object cues, and a -1 dBFS limiter.+python3 skills/ppt-master/scripts/video_sound_mix.py <project_path> \+ --pptx <final_narrated_pptx> \+ --trace <final_narrated_trace> \+ --video <raw_powerpoint_video.mp4> \+ -o <final_mixed_video.mp4> \+ --stem-output <final_sfx_stem.wav> \+ --report-output <sound_mix_report.json> --force++# 2F. Only when page-local SRT exists, align the frozen narration text against+# the final delivery video: mixed when 2E ran, otherwise the raw video.python3 skills/ppt-master/scripts/video_subtitles.py <project_path> \- --video <final_video.mp4> --language <language> --force+ --video <final_delivery_video.mp4> --language <language> --force```**Default — bounded Edge concurrency (may override)**: Generate up to three@@ -322,13 +344,37 @@ python3 skills/ppt-master/scripts/narration_sync.py fingerprint <project_path>`narration_sync.py subtitles` may still write `<project_path>/audio/total.srt` as a PPTX-timeline diagnostic. It is not the delivery subtitle for a finished video.-When video export was selected, `powerpoint_video.py` opens the final narrated PPTX through local Windows PowerPoint, requests its native video encoder with recorded timings and narrations enabled, and polls `CreateVideoStatus` until the MP4 succeeds, fails, or times out. The interface is synchronous to its caller even though PowerPoint performs encoding asynchronously. It preserves PowerPoint's own animation and media behavior rather than re-rendering the deck.+When video export was selected, `powerpoint_video.py` opens the final narrated+PPTX through local Windows PowerPoint, requests its native video encoder with+recorded timings and narrations enabled, and polls `CreateVideoStatus` until the+MP4 succeeds, fails, or times out. The interface is synchronous to its caller+even though PowerPoint performs encoding asynchronously. It preserves the+native visual-animation and narration path rather than re-rendering the deck,+but does not reliably write transition or object-animation sounds into the MP4+audio track.If native video export fails, keep the narrated PPTX as a successful upstreamartifact and report the video failure separately. Do not regenerate audio orthe PPTX unless their own validation failed.-After the MP4 exists, `video_subtitles.py` takes the exact narration text frozen in the page SRT set and force-aligns it against the finished video's actual audio track with `stable-ts`. Long delivery cues may be split for display at this final stage. This writes a same-stem external SRT without changing the MP4, notes, page SRT, or animation files.+When the final narrated trace and PPTX contain sound cues, treat the PowerPoint+MP4 as a raw intermediate. `video_sound_mix.py` cross-checks that trace against+the final PPTX read-back, extracts the exact embedded sound relationships,+calibrates every page against the raw video's narration, renders a float SFX+stem, and mixes it with narration at unity gain. Transition cues default to+about 35%, object cues to about 25%; `amix` normalization and ducking remain off,+and a -1 dBFS peak limiter follows the mix. The receipt must prove a non-silent+stem, preserved video-stream hash, changed and present final audio, duration+parity, non-clipping true peak, and correlation between the added final-audio+component and the stem. A valid `animations.json` or OOXML package alone is not+MP4 audio acceptance.++After the final delivery MP4 exists, `video_subtitles.py` takes the exact+narration text frozen in the page SRT set and force-aligns it against that+finished video's actual audio track with `stable-ts`. Use the mixed MP4 when+sound mixing ran; otherwise use the raw PowerPoint MP4. Long delivery cues may+be split for display at this final stage. This writes a same-stem external SRT+without changing the MP4, notes, page SRT, or animation files.This stage keeps subtitles as external SRT files. It does not burn subtitles into the video. Automatic MP4 export is an optional Windows PowerPoint integration, not an independent renderer; when PowerPoint automation is unavailable, stop after the narrated PPTX instead of claiming a downgraded video.@@ -336,10 +382,15 @@ This stage keeps subtitles as external SRT files. It does not burn subtitles int| Caller | After audio generation ||---|---|-| Generate PPTX | When narration-cue sync is selected, combine page-local SRT with `animations.json` and derive `narration_animations.json`; narration-independent custom motion passes `--animation-config animations.json`; with no sidecar, inherit the base report's resolved motion, while explicit all-motion-off uses `--no-animations`. Export with `--recorded-narration audio`; Quick also passes `--quick-generate --with-notes`. Optionally continue through `powerpoint_video.py`, then generate the delivery SRT from the finished video. |+| Generate PPTX | When narration-cue sync is selected, combine page-local SRT with `animations.json` and derive `narration_animations.json`; narration-independent custom motion passes `--animation-config animations.json`; with no sidecar, inherit the base report's resolved motion, while explicit all-motion-off uses `--no-animations`. Export with `--recorded-narration audio`; Quick also passes `--quick-generate --with-notes`. For direct MP4 with resolved sound cues, add the final narrated conversion trace, export a raw PowerPoint MP4, run `video_sound_mix.py`, then align delivery subtitles against the mixed MP4. With no cues, the raw MP4 is final. || Enhance Native PPTX | Return to [`native-enhance-pptx`](../native-enhance-pptx.md) Step 9; its `apply` command owns audio relationships, timings, transitions, and the enhanced export. If video was selected, pass that final PPTX to `powerpoint_video.py`. |-For Qwen or explicit CosyVoice audio-only mode, embed/export the audio normally but skip `narration_timing.json`, `narration_sync.py animations`, SRT merge, and final-video subtitle alignment. Pass canonical narration-independent custom motion explicitly when present. Never present those missing subtitle artifacts or object sync as generated.+For Qwen or explicit CosyVoice audio-only mode, embed/export the audio normally+but skip `narration_timing.json`, `narration_sync.py animations`, SRT merge, and+final-video subtitle alignment. Pass canonical narration-independent custom+motion explicitly when present. A direct-MP4 sound mix may still run because+page audio, not SRT, supplies its correlation template. Never present missing+subtitle artifacts or object sync as generated.For Generate PPTX, `--recorded-narration audio` prepares PowerPoint's recorded timings and narrations: every slide must have a matching supported audio file, every duration must be readable by `ffprobe`, and object animations must not use `--animation-trigger on-click`. Use `after-previous` or `with-previous` for narrated/video export. Narration changes the slide-advance layer only: the resolved page-transition effect remains unchanged, `-t none` remains visually transition-free, and narration advance disables click while using page-start lead-in plus audio duration plus page-tail padding. The re-export is saved as `exports/<project_name>_<timestamp>_narrated.pptx`, telling it apart from silent exports.@@ -356,9 +407,13 @@ Output one summary block listing:- Narration provider/model plus the `<project_path>/audio/manifest.json` provenance path.- For narrated object animation, whether current SVG semantics were reused or which missing/stale pages were reread, plus semantic mapping coverage and fallback count.- For Generate PPTX, report derived narration animation coverage/path when cue sync ran, the canonical config path for narration-independent custom motion, or inherited/all-motion-off state.-- When video export was selected, the final MP4 path and native PowerPoint export status.+- When video export was selected, the raw PowerPoint MP4 path/status. When+ resolved cues triggered sound mixing, also report the final mixed MP4, SFX+ stem, cue count, and `video_sound_mix.py` receipt; otherwise identify the raw+ MP4 as final.- When page-local SRT was merged, the PPTX-timeline `audio/total.srt` path.-- When final-video subtitle alignment ran, the aligned delivery SRT path;+- When final-video subtitle alignment ran, the aligned delivery SRT path and+ whether its source was the mixed or raw final video;otherwise do not claim a video-aligned subtitle.- The provider, voice, and rate/settings actually used.- The caller-owned integration result: narrated SVG export path, enhanced native PPTX path, or “audio only”.