Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(ppt): add customizable animation sidecar workflow

hugohe3d03fce6dbaa5
diff --git a/AGENTS.md b/AGENTS.md
index 759a6682..9a1bb320 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -18,6 +18,8 @@ PPT Master is an AI-driven presentation generation system. Multi-role collaborat
>
> Recorded narration / video export: run the standalone [`generate-audio`](skills/ppt-master/workflows/generate-audio.md) workflow after post-processing.
>
+> Object-level animation tuning: when the user asks to change animation order, effect, timing, or a specific object's reveal behavior, run the standalone [`customize-animations`](skills/ppt-master/workflows/customize-animations.md) workflow. Default export already has global animations; do not create `animations.json` unless customization was requested.
+>
> Post-export iteration: whenever the user asks to change anything on a generated slide ("改一下", "调字号", "那里看着不对", "把图片换大点"), the [`visual-edit`](skills/ppt-master/workflows/visual-edit.md) workflow is available — surface it as an option. If the user describes the change with enough specificity to apply directly ("第 3 页副标题字号改 32"), edit the SVG directly instead; if they're vaguely pointing at "somewhere" on the deck, run the workflow.
## Execution Requirements
@@ -57,6 +59,8 @@ python3 skills/ppt-master/scripts/project_manager.py validate <project_path>
python3 skills/ppt-master/scripts/analyze_images.py <project_path>/images
python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
+python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path> # optional, only for custom object-level animation
+python3 skills/ppt-master/scripts/animation_config.py validate <project_path> # optional, before re-export
# Post-processing pipeline: run sequentially, one command at a time
python3 skills/ppt-master/scripts/total_md_split.py <project_path>
diff --git a/docs/technical-design.md b/docs/technical-design.md
index ec41f737..14b709d0 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -258,14 +258,16 @@ This is the key insight that's easy to miss when reading the code. The same modu
The interesting design choice is the animation **anchor**, not the effect list.
-**Why anchor entrance animations on top-level `<g>` groups.** PowerPoint's animation timeline is shape-keyed — each animated object needs a stable shape ID. Animating individual primitives would produce 30+ separately-flying-in atoms per slide (a kinetic mess), while animating only the slide as a whole loses visual storytelling. Top-level groups are the natural granularity: Executor is required to use `<g id="...">` to mark logical content blocks anyway (so 3-8 groups per slide), and these blocks are exactly the units a viewer reads as "one thing arriving" — animation matches the existing logical structure rather than imposing a new one.
+**Why anchor entrance animations on top-level `<g>` groups.** PowerPoint's animation timeline is shape-keyed — each animated object needs a stable shape ID. Animating individual primitives would produce 30+ separately-flying-in atoms per slide (a kinetic mess), while animating only the slide as a whole loses visual storytelling. Top-level groups are the natural granularity: Executor is required to use `<g id="...">` to mark logical content blocks, and these blocks are exactly the units a viewer reads as "one thing arriving" — animation matches the existing logical structure rather than imposing a new one.
**Why page chrome is auto-skipped.** Groups named `background` / `header` / `footer` / `decoration` / `watermark` / `page_number` represent the static slide frame, not content; flying them in would feel jarring (the page itself materializing every transition) and is virtually never what the user wants. Filtering by id-token is brittle in principle but reliable in practice because the token vocabulary is small and the Executor controls naming.
+**Why object-level animation uses a sidecar, not SVG attributes.** SVG remains the static visual source of truth. Custom PPTX animation is export policy, so per-object overrides live in optional `animations.json` keyed by slide stem and top-level group id. This avoids polluting SVG with PowerPoint-specific metadata while still letting users tune order, effect, delay, and duration when the default global animation is not enough.
+
**Why recorded narration drives auto-advance from clip duration.** When narration is embedded, the deck targets video export — and a video has no presenter to click. Setting per-slide auto-advance timings to the audio clip's actual duration produces a deck PowerPoint exports cleanly to MP4 without manual timing work. Picking any other duration source (estimated reading speed, fixed per-slide) breaks the audio-visual sync.
---
## Standalone Workflows
-Four capabilities (`create-template`, `verify-charts`, `visual-edit`, `generate-audio`) live as standalone workflows rather than pipeline steps. Each is sparsely triggered — per-template, per-chart-deck, per-complaint, per-video-export — not per-deck. Folding any into the default pipeline would either run unnecessary steps for the majority of users (added latency and failure surface) or force a one-size-fits-all narrowing of the main flow. Keeping them opt-in lets the deck-generation pipeline stay tight and predictable while making the capability available when its trigger condition fires; each `workflows/<name>.md` is self-contained and loaded on demand, so paying the prompt-context cost is also opt-in.
+Five capabilities (`create-template`, `verify-charts`, `customize-animations`, `visual-edit`, `generate-audio`) live as standalone workflows rather than pipeline steps. Each is sparsely triggered — per-template, per-chart-deck, per-animation-tuning request, per-complaint, per-video-export — not per-deck. Folding any into the default pipeline would either run unnecessary steps for the majority of users (added latency and failure surface) or force a one-size-fits-all narrowing of the main flow. Keeping them opt-in lets the deck-generation pipeline stay tight and predictable while making the capability available when its trigger condition fires; each `workflows/<name>.md` is self-contained and loaded on demand, so paying the prompt-context cost is also opt-in.
diff --git a/docs/zh/animations.md b/docs/zh/animations.md
index dce1493b..8463456d 100644
--- a/docs/zh/animations.md
+++ b/docs/zh/animations.md
@@ -7,10 +7,55 @@ PPT Master 导出的 PPTX 同时支持**页间转场**(page transition)与**
| 层级 | 默认 | 原因 |
|---|---|---|
| 页间转场 | `fade`,0.4 秒 | 适合大多数 deck 的中性基线 |
-| 页内元素动画 | `mixed` 效果 + `after-previous` 触发 | 进入页面后元素自动按顺序级联入场,零交互即可看到完整动画过程,最能体现 deck 的动画能力 |
+| 页内元素动画 | `mixed` 效果 + `after-previous` 触发,0.4 秒时长 + 0.5 秒间隔 | 进入页面后元素自动按顺序级联入场,零交互即可看到完整动画过程,最能体现 deck 的动画能力 |
修改设置只需对同一份 `svg_output/`(或 `svg_final/`)重跑 `svg_to_pptx.py`,无需重新跑 LLM。如要彻底关闭页内动画,加 `-a none`。
+## 对象级自定义动画
+
+默认动画是全局策略。若需要更具体的演示节奏,例如标题先淡入、图表第二个出现、关键注释最后飞入,可以使用可选的 `animations.json` sidecar。SVG 仍然只保存静态视觉结构;sidecar 只控制 PPTX 导出动画。
+
+当用户要求调整动画顺序、效果、时长或具体对象出现方式时,运行独立 [`customize-animations`](../../skills/ppt-master/workflows/customize-animations.md) 工作流。
+
+```bash
+# 从真实顶层 <g id> 锚点生成可编辑模板
+python3 skills/ppt-master/scripts/animation_config.py scaffold <project>
+
+# 导出前校验引用是否存在
+python3 skills/ppt-master/scripts/animation_config.py validate <project>
+
+# 导出时会自动读取 <project>/animations.json
+python3 skills/ppt-master/scripts/svg_to_pptx.py <project>
+```
+
+最小 sidecar:
+
+```json
+{
+ "version": 1,
+ "slides": {
+ "03_market": {
+ "groups": {
+ "title": { "effect": "fade", "order": 1 },
+ "chart": { "effect": "wipe", "order": 2, "duration": 0.6 },
+ "insight": { "effect": "fly", "order": 3, "delay": 0.2 },
+ "footer": { "effect": "none" }
+ }
+ }
+ }
+}
+```
+
+规则:
+
+- `slides` key 匹配 SVG 文件 stem(`03_market.svg` → `03_market`)。
+- `groups` key 匹配顶层 `<g id="...">` 锚点。
+- `effect: none` 会把该组移出入场动画序列。
+- `order` 只改变动画顺序,不改变页面图层顺序。
+- `delay` 是 `after-previous` 模式下该组开始前的秒数。
+- `duration` 覆盖该组的入场时长。
+- `--animation none` 覆盖 sidecar,强制关闭所有页内动画。
+
## 页间转场
```bash
@@ -72,8 +117,9 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger w
- `-a/--animation` — 效果名、`mixed`、`random` 或 `none`。默认 `mixed`。
- `--animation-trigger` — Start 模式(与 PowerPoint 一致):`on-click`、`with-previous`、`after-previous`(默认)。
-- `--animation-duration` — 单个元素入场秒数,默认 `0.3`。
-- `--animation-stagger` — `after-previous` 模式下两组之间的额外间隔(秒,默认 `0.4`)。其他模式忽略。
+- `--animation-duration` — 单个元素入场秒数,默认 `0.4`。
+- `--animation-stagger` — `after-previous` 模式下两组之间的额外间隔(秒,默认 `0.5`)。其他模式忽略。
+- `--animation-config` — sidecar 路径。默认自动读取 `<project>/animations.json`(如果存在)。
## 锚点机制 — 顶层 `<g id="...">`
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index ba0047bb..b5622872 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -258,14 +258,16 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。Executor 在一份
值得讲的设计选择是动画**锚点**,不是效果列表。
-**为什么把入场动画锚在顶层 `<g>` group。** PowerPoint 的动画时序基于形状 ID——每个被动画的对象需要稳定的 shape ID。给单个原语做动画会产出每页 30+ 个分别飞入的原子(动感泛滥),只给整页做动画又损失视觉叙事。顶层 group 是自然粒度:Executor 本来就被强制要求用 `<g id="...">` 标记逻辑内容块(每页 3-8 个 group),而这些块正是观众读作「一个东西到达」的单位——动画对齐了已有的逻辑结构,而不是另立门户。
+**为什么把入场动画锚在顶层 `<g>` group。** PowerPoint 的动画时序基于形状 ID——每个被动画的对象需要稳定的 shape ID。给单个原语做动画会产出每页 30+ 个分别飞入的原子(动感泛滥),只给整页做动画又损失视觉叙事。顶层 group 是自然粒度:Executor 本来就被强制要求用 `<g id="...">` 标记逻辑内容块,而这些块正是观众读作「一个东西到达」的单位——动画对齐了已有的逻辑结构,而不是另立门户。
**为什么页面装饰自动跳过。** 名为 `background` / `header` / `footer` / `decoration` / `watermark` / `page_number` 的 group 代表静态页面框架,不是内容;让它们飞入会让人出戏(页面本身在每次切换时具象化),几乎不会是用户想要的。按 id token 过滤原则上脆弱,实际上可靠——因为 token 词表很小,命名权又掌握在 Executor 手里。
+**为什么对象级动画用 sidecar,而不是 SVG 属性。** SVG 继续作为静态视觉源。自定义 PPTX 动画属于导出策略,所以对象级覆盖放在可选的 `animations.json`,按 slide stem 和顶层 group id 关联。这样不会把 PowerPoint 专用元数据塞进 SVG,同时仍能在默认全局动画不够用时调整顺序、效果、延迟和时长。
+
**为什么录制旁白让自动推进时长跟着片段时长走。** 嵌入旁白意味着 deck 目标是视频导出——视频里没有演讲者去点击。把每页自动推进时长设为该页音频片段的实际时长,PowerPoint 能干净地导出为 MP4,无需人工配时。任何其他时长来源(估算朗读速度、固定每页时长)都会破坏音画同步。
---
## Standalone Workflows(独立工作流)
-四个能力(`create-template`、`verify-charts`、`visual-edit`、`generate-audio`)作为独立工作流存在,而不是流水线步骤。每个都是稀疏触发的——按模板、按含图表的 deck、按一次具体抱怨、按一次视频导出,而不是按每个 deck。把任何一个塞进默认流水线,要么对大多数用户运行无意义的步骤(增加延迟和失败面),要么强制一刀切收窄主流程。保持 opt-in 让 deck 生成主流水线保持紧凑、可预期,同时在触发条件命中时仍提供这些能力;每个 `workflows/<name>.md` 是自包含的、按需加载——所以 prompt context 的开销也是 opt-in。
+五个能力(`create-template`、`verify-charts`、`customize-animations`、`visual-edit`、`generate-audio`)作为独立工作流存在,而不是流水线步骤。每个都是稀疏触发的——按模板、按含图表的 deck、按一次动画微调、按一次具体抱怨、按一次视频导出,而不是按每个 deck。把任何一个塞进默认流水线,要么对大多数用户运行无意义的步骤(增加延迟和失败面),要么强制一刀切收窄主流程。保持 opt-in 让 deck 生成主流水线保持紧凑、可预期,同时在触发条件命中时仍提供这些能力;每个 `workflows/<name>.md` 是自包含的、按需加载——所以 prompt context 的开销也是 opt-in。
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index d16e3a73..1cb78e0b 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -76,6 +76,7 @@ For complete tool documentation, see `${SKILL_DIR}/scripts/README.md`.
| `create-template` | `workflows/create-template.md` | Standalone template creation workflow |
| `resume-execute` | `workflows/resume-execute.md` | Phase B entry — resume execution in a fresh chat after Phase A (Step 1–5) completed in another session (split mode) |
| `verify-charts` | `workflows/verify-charts.md` | Chart coordinate calibration — run after SVG generation if the deck contains data charts |
+| `customize-animations` | `workflows/customize-animations.md` | Object-level PPTX animation customization — run only when the user explicitly asks to tune animation order/effects/timing |
| `visual-edit` | `workflows/visual-edit.md` | Browser-based visual editor for fine-grained edits — run only when the user explicitly requests it after export |
---
@@ -363,8 +364,13 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
- `-t <effect>` — page transition. Default `fade`. Options: `fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random` / `none`.
- `-a <effect>` — per-element entrance animation. Default `mixed` (auto-vary across the deck). Pass `none` to disable, or pick a specific effect like `fade`. Requires top-level `<g id="...">` groups (already required by Executor).
- `--animation-trigger {on-click,with-previous,after-previous}` — Start mode (matches PowerPoint's animation-pane Start dropdown). Default `after-previous` (click-free cascade; pace via `--animation-stagger`). Use `on-click` for presenter-paced reveals, or `with-previous` for all-at-once.
+- `--animation-config <path>` — optional object-level sidecar. Default: `<project_path>/animations.json` when present.
- `--auto-advance <seconds>` — kiosk-style auto-play.
+**Optional custom animations** (only when the user asks to tune animation order/effects/timing for specific objects):
+
+Run the standalone [`customize-animations`](workflows/customize-animations.md) workflow. Default export already has global entrance animation; do not create `animations.json` unless object-level customization was requested.
+
**Optional recorded narration** (only when the user asks for narrated/video export):
Run the standalone [`generate-audio`](workflows/generate-audio.md) workflow. The AI picks a narration backend (`edge` by default, or a configured cloud provider such as ElevenLabs / MiniMax / Qwen / CosyVoice for high-quality or cloned voices), asks the user once (backend + voice + rate/settings + embed-or-not, all with recommended values), then executes `notes_to_audio.py` and (if chosen) re-exports the PPTX with `--recorded-narration audio`.
diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.md
index c7c4bb86..e882afbf 100644
--- a/skills/ppt-master/references/animations.md
+++ b/skills/ppt-master/references/animations.md
@@ -11,6 +11,51 @@ PPT Master's exported PPTX supports **page transitions** (slide-to-slide) and **
To regenerate a deck with different settings, rerun `svg_to_pptx.py` against the same `svg_output/` (or `svg_final/`) — no need to rerun the LLM. To turn per-element animation off entirely, pass `-a none`.
+## Custom Object-Level Animation
+
+Default animation is global. When a deck needs specific object timing — for example title first, chart second, annotation last — use the optional `animations.json` sidecar. The SVG remains static visual source; the sidecar only controls PPTX export behavior.
+
+Run the standalone [`customize-animations`](../workflows/customize-animations.md) workflow when the user asks to tune animation order, effects, timing, or object-level reveals.
+
+```bash
+# Build an editable scaffold from real top-level <g id> anchors
+python3 skills/ppt-master/scripts/animation_config.py scaffold <project>
+
+# Validate references before export
+python3 skills/ppt-master/scripts/animation_config.py validate <project>
+
+# Export reads <project>/animations.json automatically when present
+python3 skills/ppt-master/scripts/svg_to_pptx.py <project>
+```
+
+Minimal sidecar:
+
+```json
+{
+ "version": 1,
+ "slides": {
+ "03_market": {
+ "groups": {
+ "title": { "effect": "fade", "order": 1 },
+ "chart": { "effect": "wipe", "order": 2, "duration": 0.6 },
+ "insight": { "effect": "fly", "order": 3, "delay": 0.2 },
+ "footer": { "effect": "none" }
+ }
+ }
+ }
+}
+```
+
+Rules:
+
+- `slides` keys match SVG stems (`03_market.svg` → `03_market`).
+- `groups` keys match top-level `<g id="...">` anchors.
+- `effect: none` removes that group from the entrance sequence.
+- `order` changes animation order only; it does not change slide layering.
+- `delay` is seconds before that group starts in `after-previous` mode.
+- `duration` overrides the per-group entrance duration.
+- `--animation none` overrides the sidecar and disables all per-element animation.
+
## Page Transitions
```bash
@@ -74,6 +119,7 @@ Flags:
- `--animation-trigger` — Start mode (matches PowerPoint): `on-click`, `with-previous`, or `after-previous` (default).
- `--animation-duration` — per-element entrance seconds, default `0.4`.
- `--animation-stagger` — gap between elements in `after-previous` mode (seconds, default `0.5`). Ignored otherwise.
+- `--animation-config` — sidecar path. Default: `<project>/animations.json` when present.
## Anchor Logic — Top-Level `<g id="...">`
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index c70eb684..8faccd91 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -312,6 +312,7 @@ python3 scripts/svg_to_pptx.py <project_path>
- `-t <effect>` — page transition (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random` / `none`; default `fade`)
- `-a <effect>` — per-element entrance animation (`fade` / `mixed` / `random` / one of 22 named effects / `none`; default `mixed`). Anchors on top-level `<g id="...">` groups.
- `--animation-trigger {on-click,with-previous,after-previous}` — Start mode matching PowerPoint's animation-pane Start dropdown. Default `after-previous` (cascade on slide entry; pace via `--animation-stagger <seconds>`); `on-click` advances per click; `with-previous` plays all groups together.
+- `--animation-config <path>` — optional object-level animation sidecar. Default: `<project>/animations.json` when present.
- `--auto-advance <seconds>` — kiosk-style auto-play
**Optional recorded narration** (only when the user asks for narrated/video export):
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 8a83200b..a7f260b1 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -26,6 +26,7 @@ python3 scripts/project_manager.py init <project_name> --format ppt169
python3 scripts/project_manager.py import-sources <project_path> <source_files...> --move
python3 scripts/total_md_split.py <project_path>
python3 scripts/finalize_svg.py <project_path>
+python3 scripts/animation_config.py scaffold <project_path> # optional object-level animation overrides
python3 scripts/svg_to_pptx.py <project_path>
```
@@ -41,7 +42,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
+| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
| Image tools | `image_gen.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |
| Repo maintenance | `update_repo.py` | README install/update section |
diff --git a/skills/ppt-master/scripts/animation_config.py b/skills/ppt-master/scripts/animation_config.py
new file mode 100644
index 00000000..49e70a08
--- /dev/null
+++ b/skills/ppt-master/scripts/animation_config.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Animation Config Tool
+
+Create and validate optional per-object PPTX animation sidecar files.
+
+Usage:
+ python3 scripts/animation_config.py scaffold <project_path>
+ python3 scripts/animation_config.py validate <project_path>
+
+Examples:
+ python3 scripts/animation_config.py scaffold projects/demo --force
+ python3 scripts/animation_config.py validate projects/demo
+
+Dependencies:
+ None (standard library only)
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from svg_to_pptx.animation_config import ( # noqa: E402
+ load_animation_config,
+ validate_animation_config,
+ write_scaffold,
+)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description='Create or validate PPTX animation sidecar configuration.',
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ subparsers = parser.add_subparsers(dest='command', required=True)
+
+ scaffold = subparsers.add_parser(
+ 'scaffold',
+ help='scan svg_output/*.svg and write animations.json scaffold',
+ )
+ scaffold.add_argument('project_path', help='Project directory')
+ scaffold.add_argument('-o', '--output', default=None, help='Output path; default: <project>/animations.json')
+ scaffold.add_argument('--force', action='store_true', help='Overwrite an existing output file')
+
+ validate = subparsers.add_parser(
+ 'validate',
+ help='validate animations.json references against svg_output/*.svg',
+ )
+ validate.add_argument('project_path', help='Project directory')
+ validate.add_argument('-c', '--config', default=None, help='Config path; default: <project>/animations.json')
+
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ project_path = Path(args.project_path)
+ if not project_path.exists():
+ print(f'Error: Project path does not exist: {project_path}', file=sys.stderr)
+ return 1
+
+ if args.command == 'scaffold':
+ try:
+ output_path = write_scaffold(
+ project_path,
+ output_path=args.output,
+ force=args.force,
+ )
+ except FileExistsError as exc:
+ print(f'Error: {exc}', file=sys.stderr)
+ print('Use --force to overwrite.', file=sys.stderr)
+ return 1
+ print(f'Animation config scaffold written: {output_path}')
+ return 0
+
+ if args.command == 'validate':
+ try:
+ config = load_animation_config(project_path, args.config)
+ except Exception as exc:
+ print(f'Error: {exc}', file=sys.stderr)
+ return 1
+ if not config:
+ print('No animations.json found; default animation policy will be used.')
+ return 0
+ warnings = validate_animation_config(project_path, config)
+ if warnings:
+ for warning in warnings:
+ print(f'Warning: {warning}', file=sys.stderr)
+ return 1
+ print('Animation config validated successfully.')
+ return 0
+
+ parser.print_help()
+ return 1
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index d6fed89e..00f95207 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -69,6 +69,7 @@ Behavior:
- Flat SVG roots without top-level groups fall back to at most 8 visible primitives; beyond that, animation is skipped on the slide
- `mixed` is deterministic: the first animated group on each slide uses `fade`, then later groups cycle through a curated visible-effect pool across the whole deck; `random` samples from that same pool
- `--animation-duration` controls per-element entrance length (default `0.4`); `--animation-stagger` adds gap between elements in `after-previous` mode (default `0.5`)
+- Optional object-level overrides live in `<project>/animations.json` or a path passed via `--animation-config`; build and validate them with `animation_config.py scaffold|validate`
Dependency:
diff --git a/skills/ppt-master/scripts/pptx_animations.py b/skills/ppt-master/scripts/pptx_animations.py
index 49e62f95..857fa836 100644
--- a/skills/ppt-master/scripts/pptx_animations.py
+++ b/skills/ppt-master/scripts/pptx_animations.py
@@ -302,7 +302,8 @@ def create_sequence_timing_xml(
"""Generate a multi-target entrance sequence.
Args:
- targets: list of (shape_id, delay_ms, animation_name) tuples, in
+ targets: list of (shape_id, delay_ms, animation_name) or
+ (shape_id, delay_ms, animation_name, duration_seconds) tuples, in
the order they should play. ``delay_ms`` is the gap before
this element starts, measured from when the previous element
triggers (only used in ``after-previous`` mode; ignored in
@@ -326,9 +327,18 @@ def create_sequence_timing_xml(
if trigger not in ('on-click', 'with-previous', 'after-previous'):
trigger = 'on-click'
- dur_ms = int(duration * 1000)
+ default_dur_ms = int(duration * 1000)
next_id = 3
+ def _target_parts(target: tuple) -> tuple[int, int, str, int]:
+ shape_id, delay_ms, animation = target[:3]
+ if animation not in ANIMATIONS:
+ animation = 'fade'
+ item_dur_ms = default_dur_ms
+ if len(target) > 3 and target[3] is not None:
+ item_dur_ms = int(float(target[3]) * 1000)
+ return int(shape_id), int(delay_ms), str(animation), item_dur_ms
+
if trigger == 'on-click':
# Each element is an independent click-driven par directly under
# mainSeq. Three-level nesting per element: outer cTn holds for
@@ -336,9 +346,7 @@ def create_sequence_timing_xml(
# clickEffect + animation children. Each click advances the seq.
steps = []
for target in targets:
- shape_id, _delay_ms, animation = target
- if animation not in ANIMATIONS:
- animation = 'fade'
+ shape_id, _delay_ms, animation, item_dur_ms = _target_parts(target)
anim_info = ANIMATIONS[animation]
preset_id = anim_info.get('presetID', 1)
preset_subtype = anim_info.get('presetSubtype', 0)
@@ -348,7 +356,7 @@ def create_sequence_timing_xml(
set_id = next_id + 3
eff_id = next_id + 4
next_id += 5
- effect_xml = _build_effect_xml(animation, shape_id, dur_ms, set_id, eff_id)
+ effect_xml = _build_effect_xml(animation, shape_id, item_dur_ms, set_id, eff_id)
steps.append(f'''<p:par>
<p:cTn id="{wrapper_id}" fill="hold">
<p:stCondLst><p:cond delay="indefinite"/></p:stCondLst>
@@ -389,10 +397,9 @@ def create_sequence_timing_xml(
with_wrapper_id = next_id
next_id += 1
elapsed_ms = 0
+ prev_duration_ms = 0
for i, target in enumerate(targets):
- shape_id, delay_ms, animation = target
- if animation not in ANIMATIONS:
- animation = 'fade'
+ shape_id, delay_ms, animation, item_dur_ms = _target_parts(target)
anim_info = ANIMATIONS[animation]
preset_id = anim_info.get('presetID', 1)
preset_subtype = anim_info.get('presetSubtype', 0)
@@ -402,7 +409,7 @@ def create_sequence_timing_xml(
set_id = next_id + 1
eff_id = next_id + 2
next_id += 3
- effect_xml = _build_effect_xml(animation, shape_id, dur_ms, set_id, eff_id)
+ effect_xml = _build_effect_xml(animation, shape_id, item_dur_ms, set_id, eff_id)
inner_steps.append(f'''<p:par>
<p:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr" presetSubtype="{preset_subtype}" fill="hold" nodeType="withEffect">
<p:stCondLst><p:cond delay="0"/></p:stCondLst>
@@ -412,14 +419,16 @@ def create_sequence_timing_xml(
</p:cTn>
</p:par>''')
else:
- if i > 0:
- elapsed_ms += dur_ms + int(delay_ms)
+ if i == 0:
+ elapsed_ms = int(delay_ms)
+ else:
+ elapsed_ms += prev_duration_ms + int(delay_ms)
wrapper_id = next_id
leaf_id = next_id + 1
set_id = next_id + 2
eff_id = next_id + 3
next_id += 4
- effect_xml = _build_effect_xml(animation, shape_id, dur_ms, set_id, eff_id)
+ effect_xml = _build_effect_xml(animation, shape_id, item_dur_ms, set_id, eff_id)
inner_steps.append(f'''<p:par>
<p:cTn id="{wrapper_id}" fill="hold">
<p:stCondLst><p:cond delay="{elapsed_ms}"/></p:stCondLst>
@@ -435,6 +444,7 @@ def create_sequence_timing_xml(
</p:childTnLst>
</p:cTn>
</p:par>''')
+ prev_duration_ms = item_dur_ms
inner_xml = '\n '.join(inner_steps)
if trigger == 'with-previous':
@@ -468,7 +478,7 @@ def create_sequence_timing_xml(
</p:par>'''
bld_list = '\n '.join(
- f'<p:bldP spid="{sid}" grpId="0"/>' for sid, _, _ in targets
+ f'<p:bldP spid="{target[0]}" grpId="0"/>' for target in targets
)
return f''' <p:timing>
<p:tnLst>
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 1cf30f85..ebdab82c 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -32,6 +32,15 @@ try:
except ImportError:
_parse_spec_lock = None # spec_lock drift check will be skipped
+try:
+ from svg_to_pptx.animation_config import (
+ load_animation_config as _load_animation_config,
+ validate_animation_config as _validate_animation_config,
+ )
+except ImportError:
+ _load_animation_config = None
+ _validate_animation_config = None
+
HEX_VALUE_RE = re.compile(r"#[0-9A-Fa-f]{3,8}")
@@ -173,6 +182,7 @@ class SVGQualityChecker:
# template_mode=True). Each entry is (severity, kind, message) where
# severity is 'error' or 'warning'. Printed in print_summary.
self._template_issues: List[Tuple[str, str, str]] = []
+ self._animation_issues: List[Tuple[str, str]] = []
def check_file(self, svg_file: str, expected_format: str = None) -> Dict:
"""
@@ -232,13 +242,16 @@ class SVGQualityChecker:
# 6. Check image references (file existence and resolution)
self._check_image_references(content, svg_path, result)
- # 7. Check spec_lock drift (colors / font-family / font-size).
+ # 7. Check object-level animation anchor quality.
+ self._check_animation_group_ids(content, result)
+
+ # 8. Check spec_lock drift (colors / font-family / font-size).
# Templates do not ship a spec_lock.md, so skip in template
# mode to avoid noise.
if not self.template_mode:
self._check_spec_lock_drift(content, svg_path, result)
- # 8. Check web-sourced image attribution. Templates don't carry
+ # 9. Check web-sourced image attribution. Templates don't carry
# image_sources.json; skip in template mode.
if not self.template_mode:
self._check_sourced_image_attribution(content, svg_path, result)
@@ -559,6 +572,24 @@ class SVGQualityChecker:
except Exception:
pass # Image unreadable, skip resolution check
+ def _check_animation_group_ids(self, content: str, result: Dict):
+ """Warn when visible top-level groups cannot be customized."""
+ try:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return
+
+ non_visual = {'defs', 'title', 'desc', 'metadata', 'style'}
+ for index, child in enumerate(list(root), start=1):
+ tag = child.tag.split('}', 1)[-1]
+ if tag in non_visual:
+ continue
+ if tag == 'g' and not child.get('id'):
+ result['warnings'].append(
+ f"Top-level visible <g> #{index} has no id; "
+ "object-level animation config cannot reference it"
+ )
+
def _get_spec_lock(self, svg_path: Path):
"""Locate and parse spec_lock.md near the SVG. Returns dict or None.
@@ -817,9 +848,26 @@ class SVGQualityChecker:
if self.template_mode and dir_path.is_dir():
self._check_template_contract(dir_path, svg_files)
+ elif dir_path.is_dir():
+ self._check_animation_config_contract(dir_path)
return self.results
+ def _check_animation_config_contract(self, dir_path: Path) -> None:
+ """Project-level animations.json reference checks."""
+ if _load_animation_config is None or _validate_animation_config is None:
+ return
+ project_path = dir_path if (dir_path / 'svg_output').exists() else dir_path.parent
+ try:
+ config = _load_animation_config(project_path)
+ except Exception as exc:
+ self._animation_issues.append(('error', f"animations.json is invalid: {exc}"))
+ return
+ if not config:
+ return
+ for warning in _validate_animation_config(project_path, config):
+ self._animation_issues.append(('warning', warning))
+
def _check_template_contract(self, dir_path: Path,
svg_files: List[Path]) -> None:
"""Template-mode-only checks: roster ↔ design_spec consistency and
@@ -1105,6 +1153,9 @@ class SVGQualityChecker:
# Template-mode aggregation (orphan/missing roster + placeholder hints)
self._print_template_summary()
+ # Animation config aggregation.
+ self._print_animation_summary()
+
# Fix suggestions
if self.summary['errors'] > 0 or self.summary['warnings'] > 0:
print(f"\n[TIP] Common fixes:")
@@ -1113,6 +1164,24 @@ class SVGQualityChecker:
print(f" 3. foreignObject: Use <text> + <tspan> for manual line breaks")
print(f" 4. Font issues: end every font-family stack with a PPT-safe family (e.g. Microsoft YaHei / Arial / Consolas)")
+ def _print_animation_summary(self):
+ """Print animations.json validation issues if present."""
+ if not self._animation_issues:
+ return
+
+ errors = [item for item in self._animation_issues if item[0] == 'error']
+ warnings = [item for item in self._animation_issues if item[0] == 'warning']
+ self.summary['errors'] += len(errors)
+ self.summary['warnings'] += len(warnings)
+ for severity, _msg in self._animation_issues:
+ self.issue_types[f'animation_config_{severity}'] += 1
+
+ print("\n[ANIMATION] animations.json checks")
+ for _severity, msg in errors:
+ print(f" [ERROR] {msg}")
+ for _severity, msg in warnings:
+ print(f" [WARN] {msg}")
+
def _print_template_summary(self):
"""Aggregate template-mode roster / placeholder issues at the bottom.
diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
new file mode 100644
index 00000000..0a9adda3
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
@@ -0,0 +1,234 @@
+"""Animation sidecar loading, SVG target scanning, and validation."""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+from xml.etree import ElementTree as ET
+
+from .drawingml_utils import SVG_NS
+
+try:
+ from pptx_animations import ANIMATIONS, TRANSITIONS
+except ImportError:
+ ANIMATIONS = {}
+ TRANSITIONS = {}
+
+
+_NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))
+_CHROME_ID_TOKENS = frozenset({
+ 'background', 'bg',
+ 'decoration', 'decorations', 'decor',
+ 'header', 'footer',
+ 'chrome', 'watermark',
+ 'pagenumber', 'pagenum',
+ 'page-number',
+})
+
+
+@dataclass(frozen=True)
+class GroupTarget:
+ """Top-level SVG group available for PowerPoint animation anchoring."""
+
+ slide: str
+ group_id: str
+ order: int
+ chrome: bool = False
+
+
+def _tag_name(elem: ET.Element) -> str:
+ return elem.tag.replace(f'{{{SVG_NS}}}', '')
+
+
+def is_chrome_id(elem_id: str | None) -> bool:
+ """Return whether a group id represents static slide chrome."""
+ if not elem_id:
+ return False
+ lower = elem_id.lower()
+ compact = lower.replace('-', '').replace('_', '')
+ if compact in _CHROME_ID_TOKENS:
+ return True
+ tokens = re.split(r'[-_]', lower)
+ return any(t in _CHROME_ID_TOKENS for t in tokens if t)
+
+
+def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:
+ """Scan one SVG for top-level visible group ids and anonymous groups."""
+ root = ET.parse(str(svg_path)).getroot()
+ targets: list[GroupTarget] = []
+ anonymous_groups: list[str] = []
+ visual_index = 0
+
+ for child in root:
+ tag = _tag_name(child)
+ if tag in _NON_VISUAL_TAGS:
+ continue
+ visual_index += 1
+ if tag != 'g':
+ continue
+ group_id = child.get('id')
+ if not group_id:
+ anonymous_groups.append(f'{svg_path.stem}: top-level group #{visual_index}')
+ continue
+ targets.append(
+ GroupTarget(
+ slide=svg_path.stem,
+ group_id=group_id,
+ order=visual_index,
+ chrome=is_chrome_id(group_id),
+ )
+ )
+
+ return targets, anonymous_groups
+
+
+def scan_project_targets(project_path: Path) -> tuple[dict[str, list[GroupTarget]], list[str]]:
+ """Scan ``svg_output/*.svg`` for animation targets."""
+ svg_dir = project_path / 'svg_output'
+ targets_by_slide: dict[str, list[GroupTarget]] = {}
+ anonymous_groups: list[str] = []
+ if not svg_dir.is_dir():
+ return targets_by_slide, [f'svg_output directory not found: {svg_dir}']
+
+ for svg_path in sorted(svg_dir.glob('*.svg')):
+ targets, anonymous = scan_svg_targets(svg_path)
+ targets_by_slide[svg_path.stem] = targets
+ anonymous_groups.extend(anonymous)
+
+ return targets_by_slide, anonymous_groups
+
+
+def default_config_path(project_path: Path) -> Path:
+ return project_path / 'animations.json'
+
+
+def load_animation_config(project_path: Path, config_path: str | None = None) -> dict[str, Any] | None:
+ """Load optional animation config; return ``None`` when absent."""
+ path = Path(config_path) if config_path else default_config_path(project_path)
+ if not path.is_absolute():
+ path = project_path / path
+ if not path.exists():
+ return None
+
+ with open(path, 'r', encoding='utf-8') as f:
+ data = json.load(f)
+ if not isinstance(data, dict):
+ raise ValueError(f'Animation config must be a JSON object: {path}')
+ if data.get('version', 1) != 1:
+ raise ValueError(f'Unsupported animation config version: {data.get("version")}')
+ return data
+
+
+def _valid_animation_effect(effect: str) -> bool:
+ return effect == 'none' or effect in ANIMATIONS or effect in ('mixed', 'random')
+
+
+def _valid_transition_effect(effect: str) -> bool:
+ return effect == 'none' or effect in TRANSITIONS
+
+
+def validate_animation_config(
+ project_path: Path,
+ config: dict[str, Any] | None = None,
+ config_path: str | None = None,
+) -> list[str]:
+ """Validate sidecar references against current ``svg_output``."""
+ if config is None:
+ config = load_animation_config(project_path, config_path)
+ if not config:
+ return []
+
+ warnings: list[str] = []
+ targets_by_slide, anonymous_groups = scan_project_targets(project_path)
+ for item in anonymous_groups:
+ warnings.append(f'{item} has no id and cannot be customized in animations.json')
+
+ known_slides = set(targets_by_slide)
+ slides = config.get('slides', {})
+ if slides and not isinstance(slides, dict):
+ return ['animations.json field "slides" must be an object']
+
+ defaults = config.get('defaults', {})
+ if isinstance(defaults, dict):
+ _validate_scope_effects(defaults, 'defaults', warnings)
+
+ for slide_name, slide_cfg in (slides or {}).items():
+ if slide_name not in known_slides:
+ warnings.append(f'animations.json references missing slide: {slide_name}')
+ continue
+ if not isinstance(slide_cfg, dict):
+ warnings.append(f'animations.json slide "{slide_name}" must be an object')
+ continue
+ _validate_scope_effects(slide_cfg, f'slide "{slide_name}"', warnings)
+
+ known_groups = {target.group_id for target in targets_by_slide[slide_name]}
+ groups = slide_cfg.get('groups', {})
+ if groups and not isinstance(groups, dict):
+ warnings.append(f'animations.json slide "{slide_name}" field "groups" must be an object')
+ continue
+ for group_id, group_cfg in (groups or {}).items():
+ if group_id not in known_groups:
+ warnings.append(
+ f'animations.json references missing group: {slide_name}/{group_id}'
+ )
+ if not isinstance(group_cfg, dict):
+ warnings.append(f'animations.json group "{slide_name}/{group_id}" must be an object')
+ continue
+ effect = group_cfg.get('effect')
+ if effect is not None and not _valid_animation_effect(str(effect)):
+ warnings.append(
+ f'animations.json group "{slide_name}/{group_id}" has unknown effect: {effect}'
+ )
+ return warnings
+
+
+def _validate_scope_effects(scope: dict[str, Any], label: str, warnings: list[str]) -> None:
+ transition = scope.get('transition', {})
+ if isinstance(transition, dict):
+ effect = transition.get('effect')
+ if effect is not None and not _valid_transition_effect(str(effect)):
+ warnings.append(f'animations.json {label} has unknown transition effect: {effect}')
+ animation = scope.get('animation', {})
+ if isinstance(animation, dict):
+ effect = animation.get('effect')
+ if effect is not None and not _valid_animation_effect(str(effect)):
+ warnings.append(f'animations.json {label} has unknown animation effect: {effect}')
+
+
+def build_scaffold(project_path: Path) -> dict[str, Any]:
+ """Build an editable animation override scaffold from current SVGs."""
+ targets_by_slide, _anonymous = scan_project_targets(project_path)
+ slides: dict[str, Any] = {}
+ for slide_name, targets in targets_by_slide.items():
+ groups: dict[str, Any] = {}
+ for target in targets:
+ if target.chrome:
+ groups[target.group_id] = {'effect': 'none'}
+ else:
+ groups[target.group_id] = {}
+ slides[slide_name] = {'groups': groups}
+ return {'version': 1, 'slides': slides}
+
+
+def write_scaffold(
+ project_path: Path,
+ output_path: str | None = None,
+ *,
+ force: bool = False,
+) -> Path:
+ """Write ``animations.json`` scaffold and return its path."""
+ path = Path(output_path) if output_path else default_config_path(project_path)
+ if not path.is_absolute():
+ path = project_path / path
+ if path.exists() and not force:
+ raise FileExistsError(f'Animation config already exists: {path}')
+
+ scaffold = build_scaffold(project_path)
+ path.write_text(
+ json.dumps(scaffold, ensure_ascii=False, indent=2) + '\n',
+ encoding='utf-8',
+ )
+ return path
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
index a0f4c77c..f6603eb5 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_builder.py
@@ -7,9 +7,9 @@ import mimetypes
import re
import shutil
import tempfile
-import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
+from typing import Any
from pptx import Presentation
from pptx.util import Emu
@@ -112,55 +112,116 @@ def _content_type_for_extension(ext: str) -> str:
return content_type
-def _expand_anim_targets_to_group_children(
- slide_xml: str,
- anim_targets: list[tuple[int, str]],
-) -> list[tuple[list[int], str]]:
- """Expand top-level group animation targets to their concrete child shapes.
-
- PowerPoint for Mac may list animations assigned to ``p:grpSp`` in the
- animation pane but fail to consume slideshow clicks for those group targets.
- Animating ordinary child shapes in the same click step preserves the visual
- "one semantic block per click" behavior while avoiding group-target playback
- quirks.
- """
- ns = {'p': 'http://schemas.openxmlformats.org/presentationml/2006/main'}
- root = ET.fromstring(slide_xml)
- expanded: list[tuple[list[int], str]] = []
+def _as_dict(value: Any) -> dict[str, Any]:
+ return value if isinstance(value, dict) else {}
- for target_id, svg_id in anim_targets:
- if isinstance(target_id, (list, tuple)):
- expanded.append(([int(v) for v in target_id], svg_id))
- continue
- group = None
- for candidate in root.findall('.//p:grpSp', ns):
- c_nv_pr = candidate.find('./p:nvGrpSpPr/p:cNvPr', ns)
- if c_nv_pr is not None and c_nv_pr.get('id') == str(target_id):
- group = candidate
- break
-
- if group is None:
- expanded.append(([target_id], svg_id))
+def _to_float(value: Any, default: float) -> float:
+ if value is None:
+ return default
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return default
+ return number if number >= 0 else default
+
+
+def _slide_config(animation_config: dict[str, Any] | None, svg_stem: str) -> dict[str, Any]:
+ if not animation_config:
+ return {}
+ slides = _as_dict(animation_config.get('slides'))
+ return _as_dict(slides.get(svg_stem))
+
+
+def _slide_transition_settings(
+ slide_cfg: dict[str, Any],
+ transition: str | None,
+ duration: float,
+ auto_advance: float | None,
+ cli_overrides: dict[str, bool],
+) -> tuple[str | None, float, float | None]:
+ trans_cfg = _as_dict(slide_cfg.get('transition'))
+ effect = transition
+ if not cli_overrides.get('transition') and 'effect' in trans_cfg:
+ cfg_effect = str(trans_cfg.get('effect'))
+ effect = None if cfg_effect == 'none' else cfg_effect
+ if not cli_overrides.get('transition_duration'):
+ duration = _to_float(trans_cfg.get('duration'), duration)
+ if not cli_overrides.get('auto_advance') and 'auto_advance' in trans_cfg:
+ auto_advance = _to_float(trans_cfg.get('auto_advance'), auto_advance or 0)
+ return effect, duration, auto_advance
+
+
+def _slide_animation_settings(
+ slide_cfg: dict[str, Any],
+ animation: str | None,
+ duration: float,
+ stagger: float,
+ trigger: str,
+ cli_overrides: dict[str, bool],
+) -> tuple[str | None, float, float, str]:
+ anim_cfg = _as_dict(slide_cfg.get('animation'))
+ effect = animation
+ if not cli_overrides.get('animation') and 'effect' in anim_cfg:
+ cfg_effect = str(anim_cfg.get('effect'))
+ effect = None if cfg_effect == 'none' else cfg_effect
+ if not cli_overrides.get('animation_duration'):
+ duration = _to_float(anim_cfg.get('duration'), duration)
+ if not cli_overrides.get('animation_stagger'):
+ stagger = _to_float(anim_cfg.get('stagger'), stagger)
+ if not cli_overrides.get('animation_trigger') and anim_cfg.get('trigger'):
+ trigger = str(anim_cfg.get('trigger'))
+ return effect, duration, stagger, trigger
+
+
+def _build_sequence_targets(
+ anim_targets: list[tuple[int, str]],
+ slide_cfg: dict[str, Any],
+ animation: str,
+ duration: float,
+ stagger: float,
+ mixed_animation_offset: int,
+) -> tuple[list[tuple[int, int, str, float]], int]:
+ groups_cfg = _as_dict(slide_cfg.get('groups'))
+ ordered: list[tuple[int, int, int, str, dict[str, Any]]] = []
+ for idx, (sid, svg_id) in enumerate(anim_targets):
+ group_cfg = _as_dict(groups_cfg.get(svg_id))
+ if str(group_cfg.get('effect', '')).lower() == 'none':
continue
-
- child_ids: list[int] = []
- for child in list(group):
- if child.tag == f'{{{ns["p"]}}}sp':
- c_nv_pr = child.find('./p:nvSpPr/p:cNvPr', ns)
- elif child.tag == f'{{{ns["p"]}}}pic':
- c_nv_pr = child.find('./p:nvPicPr/p:cNvPr', ns)
- else:
- c_nv_pr = None
- if c_nv_pr is None:
- continue
- child_id = c_nv_pr.get('id')
- if child_id and child_id.isdigit():
- child_ids.append(int(child_id))
-
- expanded.append((child_ids or [target_id], svg_id))
-
- return expanded
+ order_value = group_cfg.get('order')
+ try:
+ order = int(order_value)
+ has_order = 0
+ except (TypeError, ValueError):
+ order = idx
+ has_order = 1
+ group_entry = dict(group_cfg)
+ group_entry['_shape_id'] = sid
+ ordered.append((has_order, order, idx, svg_id, group_entry))
+
+ ordered.sort(key=lambda item: (item[0], item[1], item[2]))
+
+ seq_targets: list[tuple[int, int, str, float]] = []
+ for seq_idx, (_has_order, _order, _original_idx, _svg_id, group_cfg) in enumerate(ordered):
+ shape_id = int(group_cfg['_shape_id'])
+ raw_effect = group_cfg.get('effect')
+ if raw_effect in ('mixed', 'random'):
+ effect = pick_animation_effect(str(raw_effect), seq_idx, mixed_animation_offset)
+ else:
+ effect = str(raw_effect or pick_animation_effect(
+ animation, seq_idx, mixed_animation_offset,
+ ))
+ item_duration = _to_float(group_cfg.get('duration'), duration)
+ delay_seconds = _to_float(
+ group_cfg.get('delay'),
+ 0 if seq_idx == 0 else stagger,
+ )
+ seq_targets.append((shape_id, int(delay_seconds * 1000), effect, item_duration))
+
+ mixed_count = 0
+ if animation == 'mixed':
+ mixed_count = sum(1 for _target in seq_targets[1:])
+ return seq_targets, mixed_count
def create_pptx_with_native_svg(
@@ -179,6 +240,8 @@ def create_pptx_with_native_svg(
animation_duration: float = 0.4,
animation_stagger: float = 0.5,
animation_trigger: str = 'after-previous',
+ animation_config: dict[str, Any] | None = None,
+ animation_cli_overrides: dict[str, bool] | None = None,
narration_audio: dict[str, Path] | None = None,
use_narration_timings: bool = False,
narration_padding: float = 0.5,
@@ -204,6 +267,8 @@ def create_pptx_with_native_svg(
trigger mode (seconds). Ignored otherwise.
animation_trigger: PowerPoint Start mode — ``'after-previous'`` (default),
``'on-click'``, or ``'with-previous'``.
+ animation_config: Optional sidecar overrides loaded from animations.json.
+ animation_cli_overrides: Flags indicating explicit CLI overrides.
narration_audio: Optional dict mapping SVG stem to narration audio file.
use_narration_timings: Whether to set slide auto-advance from audio duration.
narration_padding: Extra seconds added after each narration before advancing.
@@ -269,6 +334,8 @@ def create_pptx_with_native_svg(
print(f" Speaker notes: Disabled")
print()
+ animation_cli_overrides = animation_cli_overrides or {}
+
temp_dir = Path(tempfile.mkdtemp())
try:
@@ -307,45 +374,67 @@ def create_pptx_with_native_svg(
try:
# ---- Native shapes mode ----
if use_native_shapes:
+ slide_cfg = _slide_config(animation_config, svg_path.stem)
slide_xml, media_files_dict, rel_entries, anim_targets = (
convert_svg_to_slide_shapes(
svg_path, slide_num=slide_num, verbose=verbose,
)
)
+ slide_transition, slide_transition_duration, slide_auto_advance = (
+ _slide_transition_settings(
+ slide_cfg,
+ transition,
+ transition_duration,
+ auto_advance,
+ animation_cli_overrides,
+ )
+ )
+ (
+ slide_animation,
+ slide_animation_duration,
+ slide_animation_stagger,
+ slide_animation_trigger,
+ ) = _slide_animation_settings(
+ slide_cfg,
+ animation,
+ animation_duration,
+ animation_stagger,
+ animation_trigger,
+ animation_cli_overrides,
+ )
# Order matters: OOXML schema requires <p:transition>
# to precede <p:timing> inside <p:sld>. Both use the same
# </p:sld> string-replace anchor, so transition must be
# injected first and timing second.
- if transition and ANIMATIONS_AVAILABLE and create_transition_xml:
+ if slide_transition and ANIMATIONS_AVAILABLE and create_transition_xml:
transition_xml = '\n' + create_transition_xml(
- effect=transition,
- duration=transition_duration,
- advance_after=auto_advance,
+ effect=slide_transition,
+ duration=slide_transition_duration,
+ advance_after=slide_auto_advance,
)
slide_xml = slide_xml.replace(
'</p:sld>',
transition_xml + '\n</p:sld>',
)
- if (animation and animation != 'none'
+ if (slide_animation and slide_animation != 'none'
and create_sequence_timing_xml
and pick_animation_effect
and anim_targets):
- stagger_ms = int(animation_stagger * 1000)
- seq_targets = [
- (sid,
- 0 if idx == 0 else stagger_ms,
- pick_animation_effect(
- animation, idx, mixed_animation_offset,
- ))
- for idx, (sid, _svg_id) in enumerate(anim_targets)
- ]
- if animation == 'mixed':
- mixed_animation_offset += max(0, len(anim_targets) - 1)
+ seq_targets, mixed_count = _build_sequence_targets(
+ anim_targets,
+ slide_cfg,
+ slide_animation,
+ slide_animation_duration,
+ slide_animation_stagger,
+ mixed_animation_offset,
+ )
+ if slide_animation == 'mixed':
+ mixed_animation_offset += mixed_count
timing_xml = '\n' + create_sequence_timing_xml(
- seq_targets, duration=animation_duration,
- trigger=animation_trigger,
+ seq_targets, duration=slide_animation_duration,
+ trigger=slide_animation_trigger,
)
slide_xml = slide_xml.replace(
'</p:sld>',
@@ -410,6 +499,16 @@ def create_pptx_with_native_svg(
# ---- Legacy SVG embedding mode ----
else:
+ slide_cfg = _slide_config(animation_config, svg_path.stem)
+ slide_transition, slide_transition_duration, slide_auto_advance = (
+ _slide_transition_settings(
+ slide_cfg,
+ transition,
+ transition_duration,
+ auto_advance,
+ animation_cli_overrides,
+ )
+ )
svg_filename = f'image{i}.svg'
png_filename = f'image{i}.png'
png_rid = 'rId2'
@@ -438,9 +537,9 @@ def create_pptx_with_native_svg(
slide_num,
png_rid=png_rid, svg_rid=svg_rid,
width_emu=width_emu, height_emu=height_emu,
- transition=transition,
- transition_duration=transition_duration,
- auto_advance=auto_advance,
+ transition=slide_transition,
+ transition_duration=slide_transition_duration,
+ auto_advance=slide_auto_advance,
use_compat_mode=(use_compat_mode and slide_has_png),
)
with open(slide_xml_path, 'w', encoding='utf-8') as f:
@@ -538,8 +637,8 @@ def create_pptx_with_native_svg(
slide_xml = apply_recorded_timing(
slide_xml,
advance_after=duration + narration_padding,
- transition_duration=transition_duration,
- transition_effect=transition or 'fade',
+ transition_duration=slide_transition_duration,
+ transition_effect=slide_transition or 'fade',
)
slide_xml_path.write_text(slide_xml, encoding='utf-8')
narration_slides_created.add(slide_num)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
index e6a6380d..3a088589 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_cli.py
@@ -13,6 +13,7 @@ from .pptx_discovery import find_svg_files, find_notes_files
from .pptx_builder import create_pptx_with_native_svg
from .pptx_narration import find_narration_files
from .pptx_slide_xml import TRANSITIONS
+from .animation_config import load_animation_config, validate_animation_config
try:
from pptx_animations import ANIMATIONS as _ANIMATIONS
@@ -112,30 +113,42 @@ Recorded narration:
mode_group.add_argument('--native', action='store_true', default=False,
help='(Deprecated, now default) Convert SVG to native DrawingML shapes')
- parser.add_argument('-t', '--transition', type=str, choices=transition_choices, default='fade',
+ def non_negative_float(value: str) -> float:
+ try:
+ number = float(value)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError(f"must be a number: {value}") from exc
+ if number < 0:
+ raise argparse.ArgumentTypeError("must be non-negative")
+ return number
+
+ parser.add_argument('-t', '--transition', type=str, choices=transition_choices, default=None,
help='Page transition effect (default: fade, use "none" to disable)')
- parser.add_argument('--transition-duration', type=float, default=0.4,
+ parser.add_argument('--transition-duration', type=non_negative_float, default=None,
help='Transition duration in seconds (default: 0.4)')
- parser.add_argument('--auto-advance', type=float, default=None,
+ parser.add_argument('--auto-advance', type=non_negative_float, default=None,
help='Auto-advance interval in seconds (default: manual advance)')
parser.add_argument('-a', '--animation', type=str, choices=animation_choices,
- default='mixed',
+ default=None,
help='Per-element entrance animation (native shapes mode '
'only). Pick a single effect, "mixed" (auto-vary per '
'element, default), "random", or "none" to disable.')
- parser.add_argument('--animation-duration', type=float, default=0.4,
+ parser.add_argument('--animation-duration', type=non_negative_float, default=None,
help='Per-element entrance duration in seconds (default: 0.4)')
parser.add_argument('--animation-trigger', type=str,
choices=['on-click', 'with-previous', 'after-previous'],
- default='after-previous',
+ default=None,
help='Per-element Start mode (matches PowerPoint Start dropdown): '
'"on-click" (one click per element), '
'"with-previous" (all start together on slide entry), '
'"after-previous" (default, cascade after the previous element).')
- parser.add_argument('--animation-stagger', type=float, default=0.5,
+ parser.add_argument('--animation-stagger', type=non_negative_float, default=None,
help='Delay between elements in --animation-trigger=after-previous '
'(seconds, default 0.5). Ignored in other modes.')
+ parser.add_argument('--animation-config', type=str, default=None,
+ help='Optional per-slide/per-object animation config. '
+ 'Default: <project>/animations.json when present.')
parser.add_argument('--no-notes', action='store_true',
help='Disable speaker notes embedding (enabled by default)')
@@ -243,8 +256,74 @@ Recorded narration:
print(f" Narration audio directory: {narration_audio_dir}")
print(f" Narration audio matched: {len(narration_audio)}/{len(ref_files)} slide(s)")
- transition = args.transition if args.transition != 'none' else None
- animation = args.animation if args.animation != 'none' else None
+ if args.animation_config:
+ config_path = Path(args.animation_config)
+ if not config_path.is_absolute():
+ config_path = project_path / config_path
+ if not config_path.exists():
+ print(f"Error: Animation config does not exist: {config_path}")
+ sys.exit(1)
+
+ try:
+ animation_config = load_animation_config(project_path, args.animation_config)
+ except Exception as exc:
+ print(f"Error: Failed to load animation config: {exc}")
+ sys.exit(1)
+ if animation_config and verbose:
+ config_label = args.animation_config or str(project_path / 'animations.json')
+ print(f" Animation config: {config_label}")
+ for warning in validate_animation_config(project_path, animation_config):
+ print(f" [warn] {warning}")
+
+ defaults = animation_config.get('defaults', {}) if animation_config else {}
+ transition_defaults = defaults.get('transition', {}) if isinstance(defaults, dict) else {}
+ animation_defaults = defaults.get('animation', {}) if isinstance(defaults, dict) else {}
+
+ transition_arg = args.transition
+ transition_effect = (
+ transition_arg
+ if transition_arg is not None
+ else transition_defaults.get('effect', 'fade')
+ )
+ transition = None if transition_effect == 'none' else transition_effect
+ transition_duration = (
+ args.transition_duration
+ if args.transition_duration is not None
+ else float(transition_defaults.get('duration', 0.4))
+ )
+
+ animation_arg = args.animation
+ animation_effect = (
+ animation_arg
+ if animation_arg is not None
+ else animation_defaults.get('effect', 'mixed')
+ )
+ animation = None if animation_effect == 'none' else animation_effect
+ animation_duration = (
+ args.animation_duration
+ if args.animation_duration is not None
+ else float(animation_defaults.get('duration', 0.4))
+ )
+ animation_stagger = (
+ args.animation_stagger
+ if args.animation_stagger is not None
+ else float(animation_defaults.get('stagger', 0.5))
+ )
+ animation_trigger = (
+ args.animation_trigger
+ if args.animation_trigger is not None
+ else animation_defaults.get('trigger', 'after-previous')
+ )
+
+ animation_cli_overrides = {
+ 'transition': args.transition is not None,
+ 'transition_duration': args.transition_duration is not None,
+ 'auto_advance': args.auto_advance is not None,
+ 'animation': args.animation is not None,
+ 'animation_duration': args.animation_duration is not None,
+ 'animation_stagger': args.animation_stagger is not None,
+ 'animation_trigger': args.animation_trigger is not None,
+ }
# svg_files is per-product (native vs legacy may now read different
# directories); everything else is shared.
@@ -252,15 +331,17 @@ Recorded narration:
canvas_format=canvas_format,
verbose=verbose,
transition=transition,
- transition_duration=args.transition_duration,
+ transition_duration=transition_duration,
auto_advance=args.auto_advance,
use_compat_mode=not args.no_compat,
notes=notes,
enable_notes=enable_notes,
animation=animation,
- animation_duration=args.animation_duration,
- animation_stagger=args.animation_stagger,
- animation_trigger=args.animation_trigger,
+ animation_duration=animation_duration,
+ animation_stagger=animation_stagger,
+ animation_trigger=animation_trigger,
+ animation_config=animation_config,
+ animation_cli_overrides=animation_cli_overrides,
narration_audio=narration_audio,
use_narration_timings=use_narration_timings,
narration_padding=args.narration_padding,
diff --git a/skills/ppt-master/workflows/customize-animations.md b/skills/ppt-master/workflows/customize-animations.md
new file mode 100644
index 00000000..835bcab9
--- /dev/null
+++ b/skills/ppt-master/workflows/customize-animations.md
@@ -0,0 +1,91 @@
+---
+description: Customize default PPTX animations with per-slide and per-object timing/effect overrides
+---
+
+# Customize Animations Workflow
+
+> Standalone post-generation step. Run when the user asks to tune animation order, effects, timing, or object-level reveals. Default PPTX export already has global animations; this workflow only creates `animations.json` overrides when the user wants finer control.
+
+## When to Run
+
+| Condition | Action |
+|---|---|
+| User asks for object-level animation, reveal order, timing, or effect changes | Run this workflow |
+| User only wants the default animated deck | Do not run; normal `svg_to_pptx.py` export is enough |
+| `svg_output/*.svg` is missing | Complete the main Executor phase first |
+| Existing `animations.json` is present | Validate and edit it; do not overwrite unless the user asks |
+
+---
+
+## 1. Build or Validate the Scaffold
+
+**Mandatory**: use real SVG group ids. Do not invent slide or group keys.
+
+If `animations.json` does not exist:
+
+```bash
+python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path>
+```
+
+If it already exists:
+
+```bash
+python3 skills/ppt-master/scripts/animation_config.py validate <project_path>
+```
+
+---
+
+## 2. Edit `animations.json`
+
+**Hard rule**: write only overrides that differ from the default global animation. Unmentioned groups keep the normal export behavior.
+
+| Field | Behavior |
+|---|---|
+| `effect` | Any supported entrance effect, `mixed`, `random`, or `none` |
+| `order` | Animation order only; does not change SVG layer order |
+| `delay` | Extra seconds before this group starts in `after-previous` mode |
+| `duration` | Per-group entrance duration in seconds |
+
+Example:
+
+```json
+{
+ "version": 1,
+ "slides": {
+ "03_market": {
+ "groups": {
+ "title": { "effect": "fade", "order": 1 },
+ "chart": { "effect": "wipe", "order": 2, "duration": 0.6 },
+ "insight": { "effect": "fly", "order": 3, "delay": 0.2 },
+ "footer": { "effect": "none" }
+ }
+ }
+ }
+}
+```
+
+**Forbidden — SVG pollution**: do not add `data-*` animation attributes to SVG files. Animation customization belongs in `animations.json`.
+
+---
+
+## 3. Validate and Export
+
+Run sequentially:
+
+```bash
+python3 skills/ppt-master/scripts/animation_config.py validate <project_path>
+```
+
+```bash
+python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path>
+```
+
+**Validation**: the exported native PPTX should reflect the object-level overrides. `--animation none` still disables all per-element animation and overrides `animations.json`.
+
+---
+
+## ✅ Customize Animations Complete
+
+- [x] `animations.json` exists only because object-level customization was requested
+- [x] `animation_config.py validate` passed
+- [x] PPTX re-export completed with custom animation overrides