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(audio): add timed subtitles for ElevenLabs and CosyVoice
hugohe322e401c940e9
diff --git a/docs/audio-narration.md b/docs/audio-narration.mdindex 25fc26f5..78470a2a 100644--- a/docs/audio-narration.md+++ b/docs/audio-narration.md@@ -4,14 +4,14 @@----PPT Master can turn the speaker notes into per-slide narration via [`edge-tts`](https://github.com/rany2/edge-tts) (Microsoft Edge's online neural voices) by default, or via ElevenLabs, MiniMax, Qwen TTS, and CosyVoice when you need higher-quality cloud narration or a cloned voice. Edge writes a page-local SRT from the same timing stream, while MiniMax converts its synchronous subtitle response into the same SRT contract. It can then embed the audio back into the PPTX for PowerPoint's native video export.+PPT Master can turn the speaker notes into per-slide narration via [`edge-tts`](https://github.com/rany2/edge-tts) (Microsoft Edge's online neural voices) by default, or via ElevenLabs, MiniMax, Qwen TTS, and CosyVoice when you need higher-quality cloud narration or a cloned voice. Edge, ElevenLabs, MiniMax, and timestamp-capable CosyVoice voices generate page-local SRT from provider timing returned with the same synthesis. Qwen remains audio-only because its current TTS API exposes no timestamps. The audio can then be embedded back into the PPTX for PowerPoint's native video export.## What you get- One audio file per slide under `<project_path>/audio/`, named to match the SVG (`01_cover.mp3`, `02_market_landscape.mp3`, …).-- With edge or MiniMax subtitles, one matching subtitle file per slide in the same `<project_path>/audio/` directory (`01_cover.srt`, `02_market_landscape.srt`, …). Each file uses a page-local timeline with a `00:00:00,000` origin. Both providers' word timings are regrouped into the same compact cue format.+- With provider-timed subtitles, one matching subtitle file per slide in the same `<project_path>/audio/` directory (`01_cover.srt`, `02_market_landscape.srt`, …). Each file uses a page-local timeline with a `00:00:00,000` origin. Provider word/character timings are regrouped into the same compact cue format.- 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 canonical `animations.json` exists, an SVG-to-SRT timing plan derives `narration_animations.json` whose click-free object animations wait for the relevant subtitle cue. When neither animation sidecar exists, narrated export creates no sidecar and keeps the default `fade` page transition with no per-element builds. Both paths can produce a deck-wide `<project_path>/audio/total.srt` aligned to the final PPTX timeline; after PowerPoint exports a video, the same command can calibrate page starts against its audio track for frame-accurate sidecar subtitles.+- When canonical `animations.json` exists and page-local SRT is available, an SVG-to-SRT timing plan derives `narration_animations.json` whose click-free object animations wait for the relevant subtitle cue. When neither animation sidecar exists, narrated export creates no sidecar and keeps the default `fade` page transition with no per-element builds. With page-local SRT, both paths can produce a deck-wide `<project_path>/audio/total.srt` aligned to the final PPTX timeline; after PowerPoint exports a video, the same command can calibrate page starts against its audio track for frame-accurate sidecar subtitles.- 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 to the audio length, so kiosk/auto-play and video export work without manual timing.- 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.- The original speaker notes are preserved.@@ -21,7 +21,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. **One question, one answer.** You are asked once — provider, voice, rate, "embed audio back into PPTX", and "continue to video" — all with a recommended default. Reply "ok" to accept everything, or just call out the part you want to change.-4. **Generation runs.** With edge, the script writes each page's MP3 and SRT from the same stream into `audio/`. MiniMax requests service timestamps together with the MP3 and converts the returned JSON to the same page-local SRT format; ElevenLabs, Qwen, and CosyVoice write audio only. A complete run atomically writes `audio/manifest.json` for provenance. For Generate PPTX with canonical custom animation, the AI maps current SVG content groups to numbered SRT cues and derives click-free `narration_animations.json`; without animation sidecars, it skips that derivation and retains `fade` / no per-element builds. It then re-exports the deck with audio attached and merges the local SRT files 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. 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 page-local SRT and canonical custom animation, the AI maps current SVG content groups to numbered SRT cues and derives click-free `narration_animations.json`; without animation sidecars, it skips that derivation and retains `fade` / no per-element builds. 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.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.@@ -68,7 +68,7 @@ python3 skills/ppt-master/scripts/total_md_split.py <project_path>python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice zh-CN-YunjianNeural --rate +0%-# 2B. Or generate MP3s with ElevenLabs (requires ELEVENLABS_API_KEY)+# 2B. Or generate MP3/SRT pairs with ElevenLabs (requires ELEVENLABS_API_KEY)export ELEVENLABS_API_KEY="your-elevenlabs-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider elevenlabs \@@ -83,7 +83,7 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice-id <minimax-voice-id> \--minimax-model speech-2.8-hd-# 2D. Or generate audio with Qwen TTS (system voice or cloned voice)+# 2D. Or generate audio only with Qwen TTS (system voice or cloned voice)export DASHSCOPE_API_KEY="your-dashscope-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider qwen \@@ -91,14 +91,14 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--qwen-model qwen3-tts-flash \--qwen-language-type Chinese-# 2E. Or generate MP3s with CosyVoice (system voice or cloned/designed voice_id)+# 2E. Or generate MP3/SRT pairs with a timestamp-capable CosyVoice voiceexport COSYVOICE_API_KEY="your-dashscope-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider cosyvoice \--voice-id <cosyvoice-voice> \--cosyvoice-model cosyvoice-v3-flash-# 3-4. Only when canonical animations.json exists, print the SRT-set+# 3-4. Only when page-local SRT and canonical animations.json exist, print the SRT-set# fingerprint, then author# <project_path>/narration_timing.json by comparing each current# SVG content group with the numbered cues in that page's SRT. A missing@@ -115,7 +115,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \-o <final_narrated_pptx> --recorded-narration audio \--narration-padding 0.5-# 6. Merge page-local SRT using the final PowerPoint timings+# 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@@ -124,8 +124,8 @@ 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. Calibrate page starts against the exported audio track and write a-# same-stem sidecar SRT+# 8. When page-local SRT exists, calibrate page starts against the exported+# audio track and write a same-stem sidecar SRTpython3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --video <powerpoint_exported_video> \-o exports/<powerpoint_exported_video_stem>.srt --force@@ -143,7 +143,27 @@ troubleshooting. Cloud providers remain serial.The edge command creates `audio/<stem>.mp3` and `audio/<stem>.srt` from the same streaming request. Sentence-ending punctuation closes a cue. A cue over 20 visible characters first splits at commas, semicolons, or colons, then at the nearest word boundary only if it is still too long. Use `--subtitle-max-chars` to change the limit. Adjacent timing overlap up to 100 ms is tolerated by moving the later cue start to the previous cue end; larger overlap fails. Each SRT uses a page-local timebase with a zero origin and preserves edge's `WordBoundary` timing, including any leading silence before the first cue.-MiniMax requests word-level subtitles on the same non-streaming T2A request, downloads the returned JSON timing file, and applies the same punctuation-first, length-bounded regrouping as Edge. The validated MP3/SRT pair is then published together. Use `--subtitle-max-chars` to tune both providers; their compact cues are the semantic animation-mapping units. ElevenLabs, Qwen, and CosyVoice create audio only.+MiniMax requests word-level subtitles on the same non-streaming T2A request and downloads the returned JSON timing file. ElevenLabs uses its `/with-timestamps` endpoint and reads original-text character alignment from the same JSON response. CosyVoice enables HTTP streaming plus `word_timestamp_enabled`, then uses the complete audio URL and word timings returned by that synthesis. All four provider-timed paths apply the same punctuation-first, `--subtitle-max-chars`-bounded regrouping and atomically publish a validated audio/SRT pair. Their compact cues are the semantic animation-mapping units.++CosyVoice timestamp support is model/voice-specific: cloned voices from `cosyvoice-v3.5-plus`, `cosyvoice-v3.5-flash`, `cosyvoice-v3-plus`, `cosyvoice-v3-flash`, and `cosyvoice-v2` are supported, as are system voices explicitly marked timestamp-capable in the [CosyVoice voice list](https://help.aliyun.com/en/model-studio/cosyvoice-voice-list). The model and voice family must match. If a selected voice cannot return timing and audio-only output is intentional, pass `--cosyvoice-audio-only`.++Qwen's current TTS HTTP and realtime responses return audio but no word or character alignment. PPT Master therefore keeps Qwen audio-only instead of estimating SRT timing. Choose Edge, ElevenLabs, MiniMax, or a timestamp-capable CosyVoice voice when page-local subtitles are required.++### Provider capability and parameter choices++| Provider | Page-local SRT | Provider timing | Current default decision |+|---|---|---|---|+| Edge | Yes | Word | Keep the selected neural voice and `+0%` unless notes density calls for a small rate adjustment. |+| ElevenLabs | Yes | Original-text character alignment | Keep `eleven_multilingual_v2` and `mp3_44100_128` for stable long-form narration. Use `--elevenlabs-speed 0.7-1.2` for an explicit pace override; `eleven_v3` is more expressive but more variable, while Flash v2.5 favors latency/cost. |+| MiniMax | Yes | Word | Keep the existing `speech-2.8-hd`, 32 kHz mono MP3 defaults unless the selected voice or delivery target requires otherwise. |+| Qwen | No | None in the current TTS response | Keep stable `qwen3-tts-flash`; specify the exact `--qwen-language-type` for a single-language deck. The current endpoint owns WAV output and exposes no format/sample-rate/numeric speed controls; an Instruct model can still control delivery through instructions. Do not switch models merely to claim unavailable timestamps. |+| CosyVoice | Conditional | Word | Keep `cosyvoice-v3-flash` plus 24 kHz MP3 as the system-voice-compatible default. Select the model that owns a cloned/designed voice; v3.5 voices require an explicit matching v3.5 model. |++The CLI rejects out-of-range ElevenLabs stability/similarity/style values, ElevenLabs speed outside `0.7-1.2`, and CosyVoice volume/rate/pitch or sample rates outside the provider's documented ranges before any request is sent.++These decisions follow the current [ElevenLabs speech-with-timing API](https://elevenlabs.io/docs/api-reference/text-to-speech/convert-with-timestamps), [ElevenLabs model guide](https://elevenlabs.io/docs/overview/capabilities/text-to-speech), [Qwen TTS API](https://www.alibabacloud.com/help/en/model-studio/qwen-tts-api), and [Qwen-Audio-TTS/CosyVoice HTTP API](https://help.aliyun.com/en/model-studio/cosyvoice-tts-http-api). Alibaba Cloud now recommends a workspace-specific Beijing domain for the CosyVoice HTTP endpoint; pass it through `--cosyvoice-base-url` when available. The legacy domain remains functional.++Alibaba Cloud's current [TTS model guide](https://www.alibabacloud.com/help/en/model-studio/tts-model/) recommends Qwen-Audio 3.0 for new preset/cloned-voice workflows. Those model IDs use the Qwen-Audio-TTS/CosyVoice API and a different voice contract, and still do not provide timestamps. PPT Master therefore does not silently replace the compatible `qwen3-tts-flash` default; migrate the model and its matching voice explicitly when audio quality is the reason, not subtitle parity.`audio/` is the single active narration set. The manifest records its source, so provider subdirectories are not created by default. Before regeneration, the script removes stale `manifest.json` and `total.srt`; audio-only providers also remove same-stem stale page SRT files. Use a separate explicit output directory only when you intentionally need to preserve an alternate provider run.@@ -214,6 +234,7 @@ Replace `--provider minimax` with `elevenlabs` / `qwen` / `cosyvoice` as needed;- **Authorization** — only clone voices you own or have explicit permission to use. Each provider's terms forbid impersonation.- **Language coverage** — the cloned voice inherits the speaker's accent. For multilingual decks (e.g. Chinese with English terms), pick a provider whose model handles your sample's language mix; ElevenLabs `eleven_multilingual_v2` and CosyVoice tend to be the most forgiving.+- **Subtitle capability** — cloned ElevenLabs and supported CosyVoice voices can produce provider-timed SRT; cloned Qwen voices remain audio-only under the current API.- **Provider retention** — reuse the `voice_id` while that voice remains available in your provider account. Retention, deletion, and expiration policies are provider-specific.## Dependency@@ -261,7 +282,7 @@ path when animation fidelity matters.**Tips**:-- **No mic, no recording session needed** — the audio is generated, not recorded, so re-runs are deterministic.+- **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).- **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/zh/audio-narration.md b/docs/zh/audio-narration.mdindex 6252860f..0c252def 100644--- a/docs/zh/audio-narration.md+++ b/docs/zh/audio-narration.md@@ -4,14 +4,14 @@----PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edge-tts`](https://github.com/rany2/edge-tts) —— 微软 Edge 的在线神经网络语音;也可配置 ElevenLabs、MiniMax、Qwen TTS、CosyVoice 使用高质量或复刻音色)。Edge 会从同一次计时流中写出逐页 SRT;MiniMax 则把同步接口返回的字幕时间戳转换为同一套 SRT。音频可继续嵌入 PPTX,供 PowerPoint 使用原生视频导出。+PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edge-tts`](https://github.com/rany2/edge-tts) —— 微软 Edge 的在线神经网络语音;也可配置 ElevenLabs、MiniMax、Qwen TTS、CosyVoice 使用高质量或复刻音色)。Edge、ElevenLabs、MiniMax,以及支持时间戳的 CosyVoice 音色,都会从同一次合成返回的 provider 计时生成逐页 SRT。Qwen 当前 TTS API 不返回时间戳,因此仍只生成音频。音频可继续嵌入 PPTX,供 PowerPoint 使用原生视频导出。## 你会得到什么- 每页一个音频文件,存放于 `<project_path>/audio/`,文件名与 SVG 对齐(`01_cover.mp3`、`02_market_landscape.mp3` …)。-- 使用 Edge 或 MiniMax 字幕时,每页还有一个同名字幕文件,与音频一起存放于 `<project_path>/audio/`(`01_cover.srt`、`02_market_landscape.srt` …)。每个文件使用以 `00:00:00,000` 为原点的页内时间轴;两个 provider 的词级时间戳都会重组为同一套紧凑 cue。+- 使用 provider 原生计时字幕时,每页还有一个同名字幕文件,与音频一起存放于 `<project_path>/audio/`(`01_cover.srt`、`02_market_landscape.srt` …)。每个文件使用以 `00:00:00,000` 为原点的页内时间轴;provider 的词级或字符级时间戳都会重组为同一套紧凑 cue。- 完整生成成功后写出精简的 `<project_path>/audio/manifest.json`,只记录 provider、模型、音频/字幕格式、相关音色参数,以及代替云端 voice ID 原文的 SHA-256 指纹;不包含逐页清单、产物哈希或 API Key,正常生成过程也不会读取它。-- 存在规范的 `animations.json` 时,SVG 到 SRT 的计时计划会派生 `narration_animations.json`,让无点击对象动画等待相关字幕 cue。两个动画 sidecar 都不存在时,旁白导出不会创建 sidecar,而是保留默认 `fade` 页间切换和无逐元素动画。两条路径都可以生成与最终 PPTX 时间轴一致的 `<project_path>/audio/total.srt`;PowerPoint 导出视频后,还可用同一命令根据视频音轨校准每页起点,得到帧级对齐的外挂字幕。+- 存在规范的 `animations.json` 且已有逐页 SRT 时,SVG 到 SRT 的计时计划会派生 `narration_animations.json`,让无点击对象动画等待相关字幕 cue。两个动画 sidecar 都不存在时,旁白导出不会创建 sidecar,而是保留默认 `fade` 页间切换和无逐元素动画。存在逐页 SRT 时,两条路径都可以生成与最终 PPTX 时间轴一致的 `<project_path>/audio/total.srt`;PowerPoint 导出视频后,还可用同一命令根据视频音轨校准每页起点,得到帧级对齐的外挂字幕。- 可选重新导出:在 `exports/` 生成新版 PPTX,每页对应的 `m4a` / `mp3` / `wav` 音频已嵌入到该页,且页面切换时间按音频长度自动设置——无人值守自动播放和视频导出都不用再手动调时间。- Windows 下可选原生视频导出:`powerpoint_video.py` 把最终带旁白 PPTX 交给 PowerPoint 2016+,并等待其原生 MP4 编码成功或失败。- 演讲者备注原样保留。@@ -21,7 +21,7 @@ PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edg1. **备注本身就是为 TTS 写的口播稿**。PPT Master 的 notes 规范刻意产出适合朗读的散文——没有 `[过渡]` / `[停顿]` 这种舞台标记,也没有 `要点:` / `时长:` 这种 meta 行——念出来的内容就是页面上的内容。2. **AI 替你选音色**。当你提出生成旁白时,AI 根据 deck 的主语言(`zh-CN` / `en-US` / `ja-JP` / `ko-KR` / …)和所选 provider 拉取或解释可用音色,挑出候选并给每个写一句中文调性说明(如"稳重男声·适合财报")。语速/风格也会基于 notes 信息密度给出推荐值。3. **一次问完,一次回答**。AI 在一条消息里同时确认 provider、音色、语速、是否嵌入 PPTX,以及是否继续导出视频;每项都标推荐值。回"好"接受全部默认,或者只说要改的部分(如"音色 2,语速 -5%")。-4. **执行**。使用 Edge 时,脚本从同一次流中把每页 MP3 和 SRT 一起写入 `audio/`。MiniMax 会在生成 MP3 的同一请求中获取服务端时间戳,并把返回的 JSON 转成相同的逐页 SRT;ElevenLabs、Qwen 与 CosyVoice 仍只写音频。完整生成成功后会原子写入 `audio/manifest.json` 记录来源。对于存在规范自定义动画的 Generate PPTX,AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;没有动画 sidecar 时则跳过派生,保留 `fade` / 无逐元素动画。随后再导出带音频的 PPTX,并从该 PPTX 读回实际计时、合并逐页 SRT。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器,等 MP4 完成后再校准交付字幕。不支持长音频导入或自动拆分。+4. **执行**。Edge、ElevenLabs、MiniMax,以及支持时间戳的 CosyVoice 音色,会依据同一次合成返回的 provider 计时,把每页音频和 SRT 一起写入 `audio/`;Qwen 和显式 CosyVoice 纯音频模式只写音频。完整生成成功后会原子写入 `audio/manifest.json` 记录来源。对于已有逐页 SRT 且存在规范自定义动画的 Generate PPTX,AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;没有动画 sidecar 时则跳过派生,保留 `fade` / 无逐元素动画。随后再导出带音频的 PPTX;存在逐页 SRT 时,才从该 PPTX 读回实际计时并合并。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器,等 MP4 完成后再校准可用的交付字幕。不支持长音频导入或自动拆分。字幕保持为外部 SRT 文件:PPT Master 不把字幕嵌入 PPTX,也不烧录进 MP4。自动视频导出委托给本机 Windows PowerPoint,并不是另一套渲染器。@@ -67,7 +67,7 @@ python3 skills/ppt-master/scripts/total_md_split.py <project_path>python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice zh-CN-YunjianNeural --rate +0%-# 2B. 用 ElevenLabs 生成 MP3(需要 ELEVENLABS_API_KEY)+# 2B. 用 ElevenLabs 生成 MP3/SRT 对(需要 ELEVENLABS_API_KEY)export ELEVENLABS_API_KEY="your-elevenlabs-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider elevenlabs \@@ -82,7 +82,7 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice-id <minimax-voice-id> \--minimax-model speech-2.8-hd-# 2D. 用 Qwen TTS 生成音频(系统音色或复刻音色)+# 2D. 用 Qwen TTS 仅生成音频(系统音色或复刻音色)export DASHSCOPE_API_KEY="your-dashscope-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider qwen \@@ -90,14 +90,14 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--qwen-model qwen3-tts-flash \--qwen-language-type Chinese-# 2E. 用 CosyVoice 生成 MP3(系统音色或复刻/设计音色)+# 2E. 用支持时间戳的 CosyVoice 音色生成 MP3/SRT 对export COSYVOICE_API_KEY="your-dashscope-api-key"python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider cosyvoice \--voice-id <cosyvoice-voice> \--cosyvoice-model cosyvoice-v3-flash-# 3-4. 仅当规范 animations.json 存在时,输出整套 SRT 的指纹,+# 3-4. 仅当逐页 SRT 与规范 animations.json 都存在时,输出整套 SRT 的指纹,# 再对照每页当前 SVG 内容组与 SRT cue,编写# <project_path>/narration_timing.json;没有对应口播的组不写 cue,# 后续按正常动画顺序出现。两个动画 sidecar 都不存在时直接跳到第 5 步。@@ -112,7 +112,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \-o <final_narrated_pptx> --recorded-narration audio \--narration-padding 0.5-# 6. 按最终 PowerPoint 计时合并逐页 SRT+# 6. 存在逐页 SRT 时,按最终 PowerPoint 计时合并python3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --force@@ -121,7 +121,7 @@ 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+# 8. 存在逐页 SRT 时,根据导出音轨校准每页起点,生成与视频同名的外挂 SRTpython3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --video <powerpoint_exported_video> \-o exports/<powerpoint_exported_video_stem>.srt --force@@ -137,7 +137,27 @@ Edge 默认同时生成最多 3 页音频/SRT。可用 `--concurrency <N>` 调Edge 命令会从同一次流式请求中生成 `audio/<stem>.mp3` 与 `audio/<stem>.srt`。句末标点必定结束一条字幕;单条超过默认 20 个可见字符时,优先在逗号、分号或冒号处拆分,仍然过长才在最近的词边界拆分。可用 `--subtitle-max-chars` 调整上限。相邻字幕最多允许 100 毫秒的计时重叠:后一句起点会移到前一句终点;超过该范围则报错。每页 SRT 使用从零计时的页内时间基准,并保留 Edge `WordBoundary` 的实际时间(包括首条字幕前的静音)。-MiniMax 会在同一次非流式 T2A 请求中获取词级字幕,下载返回的 JSON 时间戳,再复用 Edge 的标点优先、长度受控重组逻辑。校验通过后成对发布 MP3 与 SRT;`--subtitle-max-chars` 同时控制两个 provider,整理后的紧凑 cue 用于语义动画映射。ElevenLabs、Qwen 与 CosyVoice 仍只生成音频。+MiniMax 会在同一次非流式 T2A 请求中获取词级字幕并下载返回的 JSON 时间戳。ElevenLabs 使用 `/with-timestamps` 接口,从同一 JSON 响应读取音频和原文字符级对齐。CosyVoice 开启 HTTP 流式响应与 `word_timestamp_enabled`,再使用同次合成返回的完整音频 URL 和词级时间戳。四条 provider 原生计时路径统一使用标点优先、受 `--subtitle-max-chars` 约束的重组逻辑,并原子发布通过校验的音频/SRT 对;整理后的紧凑 cue 用于语义动画映射。++CosyVoice 的时间戳能力取决于模型和音色组合:`cosyvoice-v3.5-plus`、`cosyvoice-v3.5-flash`、`cosyvoice-v3-plus`、`cosyvoice-v3-flash`、`cosyvoice-v2` 的复刻音色支持,[CosyVoice 音色清单](https://help.aliyun.com/zh/model-studio/cosyvoice-voice-list)里明确标记支持时间戳的系统音色也支持。模型与音色家族必须匹配。如果所选音色不能返回计时,而且明确只需要音频,可传入 `--cosyvoice-audio-only`。++Qwen 当前 TTS 的 HTTP 与实时响应都只返回音频,不含词级或字符级对齐。PPT Master 因此保留 Qwen 纯音频路径,不用理论时长估算 SRT。需要逐页字幕时,请选择 Edge、ElevenLabs、MiniMax 或支持时间戳的 CosyVoice 音色。++### Provider 能力与参数选择++| Provider | 逐页 SRT | 原始计时 | 当前默认裁决 |+|---|---|---|---|+| Edge | 支持 | 词级 | 保留所选神经网络音色与 `+0%`;只有 notes 密度确实需要时才小幅调速。 |+| ElevenLabs | 支持 | 原文字符级对齐 | 保留 `eleven_multilingual_v2` 与 `mp3_44100_128`,适合稳定长文旁白。显式调速使用 `--elevenlabs-speed 0.7-1.2`;`eleven_v3` 表现力更强但波动更大,Flash v2.5 更偏延迟与成本。 |+| MiniMax | 支持 | 词级 | 保留现有 `speech-2.8-hd`、32 kHz 单声道 MP3 默认值,除非所选音色或交付目标另有要求。 |+| Qwen | 不支持 | 当前 TTS 响应无计时 | 保留稳定版 `qwen3-tts-flash`;单语 deck 明确指定 `--qwen-language-type`。当前接口固定返回 WAV,不提供格式、采样率或数值语速控制;Instruct 模型仍可通过指令控制表达。不为了不存在的时间戳盲目换模型。 |+| CosyVoice | 有条件支持 | 词级 | 保留兼容系统音色的 `cosyvoice-v3-flash` 与 24 kHz MP3 默认值。复刻/设计音色使用其所属模型;v3.5 音色必须显式选择匹配的 v3.5 模型。 |++CLI 会在发送请求前拒绝超出范围的 ElevenLabs stability/similarity/style、`0.7-1.2` 以外的 ElevenLabs 语速,以及不符合 provider 官方范围的 CosyVoice 音量、语速、音高或采样率。++以上裁决依据当前 [ElevenLabs 带时间戳语音接口](https://elevenlabs.io/docs/api-reference/text-to-speech/convert-with-timestamps)、[ElevenLabs 模型指南](https://elevenlabs.io/docs/overview/capabilities/text-to-speech)、[Qwen TTS API](https://www.alibabacloud.com/help/en/model-studio/qwen-tts-api) 与 [Qwen-Audio-TTS/CosyVoice HTTP API](https://help.aliyun.com/en/model-studio/cosyvoice-tts-http-api)。阿里云目前建议 CosyVoice HTTP 使用北京地域的 workspace 专属域名;有该域名时通过 `--cosyvoice-base-url` 传入,旧域名仍可用。++阿里云当前的 [TTS 模型选型指南](https://www.alibabacloud.com/help/en/model-studio/tts-model/)建议新建的预置/复刻音色工作流优先考虑 Qwen-Audio 3.0。但这些模型使用 Qwen-Audio-TTS/CosyVoice API 和另一套音色契约,仍不返回时间戳。因此 PPT Master 不会静默替换兼容的 `qwen3-tts-flash` 默认值;只有确实为了音质迁移时,才显式更换模型及其匹配音色,而不是为了字幕能力盲目迁移。`audio/` 是唯一的当前旁白集,来源由 manifest 记录,因此默认不创建 provider 子目录。重新生成前,脚本会移除过期的 `manifest.json` 与 `total.srt`;仅生成音频的 provider 还会移除同名旧逐页 SRT。只有明确需要保留另一套 provider 结果时,才使用单独的显式输出目录。@@ -208,6 +228,7 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \- **授权** —— 只复刻你自己拥有的、或拿到了明确授权的声音。每个 provider 的服务条款都禁止冒用他人声音。- **语言覆盖** —— 复刻出来的音色会继承说话人的口音。对中英混合等多语 deck,建议挑一个对你样本语言组合处理较好的 provider;ElevenLabs `eleven_multilingual_v2` 和 CosyVoice 通常最宽容。+- **字幕能力** —— ElevenLabs 复刻音色和受支持的 CosyVoice 复刻音色可以生成 provider 原生计时 SRT;Qwen 复刻音色在当前 API 下仍只生成音频。- **Provider 保留策略** —— 只要该音色仍存在于你的 provider 账户中,就可以继续复用对应 `voice_id`;保留、删除与过期规则以各平台政策为准。## 依赖@@ -253,7 +274,7 @@ PowerPoint for Mac 可以手动导出 MP4/MOV,但微软明确说明其影片**经验值**:-- **不需要麦克风、不需要录制环节**——音频是合成的,重跑可重现。+- **不需要麦克风、不需要录制环节**——音频是合成的。重跑会复用同一份 notes 与参数,但云端模型仍可能出现轻微的非确定性差异。- **Windows 动画保真**:PowerPoint 的 Windows 视频导出会保留 PPT Master 的原生页间转场和无点击对象动画;Mac 影片导出存在上面的限制。详见 [转场与动画](./animations.md)。- **单页改音频**:改对应 `notes/<page>.md`,再跑一遍 `notes_to_audio.py` + 嵌入步骤,再重新导出视频——单页迭代通常不到一分钟。- **文件大小**:20 页全高清 deck 通常是 30–80 MB,取决于图片量。需要小文件分享时降到高清就行。diff --git a/skills/ppt-master/scripts/notes_to_audio.py b/skills/ppt-master/scripts/notes_to_audio.pyindex 3d730b66..e75353c5 100644--- a/skills/ppt-master/scripts/notes_to_audio.py+++ b/skills/ppt-master/scripts/notes_to_audio.py@@ -4,7 +4,9 @@This script uses provider backends for the same per-slide output contract onmacOS, Linux, and Windows. `edge-tts` remains the default no-key backend andalso writes one compact, word-timed SRT file per slide from the same TTS stream.-MiniMax requests word timings and applies the same compact cue regrouping.+MiniMax and CosyVoice request word timings; ElevenLabs requests character+alignment. All four apply the same compact, text-faithful cue regrouping.+Qwen remains audio-only because its current TTS API exposes no timestamps.Usage:python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural@@ -241,6 +243,7 @@ def _provider_manifest_details("stability": args.elevenlabs_stability,"similarity_boost": args.elevenlabs_similarity_boost,"style": args.elevenlabs_style,+ "speed": args.elevenlabs_speed,"speaker_boost": args.elevenlabs_speaker_boost,}if backend.provider == "minimax":@@ -296,7 +299,9 @@ def _narration_manifest(if writes_subtitles:manifest["subtitles"] = {"format": "srt",- "timing": "word",+ "timing": (+ "character" if backend.provider == "elevenlabs" else "word"+ ),"max_visible_chars": args.subtitle_max_chars,}return manifest@@ -396,7 +401,7 @@ def main() -> int:"--subtitle-max-chars",type=int,default=backend_edge.DEFAULT_SUBTITLE_MAX_CHARS,- help="maximum visible characters per Edge/MiniMax subtitle cue (default: 20)",+ help="maximum visible characters per provider-timed subtitle cue (default: 20)",)parser.add_argument("--elevenlabs-api-key-env",@@ -431,6 +436,12 @@ def main() -> int:default=None,help="optional ElevenLabs style exaggeration override, 0.0-1.0",)+ parser.add_argument(+ "--elevenlabs-speed",+ type=float,+ default=None,+ help="optional ElevenLabs speaking speed override, 0.7-1.2",+ )parser.add_argument("--elevenlabs-speaker-boost",action=argparse.BooleanOptionalAction,@@ -480,6 +491,7 @@ def main() -> int:parser.add_argument("--cosyvoice-output-format", default="mp3", choices=["mp3", "wav"],help="CosyVoice audio format for PPT narration (default: mp3)")parser.add_argument("--cosyvoice-sample-rate", type=int, default=24000,+ choices=[8000, 16000, 22050, 24000, 44100, 48000],help="CosyVoice sample rate (default: 24000)")parser.add_argument("--cosyvoice-volume", type=int, default=None,help="optional CosyVoice volume, 0-100")@@ -491,6 +503,14 @@ def main() -> int:help="optional CosyVoice instruction text for supported voices/models")parser.add_argument("--cosyvoice-language-hint", default=None,help="optional CosyVoice language hint, e.g. zh, en, ja")+ parser.add_argument(+ "--cosyvoice-audio-only",+ action="store_true",+ help=(+ "skip CosyVoice timestamps/SRT for a model or voice that does not "+ "support them"+ ),+ )parser.add_argument("--list-common-voices", action="store_true", help="print a curated voice list and exit")parser.add_argument("--list-voices", action="store_true", help="query provider voices and exit")parser.add_argument("--locale", default=None, help='filter --list-voices by locale, e.g. "zh-CN"')@@ -544,6 +564,40 @@ def main() -> int:parser.error("--concurrency must be at least 1")raise AssertionError("unreachable")+ for option, value, minimum, maximum in (+ ("--elevenlabs-stability", args.elevenlabs_stability, 0.0, 1.0),+ (+ "--elevenlabs-similarity-boost",+ args.elevenlabs_similarity_boost,+ 0.0,+ 1.0,+ ),+ ("--elevenlabs-style", args.elevenlabs_style, 0.0, 1.0),+ ("--elevenlabs-speed", args.elevenlabs_speed, 0.7, 1.2),+ ("--cosyvoice-volume", args.cosyvoice_volume, 0, 100),+ ("--cosyvoice-rate", args.cosyvoice_rate, 0.5, 2.0),+ ("--cosyvoice-pitch", args.cosyvoice_pitch, 0.5, 2.0),+ ):+ if value is not None and not minimum <= value <= maximum:+ parser.error(f"{option} must be between {minimum} and {maximum}")+ raise AssertionError("unreachable")++ if args.cosyvoice_audio_only and args.provider != "cosyvoice":+ parser.error("--cosyvoice-audio-only requires --provider cosyvoice")+ raise AssertionError("unreachable")++ if args.provider == "qwen" and args.qwen_instructions:+ if "instruct" not in args.qwen_model:+ parser.error(+ "--qwen-instructions requires a Qwen3 TTS Instruct model"+ )+ raise AssertionError("unreachable")+ if args.qwen_optimize_instructions and not args.qwen_instructions:+ parser.error(+ "--qwen-optimize-instructions requires --qwen-instructions"+ )+ raise AssertionError("unreachable")+if args.provider == "elevenlabs":if not voice_id:parser.error("--voice-id is required for --provider elevenlabs")@@ -582,15 +636,31 @@ def main() -> int:except Exception as exc:print(f"error: {exc}", file=sys.stderr)return 1- backend = AudioBackend(provider=args.provider, extension=extension, api_key=api_key, voice_id=voice_id)+ backend = AudioBackend(+ provider=args.provider,+ extension=extension,+ api_key=api_key,+ voice_id=voice_id,+ )else:- backend = AudioBackend(provider=args.provider, extension=backend_edge.edge_output_extension(), voice_id=args.voice)+ backend = AudioBackend(+ provider=args.provider,+ extension=backend_edge.edge_output_extension(),+ voice_id=args.voice,+ )project = args.project_pathnotes_dir = project / "notes"output_dir = args.output or (project / "audio")subtitle_dir = output_dir- writes_subtitles = backend.provider in {"edge", "minimax"}+ writes_subtitles = backend.provider in {+ "edge",+ "elevenlabs",+ "minimax",+ } or (+ backend.provider == "cosyvoice"+ and not args.cosyvoice_audio_only+ )try:note_roster = _expected_note_roster(project)@@ -665,6 +735,8 @@ def main() -> int:subtitle_path: Path | None = Nonetry:if backend.provider == "elevenlabs":+ if writes_subtitles:+ subtitle_path = subtitle_dir / f"{output_path.stem}.srt"backend_elevenlabs.generate(text,output_path,@@ -675,7 +747,10 @@ def main() -> int:stability=args.elevenlabs_stability,similarity_boost=args.elevenlabs_similarity_boost,style=args.elevenlabs_style,+ speed=args.elevenlabs_speed,speaker_boost=args.elevenlabs_speaker_boost,+ subtitle_path=subtitle_path,+ subtitle_max_chars=args.subtitle_max_chars,)elif backend.provider == "minimax":if writes_subtitles:@@ -711,6 +786,8 @@ def main() -> int:base_url=args.qwen_base_url,)elif backend.provider == "cosyvoice":+ if writes_subtitles:+ subtitle_path = subtitle_dir / f"{output_path.stem}.srt"backend_cosyvoice.generate(text,output_path,@@ -725,6 +802,8 @@ def main() -> int:instruction=args.cosyvoice_instruction,language_hint=args.cosyvoice_language_hint,base_url=args.cosyvoice_base_url,+ subtitle_path=subtitle_path,+ subtitle_max_chars=args.subtitle_max_chars,)_remove_stale_audio_variants(output_path)if not writes_subtitles:diff --git a/skills/ppt-master/scripts/tts_backends/backend_cosyvoice.py b/skills/ppt-master/scripts/tts_backends/backend_cosyvoice.pyindex bb784ebc..e8cd7fcc 100644--- a/skills/ppt-master/scripts/tts_backends/backend_cosyvoice.py+++ b/skills/ppt-master/scripts/tts_backends/backend_cosyvoice.py@@ -2,14 +2,30 @@from __future__ import annotations+import json+import mathimport osfrom pathlib import Path+from urllib import error, request-from tts_backends.backend_common import download_audio, extension_from_format, post_json, read_api_key+from tts_backends.backend_common import (+ download_audio,+ extension_from_format,+ get_bytes,+ post_json,+ publish_audio_subtitle,+ read_api_key,+ read_http_error,+)+from tts_backends.backend_edge import (+ DEFAULT_SUBTITLE_MAX_CHARS,+ format_word_timed_srt,+)DEFAULT_ENDPOINT = "https://dashscope.aliyuncs.com/api/v1/services/audio/tts/SpeechSynthesizer"DEFAULT_MODEL = "cosyvoice-v3-flash"+_TICKS_PER_MILLISECOND = 10_000def output_extension(audio_format: str) -> str:@@ -28,6 +44,167 @@ def resolve_url(base_url: str | None = None) -> str:return base + "/api/v1/services/audio/tts/SpeechSynthesizer"+def _parse_sse_event(data_lines: list[str]) -> dict | None:+ payload = "\n".join(data_lines).strip()+ if not payload or payload == "[DONE]":+ return None+ try:+ event = json.loads(payload)+ except json.JSONDecodeError as exc:+ raise RuntimeError("CosyVoice streaming response contains invalid JSON") from exc+ if not isinstance(event, dict):+ raise RuntimeError("CosyVoice streaming event is not an object")+ return event+++def _parse_sse(raw: bytes) -> list[dict]:+ try:+ body = raw.decode("utf-8-sig")+ except UnicodeError as exc:+ raise RuntimeError("CosyVoice streaming response is not valid UTF-8") from exc++ if not any(line.startswith("data:") for line in body.splitlines()):+ event = _parse_sse_event([body])+ return [event] if event is not None else []++ events: list[dict] = []+ data_lines: list[str] = []+ for line in body.splitlines():+ if not line:+ event = _parse_sse_event(data_lines)+ if event is not None:+ events.append(event)+ data_lines = []+ continue+ if line.startswith("data:"):+ data_lines.append(line[5:].lstrip())+ event = _parse_sse_event(data_lines)+ if event is not None:+ events.append(event)+ if not events:+ raise RuntimeError("CosyVoice streaming response contains no events")+ return events+++def _post_streaming(+ url: str,+ *,+ api_key: str,+ payload: dict,+) -> list[dict]:+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")+ req = request.Request(+ url,+ data=body,+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "X-DashScope-SSE": "enable",+ },+ method="POST",+ )+ try:+ with request.urlopen(req, timeout=180) as response:+ return _parse_sse(response.read())+ except error.HTTPError as exc:+ raise RuntimeError(read_http_error(exc)) from exc+ except error.URLError as exc:+ raise RuntimeError(+ f"CosyVoice streaming request failed: {exc.reason}"+ ) from exc+++def _ticks(value: object, *, field: str) -> int:+ if isinstance(value, bool):+ raise RuntimeError(f"CosyVoice word {field} is not numeric")+ try:+ numeric = float(value)+ except (TypeError, ValueError) as exc:+ raise RuntimeError(f"CosyVoice word {field} is not numeric") from exc+ if not math.isfinite(numeric):+ raise RuntimeError(f"CosyVoice word {field} is not finite")+ return int(round(numeric * _TICKS_PER_MILLISECOND))+++def _word_boundaries(events: list[dict]) -> tuple[list[dict], str]:+ sentence_text: dict[int, str] = {}+ sentence_words: dict[int, list] = {}+ audio_url = ""++ for event in events:+ code = event.get("code")+ message = event.get("message")+ if code or message:+ details = ": ".join(str(value) for value in (code, message) if value)+ raise RuntimeError(f"CosyVoice TTS failed: {details}")+ output = event.get("output") or {}+ if not isinstance(output, dict):+ continue+ audio = output.get("audio") or {}+ if isinstance(audio, dict) and isinstance(audio.get("url"), str):+ audio_url = audio["url"]++ sentence = output.get("sentence") or {}+ if not isinstance(sentence, dict):+ continue+ index = sentence.get("index")+ if isinstance(index, bool) or not isinstance(index, int) or index < 0:+ continue+ original_text = output.get("original_text")+ if isinstance(original_text, str) and original_text:+ sentence_text[index] = original_text+ words = sentence.get("words")+ if isinstance(words, list) and words:+ sentence_words[index] = words++ if not audio_url:+ raise RuntimeError("CosyVoice streaming response contains no audio URL")+ if not sentence_words:+ raise RuntimeError(+ "CosyVoice returned no word timestamps. Use a cloned voice from "+ "cosyvoice-v3.5-plus/flash, cosyvoice-v3-plus/flash, or cosyvoice-v2, "+ "or a system voice marked as timestamp-supported; otherwise pass "+ "--cosyvoice-audio-only."+ )++ boundaries: list[dict] = []+ for sentence_index in sorted(sentence_words):+ original_text = sentence_text.get(sentence_index, "")+ for item in sentence_words[sentence_index]:+ if not isinstance(item, dict):+ raise RuntimeError("CosyVoice word timing is not an object")+ word = item.get("text")+ begin_index = item.get("begin_index")+ end_index = item.get("end_index")+ if (+ original_text+ and isinstance(begin_index, int)+ and not isinstance(begin_index, bool)+ and isinstance(end_index, int)+ and not isinstance(end_index, bool)+ and 0 <= begin_index < end_index <= len(original_text)+ ):+ word = original_text[begin_index:end_index]+ if not isinstance(word, str) or not word:+ raise RuntimeError("CosyVoice word timing contains no text")+ start = _ticks(item.get("begin_time"), field="start time")+ end = _ticks(item.get("end_time"), field="end time")+ if start < 0 or end <= start:+ raise RuntimeError(+ "CosyVoice response contains an invalid word interval"+ )+ if boundaries and start < boundaries[-1]["offset"]:+ raise RuntimeError(+ "CosyVoice word timestamps are not in chronological order"+ )+ boundaries.append({+ "text": word,+ "offset": start,+ "duration": end - start,+ })+ return boundaries, audio_url++def generate(text: str,output_path: Path,@@ -43,6 +220,8 @@ def generate(instruction: str | None,language_hint: str | None,base_url: str | None,+ subtitle_path: Path | None = None,+ subtitle_max_chars: int = DEFAULT_SUBTITLE_MAX_CHARS,) -> None:input_payload: dict[str, object] = {"text": text,@@ -61,13 +240,38 @@ def generate(if language_hint:input_payload["language_hints"] = [language_hint]+ payload = {+ "model": model,+ "input": input_payload,+ }+ url = resolve_url(base_url)++ if subtitle_path is not None:+ input_payload["word_timestamp_enabled"] = True+ events = _post_streaming(+ url,+ api_key=api_key,+ payload=payload,+ )+ boundaries, audio_url = _word_boundaries(events)+ subtitle = format_word_timed_srt(+ text,+ boundaries,+ subtitle_max_chars,+ provider_label="CosyVoice",+ )+ publish_audio_subtitle(+ get_bytes(audio_url),+ output_path,+ subtitle,+ subtitle_path,+ )+ return+data = post_json(- resolve_url(base_url),+ url,headers={"Authorization": f"Bearer {api_key}"},- payload={- "model": model,- "input": input_payload,- },+ payload=payload,timeout=180,)audio = (data.get("output") or {}).get("audio") or {}@@ -80,4 +284,8 @@ def generate(def print_voices() -> None:print("CosyVoice voices are selected by voice.")print("Use a system voice name or a cloned/designed voice_id from CosyVoice.")- print("Example system voice from Alibaba Cloud docs: longanyang")+ print("Timestamp-supported system voice example: longanyang")+ print(+ "For SRT, use a supported CosyVoice cloned voice or a system voice "+ "marked timestamp-supported in the provider catalog."+ )diff --git a/skills/ppt-master/scripts/tts_backends/backend_elevenlabs.py b/skills/ppt-master/scripts/tts_backends/backend_elevenlabs.pyindex 111c7e62..ac3619ab 100644--- a/skills/ppt-master/scripts/tts_backends/backend_elevenlabs.py+++ b/skills/ppt-master/scripts/tts_backends/backend_elevenlabs.py@@ -2,14 +2,27 @@from __future__ import annotations+import base64+import binasciiimport json+import mathfrom pathlib import Pathfrom urllib import error, request+from urllib.parse import quote, urlencode-from tts_backends.backend_common import publish_audio_bytes, read_api_key+from tts_backends.backend_common import (+ publish_audio_bytes,+ publish_audio_subtitle,+ read_api_key,+)+from tts_backends.backend_edge import (+ DEFAULT_SUBTITLE_MAX_CHARS,+ format_word_timed_srt,+)API_BASE = "https://api.elevenlabs.io/v1"+_TICKS_PER_SECOND = 10_000_000def read_elevenlabs_api_key(env_name: str) -> str:@@ -34,6 +47,118 @@ def _read_http_error(exc: error.HTTPError) -> str:return f"HTTP {exc.code}: {body or exc.reason}"+def _seconds_to_ticks(value: object, *, field: str) -> int:+ if isinstance(value, bool):+ raise RuntimeError(f"ElevenLabs alignment {field} is not numeric")+ try:+ numeric = float(value)+ except (TypeError, ValueError) as exc:+ raise RuntimeError(+ f"ElevenLabs alignment {field} is not numeric"+ ) from exc+ if not math.isfinite(numeric):+ raise RuntimeError(f"ElevenLabs alignment {field} is not finite")+ return int(round(numeric * _TICKS_PER_SECOND))+++def _is_unspaced_character(character: str) -> bool:+ """Return whether a script is safer to time one character at a time."""+ codepoint = ord(character)+ return (+ 0x3040 <= codepoint <= 0x30FF+ or 0x3400 <= codepoint <= 0x4DBF+ or 0x4E00 <= codepoint <= 0x9FFF+ or 0xAC00 <= codepoint <= 0xD7AF+ or 0xF900 <= codepoint <= 0xFAFF+ or 0x20000 <= codepoint <= 0x2FA1F+ )+++def _alignment_characters(+ text: str,+ alignment: object,+) -> tuple[list[str], list[object], list[object]]:+ if not isinstance(alignment, dict):+ raise RuntimeError("ElevenLabs response contains no original-text alignment")+ raw_characters = alignment.get("characters")+ raw_starts = alignment.get("character_start_times_seconds")+ raw_ends = alignment.get("character_end_times_seconds")+ if not all(isinstance(values, list) for values in (+ raw_characters,+ raw_starts,+ raw_ends,+ )):+ raise RuntimeError("ElevenLabs alignment arrays are missing")+ if not raw_characters or not (+ len(raw_characters) == len(raw_starts) == len(raw_ends)+ ):+ raise RuntimeError("ElevenLabs alignment arrays have inconsistent lengths")+ if any(not isinstance(item, str) or not item for item in raw_characters):+ raise RuntimeError("ElevenLabs alignment contains an invalid character")+ if "".join(raw_characters) != text:+ raise RuntimeError(+ "ElevenLabs original-text alignment differs from the narration text; "+ "audio and subtitles were not published"+ )++ characters: list[str] = []+ starts: list[object] = []+ ends: list[object] = []+ for raw_character, start, end in zip(+ raw_characters,+ raw_starts,+ raw_ends,+ ):+ for character in raw_character:+ characters.append(character)+ starts.append(start)+ ends.append(end)+ return characters, starts, ends+++def _word_boundaries(text: str, alignment: object) -> list[dict]:+ characters, starts, ends = _alignment_characters(text, alignment)+ boundaries: list[dict] = []+ index = 0+ while index < len(characters):+ character = characters[index]+ if not character.isalnum():+ index += 1+ continue++ token_end = index + 1+ if not _is_unspaced_character(character):+ while token_end < len(characters):+ following = characters[token_end]+ if (+ not following.isalnum()+ or _is_unspaced_character(following)+ ):+ break+ token_end += 1++ start = _seconds_to_ticks(starts[index], field="start time")+ end = _seconds_to_ticks(ends[token_end - 1], field="end time")+ if start < 0 or end <= start:+ raise RuntimeError(+ "ElevenLabs alignment contains an invalid character interval"+ )+ if boundaries and start < boundaries[-1]["offset"]:+ raise RuntimeError(+ "ElevenLabs alignment is not in chronological order"+ )+ boundaries.append({+ "text": "".join(characters[index:token_end]),+ "offset": start,+ "duration": end - start,+ })+ index = token_end++ if not boundaries:+ raise RuntimeError("ElevenLabs alignment contains no timed words")+ return boundaries++def generate(text: str,output_path: Path,@@ -45,7 +170,10 @@ def generate(stability: float | None,similarity_boost: float | None,style: float | None,+ speed: float | None,speaker_boost: bool | None,+ subtitle_path: Path | None = None,+ subtitle_max_chars: int = DEFAULT_SUBTITLE_MAX_CHARS,) -> None:payload: dict[str, object] = {"text": text,@@ -59,13 +187,19 @@ def generate(voice_settings["similarity_boost"] = similarity_boostif style is not None:voice_settings["style"] = style+ if speed is not None:+ voice_settings["speed"] = speedif speaker_boost is not None:voice_settings["use_speaker_boost"] = speaker_boostif voice_settings:payload["voice_settings"] = voice_settings+ query = urlencode({"output_format": output_format})+ suffix = "/with-timestamps" if subtitle_path is not None else ""+ url = (+ f"{API_BASE}/text-to-speech/{quote(voice_id, safe='')}{suffix}?{query}"+ )body = json.dumps(payload, ensure_ascii=False).encode("utf-8")- url = f"{API_BASE}/text-to-speech/{voice_id}?output_format={output_format}"req = request.Request(url,data=body,@@ -77,12 +211,39 @@ def generate()try:with request.urlopen(req, timeout=120) as response:- publish_audio_bytes(response.read(), output_path)+ response_data = response.read()except error.HTTPError as exc:raise RuntimeError(_read_http_error(exc)) from excexcept error.URLError as exc:raise RuntimeError(f"ElevenLabs request failed: {exc.reason}") from exc+ if subtitle_path is None:+ publish_audio_bytes(response_data, output_path)+ return++ try:+ data = json.loads(response_data.decode("utf-8"))+ except (UnicodeError, json.JSONDecodeError) as exc:+ raise RuntimeError(+ "ElevenLabs timing response is not valid UTF-8 JSON"+ ) from exc+ encoded_audio = data.get("audio_base64")+ if not isinstance(encoded_audio, str) or not encoded_audio:+ raise RuntimeError("ElevenLabs timing response contains no audio")+ try:+ audio = base64.b64decode(encoded_audio, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise RuntimeError(+ "ElevenLabs timing response audio is not valid base64"+ ) from exc+ subtitle = format_word_timed_srt(+ text,+ _word_boundaries(text, data.get("alignment")),+ subtitle_max_chars,+ provider_label="ElevenLabs",+ )+ publish_audio_subtitle(audio, output_path, subtitle, subtitle_path)+def print_voices(api_key: str) -> None:req = request.Request(diff --git a/skills/ppt-master/scripts/tts_backends/backend_qwen.py b/skills/ppt-master/scripts/tts_backends/backend_qwen.pyindex 04f2c413..325abdba 100644--- a/skills/ppt-master/scripts/tts_backends/backend_qwen.py+++ b/skills/ppt-master/scripts/tts_backends/backend_qwen.py@@ -72,4 +72,4 @@ def print_voices() -> None:print("Qwen TTS voices are selected by voice.")print("Use a system voice name or a cloned voice from Qwen voice cloning.")print("Example system voice from Alibaba Cloud docs: Cherry")-+ print("Current Qwen TTS responses do not include word/character timestamps.")diff --git a/skills/ppt-master/workflows/stages/generate-audio.md b/skills/ppt-master/workflows/stages/generate-audio.mdindex 61921f18..4855c0ee 100644--- a/skills/ppt-master/workflows/stages/generate-audio.md+++ b/skills/ppt-master/workflows/stages/generate-audio.md@@ -4,7 +4,7 @@ description: Shared post-processing stage for narration audio, PPTX embedding, a# Generate Audio Stage-> Shared narration stage. Run from the Generate PPTX route after notes/export readiness, or from the Enhance Native PPTX narration module after its notes step. By default, `edge-tts` produces one audio/SRT pair per slide from the same streaming request. MiniMax also produces an audio/SRT pair through its synchronous subtitle response; ElevenLabs, Qwen, and CosyVoice produce audio only. The caller owns final PPTX integration.+> Shared narration stage. Run after the owning route's notes step. Edge, ElevenLabs, MiniMax, and timestamp-capable CosyVoice produce per-slide audio/SRT from synthesis timing. Qwen is audio-only because its TTS API exposes no timing. The caller owns final PPTX integration.This stage is **context-independent**: it reads `notes/*.md` and queries the selected TTS voice catalog, so either owning route may invoke it in a fresh session. It does not choose the top-level route and does not patch slide design.@@ -26,7 +26,7 @@ this stage.- Per-page narration files exist at `notes/*.md`. In Generate PPTX, split `notes/total.md` during Step 7.1. In Enhance Native PPTX, the notes module writes numeric files such as `001.md`.- Default mode: `edge-tts` is installed (`python3 -m pip install edge-tts`).-- The stage is page-level only: with edge or MiniMax, one notes file becomes `audio/<stem>.mp3` plus `audio/<stem>.srt`; with another cloud provider, it becomes one audio file. Do not use a single long audio track or attempt automatic long-audio splitting.+- The stage is page-level only: one note becomes `audio/<stem>.<audio-ext>` plus `audio/<stem>.srt` on provider-timed paths, or one audio file with Qwen / explicit CosyVoice audio-only mode. Never substitute one long track or automatic splitting.- A fully successful run writes a compact `audio/manifest.json` with only provider/model, audio/subtitle format, relevant voice settings, and a SHA-256 fingerprint instead of the raw cloud voice ID. It has no per-slide inventory, artifact hashes, or API keys and is not a normal generation input. The flat `audio/` directory is the single active narration set; do not create provider subdirectories unless the user explicitly asks to preserve multiple variants.- PPT narration assets must be PowerPoint-reliable audio: `m4a` (AAC), `mp3`, or `wav`. The built-in TTS path defaults to `mp3`; provider formats such as `pcm`, `opus`, or `flac` must be transcoded before embedding.- PowerPoint recorded narration export requires `ffprobe` so slide timings can be written from actual audio duration.@@ -93,6 +93,7 @@ The output is a flat list of all available voices for the selected provider. Fro- **For edge**: prefer `COMMON_VOICES`-listed voices (curated set inside `notes_to_audio.py`) when the locale has them — they are battle-tested.- **For ElevenLabs**: prefer voices already present in the user's account; if the user provides a specific `voice_id`, do not override it.- **For MiniMax / Qwen / CosyVoice**: if the user provides a cloned `voice_id`, use it directly. Do not attempt voice cloning inside this narration stage.+- **For CosyVoice subtitles**: use a cloned voice from a supported v3.5/v3/v2 model or a system voice marked timestamp-supported. Model and voice families must match. Use `--cosyvoice-audio-only` only when the user accepts no page-local SRT.- **Match the deck's tone** — pick the strongest recommendation based on style:- Consultant / data-driven / 财报 → 稳重男声(如 `zh-CN-YunjianNeural`)or 清晰女声(如 `zh-CN-XiaoxiaoNeural`)- General / 教学 / 产品介绍 → 明亮女声 / 年轻男声(如 `zh-CN-XiaoyiNeural` / `zh-CN-YunxiNeural`)@@ -133,7 +134,7 @@ Send a single message to the user that resolves all five configuration decisions> 直接回"好"用全部推荐值,或告诉我想改的部分(如"音色 2,语速 -5%"或"用 MiniMax 的 voice_id xxx")。**Recommended-value rules**:-- 生成模式:默认 `edge`;当用户明确追求高质量云端音色或提供 cloud voice ID 时,按用户指定选 `elevenlabs` / `minimax` / `qwen` / `cosyvoice`。+- 生成模式:默认 `edge`;用户指定 cloud provider / voice ID 时按其选择。需要逐页 SRT、字幕动画或视频字幕时不推荐 Qwen;用户坚持时,说明仅交付音频并跳过 SRT 步骤。- 音色:从 Step 2 候选里挑最贴合 deck 调性的那一个。- 语速:edge 默认 `+0%`;notes 字数密集(页均 >4 句长句)建议 `-5%`;notes 简短紧凑建议 `+5%`;超出此范围需说明理由。Cloud providers 默认用 provider defaults,除非用户明确要调速或改风格。- 嵌入:默认推荐"是";除非用户已有定制 PPTX 不希望覆盖。@@ -157,7 +158,7 @@ Run sequentially — do NOT bundle:python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice <chosen-ShortName> --rate <chosen-rate>-# 1B. Or generate audio with ElevenLabs+# 1B. Or generate audio/SRT pairs with ElevenLabspython3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider elevenlabs --voice-id <chosen-voice-id> \--elevenlabs-model eleven_multilingual_v2@@ -168,17 +169,18 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider minimax --voice-id <chosen-voice-id> \--minimax-model speech-2.8-hd-# 1D. Or generate audio with Qwen TTS+# 1D. Or generate audio only with Qwen TTS (the API returns no timestamps)python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider qwen --voice-id <chosen-voice> \--qwen-model qwen3-tts-flash --qwen-language-type Chinese-# 1E. Or generate audio with CosyVoice+# 1E. Or generate audio/SRT pairs with a timestamp-capable CosyVoice voicepython3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--provider cosyvoice --voice-id <chosen-voice> \--cosyvoice-model cosyvoice-v3-flash-# 2A. When animations.json is active, author or refresh narration_timing.json+# 2A. Only when page-local SRT exists and animations.json is active, author or+# refresh narration_timing.json# by matching SVG group semantics to SRT topics, then derive the narrated# sidecar. Reuse current SVG semantics when complete; otherwise read only# the missing or stale svg_output pages.@@ -202,7 +204,8 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \--recorded-narration audio --narration-padding 0.5 \--no-animations-# 2C. Merge page-local SRT against timing values read from the final PPTX+# 2C. Only when page-local SRT exists, merge it against timing values read+# from the final PPTXpython3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \--pptx <final_narrated_pptx> --force@@ -210,7 +213,8 @@ python3 skills/ppt-master/scripts/narration_sync.py subtitles <project_path> \python3 skills/ppt-master/scripts/powerpoint_video.py \<final_narrated_pptx> -o <final_video.mp4>-# 2E. Align the frozen narration text against the finished video's audio track+# 2E. Only when page-local SRT exists, align the frozen narration text against+# the finished video's audio trackpython3 skills/ppt-master/scripts/video_subtitles.py <project_path> \--video <final_video.mp4> --language <language> --force```@@ -224,7 +228,9 @@ If `notes_to_audio.py` errors with a missing dependency or missing provider APIThe edge command writes each MP3 and its internal page SRT from the same `edge-tts` stream. SRT cues use the service's `WordBoundary` timing: sentence-ending punctuation always closes a cue; text over the default 20-visible-character limit first splits at commas, semicolons, or colons, then at the nearest word boundary. Override the limit with `--subtitle-max-chars`. Adjacent timing overlap up to 100 ms is tolerated by moving the later cue start to the previous cue end; larger overlap fails instead of silently distorting timing. Each SRT uses a page-local timeline whose origin is `00:00:00,000`, including any leading silence before the first cue.-The MiniMax command requests word-level subtitles on the same non-streaming `/v1/t2a_v2` call, downloads the returned JSON timing file, and applies the same punctuation-first, `--subtitle-max-chars`-bounded regrouping as Edge. It publishes the validated MP3/SRT as a rollback-safe pair; the compact cues are the units used for semantic animation mapping. ElevenLabs, Qwen, and CosyVoice commands write audio only.+MiniMax reads word timing from its synchronous subtitle file. ElevenLabs uses `/with-timestamps` and original-text character alignment. CosyVoice enables HTTP streaming plus `word_timestamp_enabled`, then uses the final audio URL and word timing from that synthesis; unsupported model/voice pairs fail without replacing the prior pair unless `--cosyvoice-audio-only` was explicit. Qwen exposes no timing, so it remains audio-only and this stage never estimates SRT timing.++Provider-timed paths share punctuation-first, `--subtitle-max-chars`-bounded regrouping, exact-text validation, and rollback-safe pair publication. See [`docs/audio-narration.md`](../../../../docs/audio-narration.md) for current model and audio-parameter recommendations.Before generation starts, `notes_to_audio.py` removes stale `audio/manifest.json` and `audio/total.srt`; an incomplete run therefore cannot claim the previous set's provenance or merged timeline. A successful audio-only provider run also removes same-stem stale SRT files. The new manifest is published atomically only after the complete page roster succeeds.@@ -295,9 +301,11 @@ This stage keeps subtitles as external SRT files. It does not burn subtitles int| Caller | After audio generation ||---|---|-| Generate PPTX | With page-local SRT from Edge or MiniMax and an existing `animations.json`, derive `narration_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`, optionally continue through `powerpoint_video.py`, then generate the delivery SRT from the finished video. |+| Generate PPTX | With page-local SRT from Edge, ElevenLabs, MiniMax, or timestamp-capable CosyVoice and an existing `animations.json`, derive `narration_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`, optionally continue through `powerpoint_video.py`, then generate the delivery SRT from the finished video. || 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. Never present those missing subtitle artifacts 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 audio duration plus padding. The re-export is saved as `exports/<project_name>_<timestamp>_narrated.pptx`, telling it apart from silent exports.**Narrated SVG export**: use the default text-flow mode. It keeps authored line breaks in one editable, no-wrap text frame; narration does not require per-line text frames.@@ -309,7 +317,7 @@ For Generate PPTX, `--recorded-narration audio` prepares PowerPoint's recorded tOutput one summary block listing:- Number of audio files generated and their location (`<project_path>/audio/*`).-- For edge or MiniMax subtitles, number of matching page-local SRT files and their location (`<project_path>/audio/*`).+- For provider-timed subtitles, number of matching page-local SRT files and their location (`<project_path>/audio/*`); for Qwen or explicit CosyVoice audio-only mode, report that no page-local SRT was generated.- 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 with page-local SRT and canonical custom animation, derived narration animation group count and `narration_animations.json` path; otherwise report inherited base motion or explicit all-motion-off.