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 MiniMax word-timed subtitles
hugohe3911ea34a2783
diff --git a/docs/audio-narration.md b/docs/audio-narration.mdindex d5d86f1f..9920f1b2 100644--- a/docs/audio-narration.md+++ b/docs/audio-narration.md@@ -4,12 +4,12 @@----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. The edge path also writes a page-local SRT from the same TTS stream. 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 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.## 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, one matching subtitle file per slide under `<project_path>/notes/subtitles/` (`01_cover.srt`, `02_market_landscape.srt`, …). Each file uses a page-local timeline with a `00:00:00,000` origin and edge's word-boundary timing.+- With edge or MiniMax subtitles, one matching subtitle file per slide under `<project_path>/notes/subtitles/` (`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.- 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>/notes/subtitles/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.@@ -20,7 +20,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 to `audio/` and `notes/subtitles/`; cloud providers currently write audio only. 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.** With edge, the script writes each page's MP3 and SRT from the same stream to `audio/` and `notes/subtitles/`. 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. 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.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.@@ -74,7 +74,7 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice-id <elevenlabs-voice-id> \--elevenlabs-model eleven_multilingual_v2-# 2C. Or generate MP3s with MiniMax (supports system and cloned voice_id)+# 2C. Or generate MP3/SRT pairs with MiniMax (supports system and cloned voice_id)export MINIMAX_API_KEY="your-minimax-api-key"# Defaults to the China endpoint. For overseas access, set MINIMAX_TTS_BASE_URL=https://api.minimax.io/v1/t2a_v2.python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \@@ -140,11 +140,13 @@ Edge generates up to three slide-level audio/SRT pairs concurrently by default.Use `--concurrency <N>` to tune it or `--concurrency 1` for serialtroubleshooting. Cloud providers remain serial.-The edge command creates `audio/<stem>.mp3` and `notes/subtitles/<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. The cloud-provider commands currently create audio only.+The edge command creates `audio/<stem>.mp3` and `notes/subtitles/<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.When canonical custom animation exists, `narration_timing.json` remains deliberately separate from read-only `animations.json`. It records the ordered SRT-set SHA-256, 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. 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. With no animation sidecars, skip that derivation. `narration_sync.py subtitles` reads the final PPTX's actual presentation order plus millisecond slide-advance and transition 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. Passing the finished `.mp4` / `.wmv` / `.mov` with `--video` uses normalized audio correlation to locate each original page narration in the exported audio track. It changes only the page-level offsets: edge's cue text and page-local `WordBoundary` timing remain untouched. This is a post-export subtitle calibration step and does not rewrite the video.+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. Passing the finished `.mp4` / `.wmv` / `.mov` with `--video` uses normalized audio correlation to locate each original page narration in the exported audio track. It changes only the page-level offsets: the provider's cue text and page-local timing remain untouched. This is a post-export subtitle calibration step and does not rewrite the video.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.diff --git a/docs/zh/audio-narration.md b/docs/zh/audio-narration.mdindex 4307b48f..8b960328 100644--- a/docs/zh/audio-narration.md+++ b/docs/zh/audio-narration.md@@ -4,12 +4,12 @@----PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edge-tts`](https://github.com/rany2/edge-tts) —— 微软 Edge 的在线神经网络语音;也可配置 ElevenLabs、MiniMax、Qwen TTS、CosyVoice 使用高质量或复刻音色)。Edge 路径还会从同一次 TTS 流中写出该页的 SRT;音频可继续嵌入 PPTX,供 PowerPoint 使用原生视频导出。+PPT Master 可以把演讲者备注转成逐页音频旁白(默认基于 [`edge-tts`](https://github.com/rany2/edge-tts) —— 微软 Edge 的在线神经网络语音;也可配置 ElevenLabs、MiniMax、Qwen TTS、CosyVoice 使用高质量或复刻音色)。Edge 会从同一次计时流中写出逐页 SRT;MiniMax 则把同步接口返回的字幕时间戳转换为同一套 SRT。音频可继续嵌入 PPTX,供 PowerPoint 使用原生视频导出。## 你会得到什么- 每页一个音频文件,存放于 `<project_path>/audio/`,文件名与 SVG 对齐(`01_cover.mp3`、`02_market_landscape.mp3` …)。-- 使用 Edge 时,每页还有一个同名字幕文件,存放于 `<project_path>/notes/subtitles/`(`01_cover.srt`、`02_market_landscape.srt` …)。每个文件使用以 `00:00:00,000` 为原点的页内时间轴,时间来自 Edge 的词边界。+- 使用 Edge 或 MiniMax 字幕时,每页还有一个同名字幕文件,存放于 `<project_path>/notes/subtitles/`(`01_cover.srt`、`02_market_landscape.srt` …)。每个文件使用以 `00:00:00,000` 为原点的页内时间轴;两个 provider 的词级时间戳都会重组为同一套紧凑 cue。- 存在规范的 `animations.json` 时,SVG 到 SRT 的计时计划会派生 `narration_animations.json`,让无点击对象动画等待相关字幕 cue。两个动画 sidecar 都不存在时,旁白导出不会创建 sidecar,而是保留默认 `fade` 页间切换和无逐元素动画。两条路径都可以生成与最终 PPTX 时间轴一致的 `<project_path>/notes/subtitles/total.srt`;PowerPoint 导出视频后,还可用同一命令根据视频音轨校准每页起点,得到帧级对齐的外挂字幕。- 可选重新导出:在 `exports/` 生成新版 PPTX,每页对应的 `m4a` / `mp3` / `wav` 音频已嵌入到该页,且页面切换时间按音频长度自动设置——无人值守自动播放和视频导出都不用再手动调时间。- Windows 下可选原生视频导出:`powerpoint_video.py` 把最终带旁白 PPTX 交给 PowerPoint 2016+,并等待其原生 MP4 编码成功或失败。@@ -20,7 +20,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/` 与 `notes/subtitles/`;云端 provider 目前仍只写音频。对于存在规范自定义动画的 Generate PPTX,AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;没有动画 sidecar 时则跳过派生,保留 `fade` / 无逐元素动画。随后再导出带音频的 PPTX,并从该 PPTX 读回实际计时、合并逐页 SRT。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器,等 MP4 完成后再校准交付字幕。不支持长音频导入或自动拆分。+4. **执行**。使用 Edge 时,脚本从同一次流中把每页 MP3 和 SRT 分别写到 `audio/` 与 `notes/subtitles/`。MiniMax 会在生成 MP3 的同一请求中获取服务端时间戳,并把返回的 JSON 转成相同的逐页 SRT;ElevenLabs、Qwen 与 CosyVoice 仍只写音频。对于存在规范自定义动画的 Generate PPTX,AI 将当前 SVG 内容组映射到编号后的 SRT cue,并派生无点击的 `narration_animations.json`;没有动画 sidecar 时则跳过派生,保留 `fade` / 无逐元素动画。随后再导出带音频的 PPTX,并从该 PPTX 读回实际计时、合并逐页 SRT。若用户选择自动视频导出且本机 Windows PowerPoint 兼容,则继续调用 PowerPoint 原生编码器,等 MP4 完成后再校准交付字幕。不支持长音频导入或自动拆分。字幕保持为外部 SRT 文件:PPT Master 不把字幕嵌入 PPTX,也不烧录进 MP4。自动视频导出委托给本机 Windows PowerPoint,并不是另一套渲染器。@@ -73,7 +73,7 @@ python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \--voice-id <elevenlabs-voice-id> \--elevenlabs-model eleven_multilingual_v2-# 2C. 用 MiniMax 生成 MP3(支持系统音色或复刻 voice_id)+# 2C. 用 MiniMax 生成 MP3/SRT 对(支持系统音色或复刻 voice_id)export MINIMAX_API_KEY="your-minimax-api-key"# 默认使用国内地址;海外访问可设置 MINIMAX_TTS_BASE_URL=https://api.minimax.io/v1/t2a_v2python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> \@@ -134,11 +134,13 @@ edge 模式下 `--voice` 是必填项,可用 `--list-voices --locale <locale>`Edge 默认同时生成最多 3 页音频/SRT。可用 `--concurrency <N>` 调整;排查连接问题时可设为 `--concurrency 1`。云端 provider 仍保持串行。-Edge 命令会从同一次流式请求中生成 `audio/<stem>.mp3` 与 `notes/subtitles/<stem>.srt`。句末标点必定结束一条字幕;单条超过默认 20 个可见字符时,优先在逗号、分号或冒号处拆分,仍然过长才在最近的词边界拆分。可用 `--subtitle-max-chars` 调整上限。相邻字幕最多允许 100 毫秒的计时重叠:后一句起点会移到前一句终点;超过该范围则报错。每页 SRT 使用从零计时的页内时间基准,并保留 Edge `WordBoundary` 的实际时间(包括首条字幕前的静音);云端 provider 命令目前只生成音频。+Edge 命令会从同一次流式请求中生成 `audio/<stem>.mp3` 与 `notes/subtitles/<stem>.srt`。句末标点必定结束一条字幕;单条超过默认 20 个可见字符时,优先在逗号、分号或冒号处拆分,仍然过长才在最近的词边界拆分。可用 `--subtitle-max-chars` 调整上限。相邻字幕最多允许 100 毫秒的计时重叠:后一句起点会移到前一句终点;超过该范围则报错。每页 SRT 使用从零计时的页内时间基准,并保留 Edge `WordBoundary` 的实际时间(包括首条字幕前的静音)。++MiniMax 会在同一次非流式 T2A 请求中获取词级字幕,下载返回的 JSON 时间戳,再复用 Edge 的标点优先、长度受控重组逻辑。校验通过后成对发布 MP3 与 SRT;`--subtitle-max-chars` 同时控制两个 provider,整理后的紧凑 cue 用于语义动画映射。ElevenLabs、Qwen 与 CosyVoice 仍只生成音频。存在规范自定义动画时,`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`。包含 `effects[]` 的分组仍只映射一条 cue:第一条有效动画行锚定该 cue,后续动画行保留相对延迟。没有动画 sidecar 时跳过该派生步骤。`narration_sync.py subtitles` 从最终 PPTX 读取真实页面关系顺序、毫秒级页面推进与转场时间,因此 `total.srt` 使用原生 PPTX 时间轴。相对 `--pptx` 路径按 `<project_path>` 解析。-PowerPoint 的视频编码器可能把每个页面 / 媒体段落量化到输出帧时钟;即使 PPTX 计时值正确,这些很小的分页误差仍可能逐页累积。把最终 `.mp4` / `.wmv` / `.mov` 通过 `--video` 传入后,脚本会用归一化音频相关性在视频音轨中定位每页原始旁白。它只改页级偏移,Edge 的字幕文本和页内 `WordBoundary` 时间保持不变;这是视频导出后的字幕校准步骤,不会改写视频。+PowerPoint 的视频编码器可能把每个页面 / 媒体段落量化到输出帧时钟;即使 PPTX 计时值正确,这些很小的分页误差仍可能逐页累积。把最终 `.mp4` / `.wmv` / `.mov` 通过 `--video` 传入后,脚本会用归一化音频相关性在视频音轨中定位每页原始旁白。它只改页级偏移,provider 返回的字幕文本和页内时间保持不变;这是视频导出后的字幕校准步骤,不会改写视频。最终带旁白的 SVG 导出使用默认文本流模式即可:在一个禁用自动换行的可编辑文本框中保留作者断行;旁白不要求每一行拆成独立文本框。diff --git a/skills/ppt-master/scripts/notes_to_audio.py b/skills/ppt-master/scripts/notes_to_audio.pyindex 8e2324b0..de769881 100644--- a/skills/ppt-master/scripts/notes_to_audio.py+++ b/skills/ppt-master/scripts/notes_to_audio.py@@ -4,6 +4,7 @@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.Usage:python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --voice zh-CN-XiaoxiaoNeural@@ -293,7 +294,7 @@ def main() -> int:"--subtitle-max-chars",type=int,default=backend_edge.DEFAULT_SUBTITLE_MAX_CHARS,- help="maximum visible characters per Edge subtitle cue (default: 20)",+ help="maximum visible characters per Edge/MiniMax subtitle cue (default: 20)",)parser.add_argument("--elevenlabs-api-key-env",@@ -487,6 +488,7 @@ def main() -> int:notes_dir = project / "notes"output_dir = args.output or (project / "audio")subtitle_dir = notes_dir / "subtitles"+ writes_subtitles = backend.provider in {"edge", "minimax"}try:note_roster = _expected_note_roster(project)@@ -502,7 +504,7 @@ def main() -> int:return 2output_dir.mkdir(parents=True, exist_ok=True)- if backend.provider == "edge":+ if writes_subtitles:subtitle_dir.mkdir(parents=True, exist_ok=True)generated = 0@@ -553,6 +555,7 @@ def main() -> int:for job in jobs:output_path = job.output_pathtext = job.text+ subtitle_path: Path | None = Nonetry:if backend.provider == "elevenlabs":backend_elevenlabs.generate(@@ -568,6 +571,8 @@ def main() -> int:speaker_boost=args.elevenlabs_speaker_boost,)elif backend.provider == "minimax":+ if writes_subtitles:+ subtitle_path = subtitle_dir / f"{output_path.stem}.srt"backend_minimax.generate(text,output_path,@@ -583,6 +588,8 @@ def main() -> int:pitch=args.minimax_pitch,language_boost=args.minimax_language_boost,base_url=args.minimax_base_url,+ subtitle_path=subtitle_path,+ subtitle_max_chars=args.subtitle_max_chars,)elif backend.provider == "qwen":backend_qwen.generate(@@ -618,8 +625,10 @@ def main() -> int:return 1generated += 1print(f"[OK] {output_path}")+ if subtitle_path is not None:+ print(f" {subtitle_path}")- if backend.provider == "edge":+ if writes_subtitles:print(f"[Done] Generated {generated}/{len(note_roster)} audio/SRT pair(s): "f"{output_dir} + {subtitle_dir}"diff --git a/skills/ppt-master/scripts/tts_backends/backend_common.py b/skills/ppt-master/scripts/tts_backends/backend_common.pyindex 190d684a..787a0926 100644--- a/skills/ppt-master/scripts/tts_backends/backend_common.py+++ b/skills/ppt-master/scripts/tts_backends/backend_common.py@@ -61,18 +61,66 @@ def download_audio(url: str, output_path: Path) -> None:publish_audio_bytes(get_bytes(url), output_path)+def temporary_path(target: Path, suffix: str) -> tuple[int, Path]:+ """Create a temporary file beside its eventual target."""+ target.parent.mkdir(parents=True, exist_ok=True)+ descriptor, raw_path = tempfile.mkstemp(+ prefix=f".{target.name}.",+ suffix=suffix,+ dir=target.parent,+ )+ return descriptor, Path(raw_path)+++def publish_staged_pair(+ staged_first: Path,+ first_target: Path,+ staged_second: Path,+ second_target: Path,+) -> None:+ """Publish two staged files together, restoring prior targets on failure."""+ targets = (first_target, second_target)+ if first_target.resolve() == second_target.resolve():+ raise ValueError("paired outputs must use different paths")++ backups: dict[Path, Path] = {}+ published: set[Path] = set()+ try:+ for target in targets:+ if not target.exists():+ continue+ descriptor, backup = temporary_path(target, ".bak")+ os.close(descriptor)+ backup.unlink()+ os.replace(target, backup)+ backups[target] = backup++ for staged, target in (+ (staged_first, first_target),+ (staged_second, second_target),+ ):+ os.replace(staged, target)+ published.add(target)+ except Exception:+ for target in published:+ target.unlink(missing_ok=True)+ for target, backup in backups.items():+ if backup.exists():+ os.replace(backup, target)+ raise+ finally:+ staged_first.unlink(missing_ok=True)+ staged_second.unlink(missing_ok=True)+ for backup in backups.values():+ backup.unlink(missing_ok=True)++def publish_audio_bytes(audio: bytes, output_path: Path) -> None:"""Publish non-empty provider audio without exposing a partial target."""if not audio:raise RuntimeError("TTS provider returned empty audio data")- output_path.parent.mkdir(parents=True, exist_ok=True)- descriptor, raw_path = tempfile.mkstemp(- prefix=f".{output_path.name}.",- suffix=".tmp",- dir=output_path.parent,- )- staged_path = Path(raw_path)+ descriptor, staged_path = temporary_path(output_path, ".tmp")try:with os.fdopen(descriptor, "wb") as stream:descriptor = -1@@ -88,6 +136,62 @@ def publish_audio_bytes(audio: bytes, output_path: Path) -> None:staged_path.unlink(missing_ok=True)+def publish_audio_subtitle(+ audio: bytes,+ output_path: Path,+ subtitle: str,+ subtitle_path: Path,+) -> None:+ """Publish one audio/SRT pair without exposing mismatched targets."""+ if not audio:+ raise RuntimeError("TTS provider returned empty audio data")+ if not subtitle.strip():+ raise RuntimeError("TTS provider returned empty subtitle data")++ audio_descriptor = -1+ subtitle_descriptor = -1+ staged_audio: Path | None = None+ staged_subtitle: Path | None = None+ try:+ audio_descriptor, staged_audio = temporary_path(output_path, ".tmp")+ subtitle_descriptor, staged_subtitle = temporary_path(subtitle_path, ".tmp")++ audio_stream = os.fdopen(audio_descriptor, "wb")+ audio_descriptor = -1+ with audio_stream:+ audio_stream.write(audio)+ audio_stream.flush()+ os.fsync(audio_stream.fileno())++ subtitle_stream = os.fdopen(+ subtitle_descriptor,+ "w",+ encoding="utf-8",+ newline="\n",+ )+ subtitle_descriptor = -1+ with subtitle_stream:+ subtitle_stream.write(subtitle)+ subtitle_stream.flush()+ os.fsync(subtitle_stream.fileno())++ publish_staged_pair(+ staged_audio,+ output_path,+ staged_subtitle,+ subtitle_path,+ )+ finally:+ if audio_descriptor >= 0:+ os.close(audio_descriptor)+ if subtitle_descriptor >= 0:+ os.close(subtitle_descriptor)+ if staged_audio is not None:+ staged_audio.unlink(missing_ok=True)+ if staged_subtitle is not None:+ staged_subtitle.unlink(missing_ok=True)++def extension_from_format(audio_format: str) -> str:normalized = audio_format.strip().lower()if normalized in {"mp3", "wav"}:diff --git a/skills/ppt-master/scripts/tts_backends/backend_edge.py b/skills/ppt-master/scripts/tts_backends/backend_edge.pyindex 8f0e433f..8d0856e0 100644--- a/skills/ppt-master/scripts/tts_backends/backend_edge.py+++ b/skills/ppt-master/scripts/tts_backends/backend_edge.py@@ -4,10 +4,11 @@ from __future__ import annotationsimport osimport re-import tempfilefrom dataclasses import dataclassfrom pathlib import Path+from tts_backends.backend_common import publish_staged_pair, temporary_path+DEFAULT_SUBTITLE_MAX_CHARS = 20DEFAULT_BOUNDARY_OVERLAP_TOLERANCE_MS = 100@@ -102,58 +103,6 @@ async def generate(await communicate.save(str(output_path))-def _temporary_path(target: Path, suffix: str) -> tuple[int, Path]:- target.parent.mkdir(parents=True, exist_ok=True)- descriptor, raw_path = tempfile.mkstemp(- prefix=f".{target.name}.",- suffix=suffix,- dir=target.parent,- )- return descriptor, Path(raw_path)---def _publish_pair(- staged_audio: Path,- output_path: Path,- staged_subtitle: Path,- subtitle_path: Path,-) -> None:- targets = (output_path, subtitle_path)- if output_path.resolve() == subtitle_path.resolve():- raise ValueError("audio and subtitle outputs must use different paths")-- backups: dict[Path, Path] = {}- published: set[Path] = set()- try:- for target in targets:- if not target.exists():- continue- descriptor, backup = _temporary_path(target, ".bak")- os.close(descriptor)- backup.unlink()- os.replace(target, backup)- backups[target] = backup-- for staged, target in (- (staged_audio, output_path),- (staged_subtitle, subtitle_path),- ):- os.replace(staged, target)- published.add(target)- except Exception:- for target in published:- target.unlink(missing_ok=True)- for target, backup in backups.items():- if backup.exists():- os.replace(backup, target)- raise- finally:- staged_audio.unlink(missing_ok=True)- staged_subtitle.unlink(missing_ok=True)- for backup in backups.values():- backup.unlink(missing_ok=True)--def _text_key(text: str) -> str:return "".join(character.casefold() for character in text if character.isalnum())@@ -170,13 +119,17 @@ def _source_key_positions(text: str) -> tuple[str, list[int]]:return "".join(key), positions-def _map_word_boundaries(text: str, boundaries: list[dict]) -> list[_MappedWord]:+def _map_word_boundaries(+ text: str,+ boundaries: list[dict],+ provider_label: str,+) -> list[_MappedWord]:source_key, source_positions = _source_key_positions(text)boundary_keys = [_text_key(boundary["text"]) for boundary in boundaries]boundary_key = "".join(boundary_keys)if not source_key or source_key != boundary_key:raise RuntimeError(- "Edge TTS word boundaries could not be aligned with the narration text; "+ f"{provider_label} word boundaries could not be aligned with the narration text; ""subtitle timing was not generated")@@ -335,6 +288,7 @@ def _clamp_small_overlaps(cues: list[_SubtitleCue],*,tolerance_ms: int = DEFAULT_BOUNDARY_OVERLAP_TOLERANCE_MS,+ provider_label: str,) -> list[_SubtitleCue]:tolerance = tolerance_ms * _TICKS_PER_MILLISECONDnormalized: list[_SubtitleCue] = []@@ -344,7 +298,7 @@ def _clamp_small_overlaps(if overlap > tolerance:overlap_ms = overlap / _TICKS_PER_MILLISECONDraise RuntimeError(- f"Edge TTS returned {overlap_ms:g} ms of overlapping "+ f"{provider_label} returned {overlap_ms:g} ms of overlapping ""word-boundary timing; audio and subtitles were not published")cue = _SubtitleCue(@@ -354,7 +308,7 @@ def _clamp_small_overlaps()if cue.end <= cue.start:raise RuntimeError(- "Edge TTS returned an invalid subtitle timing interval; "+ f"{provider_label} returned an invalid subtitle timing interval; ""audio and subtitles were not published")normalized.append(cue)@@ -365,10 +319,11 @@ def _subtitle_cues(text: str,boundaries: list[dict],max_chars: int,+ provider_label: str,) -> list[_SubtitleCue]:if max_chars < 1:raise ValueError("subtitle_max_chars must be at least 1")- words = _map_word_boundaries(text, boundaries)+ words = _map_word_boundaries(text, boundaries, provider_label)spans = [spanfor sentence in _sentence_spans(text)@@ -391,29 +346,29 @@ def _subtitle_cues(if assigned_word_indexes != list(range(len(words))):raise RuntimeError(- "Edge TTS word boundaries crossed subtitle split points; "+ f"{provider_label} word boundaries crossed subtitle split points; ""subtitle timing was not generated")if not pending:- raise RuntimeError("Edge TTS produced no timed subtitle cues")+ raise RuntimeError(f"{provider_label} produced no timed subtitle cues")cues: list[_SubtitleCue] = []for index, (start, word_end, cue_text) in enumerate(pending):next_start = pending[index + 1][0] if index + 1 < len(pending) else Noneend = next_start if next_start is not None and next_start > word_end else word_endcues.append(_SubtitleCue(start=start, end=end, text=cue_text))- cues = _clamp_small_overlaps(cues)+ cues = _clamp_small_overlaps(cues, provider_label=provider_label)source_text = re.sub(r"\s+", "", text)subtitle_text = re.sub(r"\s+", "", "".join(cue.text for cue in cues))if subtitle_text != source_text:raise RuntimeError(- "Generated subtitle text does not match the narration text; "+ f"{provider_label} subtitle text does not match the narration text; ""audio and subtitles were not published")if any(_display_length(cue.text, 0, len(cue.text)) > max_chars for cue in cues):raise RuntimeError(- "A single Edge TTS word boundary exceeds the subtitle character limit; "+ f"A single {provider_label} word boundary exceeds the subtitle character limit; ""audio and subtitles were not published")return cues@@ -439,6 +394,24 @@ def _format_srt(cues: list[_SubtitleCue]) -> str:return "\n\n".join(blocks) + "\n"+def format_word_timed_srt(+ text: str,+ boundaries: list[dict],+ max_chars: int = DEFAULT_SUBTITLE_MAX_CHARS,+ *,+ provider_label: str = "Edge TTS",+) -> str:+ """Regroup provider word timings into compact, text-faithful SRT cues."""+ return _format_srt(+ _subtitle_cues(+ text,+ boundaries,+ max_chars,+ provider_label,+ )+ )++async def _generate_with_subtitles(text: str,output_path: Path,@@ -470,8 +443,8 @@ async def _generate_with_subtitles(boundaries: list[dict] = []received_audio = Falsetry:- audio_descriptor, staged_audio = _temporary_path(output_path, ".tmp")- subtitle_descriptor, staged_subtitle = _temporary_path(subtitle_path, ".tmp")+ audio_descriptor, staged_audio = temporary_path(output_path, ".tmp")+ subtitle_descriptor, staged_subtitle = temporary_path(subtitle_path, ".tmp")audio_stream = os.fdopen(audio_descriptor, "wb")audio_descriptor = -1@@ -489,7 +462,7 @@ async def _generate_with_subtitles(raise RuntimeError("Edge TTS returned no audio data")if not boundaries:raise RuntimeError("Edge TTS returned no word-boundary timing")- subtitle_text = _format_srt(_subtitle_cues(text, boundaries, max_chars))+ subtitle_text = format_word_timed_srt(text, boundaries, max_chars)subtitle_stream = os.fdopen(subtitle_descriptor,@@ -504,7 +477,7 @@ async def _generate_with_subtitles(os.fsync(subtitle_stream.fileno())assert staged_audio is not Noneassert staged_subtitle is not None- _publish_pair(+ publish_staged_pair(staged_audio,output_path,staged_subtitle,diff --git a/skills/ppt-master/scripts/tts_backends/backend_minimax.py b/skills/ppt-master/scripts/tts_backends/backend_minimax.pyindex 99d2b6d2..46b7dd65 100644--- a/skills/ppt-master/scripts/tts_backends/backend_minimax.py+++ b/skills/ppt-master/scripts/tts_backends/backend_minimax.py@@ -3,19 +3,28 @@from __future__ import annotationsimport binascii+import json+import mathimport osfrom pathlib import Pathfrom tts_backends.backend_common import (extension_from_format,+ get_bytes,post_json,publish_audio_bytes,+ publish_audio_subtitle,read_api_key,)+from tts_backends.backend_edge import (+ DEFAULT_SUBTITLE_MAX_CHARS,+ format_word_timed_srt,+)DEFAULT_ENDPOINT = "https://api.minimaxi.com/v1/t2a_v2"DEFAULT_MODEL = "speech-2.8-hd"+_TICKS_PER_MILLISECOND = 10_000# International fallback: set MINIMAX_TTS_BASE_URL=https://api.minimax.io if needed.@@ -37,6 +46,70 @@ def resolve_url(base_url: str | None = None) -> str:return base + "/v1/t2a_v2"+def _ticks(value: object, *, field: str) -> int:+ if isinstance(value, bool):+ raise RuntimeError(f"MiniMax subtitle {field} is not numeric")+ try:+ numeric = float(value)+ except (TypeError, ValueError) as exc:+ raise RuntimeError(f"MiniMax subtitle {field} is not numeric") from exc+ if not math.isfinite(numeric):+ raise RuntimeError(f"MiniMax subtitle {field} is not finite")+ return int(round(numeric * _TICKS_PER_MILLISECOND))+++def _word_boundaries(raw: object) -> list[dict]:+ if not isinstance(raw, list) or not raw:+ raise RuntimeError("MiniMax subtitle response contains no sentence blocks")++ boundaries: list[dict] = []+ for sentence in raw:+ if not isinstance(sentence, dict):+ raise RuntimeError("MiniMax subtitle sentence block is not an object")+ words = sentence.get("timestamped_words")+ if not isinstance(words, list) or not words:+ raise RuntimeError("MiniMax subtitle sentence block contains no word timings")+ for item in words:+ if not isinstance(item, dict):+ raise RuntimeError("MiniMax subtitle word timing is not an object")+ word = item.get("word")+ if not isinstance(word, str) or not word:+ raise RuntimeError("MiniMax subtitle word timing contains no text")+ start = _ticks(item.get("time_begin"), field="start time")+ end = _ticks(item.get("time_end"), field="end time")+ if start < 0 or end <= start:+ raise RuntimeError(+ "MiniMax subtitle response contains an invalid word interval"+ )+ if boundaries and start < boundaries[-1]["offset"]:+ raise RuntimeError("MiniMax subtitle words are not in chronological order")+ boundaries.append(+ {+ "text": word,+ "offset": start,+ "duration": end - start,+ }+ )+ return boundaries+++def _download_subtitle(+ url: str,+ text: str,+ max_chars: int,+) -> str:+ try:+ raw = json.loads(get_bytes(url).decode("utf-8-sig"))+ except (UnicodeError, json.JSONDecodeError) as exc:+ raise RuntimeError("MiniMax subtitle response is not valid UTF-8 JSON") from exc+ return format_word_timed_srt(+ text,+ _word_boundaries(raw),+ max_chars,+ provider_label="MiniMax",+ )++def generate(text: str,output_path: Path,@@ -53,6 +126,8 @@ def generate(pitch: int,language_boost: str,base_url: str | None,+ subtitle_path: Path | None = None,+ subtitle_max_chars: int = DEFAULT_SUBTITLE_MAX_CHARS,) -> None:payload = {"model": model,@@ -73,6 +148,10 @@ def generate("channel": channel,},}+ if subtitle_path is not None:+ payload["subtitle_enable"] = True+ payload["subtitle_type"] = "word"+data = post_json(resolve_url(base_url),headers={"Authorization": f"Bearer {api_key}"},@@ -83,14 +162,31 @@ def generate(if base_resp.get("status_code") not in (None, 0, "0"):raise RuntimeError(f"MiniMax TTS failed: {data}")- audio_hex = (data.get("data") or {}).get("audio")+ response_data = data.get("data") or {}+ audio_hex = response_data.get("audio")if not audio_hex:raise RuntimeError(f"MiniMax response missing audio data: {data}")try:audio = binascii.unhexlify(audio_hex)except (binascii.Error, ValueError) as exc:raise RuntimeError("MiniMax response audio is not valid hex data") from exc- publish_audio_bytes(audio, output_path)++ if subtitle_path is None:+ publish_audio_bytes(audio, output_path)+ return++ subtitle_url = response_data.get("subtitle_file")+ if not isinstance(subtitle_url, str) or not subtitle_url.strip():+ trace_id = data.get("trace_id") or "unknown"+ raise RuntimeError(+ f"MiniMax response missing subtitle file (trace_id={trace_id})"+ )+ subtitle = _download_subtitle(+ subtitle_url,+ text,+ subtitle_max_chars,+ )+ publish_audio_subtitle(audio, output_path, subtitle, subtitle_path)def print_voices() -> None:diff --git a/skills/ppt-master/workflows/stages/generate-audio.md b/skills/ppt-master/workflows/stages/generate-audio.mdindex 85ab1c3b..313ad9bc 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. Cloud TTS providers (`elevenlabs` / `minimax` / `qwen` / `cosyvoice`) currently produce audio only. The caller owns final PPTX integration.+> 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.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, one notes file becomes `audio/<stem>.mp3` plus `notes/subtitles/<stem>.srt`; with a 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: with edge or MiniMax, one notes file becomes `audio/<stem>.mp3` plus `notes/subtitles/<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.- 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.- Optional automatic video export requires Windows PowerPoint 2016+ and runs@@ -221,7 +221,9 @@ remain serial.If `notes_to_audio.py` errors with a missing dependency or missing provider API key, fix the prerequisite and re-run — do NOT swallow the error.-The 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. Cloud-provider commands currently write audio only.+The 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.**Mandatory when `animations.json` is consumed — semantic animation context**: Before writing or refreshing `<project_path>/narration_timing.json`, determine whether the active context already contains the current top-level SVG group IDs and visible group-content semantics for every affected page. Reuse that context without rereading SVG when it is complete and still matches the current `svg_output/`. If any page is missing, stale, or represented only by group IDs/order without content meaning, read only that page's SVG as a read-only source and extract the missing group semantics. Always combine those semantics with the page SRT topics/timestamps and `animations.json`; group order alone is not a semantic narration mapping.@@ -290,7 +292,7 @@ This stage keeps subtitles as external SRT files. It does not burn subtitles int| Caller | After audio generation ||---|---|-| Generate PPTX | With Edge SRT 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 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. || 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 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.@@ -304,9 +306,9 @@ 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, number of matching page-local SRT files and their location (`<project_path>/notes/subtitles/*`).+- For edge or MiniMax subtitles, number of matching page-local SRT files and their location (`<project_path>/notes/subtitles/*`).- 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 Edge 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.+- 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.- When video export was selected, the final MP4 path and native PowerPoint export status.- When a finished video exists, the final aligned sidecar SRT path.- The provider, voice, and rate/settings actually used.