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(pptx-animations): unify animation behavior across export routes
hugohe3918bf082782b
diff --git a/README.md b/README.mdindex 65f31091..86f765c2 100644--- a/README.md+++ b/README.md@@ -90,7 +90,7 @@ English | [中文](./README_CN.md)----Drop in your source material, and the deck you get back is **more than just editable**: it has native slide transitions and entrance animations, speaker notes that can become audio narration, charts and tables that can ship as real data-backed PowerPoint objects, and it can follow your own PPT template — a complete deck you can present as-is and keep refining. How to use each capability → [Getting Started](./docs/getting-started.md).+Drop in your source material, and the deck you get back is **more than just editable**: it has native slide transitions plus opt-in entrance animations (off by default), speaker notes that can become audio narration, charts and tables that can ship as real data-backed PowerPoint objects, and it can follow your own PPT template — a complete deck you can present as-is and keep refining. How to use each capability → [Getting Started](./docs/getting-started.md).## Product Positioningdiff --git a/README_CN.md b/README_CN.mdindex e5e21b9d..e7a24431 100644--- a/README_CN.md+++ b/README_CN.md@@ -94,7 +94,7 @@----丢进原材料,拿回的这份 PPT **不只是能改**:它有 PPT 原生的转场与入场动画,演讲者备注能直接合成音频旁白,图表和表格还能以带数据的 PowerPoint 原生对象形式导出,也能参考你自己的 PPT 模板来设计——一份能直接拿去讲、回头还能改的成品。每项能力怎么用 → [快速入门](./docs/zh/getting-started.md)。+丢进原材料,拿回的这份 PPT **不只是能改**:它有 PPT 原生转场,也支持按需开启的入场动画(默认关闭),演讲者备注能直接合成音频旁白,图表和表格还能以带数据的 PowerPoint 原生对象形式导出,也能参考你自己的 PPT 模板来设计——一份能直接拿去讲、回头还能改的成品。每项能力怎么用 → [快速入门](./docs/zh/getting-started.md)。## 产品定位diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 66322a78..36e78657 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -82,7 +82,9 @@ Full guide → [Live Preview Workflow](../skills/ppt-master/workflows/live-previ## Animations & transitions-Exported decks ship **page transitions** and **per-element entrance animations** as real OOXML — not embedded video. By default, elements cascade in on slide entry with no setup, and the deck plays natively in PowerPoint and Keynote with no extra tooling. Reach for customization only when you want a specific order, effect, or timing.+Exported decks carry page transitions and optional per-element entrance animations as real OOXML — not embedded video. The default is a `fade` page transition with **no element animation**; opt in with `-a auto`, a named effect, or an `animations.json` sidecar when you want a reveal sequence.++Animation settings are strict: unknown effects or Start modes, invalid timing values, and missing sidecar targets fail instead of silently becoming another effect. Before the result replaces an existing output, PPT Master reads the candidate package back and checks timing placement, IDs, shape targets, effects, durations, and Start modes. Microsoft PowerPoint is the primary motion-validation target; other presentation apps can open the PPTX but may map individual animation effects differently.Full guide → [Animations & Transitions](../skills/ppt-master/references/animations.md)@@ -121,7 +123,7 @@ The [FAQ](./faq.md) is the living troubleshooting reference — continuously upd| Visual quality disappoints | Switch to a large-context Claude model + `gpt-image-2` — the harness sets the floor, the model sets the ceiling. || Text overflows or elements overlap | Re-run that page, or fix it in live preview; see the [FAQ](./faq.md). || No image-generation API key | Zero-config web search still works as a fallback; see the [FAQ](./faq.md). |-| Animations or some effects look off in another app | The file is standard `.pptx` and opens in PowerPoint / Keynote / WPS / LibreOffice; element animations render most completely in PowerPoint 2016+ and Keynote, while older Office may downgrade some to plain Appear. |+| Animations or some effects look off in another app | Microsoft PowerPoint is the primary motion-validation target. Keynote / WPS / LibreOffice can open the `.pptx`, but may remap or omit individual effects or Start semantics; validate motion-critical delivery in PowerPoint. || A long deck might blow the context window | Generation can run in split mode; details in the [FAQ](./faq.md). |For model choice, cost, chart editability, custom templates, and more, the [FAQ](./faq.md) is the place to look.diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 7db6191a..e2f71a19 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -25,7 +25,7 @@ The past two months' structural capability growth. Single flags / incremental po- **PPTX export step-change**: SVG clipPath → DrawingML picture geometry, marker → native arrows, output consolidated to `exports/`- **Chart library expands to 70 templates + three icon libraries** (simple-icons / phosphor-duotone / brand-logo)- **`spec_lock.md` machine-readable contract**: Strategist locks the spec, Executor re-reads it before every page — cross-page consistency gets a real guarantee-- **Per-element animation on by default** + recorded narration / video export ([`workflows/generate-audio.md`](../skills/ppt-master/workflows/generate-audio.md))+- **Per-element animation support** + recorded narration / video export ([`workflows/generate-audio.md`](../skills/ppt-master/workflows/generate-audio.md)); the current behavior is opt-in, with element animation defaulting to `none`### 2026-05 — Visual editing + AI image systematization@@ -76,10 +76,12 @@ The past two months' structural capability growth. Single flags / incremental po- **Native PPTX export caps image media size** — keep generated decks editable without embedding huge source images: new native image sizing modes — `cap` (default) limits only oversized source images to a max dimension, while `display` sizes from the rendered SVG box for more aggressive compression; native export preserves full embedded pixels while SVG/PPT display cropping stays as editable picture-crop metadata; `finalize_svg` keeps its existing slice/meet behavior and adds default rendered-size downsampling for compact SVG snapshots. Docs land the `cap` / `display` modes and the `--no-image-optimize` escape hatch-### 2026-07 — Staged confirmation UI + native chart / table maturation+### 2026-07 — Staged confirmation UI + native objects + motion hardening- **Step 4 confirmation gate restaged into a three-pass wizard + visual previews** — the single Eight-Confirmations gate became a three-stage flow in one browser session (direction anchors → design system → images / execution), each downstream stage re-derived from the user's **actual** confirmed upstream choices instead of the AI's originals — so, e.g., the image strategy fits the confirmed color system by construction. The confirm page adds visual aids for the hard-to-name picks: a bespoke real-SVG page thumbnail for each of the 18 `visual_style` options, real icon-library samples, and AI-image reference previews. `recommendations.json` now carries a canonical `stage` selector (`tier` retained only as an internal back-compat read) and user-facing wording is unified on "stage"; the chat fallback mirrors the same staged order+- **Transitions and entrance-animation export hardened against silent downgrade** — the current defaults stay `fade` / 0.4 s for page transitions and `none` for element entrances; object motion remains opt-in through `-a` or `animations.json`. Unknown effects / Start modes, non-finite or out-of-range timing, invalid order values, and missing slide/group references now fail instead of falling back to `fade`, another Start mode, or inherited timing. Export reads the candidate PPTX back before replacement and validates root timing placement, unique time-node IDs, live shape targets, effect/duration/Start semantics, and narration timing merges. Direct-PPTX routes preserve existing object animation rather than translating it into the generated animation model. Microsoft PowerPoint is the primary behavior-validation target; other presentation apps remain compatibility targets without an identical-motion guarantee+- **`--native-objects` hardened from dormant marker to usable opt-in** — the narrow native-object exception (see Non-goals below) now emits charts and pure-text tables that keep the deck's own design instead of snapping to PowerPoint's white default theme. Classic native charts write explicit chart-area / plot-area / axis-line / gridline / label-text colors — inferred from the visible SVG fallback (largest panel `<rect>` → background, fallback text → labels, fallback strokes → axis/grid) or overridden per `style` (`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`, `"none"` for transparent); the color parser normalizes named CSS colors, `#RGB` shorthand, and `rgb()` / `rgba()` to OOXML hex; bar/column series disable negative-value fill inversion so negative bars keep their series color. The activated export is named `<name>_<ts>_native_charts.pptx` to tell it apart from the default flattened-shape export. **The default route is unchanged** — charts/tables still export as SVG-derived DrawingML shapes for cross-renderer fidelity; native objects stay the deliberate opt-in trade documented under Non-goals below- **Native package structure + conservative PPTX object round-trip** — free-design baseline export promotes only safe shared backgrounds/chrome, assigns marker-backed Layout families, and may lift exact family-wide leading structurally marked chrome without inferring placeholders; marker-free legacy SVGs retain filename/id fallback. Template export deterministically compiles complete SVG pages whose Master/Layout/placeholder ownership is explicit. `create-template` uses imported source structure as analysis input and always rebuilds explicit SVG structure; strict keeps a selected Layout, adaptive may add a new Layout under the same Master. Legacy `preserve` remains compatibility-only. Raw one-off PPTX filling remains `template-fill-pptx`.diff --git a/docs/zh/animations.md b/docs/zh/animations.mdindex 3e6afde5..2c74d9cf 100644--- a/docs/zh/animations.md+++ b/docs/zh/animations.md@@ -1,6 +1,6 @@# 页间转场与页内元素动画-PPT Master 导出的 PPTX 同时支持**页间转场**(page transition)与**页内元素入场动画**(per-element entrance animation)。两者都通过 `svg_to_pptx.py` 的 CLI 参数控制,输出为真正的 OOXML 动画——在 PowerPoint 和 Keynote 中原生播放,不是嵌入视频。+PPT Master 导出的 PPTX 同时支持**页间转场**(page transition)与**页内元素入场动画**(per-element entrance animation)。两者都通过 `svg_to_pptx.py` 的 CLI 参数控制,输出为真正的 OOXML 动画,不是嵌入视频。Microsoft PowerPoint 桌面版是动效行为的主要验证目标;Keynote、WPS、LibreOffice 可以打开 PPTX,但可能以不同方式映射个别效果或 Start 语义。## 默认行为@@ -28,18 +28,44 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project>python3 skills/ppt-master/scripts/svg_to_pptx.py <project>```-最小 sidecar:+完整 sidecar 示例(假设项目只有下面两页):```json{"version": 1,+ "defaults": {+ "transition": { "effect": "fade", "duration": 0.4 },+ "animation": {+ "effect": "auto",+ "duration": 0.4,+ "stagger": 0.5,+ "trigger": "after-previous"+ }+ },"slides": {+ "01_cover": {+ "transition": { "effect": "fade", "duration": 0.5 },+ "animation": {+ "effect": "fade",+ "duration": 0.5,+ "stagger": 0.3,+ "trigger": "after-previous"+ },+ "groups": {+ "cover-hero": { "effect": "zoom", "order": 2, "duration": 0.6 }+ }+ },"03_market": {+ "transition": { "effect": "wipe", "duration": 0.35 },+ "animation": {+ "effect": "fade",+ "duration": 0.4,+ "stagger": 0.25,+ "trigger": "after-previous"+ },"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" }+ "insight": { "effect": "fly", "order": 3, "delay": 0.2 }}}}@@ -48,12 +74,14 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project>规则:+- `defaults` 是未列页面的回退值;正式自定义配置仍应把 `svg_output/` 中的每一页都写进 `slides`。- `slides` key 匹配 SVG 文件 stem(`03_market.svg` → `03_market`)。-- `groups` key 匹配顶层 `<g id="...">` 锚点。+- 每个页面都显式写完整的 `transition`、`animation` 和 `groups`;`groups` 只列真正偏离页面默认值的对象。+- `groups` key 只能匹配可动画的顶层 `<g id="...">` 内容锚点;带 `data-pptx-layer` 或显式静态 role/placeholder 标记的 Master / Layout / 静态框架对象不属于可覆盖目标。- `effect: none` 会把该组移出入场动画序列。-- `order` 只改变动画顺序,不改变页面图层顺序。+- `order` 必须是大于零的整数,只改变动画顺序,不改变页面图层顺序。- `delay` 是 `after-previous` 模式下该组开始前的秒数。-- `duration` 覆盖该组的入场时长。+- `duration` 覆盖该组的排程时长;`appear` 的可见性切换固定为 1ms,该值只用于计算下一条 `after-previous` 的间隔。- `--animation none` 覆盖 sidecar,强制关闭所有页内动画。## 页间转场@@ -103,14 +131,16 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation mixed \--animation-stagger 0.6 --animation-duration 0.5# 所有组进入页面时同时入场-python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger with-previous+python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -a auto --animation-trigger with-previous```22 种单一效果:`appear`、`fade`、`fly`、`cut`、`zoom`、`wipe`、`split`、`blinds`、`checkerboard`、`dissolve`、`random_bars`、`peek`、`wheel`、`box`、`circle`、`diamond`、`plus`、`strips`、`wedge`、`stretch`、`expand`、`swivel`。再加三种自动模式:+这些 key 保留既有的 `filter + presetID + presetSubtype` tuple。`cut` 是兼容旧配置的公开 key;项目承诺保持其既有 tuple,不根据外部 preset 表推测或重命名视觉语义。+- `auto`(开启时推荐)—— 按 group 的 SVG id 映射效果。信息密集元素稳定映射:`chart` / `table` / `legend` / `timeline` / `track` → `wipe`;`card-*` / `pillar-*` / `item-*` / `step-*` / `stage-*` / `tier-*` / `principle-*` → `fly`;`title` / `chapter-*` / `section-*` / `cover-*` / `tagline` / `subtitle` → `fade`;`takeaway` / `callout` / `quote` / `source` / `conclusion` / `note` → `fade`。图片类 id `hero` / `figure-*` / `image` / `img-*` / `kpi` 则在更丰富的视觉池(`zoom` / `dissolve` / `circle` / `box` / `diamond` / `wheel`)中循环,使多张图片在 deck 内呈现不同入场。未命中的 id 在 `fade` / `wipe` / `fly` / `zoom` 之间循环。- `mixed`(旧逻辑)—— 确定性轮换。每页第一个动画组使用 `fade`,后续组在整份 deck 范围内按 16 效果池(`blinds` / `checkerboard` / `dissolve` / `fly` / `cut` / `random_bars` / `box` / `split` / `strips` / `wedge` / `wheel` / `wipe` / `expand` / `fade` / `swivel` / `zoom`)连续轮换。保留以兼容旧配置。-- `random` —— 在旧的 16 效果池中随机抽取。+- `random` —— 从旧的 16 效果池中按有效 deck 输入使用稳定 seed 抽取;相同输入得到相同结果,启用 `--conversion-trace` 时记录每个已解析效果。所有轮换池都排除了 `appear`,因为它没有可见动画过程。@@ -124,13 +154,28 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger w> Note: `--recorded-narration` 会拒绝 `on-click`;带旁白的视频导出请使用 `after-previous` 或 `with-previous`。+## 严格校验与导出回读++动画配置不会静默换成另一个效果或触发方式。运行 `animation_config.py validate` 后,以下问题都会返回非零:++| 问题 | 结果 |+|---|---|+| 未知效果、自动模式或 Start 模式 | 报错;不会回退为 `fade` 或 `on-click` |+| `duration` 非有限或不大于零 | 报错;页间 `effect: none` 是兼容例外,可使用 `duration: 0` |+| `stagger` / `delay` 非有限或小于零 | 报错 |+| `order` 不是大于零的整数(含布尔、浮点或字符串) | 报错 |+| `slides` / `groups` 引用不存在 | 报错并阻止导出 |+| 顶层 `<g>` 没有 `id` | 给出警告;该组不能被 `groups` 精确引用,建议补稳定 id |++导出先写候选 PPTX,再回读整个包:每页只能有一个合法的根级 `p:timing`,时间节点 ID 必须唯一,`spTgt` / `bldP` 必须指向现存 shape,效果、时长和 Start 模式必须与已解析配置一致。旁白加入音频 timing 后也走同一包级校验;任何失败都不会替换已有公开产物。+## 锚点机制 — 顶层 `<g id="...">`-页内动画锚定在 SVG 的**顶层 `<g id="...">` 内容组**上(如 `<g id="cover-title">`、`<g id="card-1">`),一个组对应一次点击入场。+页内动画锚定在 SVG 的**顶层 `<g id="...">` 内容组**上(如 `<g id="cover-title">`、`<g id="card-1">`),一个组对应动画窗格中的一条入场记录;是否需要点击由 Start 模式决定。每页建议 **3–8 个内容组**。这同时也是 PowerPoint 框选 / 整体移动的颗粒度,与是否启用动画无关,都能改善编辑体验。-**装饰类分组自动跳过。** 顶层中看起来属于页面装饰的组(背景、页头页脚、装饰元素、水印、页码、导航、logo、分隔线)会被排除在点击序列外,跟随页面立即显示。识别基于 `id`:按 `-` 和 `_` 切分后,若任一 token 命中 `background` / `bg` / `decoration` / `decorations` / `decor` / `header` / `footer` / `chrome` / `watermark` / `pagenumber` / `pagenum` / `nav` / `logo` / `rule`,则视为装饰类。会自动跳过的例子:`<g id="background">`、`<g id="bg-texture">`、`<g id="cover-footer">`、`<g id="p03-header">`、`<g id="bottom-decor">`、`<g id="watermark">`、`<g id="nav">`、`<g id="logo-area">`、`<g id="column-rule">`。仍会动画的例子:`<g id="card-1">`、`<g id="cover-title">`、`<g id="step-discover">`、`<g id="timeline-track">`。**不要为了规避动画去掉 `<g>` 包裹**——保留分组(PowerPoint 框选需要),只要给个合适的 id 即可。+**静态结构优先于动画覆盖。** `data-pptx-layer` 明确标记 Master / Layout / 静态页面框架,永远不会成为页内动画锚点,`groups` 中的手工覆盖也不能强制开启。没有该标记时,结构角色 / placeholder 语义继续优先;只对缺少显式语义的旧 SVG 使用 id token 回退。若 id 按 `-` 和 `_` 切分后命中 `background` / `bg` / `decoration` / `decorations` / `decor` / `header` / `footer` / `chrome` / `watermark` / `pagenumber` / `pagenum` / `nav` / `logo` / `rule`,该组会跟随页面立即显示。会跳过的例子:`<g id="background">`、`<g id="cover-footer">`、`<g id="p03-header">`、`<g id="bottom-decor">`、`<g id="watermark">`、`<g id="logo-area">`。仍会动画的例子:`<g id="card-1">`、`<g id="cover-title">`、`<g id="step-discover">`、`<g id="timeline-track">`。**不要为了规避动画去掉 `<g>` 包裹**——保留分组(PowerPoint 框选需要),为静态结构使用正确的 layer / role 标记。**扁平 SVG 的回退逻辑**(顶层没有 `<g>`,只有裸 `<rect>` / `<text>` / `<path>`):@@ -142,7 +187,8 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger w## 限制- **动画只写入原生 DrawingML PPTX。** 页间转场和页内元素动画都属于项目转换器从 `svg_output/` 生成的 PPTX;`svg_final/` 仍是静态视觉预览,不是带动画的替代 PPTX 路线。-- **不同 Office 版本对元素动画存在轻微差异。** 实现走 `<p:animEffect filter=...>` 路径(而非 `presetID` 查找表),在 PowerPoint 2016+ 上表现一致;更老的 Office 可能把部分效果降级为 Appear。+- **直接 PPTX 路线只保留对象动画。** Template Fill 与 Native Enhance 不把源 `p:timing` 翻译或重建为生成路线的效果模型;它们保留源对象动画,Native Enhance 仅在需要时合并旁白音频 timing,并在封包前校验结果。旁白合并只接受根级 `p:sld/p:timing`;若源 timing 位于 `mc:AlternateContent` 或其他非根容器中,会安全报错,不会重写或重复 timing 树。+- **PowerPoint 是主要动效验证目标。** Keynote、WPS、LibreOffice 与较旧 Office 可能重新映射、简化或忽略部分效果;动效是交付要求时,请在 Microsoft PowerPoint 桌面版中完成最终播放检查。- **手工 SVG 形状转换不受支持。** 把 `svg_final/` 页面作为 SVG 图片插入 PowerPoint,不会获得元素级动画锚点;需要可编辑且可动画的形状时,请使用原生 PPTX。## 常用速查@@ -154,10 +200,10 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger w| 转场放慢 | `--transition-duration 0.8` || 自动播放 | `--auto-advance 5` || 关闭页内动画 | `-a none` |-| 改为单击触发 | `--animation-trigger on-click` |+| 改为单击触发 | `-a auto --animation-trigger on-click` || 切换为单一效果 | `--animation fade` |-| 所有组同时入场 | `--animation-trigger with-previous` |-| 元素入场放慢 | `--animation-duration 0.5` |-| after-previous 拉大间隔 | `--animation-stagger 0.8` |+| 所有组同时入场 | `-a auto --animation-trigger with-previous` |+| 元素入场放慢 | `-a auto --animation-duration 0.5` |+| after-previous 拉大间隔 | `-a auto --animation-stagger 0.8` |完整 `svg_to_pptx.py` 参考:[`scripts/docs/svg-pipeline.md`](../../skills/ppt-master/scripts/docs/svg-pipeline.md)。diff --git a/docs/zh/getting-started.md b/docs/zh/getting-started.mdindex 451c08d6..ae332bca 100644--- a/docs/zh/getting-started.md+++ b/docs/zh/getting-started.md@@ -82,7 +82,7 @@ PPT Master 最初是纯对话设计;可视化编辑是在很多用户提出后## 转场与动画-导出的 deck 自带**页间转场**和**页内元素入场动画**,输出为真正的 OOXML——不是嵌入视频。默认元素进入页面时自动级联入场,无需设置,在 PowerPoint 和 Keynote 中原生播放,无需额外工具。只有当你想要特定顺序、效果或时序时,才需要定制。+导出的 deck 用真正的 OOXML 保存**页间转场**和可选的**页内元素入场动画**,不是嵌入视频。默认保留 `fade` 页间转场,页内动画为 `none`;只有显式使用 `-a auto`、其它效果或 `animations.json` 才会启用对象入场。未知效果、Start 模式、非法时序值或缺失对象引用会直接阻断导出,候选 PPTX 还会在发布前回读动画目标、效果和 timing 结构。Microsoft PowerPoint 是动效行为的主要验证目标;Keynote、WPS、LibreOffice 可能重新映射个别效果。完整说明 → [转场与动画](./animations.md)@@ -121,7 +121,7 @@ PPT Master 最初是纯对话设计;可视化编辑是在很多用户提出后| 视觉质量不理想 | 换成大上下文 Claude 模型 + `gpt-image-2`——harness 决定下限,模型决定上限。 || 文字溢出或元素重叠 | 重跑那一页,或用实时预览修;详见 [FAQ](./faq.md)。 || 没有生图 API key | 零配置的网络图片搜索仍可作为兜底;见 [FAQ](./faq.md)。 |-| 动画或部分效果在别的软件里不对 | 文件是标准 `.pptx`,PowerPoint / Keynote / WPS / LibreOffice 都能打开;元素动画在 PowerPoint 2016+ 和 Keynote 还原最完整,更老的 Office 会把部分效果降级为 Appear。 |+| 动画或部分效果在别的软件里不对 | Microsoft PowerPoint 是动效行为的主要验证目标。Keynote / WPS / LibreOffice 可以打开 `.pptx`,但可能重新映射或省略个别效果或 Start 语义;动效关键交付应在 PowerPoint 中验证。 || 担心长 deck 撑爆上下文 | 生成可走分段模式;详见 [FAQ](./faq.md)。 |模型选择、费用、图表可编辑性、自定义模板等,都在 [FAQ](./faq.md) 里。diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.mdindex d78d9967..3853ff29 100644--- a/docs/zh/roadmap.md+++ b/docs/zh/roadmap.md@@ -25,7 +25,7 @@- **PPTX 导出质变**:SVG clipPath → DrawingML picture geometry、marker → 原生箭头、输出归集到 `exports/`- **图表库 70 个 + 图标三库**(simple-icons / phosphor-duotone / brand-logo)- **`spec_lock.md` 机器可读契约**:Strategist 锁定后 Executor 每页强制重读,跨页一致性有了保证-- **元素级动画默认开启** + 旁白音频 / 视频导出([`workflows/generate-audio.md`](../../skills/ppt-master/workflows/generate-audio.md))+- **元素级动画能力** + 旁白音频 / 视频导出([`workflows/generate-audio.md`](../../skills/ppt-master/workflows/generate-audio.md));当前行为为按需开启,元素动画默认 `none`### 2026-05(视觉编辑 + AI 图系统化)@@ -76,10 +76,12 @@- **原生 PPTX 导出图片媒体大小封顶** — 保持生成 deck 可编辑、不嵌入巨幅源图:新增原生图片尺寸模式——`cap`(默认)只对超大源图限制最大边长,`display` 按渲染 SVG 框尺寸做更激进压缩;原生导出保留完整嵌入像素,SVG/PPT 显示裁剪仍走可编辑的 picture-crop 元数据;`finalize_svg` 保留原有 slice/meet 行为,另加默认按渲染尺寸下采样以产出紧凑 SVG 快照。文档落地 `cap` / `display` 两模式与 `--no-image-optimize` 逃生舱-### 2026-07(分阶段确认 UI + 原生图表 / 表格成熟)+### 2026-07(分阶段确认 UI + 原生对象 + 动效加固)- **Step 4 确认 gate 重构为三阶段向导 + 可视化预览** — 原来单次「八项确认」gate 拆成一个浏览器会话内的三阶段流程(方向锚点 → 设计系统 → 图片 / 执行方式),每个下游阶段都从用户**实际已确认**的上游选择重新推导,而非 AI 原始推荐——于是图片策略天然吻合已确认的配色系统。确认页为难以凭名字判断的选项补上视觉辅助:18 个 `visual_style` 每个一张专属 real-SVG 页面缩略图、真实图标库样本、AI 图参考图预览。`recommendations.json` 改用规范的 `stage` 选择器(`tier` 仅作内部向后兼容读取),用户可见措辞统一为「阶段」;聊天 fallback 镜像同样的分阶段顺序+- **页间转场与元素入场动画完成无静默降级加固** — 当前默认保持页间 `fade` / 0.4 秒、元素入场 `none`,对象动画仍通过 `-a` 或 `animations.json` 按需开启。未知效果 / Start 模式、非有限或越界时长、非法顺序,以及缺失 slide/group 引用都会直接失败,不再偷换为 `fade`、其它 Start 模式或继承值。公开产物替换前会回读候选 PPTX,校验根级 timing 位置、时间节点 ID 唯一性、shape 引用、效果 / 时长 / Start 语义及旁白 timing 合并。直接 PPTX 路线只保留源对象动画,不把它翻译成生成路线的动画模型。Microsoft PowerPoint 是动效行为的主要验证目标;其它演示软件仅作为兼容目标,不承诺完全相同的播放结果+- **`--native-objects` 从休眠 marker 硬化为可用级 opt-in** — 那条窄「原生对象」例外(见下文 Non-goals)现在导出的图表与纯文本表格会**保留 deck 自己的设计**,不再塌回 PowerPoint 的白底默认主题。classic 原生图表显式写入 chart-area / plot-area / 轴线 / 网格线 / 标签文字颜色——从可见的 SVG fallback 推断(最大面板型 `<rect>` → 背景、fallback 文字 → 标签、fallback 描边 → 轴线/网格),或用 `style` 显式覆盖(`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`,`"none"` 表透明);颜色解析把命名色、`#RGB` 简写、`rgb()` / `rgba()` 归一为 OOXML hex;bar/column 系列关掉负值反色,负值柱保持系列色。激活导出命名为 `<name>_<ts>_native_charts.pptx` 以与默认压平形状导出区分。**默认路线不变**——图表/表格仍以 SVG 派生的 DrawingML 形状导出以保跨渲染器保真;原生对象仍是下文 Non-goals 里那条刻意的 opt-in 取舍- **原生 package 结构 + 保守 PPTX 对象回转** — 自由设计的 baseline 只提升安全共享背景/chrome,分配文件名页型 Layout,并可进一步提升家族内完全一致的前置 chrome,不推断 placeholder。模板路线则确定性编译完整 SVG 中显式声明的 Master/Layout/placeholder。`create-template` 只把源结构当分析输入并统一重建显式 SVG;`strict` 保持所选 Layout,`adaptive` 可在同一 Master 下新建 Layout。旧 `preserve` 仅保留兼容读取。diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.mdindex 46a5a23e..b36ff06b 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -818,6 +818,21 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>- `--animation-config <path>` — optional object-level sidecar. Default: `<project_path>/animations.json` when present.- `--auto-advance <seconds>` — kiosk-style auto-play. Click remains enabled, so click or timer may advance the slide.+**Animation compatibility gate**: the default element animation remains `none`.+When animation is enabled, unknown effects/modes/triggers, invalid numeric or+order values, missing slide/group references, and explicit structural layer,+static-role, or static-placeholder targets fail export; they never downgrade+or disappear silently. An explicit+sidecar group may override only the legacy chrome-name heuristic. `random`+resolution is stable for the same effective input; with `--conversion-trace`,+its resolved rows are written to the trace. Generated export performs per-slide semantic+read-back plus package timing/`p:cTn`/`p:spTgt` validation. Narration merges+audio timing into the existing DOM and preserves animation rows. Direct-PPTX+routes preserve source object animation, compare its object-animation fingerprint+before/after allowed edits, and validate structure; they do not author+animation effects. The exact 22 tuples and OOXML rules live in+[`scripts/docs/pptx-animations.md`](scripts/docs/pptx-animations.md).+**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 applies page transitions but no per-element entrance animation; create `animations.json` (or pass `-a auto`) only when the user asks for element animation or object-level customization.@@ -829,6 +844,8 @@ Run the standalone [`generate-audio`](workflows/generate-audio.md) workflow. TheDo NOT call `notes_to_audio.py` directly without going through the workflow — `--voice` / `--voice-id` is required and the workflow produces the locale/provider-aware recommendation that makes the choice meaningful.Full effect list, anchor logic, and limits: [`references/animations.md`](references/animations.md).+The compatibility contract covers PowerPoint OOXML; do not promise identical+animation playback in Keynote or other presentation applications.> ❌ **NEVER** substitute `cp` for `finalize_svg.py` — finalize performs multiple critical processing steps> ❌ **NEVER** use `-s final` for a release export. It is a diagnostic comparison only; the supported native route reads `svg_output/`.diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.mdindex af350727..44c5ca7b 100644--- a/skills/ppt-master/references/animations.md+++ b/skills/ppt-master/references/animations.md@@ -1,8 +1,10 @@# Page Transitions & Per-Element Animations-PPT Master's exported PPTX supports **page transitions** (slide-to-slide) and **per-element entrance animations** (within a slide). Both are controlled by `svg_to_pptx.py` CLI flags and ship as real OOXML — they animate inside PowerPoint and Keynote, no embedded video.+PPT Master's exported PPTX supports **page transitions** and **per-element+entrance animations** as real PowerPoint OOXML. Other applications may+interpret timing differently; this contract makes no unconditional Keynote guarantee.-## Defaults+## 1. Defaults| Layer | Default | Why ||---|---|---|@@ -11,7 +13,9 @@ 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/` — no need to rerun the LLM. `-s final` is reserved for diagnostic comparison and is not a supported release source. To turn per-element animation on for the whole deck, pass `-a auto`.-## Custom Object-Level Animation+---++## 2. Custom Object-Level AnimationPer-element animation is off by default. To enable it deck-wide, pass `-a auto` at export (no config needed). When a deck instead 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.@@ -44,8 +48,7 @@ Single-slide sidecar excerpt (repeat the complete slide block for every SVG in `"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" }+ "insight": { "effect": "fly", "order": 3, "delay": 0.2 }}}}@@ -59,10 +62,14 @@ Rules:- `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.+- `duration` overrides the per-group schedule duration. `appear` remains a 1ms visibility flip; its configured duration spaces the next `after-previous` row.- `--animation none` overrides the sidecar and disables all per-element animation.+- An explicit sidecar group may override the legacy chrome-name heuristic, but it cannot override `data-pptx-layer` or an explicit static role/placeholder marker.+- Unknown effects, modes, or triggers and invalid numeric/order fields fail validation; no fallback effect is substituted.++----## Page Transitions+## 3. Page Transitions```bash# Pick a different effect@@ -88,7 +95,9 @@ Flags:**Hard rule — no silent downgrade**: an unknown transition effect or invalid/non-finite duration fails export. It is never replaced by `fade`. Recorded narration keeps the resolved visual transition; `-t none --recorded-narration ...` writes narration-driven advance timing without restoring a visual effect.-## Per-Element Animations+---++## 4. Per-Element AnimationsOff by default — enable deck-wide with `-a auto` (or another effect). Once enabled, three Start modes are available — these mirror PowerPoint's animation-pane "Start" dropdown:@@ -119,9 +128,11 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -a auto --animation-t22 single effects: `appear`, `fade`, `fly`, `cut`, `zoom`, `wipe`, `split`, `blinds`, `checkerboard`, `dissolve`, `random_bars`, `peek`, `wheel`, `box`, `circle`, `diamond`, `plus`, `strips`, `wedge`, `stretch`, `expand`, `swivel`. Plus three auto-vary modes:+These names preserve the established filter / `presetID` / `presetSubtype` tuples documented in [`pptx-animations.md`](../scripts/docs/pptx-animations.md#3-compatibility-contract). `cut` is a legacy public key; compatibility promises its existing tuple, not a semantic interpretation inferred from an external preset-id table.+- `auto` (recommended when enabling) — map effect from the group's SVG id. Information-dense elements get a single stable effect: `chart` / `table` / `legend` / `timeline` / `track` → `wipe`; `card-*` / `pillar-*` / `item-*` / `step-*` / `stage-*` / `tier-*` / `principle-*` → `fly`; `title` / `chapter-*` / `section-*` / `cover-*` / `tagline` / `subtitle` → `fade`; `takeaway` / `callout` / `quote` / `source` / `conclusion` / `note` → `fade`. Image-like ids `hero` / `figure-*` / `image` / `img-*` / `kpi` instead cycle a richer visual pool (`zoom` / `dissolve` / `circle` / `box` / `diamond` / `wheel`) so multiple images vary across the deck. Unmatched ids cycle through `fade` / `wipe` / `fly` / `zoom`.- `mixed` (legacy) — deterministic. The first animated group on each slide uses `fade`; later groups cycle through a 16-effect pool (`blinds` / `checkerboard` / `dissolve` / `fly` / `cut` / `random_bars` / `box` / `split` / `strips` / `wedge` / `wheel` / `wipe` / `expand` / `fade` / `swivel` / `zoom`) across the deck. Kept for backward compatibility.-- `random` — samples from the legacy 16-effect pool.+- `random` — samples from the legacy 16-effect pool. Resolution is seeded from the effective deck input, so the same input produces the same choices; `--conversion-trace` records every resolved effect when diagnostics are enabled.`appear` is excluded from every variation pool because it has no visible motion.@@ -135,13 +146,15 @@ Flags:> Note: `--recorded-narration` rejects `on-click`; use `after-previous` or `with-previous` for video-ready narrated decks.-## Anchor Logic — Top-Level `<g id="...">`+---++## 5. Anchor Logic — Top-Level `<g id="...">`-Per-element animations are anchored on **top-level `<g id="...">` content groups** in the SVG (e.g. `<g id="cover-title">`, `<g id="card-1">`). One group = one click reveal.+Per-element animations are anchored on **top-level `<g id="...">` content groups** in the SVG (e.g. `<g id="cover-title">`, `<g id="card-1">`). One group produces one animation-pane entrance row; whether that row needs a click depends on the selected Start mode.Aim for **3–8 content groups per slide**. This is also the granularity PowerPoint uses for group-select / group-move, so it improves editing ergonomics regardless of animation.-**Chrome groups skip the cascade automatically.** Top-level groups that look like page chrome (background, header/footer, decorations, watermark, page number, nav, logo, dividing rule) are excluded from the click sequence and appear together with the slide. Detection is done on the `id`: after splitting on `-` and `_`, if any token matches `background` / `bg` / `decoration` / `decorations` / `decor` / `header` / `footer` / `chrome` / `watermark` / `pagenumber` / `pagenum` / `nav` / `logo` / `rule`, the group is treated as chrome. Examples that auto-skip: `<g id="background">`, `<g id="bg-texture">`, `<g id="cover-footer">`, `<g id="p03-header">`, `<g id="bottom-decor">`, `<g id="watermark">`, `<g id="nav">`, `<g id="logo-area">`, `<g id="column-rule">`. Examples that still animate: `<g id="card-1">`, `<g id="cover-title">`, `<g id="step-discover">`, `<g id="timeline-track">`. Don't strip the `<g>` wrapper to avoid animation — keep it (PowerPoint group-select needs it) and just name it appropriately.+**Chrome groups skip the cascade automatically.** Explicit SVG role and placeholder semantics are authoritative. A group with `data-pptx-layer` or an explicit static role/placeholder marker can never animate. For marker-free legacy SVGs only, top-level groups whose id tokens look like page chrome (background, header/footer, decorations, watermark, page number, nav, logo, dividing rule) are excluded and appear with the slide. An explicit `animations.json` group entry may override this id-name heuristic, but never an explicit structural marker. Examples that auto-skip by legacy id: `<g id="background">`, `<g id="bg-texture">`, `<g id="cover-footer">`, `<g id="p03-header">`, `<g id="bottom-decor">`, `<g id="watermark">`, `<g id="nav">`, `<g id="logo-area">`, `<g id="column-rule">`. Examples that still animate: `<g id="card-1">`, `<g id="cover-title">`, `<g id="step-discover">`, `<g id="timeline-track">`. Do not strip the `<g>` wrapper to avoid animation — keep it for PowerPoint group selection and use `effect: none` when the content should remain static.**Fallback for flat SVGs** (no top-level `<g>` wrappers, only raw `<rect>` / `<text>` / `<path>` at the root):@@ -150,14 +163,28 @@ Aim for **3–8 content groups per slide**. This is also the granularity PowerPoExecutors should wrap logical sections in `<g id>` regardless of whether you plan to animate. The Executor reference (`skills/ppt-master/references/shared-standards.md`) requires it.-## Limitations+---++## 6. Validation and Read-Back++Animation configuration is strict. Export fails on an unknown effect, mode, or trigger; a boolean or non-finite duration/delay/stagger; a non-positive duration; a negative delay/stagger; a non-positive or non-integer order; a missing slide/group reference; or any attempt to animate a structural layer. These errors never downgrade to another effect or silently omit a requested target.++Generated export reads each slide's timing tree back and checks row count/order, trigger, shape target, resolved effect tuple, duration, and timeline offset. Package validation then checks root timing placement, unique and valid `p:cTn` ids, and every `p:spTgt` reference. The writer does not emit `p:bldP` for groups or pictures. Direct-PPTX preserve mode tolerates unchanged legacy group/picture `p:bldP` rows from earlier PPT Master exports; new generated packages remain strict.++Narration injection merges audio timing into an existing direct `p:sld/p:timing` DOM and preserves entrance rows. A source timing tree nested in `mc:AlternateContent` or another non-root container fails safely instead of being rewritten or duplicated. Direct-PPTX routes fingerprint source object-animation timing before and after their allowed edits, then run structural package validation; they do not author or normalize animation effects.++---++## 7. Limitations- **Native DrawingML output only.** Page transitions and per-element animations are authored on the PPTX produced by the project converter from `svg_output/`. `svg_final/` remains a static SVG visual preview, not an animated or alternate PPTX route.-- **Office version drift on element animations.** Effects use the `<p:animEffect filter=...>` path (vs. `presetID` lookup tables) to stay stable across Office versions. Most filters render identically in PowerPoint 2016+; older Office may downgrade some filters to plain Appear.+- **PowerPoint OOXML scope.** Effects preserve their established filter / `presetID` / `presetSubtype` tuples and are validated against the serialized PowerPoint package. Rendering in Keynote, LibreOffice, WPS, or other applications is outside the unconditional compatibility guarantee.- **Manual SVG shape conversion is unsupported.** Inserting an `svg_final/` page as an SVG picture does not establish element animation anchors; use the native PPTX when editable animated shapes are required.- **Source extension preservation.** Direct-PPTX routes preserve unknown transition `AlternateContent` when configured to keep the source. When advance timing changes, Choice and Fallback receive the same `advClick` / `advTm` values.-## Quick Reference+---++## 8. Quick Reference| Goal | Command ||---|---|@@ -166,13 +193,14 @@ Executors should wrap logical sections in `<g id>` regardless of whether you pla| Slower transition | `--transition-duration 0.8` || Auto-play | `--auto-advance 5` || Disable element animation | `-a none` |-| Switch to on-click trigger | `--animation-trigger on-click` |+| Switch to on-click trigger | `-a auto --animation-trigger on-click` || Use a single effect instead of auto | `--animation fade` |-| All groups animate together | `--animation-trigger with-previous` |-| Slower per-element reveal | `--animation-duration 0.5` |-| Wider gap in after-previous | `--animation-stagger 0.7` |+| All groups animate together | `-a auto --animation-trigger with-previous` |+| Slower per-element reveal | `-a auto --animation-duration 0.5` |+| Wider gap in after-previous | `-a auto --animation-stagger 0.7` |See also:- [`scripts/docs/svg-pipeline.md`](../scripts/docs/svg-pipeline.md) for the full `svg_to_pptx.py` reference.- [`pptx-transitions.md`](../scripts/docs/pptx-transitions.md) for the shared OOXML writer, MCE preservation, and read-back contract.+- [`pptx-animations.md`](../scripts/docs/pptx-animations.md) for the exact effect tuples, timing-tree rules, and animation package validator.diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex 75ee5e78..663ecfb7 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -46,7 +46,8 @@ python3 scripts/update_repo.py| Conversion | `source_to_md.py`, `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`, `pptx_intake.py`, `pptx_to_svg.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`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) || SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |-| PPTX transitions | `pptx_transitions.py`, `pptx_animations.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |+| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |+| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) || Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) || Image tools | `image_gen.py`, `latex_render.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.pyindex cd7ee2c5..275022ab 100644--- a/skills/ppt-master/scripts/animation_config.py+++ b/skills/ppt-master/scripts/animation_config.py@@ -33,6 +33,7 @@ from svg_to_pptx.animation_config import ( # noqa: E402build_group_listing,load_animation_config,validate_animation_config,+ validate_animation_config_errors,validate_transition_config,write_scaffold,)@@ -112,15 +113,28 @@ def main(argv: list[str] | None = None) -> int:if not config:print('No animations.json found; default animation policy will be used.')return 0- errors = validate_transition_config(config)+ errors = list(dict.fromkeys(+ validate_transition_config(config)+ + validate_animation_config_errors(config)+ ))if errors:for error in errors:print(f'Error: {error}', file=sys.stderr)return 1- warnings = validate_animation_config(project_path, config)- if warnings:- for warning in warnings:- print(f'Warning: {warning}', file=sys.stderr)+ reference_messages = validate_animation_config(project_path, config)+ reference_warnings = [+ message for message in reference_messages+ if ' has no id and cannot be customized in animations.json' in message+ ]+ reference_errors = [+ message for message in reference_messages+ if message not in reference_warnings+ ]+ for warning in reference_warnings:+ print(f'Warning: {warning}', file=sys.stderr)+ if reference_errors:+ for error in reference_errors:+ print(f'Error: {error}', file=sys.stderr)return 1print('Animation config validated successfully.')return 0diff --git a/skills/ppt-master/scripts/docs/pptx-animations.md b/skills/ppt-master/scripts/docs/pptx-animations.mdnew file mode 100644index 00000000..808b48d5--- /dev/null+++ b/skills/ppt-master/scripts/docs/pptx-animations.md@@ -0,0 +1,194 @@+# PPTX Animation Core++The shared animation core owns the entrance-effect vocabulary, trigger+semantics, OOXML timing writer, semantic read-back, and package validation for+PowerPoint OOXML. Per-element animation remains opt-in: generated PPTX export+defaults to `none`, exactly as before this validation upgrade.++## 1. Ownership++| Concern | Owner |+|---|---|+| Effect registry, timing writer, and read-back | `scripts/pptx_animations.py` |+| Sidecar parsing and SVG target discovery | `svg_to_pptx/animation_config.py` |+| SVG group-to-shape mapping | `svg_to_pptx/drawingml/converter.py` |+| Generated PPTX resolution and validation | `svg_to_pptx/pptx_package/builder.py` |+| Narration timing merge | `svg_to_pptx/pptx_package/narration.py` |+| Public authoring contract | `references/animations.md` |+| Customization workflow | `workflows/customize-animations.md` |++**Hard rule**: only the generated SVG-to-PPTX route writes object entrance+animations. Direct-PPTX routes preserve source animations and run structural+package validation; they do not resolve or author animation effects.++---++## 2. Domain Model++One resolved animation-pane row contains these fields:++| Field | Meaning |+|---|---|+| Target | Positive PowerPoint shape id written to `p:spTgt@spid` |+| Effect | One exact registry tuple: filter, `presetID`, and `presetSubtype` |+| Trigger | `on-click`, `with-previous`, or `after-previous` |+| Duration | Finite positive schedule duration; filter effects serialize it as behavior duration |+| Delay | Finite non-negative offset used by `after-previous` |+| Order | Positive integer sidecar order; ties retain stable SVG order |++Modes resolve before XML writing:++| Mode | Resolution |+|---|---|+| `auto` | Deterministic semantic mapping from the SVG group id |+| `mixed` | Deterministic legacy cycle |+| `random` | Stable seeded choice from the legacy pool |+| `none` | No entrance sequence |++The same effective input produces the same `random` choices. When enabled,+`--conversion-trace` records each resolved row and effect, so a generated deck+can be audited without replaying the resolver.++---++## 3. Compatibility Contract++The registry preserves these established 22 tuples exactly:++| Key | `p:animEffect@filter` | `presetID` | `presetSubtype` |+|---|---|---:|---:|+| `appear` | none | 1 | 0 |+| `fade` | `fade` | 10 | 0 |+| `fly` | `slide(fromBottom)` | 2 | 4 |+| `cut` | `slide(fromLeft)` | 42 | 8 |+| `zoom` | `image` | 23 | 0 |+| `wipe` | `wipe(left)` | 22 | 1 |+| `split` | `barn(inVertical)` | 16 | 21 |+| `blinds` | `blinds(horizontal)` | 3 | 10 |+| `checkerboard` | `checkerboard(across)` | 5 | 6 |+| `dissolve` | `dissolve` | 9 | 0 |+| `random_bars` | `randombar(horizontal)` | 14 | 10 |+| `peek` | `wipe(down)` | 12 | 4 |+| `wheel` | `wheel(4)` | 21 | 0 |+| `box` | `box(in)` | 4 | 0 |+| `circle` | `circle(in)` | 6 | 0 |+| `diamond` | `diamond(in)` | 8 | 0 |+| `plus` | `plus(in)` | 13 | 0 |+| `strips` | `strips(downRight)` | 18 | 12 |+| `wedge` | `wedge` | 20 | 0 |+| `stretch` | `stretch(across)` | 17 | 0 |+| `expand` | `stretch(across)` | 50 | 0 |+| `swivel` | `wheel(1)` | 19 | 0 |++`cut` is a legacy public key. Compatibility promises the tuple above; it does+not infer a different semantic name from external preset-id tables.++**Hard rule — no downgrade**:++- Keep the 22 established tuples byte-for-byte equivalent in meaning.+- Reject an unknown effect, mode, or trigger; never substitute another value.+- Reject booleans and non-finite, out-of-range, or invalidly ordered values.+- Reject a missing slide, missing group, or structural-layer target.+- Keep the generated-route default at `none`; validation does not opt a deck in.++---++## 4. Target Resolution++Generated object animation targets top-level SVG content groups. Explicit SVG+semantics are authoritative; the group-id chrome heuristic is only a fallback+for marker-free legacy SVGs.++| Target state | Behavior |+|---|---|+| Ordinary content group | Animatable |+| Legacy chrome-like id | Skipped unless explicitly named in `animations.json` |+| Explicit sidecar group override | May override only the legacy chrome-name heuristic |+| `data-pptx-layer` or explicit static role/placeholder | Structural and never animatable |++An explicit sidecar entry cannot turn a Master/Layout/Slide structural layer or+an explicitly marked static page-frame role/placeholder into an animation+target. This boundary preserves PPTX structure even when a legacy id resembles+content.++---++## 5. OOXML Rules++The writer emits one root-level `p:timing` after `p:transition` and before+`p:extLst`. Its animation tree contains a `tmRoot`, one `mainSeq`, unique+`p:cTn@id` values, and `p:spTgt` references to shapes on the same slide.++Trigger mapping:++| Public trigger | Entrance `p:cTn@nodeType` |+|---|---|+| `on-click` | `clickEffect` |+| `with-previous` | `withEffect` |+| `after-previous` | `afterEffect` |++The writer does not emit `p:bldP` for grouped content or pictures. Microsoft+defines `p:bldP@spid` for a text-bearing `p:sp`; using it for `p:grpSp` or+`p:pic` creates an invalid build reference. Package validation still accepts a+valid source `p:bldP` that targets a text-bearing shape.++Direct-PPTX preserve mode also tolerates an unchanged legacy `p:bldP` that+targets an existing group/picture. Earlier PPT Master exports wrote this form;+the direct routes fingerprint and preserve it instead of blocking those decks.+New generated output never writes it, and generated-package validation remains+strict.++`appear` is the visibility-flip exception: its `p:set` behavior is always 1ms.+The configured positive duration remains the row's scheduling span used when+computing the next `after-previous` offset; read-back verifies the 1ms behavior+and the resulting timeline offset separately.++---++## 6. Validation and Read-Back++Generated export reads every slide back before packaging and compares each+requested row with the serialized result:++- row count and row order;+- trigger and shape target;+- resolved effect key, filter, `presetID`, and `presetSubtype`;+- serialized behavior duration and computed timeline offset (`appear` uses the+ 1ms exception above).++After packaging, validation scans every slide part for root timing placement,+duplicate or malformed `p:cTn` ids, missing `p:spTgt` shapes, invalid build+targets, and unsupported generated effect tuples. A mismatch fails export+before the requested output file replaces an existing deck.++Narration injection parses and merges the slide DOM. It adds audio timing under+the existing `tmRoot` child list, allocates fresh time-node ids, and preserves+the object entrance sequence. It does not replace an existing `p:timing` tree.+The merge accepts only a direct `p:sld/p:timing` source tree; a timing tree+wrapped in `mc:AlternateContent` or another non-root container fails safely+instead of being rewritten or duplicated.++Direct-PPTX routes run the structural package validator with generated-effect+enforcement disabled. This permits preservation of source/extension effects and+legacy group build rows while still rejecting corrupt timing IDs or missing+targets. Template fill and native enhancement fingerprint the source+object-animation tree before and after their allowed edits; any semantic change+fails. These routes have no object-animation write ownership.++---++## 7. Compatibility Scope++The compatibility contract covers PowerPoint OOXML and PowerPoint read-back.+Other presentation applications may interpret timing trees or filter values+differently; the exporter does not make an unconditional Keynote guarantee.++Official references:++- [Microsoft animation-filter implementation notes](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/a96dab70-2e72-4319-928d-0eb4b275ce58)+- [Microsoft `p:bldP` implementation restrictions](https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/40d17b6d-30c0-4c10-b042-b2597824a820)+- [Open XML SDK time-node values](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.presentation.timenodevalues?view=openxml-3.0.1)+- [Open XML SDK shape target](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.presentation.shapetarget?view=openxml-3.0.1)++See [`pptx-transitions.md`](./pptx-transitions.md) for the symmetric page-motion+core, MCE handling, and slide-advance contract.diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex a0a3ba14..455daf88 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -86,6 +86,7 @@ Behavior:- Narration text is read strictly from the matching `notes/*.md` file; the script only skips Markdown heading lines (`# ...`) and does not summarize, rewrite, or filter delivery notes- `--recorded-narration audio` prepares PowerPoint's "recorded timings and narrations": every slide must have matching `m4a` / `mp3` / `wav` audio, `ffprobe` must read every duration, and `--animation-trigger on-click` is rejected- `--recorded-narration audio` keeps speaker notes, embeds each matching audio file, and writes slide auto-advance timings from audio duration+ - Narration timing is merged into the existing slide timing DOM; object entrance rows and the resolved page transition are preserved rather than regenerated- `--narration-audio-dir audio` is the lower-level embedding path: it embeds whatever files match and allows partial audio coverage- Either narration flag names the default-flow export `<project_name>_<timestamp>_narrated.pptx`, telling it apart from silent exports in the same directory- This is intended for direct PowerPoint video export with "Use recorded timings and narrations"@@ -93,6 +94,7 @@ Behavior:- Voice choices can be listed with `python3 scripts/notes_to_audio.py --list-common-voices`, `python3 scripts/notes_to_audio.py --list-voices --locale zh-CN`, or provider-specific `--provider <name> --list-voices`- Page transitions are controlled by `-t/--transition`; per-element entrance animations are controlled by `-a/--animation`- Per-element animation applies to top-level SVG `<g id="...">` groups in z-order; aim for 3–8 content groups per slide. Existing layer/slide-number placeholder semantics are read before minimal structural roles; exact id tokens remain a fallback only when all explicit markers are absent+- An explicit `animations.json` group entry may override the marker-free legacy chrome-name heuristic. It cannot override `data-pptx-layer` or an explicit static role/placeholder marker- Start mode is set by `--animation-trigger`, mirroring PowerPoint's Start dropdown: `after-previous` (default, cascade with `--animation-stagger` spacing on slide entry), `on-click` (presenter-paced), `with-previous` (all together on slide entry)- `on-click` is for live presentations only; recorded narration rejects it because the tool does not generate object-level click timings- Flat SVG roots without top-level groups fall back to at most 8 visible primitives; beyond that, animation is skipped on the slide@@ -102,9 +104,13 @@ Behavior:ids (hero/figure-/image/img-/kpi) cycle through a richer pool(zoom/dissolve/circle/box/diamond/wheel), while unmatched ids cycle throughfade/wipe/fly/zoom.-- `mixed` (legacy) is deterministic: the first animated group on each slide uses `fade`, then later groups cycle through a larger 16-effect pool across the whole deck; `random` samples from that same legacy pool+- `mixed` (legacy) is deterministic: the first animated group on each slide uses `fade`, then later groups cycle through a larger 16-effect pool across the whole deck; `random` uses a stable seed from the effective deck input, and `--conversion-trace` records each resolved effect when enabled- `--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`+- Animation configuration is strict: unknown effects/modes/triggers, invalid finite/range/order values, missing slides/groups, and structural-layer targets fail export without fallback or silent omission+- Generated export reads every slide back and verifies animation row order, trigger, shape target, resolved effect tuple, duration, and offset. Package validation then checks timing placement, `p:cTn` ids, and `p:spTgt` references before publication+- The animation writer does not emit `p:bldP` for groups or pictures. Direct-PPTX routes preserve source object animation and perform structural package validation only; they do not author effects+- The full registry, OOXML rules, and compatibility boundary are documented in [`pptx-animations.md`](./pptx-animations.md)Dependency:diff --git a/skills/ppt-master/scripts/native_narration_pptx.py b/skills/ppt-master/scripts/native_narration_pptx.pyindex 78f846a2..914820e5 100644--- a/skills/ppt-master/scripts/native_narration_pptx.py+++ b/skills/ppt-master/scripts/native_narration_pptx.py@@ -42,6 +42,10 @@ if str(_SCRIPTS_DIR) not in sys.path:sys.path.insert(0, str(_SCRIPTS_DIR))from console_encoding import configure_utf8_stdio # noqa: E402+from pptx_animations import ( # noqa: E402+ object_animation_fingerprint,+ validate_pptx_animation_package,+)from pptx_transitions import ( # noqa: E402AdvanceUpdate,EnterUpdate,@@ -358,6 +362,7 @@ def _apply_audio(slide_xml_path = extract_dir / slide.part_nameslide_xml = slide_xml_path.read_text(encoding="utf-8")+ source_animation_fingerprint = object_animation_fingerprint(slide_xml)shape_id = next_shape_id(slide_xml)slide_xml = inject_narration(slide_xml,@@ -385,6 +390,10 @@ def _apply_audio(enter=enter,advance=advance,)+ if object_animation_fingerprint(slide_xml) != source_animation_fingerprint:+ raise RuntimeError(+ f"Slide {slide.index} object animations changed while adding narration"+ )slide_xml_path.write_text(slide_xml, encoding="utf-8")return timings_enabled and wrote_advance@@ -788,11 +797,22 @@ def apply_project(args: argparse.Namespace) -> int:):slide_xml_path = extract_dir / slide.part_nameslide_xml = slide_xml_path.read_text(encoding="utf-8")+ source_animation_fingerprint = object_animation_fingerprint(+ slide_xml+ )slide_xml, _uses_timings = apply_slide_motion_xml(slide_xml,enter=enter_update,advance=AdvanceUpdate(mode="preserve"),)+ if (+ object_animation_fingerprint(slide_xml)+ != source_animation_fingerprint+ ):+ raise RuntimeError(+ f"Slide {slide.index} object animations changed while "+ "updating the transition"+ )slide_xml_path.write_text(slide_xml,encoding="utf-8",@@ -818,6 +838,15 @@ def apply_project(args: argparse.Namespace) -> int:raise RuntimeError(f"PPTX transition package validation failed: {exc}") from exc+ try:+ validate_pptx_animation_package(+ candidate_path,+ require_supported_effects=False,+ )+ except ValueError as exc:+ raise RuntimeError(+ f"PPTX animation/timing package validation failed: {exc}"+ ) from exccandidate_path.replace(output_path)print(f"Output: {output_path}", file=sys.stderr)diff --git a/skills/ppt-master/scripts/pptx_animations.py b/skills/ppt-master/scripts/pptx_animations.pyindex c82d1144..8c1e02ed 100644--- a/skills/ppt-master/scripts/pptx_animations.py+++ b/skills/ppt-master/scripts/pptx_animations.py@@ -2,7 +2,7 @@"""PPT Master - PPTX Animation Module-Provides XML generation for slide transition effects and entrance animations.+Provides one strict entrance-animation registry plus OOXML read/write helpers.Supported transition effects:- fade: Fade in/out@@ -32,7 +32,13 @@ Animation modes used by the builder:larger curated visible pool (kept for backward compatibility).- 'random' — pick a random effect from the legacy pool per element-Dependencies: None (pure XML generation)+Generated animation rows are validated against their requested effect, target,+duration, order, and Start mode before a PPTX is published. Package validation+also checks timing-tree placement, time-node identifiers, and shape references.++See references/animations.md for the public workflow contract.++Dependencies: None (standard-library XML generation and validation)Usage:python3 scripts/pptx_animations.py --demo@@ -40,10 +46,25 @@ Usage:"""import argparse-from typing import Optional, Dict, Any+import hashlib+import math+import random+import re+import zipfile+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Mapping, Sequence+from xml.etree import ElementTree as ETfrom console_encoding import configure_utf8_stdio-from pptx_transitions import TRANSITIONS, create_transition_xml+from pptx_transitions import (+ MAX_OOXML_MILLISECONDS,+ MAX_OOXML_UNSIGNED_INT,+ PML_NS,+ TRANSITIONS,+ create_transition_xml,+ validate_seconds,+)configure_utf8_stdio()@@ -57,7 +78,7 @@ configure_utf8_stdio()# (see ECMA-376 §19.5.10 ST_TLAnimateEffectTransition / filter dictionary).# Effects with filter=None render as plain "Appear" (visibility flip only).#-ANIMATIONS: Dict[str, Dict[str, Any]] = {+ANIMATIONS: dict[str, dict[str, Any]] = {'appear': {'name': 'Appear', 'filter': None, 'presetID': 1, 'presetSubtype': 0},'fade': {'name': 'Fade', 'filter': 'fade', 'presetID': 10, 'presetSubtype': 0},'fly': {'name': 'Fly In', 'filter': 'slide(fromBottom)', 'presetID': 2, 'presetSubtype': 4},@@ -82,6 +103,178 @@ ANIMATIONS: Dict[str, Dict[str, Any]] = {'swivel': {'name': 'Swivel', 'filter': 'wheel(1)', 'presetID': 19, 'presetSubtype': 0},}+ANIMATION_MODES = ('auto', 'mixed', 'random')+ANIMATION_TRIGGERS = ('on-click', 'with-previous', 'after-previous')++_TRIGGER_NODE_TYPES = {+ 'on-click': 'clickEffect',+ 'with-previous': 'withEffect',+ 'after-previous': 'afterEffect',+}+_NODE_TYPE_TRIGGERS = {+ value: key for key, value in _TRIGGER_NODE_TYPES.items()+}+++@dataclass(frozen=True)+class AnimationTarget:+ """Resolved entrance-animation request for one PowerPoint shape."""++ shape_id: int+ delay_ms: int+ effect: str+ duration_ms: int+++@dataclass(frozen=True)+class AnimationRowSummary:+ """Read-back summary for one entrance row in the animation pane."""++ shape_id: int+ effect: str | None+ trigger: str+ duration_ms: int+ offset_ms: int+ preset_id: int+ preset_subtype: int+ filter_name: str | None+++@dataclass(frozen=True)+class AnimationSequenceSummary:+ """Read-back summary for the logical entrance sequence on one slide."""++ timing_count: int+ trigger: str | None+ rows: tuple[AnimationRowSummary, ...]+ audio_target_ids: tuple[int, ...]+++def _qn(namespace: str, tag: str) -> str:+ return f'{{{namespace}}}{tag}'+++def _local_name(tag: str) -> str:+ return tag.rsplit('}', 1)[-1]+++def normalize_animation_effect(+ effect: object,+ *,+ allow_none: bool = True,+ allow_modes: bool = True,+) -> str | None:+ """Return a supported effect/mode without silently substituting another."""+ if effect is None or effect == 'none':+ if allow_none:+ return None+ raise ValueError('animation effect is required')+ if not isinstance(effect, str):+ raise ValueError(f'animation effect must be a string: {effect!r}')+ if effect in ANIMATIONS:+ return effect+ if allow_modes and effect in ANIMATION_MODES:+ return effect+ valid = list(ANIMATIONS)+ if allow_modes:+ valid.extend(ANIMATION_MODES)+ if allow_none:+ valid.append('none')+ raise ValueError(+ f'unknown animation effect {effect!r}; valid effects: {", ".join(valid)}'+ )+++def normalize_animation_trigger(trigger: object) -> str:+ """Return a supported PowerPoint Start mode or raise a precise error."""+ if not isinstance(trigger, str):+ raise ValueError(f'animation trigger must be a string: {trigger!r}')+ if trigger not in ANIMATION_TRIGGERS:+ raise ValueError(+ f'unknown animation trigger {trigger!r}; valid triggers: '+ f'{", ".join(ANIMATION_TRIGGERS)}'+ )+ return trigger+++def _seconds_to_ms(value: object, field: str, *, allow_zero: bool) -> int:+ seconds = validate_seconds(value, field, allow_zero=allow_zero)+ raw_milliseconds = seconds * 1000+ if (+ not math.isfinite(raw_milliseconds)+ or raw_milliseconds > MAX_OOXML_MILLISECONDS+ ):+ raise ValueError(f'{field} exceeds the OOXML millisecond limit: {value!r}')+ milliseconds = int(raw_milliseconds)+ return milliseconds if allow_zero else max(1, milliseconds)+++def animation_seconds_to_milliseconds(+ value: object,+ field: str,+ *,+ allow_zero: bool,+) -> int:+ """Convert validated animation seconds to the OOXML millisecond range."""+ return _seconds_to_ms(value, field, allow_zero=allow_zero)+++def _positive_shape_id(value: object, field: str = 'animation shape_id') -> int:+ if isinstance(value, bool):+ raise ValueError(f'{field} must be a positive integer: {value!r}')+ if isinstance(value, int):+ shape_id = value+ elif isinstance(value, str) and re.fullmatch(r'[1-9]\d*', value):+ shape_id = int(value)+ else:+ raise ValueError(f'{field} must be a positive integer: {value!r}')+ if shape_id <= 0 or shape_id > MAX_OOXML_UNSIGNED_INT:+ raise ValueError(f'{field} must be a positive integer: {value!r}')+ return shape_id+++def _non_negative_milliseconds(value: object, field: str) -> int:+ if isinstance(value, bool):+ raise ValueError(f'{field} must be a non-negative integer: {value!r}')+ if isinstance(value, int):+ milliseconds = value+ elif isinstance(value, str) and re.fullmatch(r'\d+', value):+ milliseconds = int(value)+ else:+ raise ValueError(f'{field} must be a non-negative integer: {value!r}')+ if milliseconds < 0 or milliseconds > MAX_OOXML_MILLISECONDS:+ raise ValueError(+ f'{field} must be between 0 and {MAX_OOXML_MILLISECONDS}: {value!r}'+ )+ return milliseconds+++def _normalize_target(target: Sequence[object], default_duration_ms: int) -> AnimationTarget:+ if isinstance(target, (str, bytes)) or not isinstance(target, Sequence):+ raise ValueError(f'animation target must be a 3- or 4-item sequence: {target!r}')+ if len(target) not in (3, 4):+ raise ValueError(f'animation target must contain 3 or 4 items: {target!r}')+ shape_id = _positive_shape_id(target[0])+ delay_ms = _non_negative_milliseconds(target[1], 'animation target delay_ms')+ effect = normalize_animation_effect(+ target[2],+ allow_none=False,+ allow_modes=False,+ )+ duration_ms = default_duration_ms+ if len(target) == 4 and target[3] is not None:+ duration_ms = _seconds_to_ms(+ target[3],+ 'animation target duration',+ allow_zero=False,+ )+ return AnimationTarget(+ shape_id=shape_id,+ delay_ms=delay_ms,+ effect=effect,+ duration_ms=duration_ms,+ )+# Pool used by 'mixed' / 'random' modes. Excludes 'appear' because it has no# visible motion; mixed handles the first title-like element as fade separately._MIXED_POOL = [@@ -158,12 +351,23 @@ def create_timing_xml(Returns:A <p:timing> element string insertable into slide XML"""- if animation not in ANIMATIONS:- animation = 'fade'-+ animation = normalize_animation_effect(+ animation,+ allow_none=False,+ allow_modes=False,+ )+ shape_id = _positive_shape_id(shape_id)anim_info = ANIMATIONS[animation]- dur_ms = int(duration * 1000)- delay_ms = int(delay * 1000)+ dur_ms = _seconds_to_ms(+ duration,+ 'animation duration',+ allow_zero=False,+ )+ delay_ms = _seconds_to_ms(+ delay,+ 'animation delay',+ allow_zero=True,+ )# Generate different effect XML depending on animation typeif anim_info['filter'] is None:@@ -249,7 +453,19 @@ def _build_effect_xml(Appear uses a visibility set; motion/filter effects use animEffect directlyto avoid duplicate rows for the same shape in PowerPoint."""- anim_info = ANIMATIONS.get(animation, ANIMATIONS['fade'])+ animation = normalize_animation_effect(+ animation,+ allow_none=False,+ allow_modes=False,+ )+ shape_id = _positive_shape_id(shape_id)+ duration_ms = _non_negative_milliseconds(+ duration_ms,+ 'animation duration_ms',+ )+ if duration_ms == 0:+ raise ValueError('animation duration_ms must be greater than zero')+ anim_info = ANIMATIONS[animation]set_block = f'''<p:set><p:cBhvr><p:cTn id="{set_id}" dur="1" fill="hold">@@ -298,32 +514,35 @@ def create_sequence_timing_xml(A ``<p:timing>`` element string. Returns an empty string when``targets`` is empty."""+ trigger = normalize_animation_trigger(trigger)+ default_dur_ms = _seconds_to_ms(+ duration,+ 'animation duration',+ allow_zero=False,+ )+ if targets is None or isinstance(targets, (str, bytes)):+ raise ValueError('animation targets must be a sequence of target tuples')if not targets:return ''-- if trigger not in ('on-click', 'with-previous', 'after-previous'):- trigger = 'on-click'-- default_dur_ms = int(duration * 1000)+ normalized_targets = [+ _normalize_target(target, default_dur_ms)+ for target in targets+ ]+ shape_ids = [target.shape_id for target in normalized_targets]+ if len(shape_ids) != len(set(shape_ids)):+ raise ValueError('animation targets must not contain duplicate shape ids')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# the click via delay="indefinite", innermost cTn owns the# clickEffect + animation children. Each click advances the seq.steps = []- for target in targets:- shape_id, _delay_ms, animation, item_dur_ms = _target_parts(target)+ for target in normalized_targets:+ shape_id = target.shape_id+ animation = target.effect+ item_dur_ms = target.duration_msanim_info = ANIMATIONS[animation]preset_id = anim_info.get('presetID', 1)preset_subtype = anim_info.get('presetSubtype', 0)@@ -343,7 +562,8 @@ def create_sequence_timing_xml(<p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:par>- <p:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr" presetSubtype="{preset_subtype}" fill="hold" nodeType="clickEffect">+ <p:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr"+ presetSubtype="{preset_subtype}" fill="hold" nodeType="clickEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>{effect_xml}@@ -375,8 +595,11 @@ def create_sequence_timing_xml(next_id += 1elapsed_ms = 0prev_duration_ms = 0- for i, target in enumerate(targets):- shape_id, delay_ms, animation, item_dur_ms = _target_parts(target)+ for i, target in enumerate(normalized_targets):+ shape_id = target.shape_id+ delay_ms = target.delay_ms+ animation = target.effect+ item_dur_ms = target.duration_msanim_info = ANIMATIONS[animation]preset_id = anim_info.get('presetID', 1)preset_subtype = anim_info.get('presetSubtype', 0)@@ -388,7 +611,8 @@ def create_sequence_timing_xml(next_id += 3effect_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:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr"+ presetSubtype="{preset_subtype}" fill="hold" nodeType="withEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>{effect_xml}@@ -400,6 +624,11 @@ def create_sequence_timing_xml(elapsed_ms = int(delay_ms)else:elapsed_ms += prev_duration_ms + int(delay_ms)+ if elapsed_ms > MAX_OOXML_MILLISECONDS:+ raise ValueError(+ 'animation sequence offset exceeds the OOXML '+ f'millisecond limit at target {i + 1}: {elapsed_ms}'+ )wrapper_id = next_idleaf_id = next_id + 1set_id = next_id + 2@@ -411,7 +640,8 @@ def create_sequence_timing_xml(<p:stCondLst><p:cond delay="{elapsed_ms}"/></p:stCondLst><p:childTnLst><p:par>- <p:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr" presetSubtype="{preset_subtype}" fill="hold" nodeType="afterEffect">+ <p:cTn id="{leaf_id}" presetID="{preset_id}" presetClass="entr"+ presetSubtype="{preset_subtype}" fill="hold" nodeType="afterEffect"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>{effect_xml}@@ -454,9 +684,6 @@ def create_sequence_timing_xml(</p:cTn></p:par>'''- bld_list = '\n '.join(- f'<p:bldP spid="{target[0]}" grpId="0"/>' for target in targets- )return f''' <p:timing><p:tnLst><p:par>@@ -475,9 +702,6 @@ def create_sequence_timing_xml(</p:cTn></p:par></p:tnLst>- <p:bldLst>- {bld_list}- </p:bldLst></p:timing>'''@@ -486,6 +710,8 @@ def pick_animation_effect(idx: int,offset: int = 0,group_id: str | None = None,+ *,+ rng: random.Random | None = None,) -> str:"""Resolve a per-element effect name from a mode string.@@ -502,8 +728,19 @@ def pick_animation_effect(across slides). Kept for backward compatibility with existing CLI flagsand animations.json sidecars.- 'random' (legacy): uniform random choice from ``_MIXED_POOL``.- - Unknown mode falls back to 'fade'.+ Unknown modes fail explicitly; no effect is silently substituted."""+ mode = normalize_animation_effect(+ mode,+ allow_none=False,+ allow_modes=True,+ )+ if isinstance(idx, bool) or not isinstance(idx, int) or idx < 0:+ raise ValueError(f'animation index must be a non-negative integer: {idx!r}')+ if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:+ raise ValueError(+ f'animation offset must be a non-negative integer: {offset!r}'+ )if mode in ANIMATIONS:return modeif mode == 'auto':@@ -516,9 +753,691 @@ def pick_animation_effect(return 'fade'return _MIXED_POOL[(idx - 1 + offset) % len(_MIXED_POOL)]if mode == 'random':- import random- return random.choice(_MIXED_POOL)- return 'fade'+ chooser = rng if rng is not None else random+ return chooser.choice(_MIXED_POOL)+ raise AssertionError(f'unhandled animation mode: {mode}')+++def _int_attribute(+ element: ET.Element,+ name: str,+ label: str,+ errors: list[str],+ *,+ minimum: int = 0,+ maximum: int | None = None,+) -> int | None:+ value = element.get(name)+ if value is None or not re.fullmatch(r'\d+', value):+ errors.append(f'{label} must be an integer; found {value!r}')+ return None+ number = int(value)+ if number < minimum:+ errors.append(f'{label} must be at least {minimum}; found {number}')+ return None+ if maximum is not None and number > maximum:+ errors.append(f'{label} must be at most {maximum}; found {number}')+ return None+ return number+++def _direct_conditions(ctn: ET.Element) -> list[ET.Element]:+ condition_list = ctn.find(_qn(PML_NS, 'stCondLst'))+ if condition_list is None:+ return []+ return [+ child for child in list(condition_list)+ if child.tag == _qn(PML_NS, 'cond')+ ]+++def _shape_index(+ slide_root: ET.Element,+) -> tuple[dict[int, tuple[str, bool]], list[str]]:+ parent_map = {+ child: parent+ for parent in slide_root.iter()+ for child in list(parent)+ }+ index: dict[int, tuple[str, bool]] = {}+ errors: list[str] = []+ shape_tags = {'sp', 'grpSp', 'pic', 'graphicFrame', 'cxnSp', 'contentPart'}+ for non_visual in slide_root.iter(_qn(PML_NS, 'cNvPr')):+ shape_id = _int_attribute(+ non_visual,+ 'id',+ 'p:cNvPr@id',+ errors,+ minimum=1,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if shape_id is None:+ continue+ owner = parent_map.get(non_visual)+ while owner is not None and _local_name(owner.tag) not in shape_tags:+ owner = parent_map.get(owner)+ kind = _local_name(owner.tag) if owner is not None else 'unknown'+ has_text = bool(+ owner is not None+ and kind == 'sp'+ and any(+ _local_name(element.tag) == 't' and (element.text or '').strip()+ for element in owner.iter()+ )+ )+ if shape_id in index:+ errors.append(f'duplicate p:cNvPr@id {shape_id}')+ else:+ index[shape_id] = (kind, has_text)+ return index, errors+++def _row_shape_id(row: ET.Element, errors: list[str]) -> int | None:+ shape_ids: list[int] = []+ for target in row.iter(_qn(PML_NS, 'spTgt')):+ value = _int_attribute(+ target,+ 'spid',+ 'animation p:spTgt@spid',+ errors,+ minimum=1,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if value is not None:+ shape_ids.append(value)+ unique = sorted(set(shape_ids))+ if len(unique) != 1:+ errors.append(+ 'one entrance row must resolve to exactly one shape id; '+ f'found {unique or "none"}'+ )+ return None+ return unique[0]+++def _row_filter(row: ET.Element, errors: list[str]) -> str | None:+ effects = list(row.iter(_qn(PML_NS, 'animEffect')))+ if len(effects) > 1:+ errors.append(f'entrance row contains {len(effects)} p:animEffect nodes')+ if not effects:+ return None+ effect = effects[0]+ if effect.get('transition') != 'in':+ errors.append('entrance p:animEffect must set transition="in"')+ return effect.get('filter')+++def _resolve_row_effect(+ row: ET.Element,+ filter_name: str | None,+ errors: list[str],+) -> tuple[str | None, int | None, int | None]:+ preset_id = _int_attribute(+ row,+ 'presetID',+ 'entrance p:cTn@presetID',+ errors,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ preset_subtype = _int_attribute(+ row,+ 'presetSubtype',+ 'entrance p:cTn@presetSubtype',+ errors,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if preset_id is None or preset_subtype is None:+ return None, preset_id, preset_subtype+ matches = [+ key+ for key, info in ANIMATIONS.items()+ if int(info['presetID']) == preset_id+ and int(info['presetSubtype']) == preset_subtype+ and info['filter'] == filter_name+ ]+ if len(matches) == 1:+ return matches[0], preset_id, preset_subtype+ return None, preset_id, preset_subtype+++def _behavior_duration_ms(+ row: ET.Element,+ filter_name: str | None,+ errors: list[str],+) -> int:+ if filter_name is None:+ behaviors = list(row.iter(_qn(PML_NS, 'set')))+ else:+ behaviors = list(row.iter(_qn(PML_NS, 'animEffect')))+ if len(behaviors) != 1:+ errors.append(+ 'entrance row must contain exactly one primary behavior; '+ f'found {len(behaviors)}'+ )+ return 0+ common_behavior = behaviors[0].find(_qn(PML_NS, 'cBhvr'))+ duration_node = (+ common_behavior.find(_qn(PML_NS, 'cTn'))+ if common_behavior is not None+ else None+ )+ if duration_node is None:+ errors.append('entrance behavior is missing p:cBhvr/p:cTn')+ return 0+ duration = _int_attribute(+ duration_node,+ 'dur',+ 'entrance behavior duration',+ errors,+ minimum=1,+ maximum=MAX_OOXML_MILLISECONDS,+ )+ return duration or 0+++def _row_offset_ms(+ row: ET.Element,+ trigger: str,+ parent_map: Mapping[ET.Element, ET.Element],+ errors: list[str],+) -> int:+ leaf_conditions = _direct_conditions(row)+ if len(leaf_conditions) != 1 or leaf_conditions[0].get('delay') != '0':+ errors.append('entrance row must have one leaf start condition with delay="0"')++ current = parent_map.get(row)+ saw_indefinite = False+ saw_main_begin = False+ numeric_offset: int | None = None+ while current is not None:+ if current.tag == _qn(PML_NS, 'cTn'):+ conditions = _direct_conditions(current)+ if any(condition.get('delay') == 'indefinite' for condition in conditions):+ saw_indefinite = True+ if any(+ condition.get('evt') == 'onBegin'+ and condition.get('delay') == '0'+ and any(+ target.get('val') == '2'+ for target in condition.iter(_qn(PML_NS, 'tn'))+ )+ for condition in conditions+ ):+ saw_main_begin = True+ if trigger in {'with-previous', 'after-previous'}:+ numeric = [+ condition.get('delay')+ for condition in conditions+ if condition.get('evt') is None+ and re.fullmatch(r'\d+', condition.get('delay') or '')+ ]+ if numeric and numeric_offset is None:+ numeric_offset = int(numeric[0])+ if numeric_offset > MAX_OOXML_MILLISECONDS:+ errors.append(+ 'animation row offset exceeds the OOXML '+ f'millisecond limit: {numeric_offset}'+ )+ current = parent_map.get(current)++ if trigger == 'on-click' and not saw_indefinite:+ errors.append('on-click entrance row is missing an indefinite click wrapper')+ if trigger in {'with-previous', 'after-previous'} and not (+ saw_indefinite and saw_main_begin+ ):+ errors.append(f'{trigger} sequence is missing the slide-entry onBegin anchor')+ if trigger == 'after-previous' and numeric_offset is None:+ errors.append('after-previous entrance row is missing its numeric offset wrapper')+ if trigger == 'after-previous':+ return numeric_offset or 0+ return 0+++def _animation_rows(+ slide_root: ET.Element,+ errors: list[str],+) -> list[AnimationRowSummary]:+ parent_map = {+ child: parent+ for parent in slide_root.iter()+ for child in list(parent)+ }+ rows: list[AnimationRowSummary] = []+ for row in slide_root.iter(_qn(PML_NS, 'cTn')):+ if row.get('presetClass') != 'entr':+ continue+ node_type = row.get('nodeType')+ trigger = _NODE_TYPE_TRIGGERS.get(node_type or '')+ if trigger is None:+ errors.append(+ f'unsupported entrance nodeType {node_type!r}; expected '+ f'{", ".join(_NODE_TYPE_TRIGGERS)}'+ )+ continue+ shape_id = _row_shape_id(row, errors)+ filter_name = _row_filter(row, errors)+ effect, preset_id, preset_subtype = _resolve_row_effect(+ row,+ filter_name,+ errors,+ )+ duration_ms = _behavior_duration_ms(row, filter_name, errors)+ offset_ms = _row_offset_ms(row, trigger, parent_map, errors)+ if shape_id is None or preset_id is None or preset_subtype is None:+ continue+ rows.append(+ AnimationRowSummary(+ shape_id=shape_id,+ effect=effect,+ trigger=trigger,+ duration_ms=duration_ms,+ offset_ms=offset_ms,+ preset_id=preset_id,+ preset_subtype=preset_subtype,+ filter_name=filter_name,+ )+ )+ return rows+++def validate_slide_animation_structure(+ slide_root: ET.Element,+ *,+ require_supported_effects: bool = False,+) -> list[str]:+ """Return root timing, target, and generated-entrance structure errors."""+ errors: list[str] = []+ if slide_root.tag != _qn(PML_NS, 'sld'):+ return ['animation validation requires a PresentationML p:sld root']++ direct_timings = [+ child for child in list(slide_root)+ if child.tag == _qn(PML_NS, 'timing')+ ]+ all_timings = list(slide_root.iter(_qn(PML_NS, 'timing')))+ nested_count = len(all_timings) - len(direct_timings)+ if nested_count:+ errors.append(+ f'slide contains {nested_count} nested p:timing element(s); '+ 'timing must be a direct child of p:sld'+ )+ if len(direct_timings) > 1:+ errors.append(+ f'slide has {len(direct_timings)} root p:timing elements; expected at most 1'+ )+ if not direct_timings:+ return errors++ timing = direct_timings[0]+ root_children = list(slide_root)+ timing_index = root_children.index(timing)+ for required_before in ('cSld', 'clrMapOvr', 'transition'):+ sibling = next(+ (+ child for child in root_children+ if child.tag == _qn(PML_NS, required_before)+ ),+ None,+ )+ if sibling is not None and root_children.index(sibling) > timing_index:+ errors.append(f'p:{required_before} must precede p:timing')+ extension_list = next(+ (+ child for child in root_children+ if child.tag == _qn(PML_NS, 'extLst')+ ),+ None,+ )+ if extension_list is not None and root_children.index(extension_list) < timing_index:+ errors.append('root p:extLst must follow p:timing')++ timing_children = list(timing)+ timing_name_order = [_local_name(child.tag) for child in timing_children]+ if 'bldLst' in timing_name_order and 'tnLst' in timing_name_order:+ if timing_name_order.index('bldLst') < timing_name_order.index('tnLst'):+ errors.append('p:tnLst must precede p:bldLst')++ ctn_ids: list[int] = []+ for ctn in timing.iter(_qn(PML_NS, 'cTn')):+ value = _int_attribute(+ ctn,+ 'id',+ 'p:cTn@id',+ errors,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if value is not None:+ ctn_ids.append(value)+ duplicates = sorted(+ value for value in set(ctn_ids) if ctn_ids.count(value) > 1+ )+ if duplicates:+ errors.append(+ 'duplicate p:cTn@id values: ' + ', '.join(map(str, duplicates))+ )++ roots = [+ node for node in timing.iter(_qn(PML_NS, 'cTn'))+ if node.get('nodeType') == 'tmRoot'+ ]+ if len(roots) != 1:+ errors.append(+ f'p:timing must contain exactly one tmRoot time node; found {len(roots)}'+ )++ shape_index, shape_errors = _shape_index(slide_root)+ errors.extend(shape_errors)+ for target in timing.iter(_qn(PML_NS, 'spTgt')):+ shape_id = _int_attribute(+ target,+ 'spid',+ 'p:spTgt@spid',+ errors,+ minimum=1,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if shape_id is not None and shape_id not in shape_index:+ errors.append(f'p:spTgt references missing shape id {shape_id}')++ build_keys: list[tuple[int, int]] = []+ for build in timing.iter(_qn(PML_NS, 'bldP')):+ shape_id = _int_attribute(+ build,+ 'spid',+ 'p:bldP@spid',+ errors,+ minimum=1,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ group_id = _int_attribute(+ build,+ 'grpId',+ 'p:bldP@grpId',+ errors,+ maximum=MAX_OOXML_UNSIGNED_INT,+ )+ if shape_id is None or group_id is None:+ continue+ build_keys.append((shape_id, group_id))+ kind, has_text = shape_index.get(shape_id, ('missing', False))+ if kind == 'missing':+ errors.append(f'p:bldP references missing shape id {shape_id}')+ elif require_supported_effects and (kind != 'sp' or not has_text):+ errors.append(+ f'p:bldP shape id {shape_id} must reference a text-bearing p:sp; '+ f'found {kind}'+ )+ if len(build_keys) != len(set(build_keys)):+ errors.append('p:bldP (spid, grpId) pairs must be unique')++ entrance_nodes = [+ node for node in timing.iter(_qn(PML_NS, 'cTn'))+ if node.get('presetClass') == 'entr'+ ]+ if entrance_nodes and require_supported_effects:+ main_sequences = [+ node for node in timing.iter(_qn(PML_NS, 'cTn'))+ if node.get('nodeType') == 'mainSeq'+ ]+ if len(main_sequences) != 1:+ errors.append(+ 'slides with entrance rows must contain exactly one mainSeq time node'+ )+ if require_supported_effects:+ rows = _animation_rows(slide_root, errors)+ if not rows and entrance_nodes:+ errors.append('generated entrance rows could not be read back')+ else:+ rows = []+ if rows:+ triggers = {row.trigger for row in rows}+ if len(triggers) != 1:+ errors.append(+ 'one generated entrance sequence must use one Start mode; found '+ + ', '.join(sorted(triggers))+ )+ row_shape_ids = [row.shape_id for row in rows]+ if len(row_shape_ids) != len(set(row_shape_ids)):+ errors.append('generated entrance sequence repeats a shape target')+ for row in rows:+ if row.effect is None:+ errors.append(+ 'unsupported entrance effect tuple for shape '+ f'{row.shape_id}: presetID={row.preset_id}, '+ f'presetSubtype={row.preset_subtype}, '+ f'filter={row.filter_name!r}'+ )+ return errors+++def read_slide_animation_sequence(+ slide_xml: str | bytes,+ *,+ require_supported_effects: bool = False,+) -> AnimationSequenceSummary:+ """Read and validate the logical entrance sequence from one slide XML."""+ data = slide_xml.encode('utf-8') if isinstance(slide_xml, str) else slide_xml+ try:+ root = ET.fromstring(data)+ except ET.ParseError as exc:+ raise ValueError(f'invalid slide XML: {exc}') from exc+ errors = validate_slide_animation_structure(+ root,+ require_supported_effects=require_supported_effects,+ )+ row_errors: list[str] = []+ rows = _animation_rows(root, row_errors)+ for error in row_errors:+ if error not in errors:+ errors.append(error)+ if errors:+ raise ValueError('; '.join(errors))+ direct_timings = [+ child for child in list(root)+ if child.tag == _qn(PML_NS, 'timing')+ ]+ audio_targets: list[int] = []+ for audio in root.iter(_qn(PML_NS, 'audio')):+ for target in audio.iter(_qn(PML_NS, 'spTgt')):+ value = target.get('spid')+ if value and value.isdigit():+ audio_targets.append(int(value))+ trigger = rows[0].trigger if rows else None+ return AnimationSequenceSummary(+ timing_count=len(direct_timings),+ trigger=trigger,+ rows=tuple(rows),+ audio_target_ids=tuple(audio_targets),+ )+++def validate_generated_animation_xml(+ slide_xml: str | bytes,+ targets: Sequence[Sequence[object]],+ *,+ duration: float = 0.3,+ trigger: str = 'after-previous',+) -> AnimationSequenceSummary:+ """Read back one generated sequence and require exact requested semantics."""+ trigger = normalize_animation_trigger(trigger)+ default_duration_ms = _seconds_to_ms(+ duration,+ 'animation duration',+ allow_zero=False,+ )+ expected = tuple(+ _normalize_target(target, default_duration_ms)+ for target in targets+ )+ summary = read_slide_animation_sequence(+ slide_xml,+ require_supported_effects=True,+ )+ errors: list[str] = []+ if len(summary.rows) != len(expected):+ errors.append(+ f'animation read-back row count is {len(summary.rows)}; '+ f'expected {len(expected)}'+ )+ if expected and summary.trigger != trigger:+ errors.append(+ f'animation read-back trigger is {summary.trigger!r}; expected {trigger!r}'+ )++ expected_offsets: list[int] = []+ elapsed_ms = 0+ previous_duration_ms = 0+ for index, target in enumerate(expected):+ if trigger == 'after-previous':+ if index == 0:+ elapsed_ms = target.delay_ms+ else:+ elapsed_ms += previous_duration_ms + target.delay_ms+ if elapsed_ms > MAX_OOXML_MILLISECONDS:+ errors.append(+ 'requested animation sequence offset exceeds the OOXML '+ f'millisecond limit at row {index + 1}: {elapsed_ms}'+ )+ expected_offsets.append(elapsed_ms)+ previous_duration_ms = target.duration_ms+ else:+ expected_offsets.append(0)++ for index, (actual, target) in enumerate(zip(summary.rows, expected), 1):+ spec = ANIMATIONS[target.effect]+ if actual.shape_id != target.shape_id:+ errors.append(+ f'animation row {index} targets shape {actual.shape_id}; '+ f'expected {target.shape_id}'+ )+ if actual.effect != target.effect:+ errors.append(+ f'animation row {index} resolved effect {actual.effect!r}; '+ f'expected {target.effect!r}'+ )+ if actual.preset_id != int(spec['presetID']):+ errors.append(f'animation row {index} presetID changed')+ if actual.preset_subtype != int(spec['presetSubtype']):+ errors.append(f'animation row {index} presetSubtype changed')+ if actual.filter_name != spec['filter']:+ errors.append(f'animation row {index} filter changed')+ expected_duration = 1 if target.effect == 'appear' else target.duration_ms+ if actual.duration_ms != expected_duration:+ errors.append(+ f'animation row {index} duration is {actual.duration_ms}ms; '+ f'expected {expected_duration}ms'+ )+ if actual.offset_ms != expected_offsets[index - 1]:+ errors.append(+ f'animation row {index} offset is {actual.offset_ms}ms; '+ f'expected {expected_offsets[index - 1]}ms'+ )+ if errors:+ raise ValueError('; '.join(errors))+ return summary+++def validate_pptx_animation_package(+ pptx_path: str | Path,+ *,+ require_supported_effects: bool = False,+) -> None:+ """Validate timing placement and shape references for every slide part."""+ path = Path(pptx_path)+ errors: list[str] = []+ try:+ with zipfile.ZipFile(path) as package:+ names = sorted(+ name+ for name in package.namelist()+ if re.fullmatch(r'ppt/slides/slide\d+\.xml', name)+ )+ for name in names:+ try:+ root = ET.fromstring(package.read(name))+ except ET.ParseError as exc:+ errors.append(f'{name}: invalid XML: {exc}')+ continue+ for error in validate_slide_animation_structure(+ root,+ require_supported_effects=require_supported_effects,+ ):+ errors.append(f'{name}: {error}')+ except (OSError, zipfile.BadZipFile) as exc:+ raise ValueError(f'unable to read PPTX package {path}: {exc}') from exc+ if errors:+ raise ValueError('; '.join(errors))+++def object_animation_fingerprint(slide_xml: str | bytes) -> str | None:+ """Return a prefix/whitespace-independent fingerprint of object animation.++ Narration audio is intentionally excluded. Direct-PPTX routes use this+ fingerprint before and after their allowed edits to prove that they did not+ take ownership of or rewrite existing object animations.+ """+ data = slide_xml.encode('utf-8') if isinstance(slide_xml, str) else slide_xml+ try:+ root = ET.fromstring(data)+ except ET.ParseError as exc:+ raise ValueError(f'invalid slide XML: {exc}') from exc+ timings = [+ child for child in list(root)+ if child.tag == _qn(PML_NS, 'timing')+ ]+ if len(timings) > 1:+ raise ValueError(+ f'slide has {len(timings)} root p:timing elements; expected at most 1'+ )+ if not timings:+ return None+ timing = timings[0]+ behavior_tags = {+ _qn(PML_NS, name)+ for name in (+ 'anim',+ 'animClr',+ 'animEffect',+ 'animMotion',+ 'animRot',+ 'animScale',+ 'cmd',+ 'set',+ )+ }+ has_object_animation = any(+ element.tag in behavior_tags+ or (+ element.tag == _qn(PML_NS, 'cTn')+ and element.get('presetClass') is not None+ )+ for element in timing.iter()+ )+ if not has_object_animation:+ return None++ def without_audio(element: ET.Element) -> tuple[object, ...] | None:+ if element.tag == _qn(PML_NS, 'audio'):+ return None+ children = tuple(+ value+ for child in list(element)+ if (value := without_audio(child)) is not None+ )+ return (+ element.tag,+ tuple(sorted(element.attrib.items())),+ (element.text or '').strip(),+ children,+ )++ canonical = without_audio(timing)+ return hashlib.sha256(repr(canonical).encode('utf-8')).hexdigest()+++def entrance_animation_fingerprint(slide_xml: str | bytes) -> str | None:+ """Compatibility alias for :func:`object_animation_fingerprint`."""+ return object_animation_fingerprint(slide_xml)def get_available_transitions() -> list:diff --git a/skills/ppt-master/scripts/pptx_transitions.py b/skills/ppt-master/scripts/pptx_transitions.pyindex 80ef4ed8..faf67e51 100644--- a/skills/ppt-master/scripts/pptx_transitions.py+++ b/skills/ppt-master/scripts/pptx_transitions.py@@ -55,6 +55,9 @@ PRESENTATION_PROPS_CONTENT_TYPE = (DEFAULT_TRANSITION = "fade"DEFAULT_TRANSITION_DURATION = 0.4MAX_OOXML_MILLISECONDS = 4_294_967_295+# OOXML stores millisecond values and identifiers (shape ids, time-node ids,+# preset codes) as xsd:unsignedInt, so both ceilings share one value.+MAX_OOXML_UNSIGNED_INT = MAX_OOXML_MILLISECONDSTRANSITIONS: dict[str, dict[str, Any]] = {diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 8770cb51..89498823 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -39,10 +39,17 @@ try:from svg_to_pptx.animation_config import (load_animation_config as _load_animation_config,validate_animation_config as _validate_animation_config,+ validate_animation_config_errors as _validate_animation_config_errors,+ validate_transition_config as _validate_transition_config,)-except ImportError:+except ImportError as exc:_load_animation_config = None_validate_animation_config = None+ _validate_animation_config_errors = None+ _validate_transition_config = None+ _animation_config_import_error = str(exc)+else:+ _animation_config_import_error = Nonetry:from svg_to_pptx.drawingml.utils import (@@ -2363,9 +2370,21 @@ class SVGQualityChecker: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:- returnproject_path = self._resolve_project_path(dir_path)+ config_path = project_path / 'animations.json'+ if (+ _load_animation_config is None+ or _validate_animation_config is None+ or _validate_animation_config_errors is None+ or _validate_transition_config is None+ ):+ if config_path.is_file():+ detail = _animation_config_import_error or 'unknown import error'+ self._animation_issues.append((+ 'error',+ f'animations.json validation is unavailable: {detail}',+ ))+ returntry:config = _load_animation_config(project_path)except Exception as exc:@@ -2373,8 +2392,19 @@ class SVGQualityChecker:returnif not config:return- for warning in _validate_animation_config(project_path, config):- self._animation_issues.append(('warning', warning))+ fatal_errors = list(dict.fromkeys(+ _validate_transition_config(config)+ + _validate_animation_config_errors(config)+ ))+ for error in fatal_errors:+ self._animation_issues.append(('error', error))+ for message in _validate_animation_config(project_path, config):+ severity = (+ 'warning'+ if ' has no id and cannot be customized in animations.json' in message+ else 'error'+ )+ self._animation_issues.append((severity, message))def _check_template_contract(self, dir_path: Path,svg_files: List[Path]) -> None:diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.pyindex 9eaedf8c..6f8e9fed 100644--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py@@ -9,15 +9,18 @@ from pathlib import Pathfrom typing import Anyfrom xml.etree import ElementTree as ET-from .drawingml.utils import SVG_NS-from .semantic_markers import is_static_page_frame-+from pptx_animations import (+ ANIMATIONS,+ ANIMATION_MODES,+ ANIMATION_TRIGGERS,+ animation_seconds_to_milliseconds,+ normalize_animation_effect,+ normalize_animation_trigger,+)from pptx_transitions import TRANSITIONS, validate_seconds-try:- from pptx_animations import ANIMATIONS-except ImportError:- ANIMATIONS = {}+from .drawingml.utils import SVG_NS+from .semantic_markers import is_static_page_frame_NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))@@ -39,6 +42,7 @@ class GroupTarget:group_id: strorder: intchrome: bool = False+ structurally_static: bool = Falsedef _tag_name(elem: ET.Element) -> str:@@ -78,10 +82,16 @@ def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:role = child.get('data-pptx-role')placeholder = child.get('data-pptx-placeholder')has_explicit_semantics = role is not None or placeholder is not None- if child.get('data-pptx-layer') is not None:+ has_structural_layer = child.get('data-pptx-layer') is not None+ semantic_static = (+ has_explicit_semantics+ and is_static_page_frame(role, placeholder)+ )+ structurally_static = has_structural_layer or semantic_static+ if has_structural_layer:chrome = Trueelif has_explicit_semantics:- chrome = is_static_page_frame(role, placeholder)+ chrome = semantic_staticelse:chrome = is_chrome_id(group_id)targets.append(@@ -90,6 +100,7 @@ def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:group_id=group_id,order=visual_index,chrome=chrome,+ structurally_static=structurally_static,))@@ -136,22 +147,69 @@ def load_animation_config(project_path: Path, config_path: str | None = None) ->return data-def _valid_animation_effect(effect: str) -> bool:- return effect == 'none' or effect in ANIMATIONS or effect in ('auto', 'mixed', 'random')--def _valid_transition_effect(effect: str) -> bool:return effect == 'none' or effect in TRANSITIONS+def _animation_effect_error(effect: object, label: str) -> str | None:+ if not isinstance(effect, str):+ return f'animations.json {label} animation effect must be a string'+ try:+ normalize_animation_effect(effect)+ except ValueError:+ valid = ', '.join((*ANIMATIONS, *ANIMATION_MODES, 'none'))+ return (+ f'animations.json {label} has unknown animation effect: {effect}; '+ f'valid effects: {valid}'+ )+ return None+++def _animation_trigger_error(trigger: object, label: str) -> str | None:+ if not isinstance(trigger, str):+ return f'animations.json {label} animation trigger must be a string'+ try:+ normalize_animation_trigger(trigger)+ except ValueError:+ valid = ', '.join(ANIMATION_TRIGGERS)+ return (+ f'animations.json {label} has unknown animation trigger: {trigger}; '+ f'valid triggers: {valid}'+ )+ return None+++def _unknown_field_errors(+ value: dict[str, Any],+ allowed: frozenset[str],+ label: str,+) -> list[str]:+ return [+ f'animations.json {label} has unknown field: {field}'+ for field in sorted(set(value) - allowed)+ ]++def validate_transition_config(config: dict[str, Any]) -> list[str]:"""Return fatal transition-sidecar errors that must block export."""errors: list[str] = []defaults = config.get('defaults', {})+ default_effect = 'fade'if not isinstance(defaults, dict):errors.append('animations.json field "defaults" must be an object')else:- errors.extend(_transition_scope_errors(defaults, 'defaults'))+ errors.extend(+ _transition_scope_errors(+ defaults,+ 'defaults',+ inherited_effect='fade',+ )+ )+ transition_defaults = defaults.get('transition', {})+ if isinstance(transition_defaults, dict):+ value = transition_defaults.get('effect', default_effect)+ if isinstance(value, str) and _valid_transition_effect(value):+ default_effect = valueslides = config.get('slides', {})if not isinstance(slides, dict):@@ -162,19 +220,32 @@ def validate_transition_config(config: dict[str, Any]) -> list[str]:errors.append(f'animations.json slide "{slide_name}" must be an object')continueerrors.extend(- _transition_scope_errors(slide_cfg, f'slide "{slide_name}"')+ _transition_scope_errors(+ slide_cfg,+ f'slide "{slide_name}"',+ inherited_effect=default_effect,+ ))return errors-def _transition_scope_errors(scope: dict[str, Any], label: str) -> list[str]:+def _transition_scope_errors(+ scope: dict[str, Any],+ label: str,+ *,+ inherited_effect: str,+) -> list[str]:if 'transition' not in scope:return []transition = scope['transition']if not isinstance(transition, dict):return [f'animations.json {label} field "transition" must be an object']- errors: list[str] = []+ errors = _unknown_field_errors(+ transition,+ frozenset({'effect', 'duration', 'auto_advance'}),+ f'{label} transition',+ )if 'effect' in transition:effect = transition['effect']if not isinstance(effect, str):@@ -185,7 +256,11 @@ def _transition_scope_errors(scope: dict[str, Any], label: str) -> list[str]:errors.append(f'animations.json {label} has unknown transition effect: {effect}')- for field, allow_zero in (('duration', False), ('auto_advance', True)):+ duration_allows_zero = transition.get('effect', inherited_effect) == 'none'+ for field, allow_zero in (+ ('duration', duration_allows_zero),+ ('auto_advance', True),+ ):if field not in transition:continuetry:@@ -199,70 +274,197 @@ def _transition_scope_errors(scope: dict[str, Any], label: str) -> list[str]:return errors+def validate_animation_config_errors(config: dict[str, Any]) -> list[str]:+ """Return fatal object-animation errors that must block export."""+ errors = _unknown_field_errors(+ config,+ frozenset({'version', 'defaults', 'slides'}),+ 'top level',+ )+ defaults = config.get('defaults', {})+ if not isinstance(defaults, dict):+ errors.append('animations.json field "defaults" must be an object')+ else:+ errors.extend(+ _unknown_field_errors(+ defaults,+ frozenset({'transition', 'animation'}),+ 'defaults',+ )+ )+ errors.extend(_animation_scope_errors(defaults, 'defaults'))++ slides = config.get('slides', {})+ if not isinstance(slides, dict):+ errors.append('animations.json field "slides" must be an object')+ return list(dict.fromkeys(errors))++ for slide_name, slide_cfg in slides.items():+ if not isinstance(slide_cfg, dict):+ errors.append(f'animations.json slide "{slide_name}" must be an object')+ continue+ errors.extend(+ _unknown_field_errors(+ slide_cfg,+ frozenset({'transition', 'animation', 'groups'}),+ f'slide "{slide_name}"',+ )+ )+ errors.extend(+ _animation_scope_errors(slide_cfg, f'slide "{slide_name}"')+ )+ errors.extend(_animation_group_errors(slide_name, slide_cfg))+ return list(dict.fromkeys(errors))+++def _animation_scope_errors(scope: dict[str, Any], label: str) -> list[str]:+ if 'animation' not in scope:+ return []+ animation = scope['animation']+ if not isinstance(animation, dict):+ return [f'animations.json {label} field "animation" must be an object']++ errors = _unknown_field_errors(+ animation,+ frozenset({'effect', 'duration', 'stagger', 'trigger'}),+ f'{label} animation',+ )+ if 'effect' in animation:+ effect_error = _animation_effect_error(animation['effect'], label)+ if effect_error:+ errors.append(effect_error)++ for field, allow_zero in (('duration', False), ('stagger', True)):+ if field not in animation:+ continue+ try:+ animation_seconds_to_milliseconds(+ animation[field],+ f'animations.json {label} animation {field}',+ allow_zero=allow_zero,+ )+ except ValueError as exc:+ errors.append(str(exc))++ if 'trigger' in animation:+ trigger_error = _animation_trigger_error(animation['trigger'], label)+ if trigger_error:+ errors.append(trigger_error)+ return errors+++def _animation_group_errors(+ slide_name: object,+ slide_cfg: dict[str, Any],+) -> list[str]:+ if 'groups' not in slide_cfg:+ return []+ groups = slide_cfg['groups']+ if not isinstance(groups, dict):+ return [+ f'animations.json slide "{slide_name}" field "groups" must be an object'+ ]++ errors: list[str] = []+ for group_id, group_cfg in groups.items():+ label = f'group "{slide_name}/{group_id}"'+ if not isinstance(group_cfg, dict):+ errors.append(f'animations.json {label} must be an object')+ continue++ errors.extend(+ _unknown_field_errors(+ group_cfg,+ frozenset({'effect', 'duration', 'delay', 'order'}),+ label,+ )+ )++ if 'effect' in group_cfg:+ effect_error = _animation_effect_error(group_cfg['effect'], label)+ if effect_error:+ errors.append(effect_error)++ for field, allow_zero in (('duration', False), ('delay', True)):+ if field not in group_cfg:+ continue+ try:+ animation_seconds_to_milliseconds(+ group_cfg[field],+ f'animations.json {label} animation {field}',+ allow_zero=allow_zero,+ )+ except ValueError as exc:+ errors.append(str(exc))++ if 'order' in group_cfg:+ order = group_cfg['order']+ if isinstance(order, bool) or not isinstance(order, int) or order <= 0:+ errors.append(+ f'animations.json {label} animation order must be a positive integer: '+ f'{order!r}'+ )+ return errors++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``."""+ """Return sidecar-reference diagnostics for ``svg_output``.++ Fatal field/type/value checks are owned by+ :func:`validate_animation_config_errors`. Anonymous groups are warnings;+ missing slides/groups and structural targets are fatal at export call sites.+ """if config is None:config = load_animation_config(project_path, config_path)if not config:return []- warnings = validate_transition_config(config)+ 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):- warnings.append('animations.json field "slides" must be an object')+ if not isinstance(slides, dict):return list(dict.fromkeys(warnings))+ for slide_name in sorted(known_slides - set(slides)):+ warnings.append(f'animations.json omits slide: {slide_name}')- defaults = config.get('defaults', {})- if isinstance(defaults, dict):- _validate_scope_effects(defaults, 'defaults', warnings)-- for slide_name, slide_cfg in (slides or {}).items():+ for slide_name, slide_cfg in slides.items():if slide_name not in known_slides:warnings.append(f'animations.json references missing slide: {slide_name}')continueif 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]}+ known_groups = {+ target.group_id: target+ for target in targets_by_slide.get(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')+ if not isinstance(groups, dict):continue- for group_id, group_cfg in (groups or {}).items():+ for group_id, group_cfg in groups.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)):+ target = known_groups[group_id]+ effect = group_cfg.get('effect') if isinstance(group_cfg, dict) else None+ if target.structurally_static and effect != 'none':warnings.append(- f'animations.json group "{slide_name}/{group_id}" has unknown effect: {effect}'+ 'animations.json references non-animatable structural group: '+ f'{slide_name}/{group_id}')return list(dict.fromkeys(warnings))-def _validate_scope_effects(scope: dict[str, Any], label: str, warnings: list[str]) -> None:- 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.diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.pyindex 2b0c0e05..7d0d4f71 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py@@ -59,6 +59,9 @@ class ConvertContext:# Top-level <g id="..."> groups, recorded as (shape_id, svg_id) in z-order.# Used by the PPTX builder to emit per-element entrance timing.anim_targets: list = field(default_factory=list)+ # Explicit sidecar group ids may override the legacy chrome-name heuristic.+ # Explicit structural layer/role/placeholder markers remain non-animatable.+ animation_group_overrides: frozenset[str] = frozenset()# Default-on flag: merge mergeable paragraph blocks into one editable# text frame with multiple <a:p>. Disable it for strict line fidelity.merge_paragraphs: bool = True@@ -173,6 +176,7 @@ class ConvertContext:depth=self.depth + 1,# anim_targets is intentionally a fresh list on the child;# only the root-level context's list is read by the builder.+ animation_group_overrides=self.animation_group_overrides,merge_paragraphs=self.merge_paragraphs,native_objects_enabled=self.native_objects_enabled,image_optimize=self.image_optimize,diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 9593dcbc..d152952f 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -173,8 +173,14 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:should_animate_group = (ctx.depth == 0and elem_id- and not is_chrome- and not elem.get('data-pptx-layer')+ and (+ not is_chrome+ or (+ not has_explicit_semantics+ and elem_id in ctx.animation_group_overrides+ )+ )+ and elem.get('data-pptx-layer') is None)visual_children = [child for child in elem@@ -639,6 +645,7 @@ def convert_svg_to_slide_shapes(image_scale: float = 2.0,image_quality: int = 85,native_objects: bool = False,+ animation_group_overrides: frozenset[str] | None = None,theme_font_spec: ThemeFontSpec | None = None,theme_color_spec: ThemeColorSpec | None = None,trace_out: list[dict[str, Any]] | None = None,@@ -668,6 +675,9 @@ def convert_svg_to_slide_shapes(image_quality: JPEG quality used for opaque optimized rasters.native_objects: Convert explicit ``data-pptx-native`` table/chartmarkers to native PowerPoint objects. Default off.+ animation_group_overrides: Explicit top-level SVG group ids from+ ``animations.json`` that override the legacy chrome-name fallback.+ Explicit structural layer/role/placeholder markers remain excluded.theme_font_spec: Optional major/minor theme-font contract. Matching SVGfamilies emit DrawingML theme tokens instead of fixed typefaces.theme_color_spec: Optional context-aware theme-color contract. Exact@@ -809,6 +819,7 @@ def convert_svg_to_slide_shapes(image_scale=image_scale,image_quality=image_quality,native_objects_enabled=native_objects,+ animation_group_overrides=animation_group_overrides or frozenset(),trace_events=trace_events,theme_font_spec=theme_font_spec,theme_color_spec=theme_color_spec,@@ -817,6 +828,10 @@ def convert_svg_to_slide_shapes(shapes: list[str] = []converted = 0skipped = 0+ has_top_level_group = any(+ child.tag.replace(f'{{{SVG_NS}}}', '') == 'g'+ for child in root+ )background_xml, background_skip_id = _extract_background_candidate(root, ctx)promoted_backgrounds = 1 if background_xml else 0if background_xml and trace_events is not None:@@ -840,12 +855,31 @@ def convert_svg_to_slide_shapes(shapes.append(result.xml)converted += 1m = re.search(r'<p:cNvPr id="(\d+)"', result.xml)- if m and not child.get('data-pptx-layer'):- if not is_static_page_frame(- child.get('data-pptx-role'),- child.get('data-pptx-placeholder'),- ):- fallback_targets.append((int(m.group(1)), tag))+ elem_id = child.get('id')+ role = child.get('data-pptx-role')+ placeholder = child.get('data-pptx-placeholder')+ has_explicit_semantics = role is not None or placeholder is not None+ structurally_static = (+ child.get('data-pptx-layer') is not None+ or (+ has_explicit_semantics+ and is_static_page_frame(role, placeholder)+ )+ )+ legacy_chrome = (+ not has_explicit_semantics+ and is_chrome_id(elem_id)+ )+ explicit_legacy_override = (+ elem_id is not None+ and elem_id in ctx.animation_group_overrides+ )+ if (+ m+ and not structurally_static+ and (not legacy_chrome or explicit_legacy_override)+ ):+ fallback_targets.append((int(m.group(1)), elem_id or tag))else:if tag not in _NON_VISUAL_TAGS:skipped += 1@@ -857,7 +891,11 @@ def convert_svg_to_slide_shapes(# semantic blocks, not atomized drawing primitives, so fallback is# intentionally capped at a low count._ANIM_FALLBACK_CAP = 8- if not ctx.anim_targets and 0 < len(fallback_targets) <= _ANIM_FALLBACK_CAP:+ if (+ not has_top_level_group+ and not ctx.anim_targets+ and 0 < len(fallback_targets) <= _ANIM_FALLBACK_CAP+ ):ctx.anim_targets = fallback_targetsif verbose:diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex 91b1dc30..6cd8982a 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py@@ -8,6 +8,7 @@ import mathimport mimetypesimport osimport posixpath+import randomimport reimport shutilimport stat@@ -36,6 +37,15 @@ from pptx_transitions import (validate_pptx_transition_package,validate_seconds,)+from pptx_animations import (+ animation_seconds_to_milliseconds,+ create_sequence_timing_xml,+ normalize_animation_effect,+ normalize_animation_trigger,+ pick_animation_effect,+ validate_generated_animation_xml,+ validate_pptx_animation_package,+)from ..drawingml.converter import convert_svg_to_slide_shapesfrom ..drawingml.theme_colors import (@@ -92,16 +102,6 @@ from .template_structure import (parse_template_slides,)-try:- from pptx_animations import (- create_sequence_timing_xml,- pick_animation_effect,- )-except ImportError:- create_sequence_timing_xml = None- pick_animation_effect = None--SLIDE_LAYOUT_REL_TYPE = ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout")@@ -2762,16 +2762,6 @@ def _ensure_notes_master(extract_dir: Path) -> None:presentation_path.write_text(presentation_xml, encoding='utf-8')-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 math.isfinite(number) and number >= 0 else default--def _slide_config(animation_config: dict[str, Any] | None, svg_stem: str) -> dict[str, Any]:if not animation_config:return {}@@ -2809,7 +2799,7 @@ def _slide_transition_settings(duration = validate_seconds(trans_cfg.get('duration'),"transition duration",- allow_zero=False,+ allow_zero=effect is None,)if not cli_overrides.get('auto_advance') and 'auto_advance' in trans_cfg:auto_advance = validate_seconds(@@ -2828,65 +2818,131 @@ def _slide_animation_settings(trigger: str,cli_overrides: dict[str, bool],) -> tuple[str | None, float, float, str]:- anim_cfg = _as_dict(slide_cfg.get('animation'))- effect = animation+ anim_value = slide_cfg.get('animation', {})+ if not isinstance(anim_value, dict):+ raise ValueError('animations.json slide animation must be an object')+ anim_cfg = anim_value+ effect = normalize_animation_effect(+ animation,+ allow_none=True,+ allow_modes=True,+ )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+ effect = normalize_animation_effect(+ anim_cfg.get('effect'),+ allow_none=True,+ allow_modes=True,+ )if not cli_overrides.get('animation_duration'):- duration = _to_float(anim_cfg.get('duration'), duration)+ duration = validate_seconds(+ anim_cfg.get('duration', duration),+ 'animation duration',+ allow_zero=False,+ )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'))+ stagger = validate_seconds(+ anim_cfg.get('stagger', stagger),+ 'animation stagger',+ allow_zero=True,+ )+ if not cli_overrides.get('animation_trigger') and 'trigger' in anim_cfg:+ trigger = normalize_animation_trigger(anim_cfg.get('trigger'))+ else:+ trigger = normalize_animation_trigger(trigger)+ animation_seconds_to_milliseconds(+ duration,+ 'animation duration',+ allow_zero=False,+ )+ animation_seconds_to_milliseconds(+ stagger,+ 'animation stagger',+ allow_zero=True,+ )return effect, duration, stagger, triggerdef _build_sequence_targets(anim_targets: list[tuple[int, str]],slide_cfg: dict[str, Any],- animation: str,+ animation: str | None,duration: float,stagger: float,mixed_animation_offset: int,+ animation_rng: random.Random,) -> 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]]] = []+ groups_value = slide_cfg.get('groups', {})+ if not isinstance(groups_value, dict):+ raise ValueError('animations.json slide groups must be an object')+ groups_cfg = groups_value+ ordered: list[tuple[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':+ group_value = groups_cfg.get(svg_id, {})+ if not isinstance(group_value, dict):+ raise ValueError(+ f'animations.json group "{svg_id}" must be an object'+ )+ group_cfg = group_value+ raw_effect = group_cfg.get('effect')+ if raw_effect is not None:+ normalized_effect = normalize_animation_effect(+ raw_effect,+ allow_none=True,+ allow_modes=True,+ )+ else:+ normalized_effect = None+ if 'effect' in group_cfg and normalized_effect is None:+ continue+ if animation is None and normalized_effect is None:continueorder_value = group_cfg.get('order')- try:- order = int(order_value)- has_order = 0- except (TypeError, ValueError):- order = idx- has_order = 1+ order = order_value if order_value is not None else idx + 1+ if isinstance(order, bool) or not isinstance(order, int) or order <= 0:+ raise ValueError(+ f'animations.json group "{svg_id}" order must be a positive integer'+ )group_entry = dict(group_cfg)group_entry['_shape_id'] = sid- ordered.append((has_order, order, idx, svg_id, group_entry))+ group_entry['_effect'] = normalized_effect+ ordered.append((order, idx, svg_id, group_entry))- ordered.sort(key=lambda item: (item[0], item[1], item[2]))+ ordered.sort(key=lambda item: (item[0], item[1]))seq_targets: list[tuple[int, int, str, float]] = []- for seq_idx, (_has_order, _order, _original_idx, _svg_id, group_cfg) in enumerate(ordered):+ resolved_group_modes: list[str | None] = []+ for seq_idx, (_order, _original_idx, _svg_id, group_cfg) in enumerate(ordered):shape_id = int(group_cfg['_shape_id'])- raw_effect = group_cfg.get('effect')+ raw_effect = group_cfg.get('_effect')+ resolved_group_modes.append(+ raw_effect if raw_effect in ('auto', 'mixed', 'random') else None+ )if raw_effect in ('auto', 'mixed', 'random'):effect = pick_animation_effect(str(raw_effect), seq_idx, mixed_animation_offset, group_id=_svg_id,+ rng=animation_rng,)else:effect = str(raw_effect or pick_animation_effect(animation, seq_idx, mixed_animation_offset, group_id=_svg_id,+ rng=animation_rng,))- item_duration = _to_float(group_cfg.get('duration'), duration)- delay_seconds = _to_float(- group_cfg.get('delay'),- 0 if seq_idx == 0 else stagger,+ item_duration = validate_seconds(+ group_cfg.get('duration', duration),+ f'animation duration for group "{_svg_id}"',+ allow_zero=False,+ )+ delay_seconds = validate_seconds(+ group_cfg.get('delay', 0 if seq_idx == 0 else stagger),+ f'animation delay for group "{_svg_id}"',+ allow_zero=True,)- seq_targets.append((shape_id, int(delay_seconds * 1000), effect, item_duration))+ delay_ms = animation_seconds_to_milliseconds(+ delay_seconds,+ f'animation delay for group "{_svg_id}"',+ allow_zero=True,+ )+ seq_targets.append((shape_id, delay_ms, effect, item_duration))mixed_count = 0if animation == 'mixed':@@ -2897,6 +2953,12 @@ def _build_sequence_targets(# semantic matches (title→fade, chart→wipe etc.) are unaffected# because they ignore the offset.mixed_count = len(seq_targets)+ else:+ mixed_count = sum(+ 1+ for seq_idx, mode in enumerate(resolved_group_modes)+ if mode == 'auto' or (mode == 'mixed' and seq_idx > 0)+ )return seq_targets, mixed_count@@ -3518,6 +3580,17 @@ def create_pptx_with_native_svg(audio_exts_used: set[str] = set()package_uses_timings = Falsemixed_animation_offset = 0+ animation_seed = json.dumps(+ {+ 'animation': animation,+ 'config': animation_config,+ 'slides': [path.name for path in svg_files],+ },+ ensure_ascii=False,+ sort_keys=True,+ separators=(',', ':'),+ )+ animation_rng = random.Random(animation_seed)conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else Nonestructure_trace: list[dict[str, Any]] | None = ([]@@ -3527,11 +3600,59 @@ def create_pptx_with_native_svg(for i, svg_path in enumerate(svg_files, 1):slide_num = i+ expected_animation_targets: list[tuple[int, int, str, float]] = []+ expected_animation_duration = animation_duration+ expected_animation_trigger = normalize_animation_trigger(animation_trigger)try:# ---- Native shapes mode ----if use_native_shapes: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,+ )+ )+ (+ 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,+ )+ groups_value = slide_cfg.get('groups', {})+ if not isinstance(groups_value, dict):+ raise ValueError(+ 'animations.json slide groups must be an object'+ )+ animation_hard_disabled = (+ animation_cli_overrides.get('animation', False)+ and animation is None+ )+ explicit_animation_groups = (+ frozenset(+ str(group_id)+ for group_id, group_cfg in groups_value.items()+ if isinstance(group_cfg, dict)+ and group_cfg.get('effect') != 'none'+ and (+ slide_animation is not None+ or 'effect' in group_cfg+ )+ )+ if not animation_hard_disabled+ else frozenset()+ )(slide_xml,media_files_dict,@@ -3549,6 +3670,7 @@ def create_pptx_with_native_svg(image_scale=image_scale,image_quality=image_quality,native_objects=native_objects,+ animation_group_overrides=explicit_animation_groups,theme_font_spec=active_theme_font_spec,theme_color_spec=active_theme_color_spec,trace_out=conversion_trace@@ -3556,29 +3678,6 @@ def create_pptx_with_native_svg(else structure_trace,))- 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@@ -3597,10 +3696,13 @@ def create_pptx_with_native_svg(if slide_auto_advance is not None:package_uses_timings = True- if (slide_animation and slide_animation != 'none'- and create_sequence_timing_xml- and pick_animation_effect- and anim_targets):+ expected_animation_duration = slide_animation_duration+ expected_animation_trigger = slide_animation_trigger+ if (+ not animation_hard_disabled+ and (slide_animation or explicit_animation_groups)+ and anim_targets+ ):seq_targets, mixed_count = _build_sequence_targets(anim_targets,slide_cfg,@@ -3608,8 +3710,10 @@ def create_pptx_with_native_svg(slide_animation_duration,slide_animation_stagger,mixed_animation_offset,+ animation_rng,)- if slide_animation in ('mixed', 'auto'):+ expected_animation_targets = seq_targets+ if mixed_count:mixed_animation_offset += mixed_counttiming_xml = '\n' + create_sequence_timing_xml(seq_targets, duration=slide_animation_duration,@@ -3876,12 +3980,24 @@ def create_pptx_with_native_svg(raise RuntimeError(f'Slide {slide_num} transition validation failed: {exc}') from exc+ try:+ resolved_animation = validate_generated_animation_xml(+ final_slide_xml,+ expected_animation_targets,+ duration=expected_animation_duration,+ trigger=expected_animation_trigger,+ )+ except ValueError as exc:+ raise RuntimeError(+ f'Slide {slide_num} animation validation failed: {exc}'+ ) from excif conversion_trace is not None:motion_summary = asdict(resolved_motion)for trace_entry in reversed(conversion_trace):if trace_entry.get('slide_num') == slide_num:trace_entry['motion'] = motion_summary+ trace_entry['animation'] = asdict(resolved_animation)breakif verbose:@@ -4100,6 +4216,15 @@ def create_pptx_with_native_svg(raise RuntimeError(f'PPTX transition package validation failed: {exc}') from exc+ try:+ validate_pptx_animation_package(+ temp_output_path,+ require_supported_effects=True,+ )+ except ValueError as exc:+ raise RuntimeError(+ f'PPTX animation package validation failed: {exc}'+ ) from excshutil.move(str(temp_output_path), str(output_path))permission_warnings = _relax_output_permissions(output_path)diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.pyindex 6814cade..9184fddc 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py@@ -16,6 +16,12 @@ if str(_SCRIPTS_DIR) not in sys.path:sys.path.insert(0, str(_SCRIPTS_DIR))from console_encoding import configure_utf8_stdio # noqa: E402+from pptx_animations import ( # noqa: E402+ ANIMATIONS,+ animation_seconds_to_milliseconds,+ normalize_animation_effect,+ normalize_animation_trigger,+)from pptx_transitions import validate_seconds # noqa: E402configure_utf8_stdio()@@ -47,14 +53,10 @@ from .template_structure import (from ..animation_config import (load_animation_config,validate_animation_config,+ validate_animation_config_errors,validate_transition_config,)-try:- from pptx_animations import ANIMATIONS as _ANIMATIONS-except ImportError:- _ANIMATIONS = {}-def _as_dict(value: object) -> dict:return value if isinstance(value, dict) else {}@@ -85,6 +87,8 @@ def _recorded_narration_on_click_slides(animation_cli_overrides: dict[str, bool],) -> list[str]:"""Return slides whose effective recorded-video animation trigger is on-click."""+ if animation_cli_overrides.get('animation') and animation is None:+ return []slides_cfg = _as_dict(_as_dict(animation_config).get('slides'))blocked: list[str] = []for svg_path in ref_files:@@ -93,14 +97,20 @@ def _recorded_narration_on_click_slides(slide_animation = animationif not animation_cli_overrides.get('animation') and 'effect' in anim_cfg:- cfg_effect = str(anim_cfg.get('effect'))- slide_animation = None if cfg_effect == 'none' else cfg_effect- if slide_animation is None:+ slide_animation = normalize_animation_effect(anim_cfg.get('effect'))+ groups_cfg = _as_dict(slide_cfg.get('groups'))+ has_explicit_animation = any(+ isinstance(group_cfg, dict)+ and 'effect' in group_cfg+ and normalize_animation_effect(group_cfg.get('effect')) is not None+ for group_cfg in groups_cfg.values()+ )+ if slide_animation is None and not has_explicit_animation:continueslide_trigger = animation_triggerif not animation_cli_overrides.get('animation_trigger') and anim_cfg.get('trigger'):- slide_trigger = str(anim_cfg.get('trigger'))+ slide_trigger = normalize_animation_trigger(anim_cfg.get('trigger'))if slide_trigger == 'on-click':blocked.append(svg_path.stem)return blocked@@ -113,11 +123,7 @@ def main(argv: list[str] | None = None) -> int:else ['fade', 'push', 'wipe', 'split', 'strips', 'cover', 'random']))- animation_choices = (- ['none'] + (list(_ANIMATIONS.keys()) if _ANIMATIONS- else ['fade', 'fly', 'zoom', 'appear'])- + ['auto', 'mixed', 'random']- )+ animation_choices = ['none', *ANIMATIONS, 'auto', 'mixed', 'random']parser = argparse.ArgumentParser(description='PPT Master - SVG to native DrawingML PPTX Tool',@@ -256,7 +262,7 @@ Recorded narration:parser.add_argument('-t', '--transition', type=str, choices=transition_choices, default=None,help='Page transition effect (default: fade; "none" removes visual motion)')- parser.add_argument('--transition-duration', type=positive_float, default=None,+ 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=non_negative_float, default=None,help='Auto-advance interval in seconds (default: manual advance)')@@ -270,7 +276,7 @@ Recorded narration:'richer pool for visual variation, fallback cycles fade/''wipe/fly/zoom), "mixed" (legacy 16-effect pool), or ''"random".')- parser.add_argument('--animation-duration', type=non_negative_float, default=None,+ parser.add_argument('--animation-duration', type=positive_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'],@@ -547,24 +553,41 @@ Recorded narration:except Exception as exc:print(f"Error: Failed to load animation config: {exc}")return 1- transition_config_errors = (- validate_transition_config(animation_config)- if animation_config- else []- )- if transition_config_errors:- for error in transition_config_errors:+ config_errors: list[str] = []+ if animation_config:+ config_errors.extend(validate_transition_config(animation_config))+ config_errors.extend(validate_animation_config_errors(animation_config))+ config_errors = list(dict.fromkeys(config_errors))+ if config_errors:+ for error in config_errors:print(f"Error: {error}", file=sys.stderr)return 1++ config_warnings: list[str] = []+ if animation_config:+ reference_messages = validate_animation_config(project_path, animation_config)+ config_warnings = [+ message for message in reference_messages+ if ' has no id and cannot be customized in animations.json' in message+ ]+ reference_errors = [+ message for message in reference_messages+ if message not in config_warnings+ ]+ if reference_errors:+ for error in reference_errors:+ print(f"Error: {error}", file=sys.stderr)+ return 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):+ for warning in config_warnings:print(f" [warn] {warning}")defaults = animation_config.get('defaults', {}) if animation_config else {}transition_defaults = _as_dict(defaults.get('transition')) if isinstance(defaults, dict) else {}- animation_defaults = defaults.get('animation', {}) if isinstance(defaults, dict) else {}+ animation_defaults = _as_dict(defaults.get('animation')) if isinstance(defaults, dict) else {}transition_arg = args.transitiontransition_effect = (@@ -581,7 +604,7 @@ Recorded narration:else transition_defaults.get('duration', 0.4)),"transition duration",- allow_zero=False,+ allow_zero=transition is None,)auto_advance = (args.auto_advance@@ -598,31 +621,52 @@ Recorded narration:print(f"Error: {exc}", file=sys.stderr)return 1- animation_arg = args.animation- animation_effect = (- animation_arg- if animation_arg is not None- # Per-element entrance is opt-in by default: auto-firing element builds- # read as the "AI deck" tell and were unsolicited. Page transitions stay- # on (see transition default above). Re-enable with -a auto / animations.json.- else animation_defaults.get('effect', 'none')- )- 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')- )+ try:+ animation_effect = (+ args.animation+ if args.animation is not None+ # Per-element entrance is opt-in by default: auto-firing element builds+ # read as the "AI deck" tell and were unsolicited. Page transitions stay+ # on (see transition default above). Re-enable with -a auto / animations.json.+ else animation_defaults.get('effect', 'none')+ )+ animation = normalize_animation_effect(animation_effect)+ animation_duration = validate_seconds(+ (+ args.animation_duration+ if args.animation_duration is not None+ else animation_defaults.get('duration', 0.4)+ ),+ "animation duration",+ allow_zero=False,+ )+ animation_seconds_to_milliseconds(+ animation_duration,+ "animation duration",+ allow_zero=False,+ )+ animation_stagger = validate_seconds(+ (+ args.animation_stagger+ if args.animation_stagger is not None+ else animation_defaults.get('stagger', 0.5)+ ),+ "animation stagger",+ allow_zero=True,+ )+ animation_seconds_to_milliseconds(+ animation_stagger,+ "animation stagger",+ allow_zero=True,+ )+ animation_trigger = normalize_animation_trigger(+ args.animation_trigger+ if args.animation_trigger is not None+ else animation_defaults.get('trigger', 'after-previous')+ )+ except ValueError as exc:+ print(f"Error: {exc}", file=sys.stderr)+ return 1animation_cli_overrides = {'transition': args.transition is not None,diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/narration.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/narration.pyindex 298b6e43..542248e9 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/narration.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/narration.py@@ -6,16 +6,26 @@ import base64import jsonimport reimport subprocess+from collections.abc import Iterablefrom pathlib import Path+from xml.etree import ElementTree as ETfrom pptx_transitions import (AdvanceUpdate,EnterUpdate,+ MAX_OOXML_UNSIGNED_INT,+ P14_NS,+ PML_NS,apply_slide_motion_xml,+ parse_source_xml,read_slide_transition_xml,+ serialize_source_xml,)+DRAWINGML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"+RELATIONSHIPS_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+MEDIA_REL_TYPE = "http://schemas.microsoft.com/office/2007/relationships/media"AUDIO_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"IMAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"@@ -43,6 +53,22 @@ AUDIO_MARKER_PNG_BYTES = base64.b64decode()+for _prefix, _uri in (+ ("p", PML_NS),+ ("a", DRAWINGML_NS),+ ("r", RELATIONSHIPS_NS),+ ("p14", P14_NS),+):+ try:+ ET.register_namespace(_prefix, _uri)+ except (AttributeError, ValueError):+ pass+++def _qn(namespace: str, tag: str) -> str:+ return f"{{{namespace}}}{tag}"++def _normalize_title(title: str) -> str:text = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff]+", "_", title.strip())return re.sub(r"_+", "_", text).strip("_").lower()@@ -109,8 +135,94 @@ def probe_audio_duration(audio_path: Path) -> float | None:def next_shape_id(slide_xml: str) -> int:- ids = [int(value) for value in re.findall(r'<p:cNvPr[^>]*\sid="(\d+)"', slide_xml)]- return max(ids, default=1) + 1+ """Return the next slide-local non-visual shape id."""+ root = parse_source_xml(slide_xml)+ if root.tag != _qn(PML_NS, "sld"):+ raise ValueError("narration source XML root must be p:sld")+ ids = _numeric_ids(+ root.iter(_qn(PML_NS, "cNvPr")),+ "shape",+ minimum=1,+ )+ next_id = max(ids, default=1) + 1+ if next_id > MAX_OOXML_UNSIGNED_INT:+ raise ValueError("narration source has no available shape identifiers")+ return next_id+++def _create_audio_pic_element(+ shape_id: int,+ shape_name: str,+ audio_rid: str,+ media_rid: str,+ poster_rid: str,+) -> ET.Element:+ pic = ET.Element(_qn(PML_NS, "pic"))+ nv_pic_pr = ET.SubElement(pic, _qn(PML_NS, "nvPicPr"))+ c_nv_pr = ET.SubElement(+ nv_pic_pr,+ _qn(PML_NS, "cNvPr"),+ {"id": str(shape_id), "name": shape_name},+ )+ ET.SubElement(+ c_nv_pr,+ _qn(DRAWINGML_NS, "hlinkClick"),+ {+ _qn(RELATIONSHIPS_NS, "id"): "",+ "action": "ppaction://media",+ },+ )+ c_nv_pic_pr = ET.SubElement(nv_pic_pr, _qn(PML_NS, "cNvPicPr"))+ ET.SubElement(+ c_nv_pic_pr,+ _qn(DRAWINGML_NS, "picLocks"),+ {"noChangeAspect": "1"},+ )+ nv_pr = ET.SubElement(nv_pic_pr, _qn(PML_NS, "nvPr"))+ ET.SubElement(+ nv_pr,+ _qn(DRAWINGML_NS, "audioFile"),+ {_qn(RELATIONSHIPS_NS, "link"): audio_rid},+ )+ ext_list = ET.SubElement(nv_pr, _qn(PML_NS, "extLst"))+ extension = ET.SubElement(+ ext_list,+ _qn(PML_NS, "ext"),+ {"uri": "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}"},+ )+ ET.SubElement(+ extension,+ _qn(P14_NS, "media"),+ {_qn(RELATIONSHIPS_NS, "embed"): media_rid},+ )++ blip_fill = ET.SubElement(pic, _qn(PML_NS, "blipFill"))+ ET.SubElement(+ blip_fill,+ _qn(DRAWINGML_NS, "blip"),+ {_qn(RELATIONSHIPS_NS, "embed"): poster_rid},+ )+ stretch = ET.SubElement(blip_fill, _qn(DRAWINGML_NS, "stretch"))+ ET.SubElement(stretch, _qn(DRAWINGML_NS, "fillRect"))++ shape_properties = ET.SubElement(pic, _qn(PML_NS, "spPr"))+ transform = ET.SubElement(shape_properties, _qn(DRAWINGML_NS, "xfrm"))+ ET.SubElement(transform, _qn(DRAWINGML_NS, "off"), {"x": "0", "y": "0"})+ ET.SubElement(+ transform,+ _qn(DRAWINGML_NS, "ext"),+ {+ "cx": str(AUDIO_MARKER_SIZE_EMU),+ "cy": str(AUDIO_MARKER_SIZE_EMU),+ },+ )+ geometry = ET.SubElement(+ shape_properties,+ _qn(DRAWINGML_NS, "prstGeom"),+ {"prst": "rect"},+ )+ ET.SubElement(geometry, _qn(DRAWINGML_NS, "avLst"))+ return picdef create_audio_pic_xml(@@ -121,51 +233,158 @@ def create_audio_pic_xml(poster_rid: str,) -> str:"""Create a visible audio picture shape carrying narration media."""- return f'''<p:pic>- <p:nvPicPr>- <p:cNvPr id="{shape_id}" name="{shape_name}">- <a:hlinkClick r:id="" action="ppaction://media"/>- </p:cNvPr>- <p:cNvPicPr>- <a:picLocks noChangeAspect="1"/>- </p:cNvPicPr>- <p:nvPr>- <a:audioFile r:link="{audio_rid}"/>- <p:extLst>- <p:ext uri="{{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}}">- <p14:media xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" r:embed="{media_rid}"/>- </p:ext>- </p:extLst>- </p:nvPr>- </p:nvPicPr>- <p:blipFill>- <a:blip r:embed="{poster_rid}"/>- <a:stretch><a:fillRect/></a:stretch>- </p:blipFill>- <p:spPr>- <a:xfrm>- <a:off x="0" y="0"/>- <a:ext cx="{AUDIO_MARKER_SIZE_EMU}" cy="{AUDIO_MARKER_SIZE_EMU}"/>- </a:xfrm>- <a:prstGeom prst="rect"><a:avLst/></a:prstGeom>- </p:spPr>- </p:pic>'''---def _next_timing_id(slide_xml: str) -> int:- ids = [int(value) for value in re.findall(r'<p:cTn[^>]*\sid="(\d+)"', slide_xml)]- return max(ids, default=1) + 1---def _create_audio_timing_xml(shape_id: int, ctn_id: int) -> str:- return f'''<p:audio>- <p:cMediaNode vol="80000">- <p:cTn id="{ctn_id}" fill="hold" display="0">- <p:stCondLst><p:cond delay="0"/></p:stCondLst>- </p:cTn>- <p:tgtEl><p:spTgt spid="{shape_id}"/></p:tgtEl>- </p:cMediaNode>- </p:audio>'''+ element = _create_audio_pic_element(+ shape_id,+ shape_name,+ audio_rid,+ media_rid,+ poster_rid,+ )+ return ET.tostring(element, encoding="unicode")+++def _numeric_ids(+ elements: Iterable[ET.Element],+ label: str,+ *,+ minimum: int = 0,+ maximum: int = MAX_OOXML_UNSIGNED_INT,+) -> list[int]:+ ids: list[int] = []+ seen: set[int] = set()+ for element in elements:+ raw_id = element.get("id")+ try:+ numeric_id = int(raw_id)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"narration source has invalid {label} id: {raw_id!r}") from exc+ if numeric_id < minimum:+ raise ValueError(+ f"narration source has {label} id below {minimum}: {numeric_id}"+ )+ if numeric_id > maximum:+ raise ValueError(+ f"narration source has {label} id above {maximum}: {numeric_id}"+ )+ if numeric_id in seen:+ raise ValueError(f"narration source has duplicate {label} id: {numeric_id}")+ ids.append(numeric_id)+ seen.add(numeric_id)+ return ids+++def _create_audio_timing_element(shape_id: int, ctn_id: int) -> ET.Element:+ audio = ET.Element(_qn(PML_NS, "audio"))+ media_node = ET.SubElement(+ audio,+ _qn(PML_NS, "cMediaNode"),+ {"vol": "80000"},+ )+ time_node = ET.SubElement(+ media_node,+ _qn(PML_NS, "cTn"),+ {"id": str(ctn_id), "fill": "hold", "display": "0"},+ )+ start_conditions = ET.SubElement(time_node, _qn(PML_NS, "stCondLst"))+ ET.SubElement(start_conditions, _qn(PML_NS, "cond"), {"delay": "0"})+ target = ET.SubElement(media_node, _qn(PML_NS, "tgtEl"))+ ET.SubElement(target, _qn(PML_NS, "spTgt"), {"spid": str(shape_id)})+ return audio+++def _direct_child(parent: ET.Element, tag: str, label: str) -> ET.Element:+ children = [child for child in parent if child.tag == tag]+ if len(children) != 1:+ raise ValueError(+ f"narration source must contain exactly one direct {label}; found {len(children)}"+ )+ return children[0]+++def _existing_timing_root(timing: ET.Element) -> ET.Element:+ children = list(timing)+ for tag, label in (+ (_qn(PML_NS, "tnLst"), "p:tnLst"),+ (_qn(PML_NS, "bldLst"), "p:bldLst"),+ (_qn(PML_NS, "extLst"), "p:extLst"),+ ):+ if sum(child.tag == tag for child in children) > 1:+ raise ValueError(f"narration source timing has multiple {label} elements")+ node_list = _direct_child(timing, _qn(PML_NS, "tnLst"), "p:timing/p:tnLst")+ node_index = children.index(node_list)+ for tag, label in (+ (_qn(PML_NS, "bldLst"), "p:bldLst"),+ (_qn(PML_NS, "extLst"), "p:extLst"),+ ):+ sibling = next((child for child in children if child.tag == tag), None)+ if sibling is not None and node_index > children.index(sibling):+ raise ValueError(f"narration source p:tnLst must precede {label}")+ timing_roots = [+ element+ for element in node_list.iter(_qn(PML_NS, "cTn"))+ if element.get("nodeType") == "tmRoot"+ ]+ if len(timing_roots) != 1:+ raise ValueError(+ "narration source timing must contain exactly one tmRoot; "+ f"found {len(timing_roots)}"+ )+ return timing_roots[0]+++def _new_timing(audio_timing: ET.Element, root_id: int) -> ET.Element:+ timing = ET.Element(_qn(PML_NS, "timing"))+ node_list = ET.SubElement(timing, _qn(PML_NS, "tnLst"))+ parallel = ET.SubElement(node_list, _qn(PML_NS, "par"))+ timing_root = ET.SubElement(+ parallel,+ _qn(PML_NS, "cTn"),+ {+ "id": str(root_id),+ "dur": "indefinite",+ "restart": "never",+ "nodeType": "tmRoot",+ },+ )+ child_nodes = ET.SubElement(timing_root, _qn(PML_NS, "childTnLst"))+ child_nodes.append(audio_timing)+ return timing+++def _root_extension_index(slide: ET.Element) -> int | None:+ extension_lists = [+ index+ for index, child in enumerate(slide)+ if child.tag == _qn(PML_NS, "extLst")+ ]+ if len(extension_lists) > 1:+ raise ValueError("narration source has multiple root p:extLst elements")+ if extension_lists and extension_lists[0] != len(slide) - 1:+ raise ValueError("narration source root p:extLst is not the last slide child")+ return extension_lists[0] if extension_lists else None+++def _validate_root_timing_position(slide: ET.Element, timing: ET.Element) -> None:+ children = list(slide)+ timing_index = children.index(timing)+ for tag, label in (+ (_qn(PML_NS, "cSld"), "p:cSld"),+ (_qn(PML_NS, "clrMapOvr"), "p:clrMapOvr"),+ ):+ siblings = [index for index, child in enumerate(children) if child.tag == tag]+ if len(siblings) > 1:+ raise ValueError(f"narration source has multiple root {label} elements")+ if siblings and siblings[0] > timing_index:+ raise ValueError(f"narration source root p:timing must follow {label}")+ extension_index = _root_extension_index(slide)+ if extension_index is not None and timing_index > extension_index:+ raise ValueError("narration source root p:timing must precede p:extLst")+++def _insert_root_timing(slide: ET.Element, timing: ET.Element) -> None:+ extension_index = _root_extension_index(slide)+ insert_at = extension_index if extension_index is not None else len(slide)+ slide.insert(insert_at, timing)def inject_narration(@@ -178,40 +397,75 @@ def inject_narration(poster_rid: str,) -> str:"""Inject a hidden narration media shape and slide-entry autoplay timing."""- audio_pic_xml = create_audio_pic_xml(- shape_id=shape_id,- shape_name=shape_name,- audio_rid=audio_rid,- media_rid=media_rid,- poster_rid=poster_rid,- )- slide_xml = slide_xml.replace("</p:spTree>", audio_pic_xml + "\n </p:spTree>", 1)-- audio_timing_xml = _create_audio_timing_xml(shape_id, _next_timing_id(slide_xml))- if "<p:timing>" not in slide_xml:- timing_xml = f''' <p:timing>- <p:tnLst>- <p:par>- <p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot">- <p:childTnLst>- {audio_timing_xml}- </p:childTnLst>- </p:cTn>- </p:par>- </p:tnLst>- </p:timing>'''- if "<p:extLst" in slide_xml:- return slide_xml.replace(- "<p:extLst",- timing_xml + "\n <p:extLst",- 1,- )- return slide_xml.replace("</p:sld>", timing_xml + "\n</p:sld>", 1)+ if isinstance(shape_id, bool) or not isinstance(shape_id, int) or shape_id <= 0:+ raise ValueError("narration shape_id must be a positive integer")+ if shape_id > MAX_OOXML_UNSIGNED_INT:+ raise ValueError(+ "narration shape_id exceeds the OOXML unsigned-integer limit: "+ f"{shape_id}"+ )++ root = parse_source_xml(slide_xml)+ if root.tag != _qn(PML_NS, "sld"):+ raise ValueError("narration source XML root must be p:sld")+ common_slide_data = _direct_child(root, _qn(PML_NS, "cSld"), "p:sld/p:cSld")+ shape_tree = _direct_child(+ common_slide_data,+ _qn(PML_NS, "spTree"),+ "p:cSld/p:spTree",+ )++ shape_ids = _numeric_ids(+ root.iter(_qn(PML_NS, "cNvPr")),+ "shape",+ minimum=1,+ )+ if shape_id in shape_ids:+ raise ValueError(f"narration shape id already exists on slide: {shape_id}")+ timing_ids = _numeric_ids(root.iter(_qn(PML_NS, "cTn")), "timing node")+ next_timing_id = max(timing_ids, default=0) + 1+ if next_timing_id > MAX_OOXML_UNSIGNED_INT:+ raise ValueError("narration source has no available timing node identifiers")++ root_timings = [child for child in root if child.tag == _qn(PML_NS, "timing")]+ all_timings = list(root.iter(_qn(PML_NS, "timing")))+ if len(all_timings) != len(root_timings):+ raise ValueError(+ "narration source contains non-root p:timing; only direct p:sld/p:timing "+ "can be merged safely"+ )+ if len(root_timings) > 1:+ raise ValueError(+ f"narration source has multiple root p:timing elements: {len(root_timings)}"+ )+ if not root_timings and next_timing_id + 1 > MAX_OOXML_UNSIGNED_INT:+ raise ValueError(+ "narration source has no identifiers available for a new timing root"+ )++ audio_picture = _create_audio_pic_element(+ shape_id,+ shape_name,+ audio_rid,+ media_rid,+ poster_rid,+ )+ shape_tree.append(audio_picture)++ if root_timings:+ _validate_root_timing_position(root, root_timings[0])+ timing_root = _existing_timing_root(root_timings[0])+ child_nodes = _direct_child(+ timing_root,+ _qn(PML_NS, "childTnLst"),+ "tmRoot/p:childTnLst",+ )+ child_nodes.append(_create_audio_timing_element(shape_id, next_timing_id))+ else:+ audio_timing = _create_audio_timing_element(shape_id, next_timing_id + 1)+ _insert_root_timing(root, _new_timing(audio_timing, next_timing_id))- pattern = re.compile(r'(<p:cTn\s+id="1"[^>]*>\s*<p:childTnLst>)', re.S)- if pattern.search(slide_xml):- return pattern.sub(r"\1\n " + audio_timing_xml, slide_xml, count=1)- return slide_xml.replace("</p:tnLst>", audio_timing_xml + "\n </p:tnLst>", 1)+ return serialize_source_xml(root, slide_xml).decode("utf-8")def apply_recorded_timing(diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.pyindex c39de8ab..e6a4f1b9 100644--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py@@ -12,6 +12,10 @@ from pathlib import Pathfrom typing import Anyfrom xml.etree import ElementTree as ET+from pptx_animations import (+ object_animation_fingerprint,+ validate_pptx_animation_package,+)from pptx_transitions import (parse_source_xml,serialize_source_xml,@@ -97,6 +101,9 @@ def apply_plan(new_rid = f"rId{next_rel_number + offset}"source_slide_xml = entries[source_ref.part_name]+ source_animation_fingerprint = object_animation_fingerprint(+ source_slide_xml+ )slide_root = parse_source_xml(source_slide_xml)replacements = item.get("replacements", [])if not isinstance(replacements, list):@@ -152,12 +159,20 @@ def apply_plan(next_embedding_number=next_embedding_number,)try:- entries[new_part] = serialize_source_xml(+ serialized_slide = serialize_source_xml(slide_root,source_slide_xml,)except ValueError as exc:raise RuntimeError(str(exc)) from exc+ if (+ object_animation_fingerprint(serialized_slide)+ != source_animation_fingerprint+ ):+ raise RuntimeError(+ f'Slide {source_slide} object animations changed during template fill'+ )+ entries[new_part] = serialized_slidenotes_text = str(item.get("notes") or item.get("speaker_notes") or "")entries[new_rels], note_entries = _slide_rels_with_notes(_xml_bytes(slide_rels_root),@@ -217,4 +232,13 @@ def apply_plan(raise RuntimeError(f"PPTX transition package validation failed: {exc}") from exc+ try:+ validate_pptx_animation_package(+ candidate_path,+ require_supported_effects=False,+ )+ except ValueError as exc:+ raise RuntimeError(+ f"PPTX animation/timing package validation failed: {exc}"+ ) from exccandidate_path.replace(output_path)diff --git a/skills/ppt-master/workflows/customize-animations.md b/skills/ppt-master/workflows/customize-animations.mdindex 78fa0568..80ecbd9c 100644--- a/skills/ppt-master/workflows/customize-animations.md+++ b/skills/ppt-master/workflows/customize-animations.md@@ -28,13 +28,17 @@ description: Customize default PPTX animations with per-slide and per-object timpython3 skills/ppt-master/scripts/animation_config.py list-groups <project_path>```-Output is one line per slide: `<slide_basename>: id1, id2, id3` — chrome-groups (`bg` / `*-header` / `*-footer` / `*-decor` / `nav` / `watermark` /-`logo` / `pagenumber`) are excluded because the exporter already pins them-to `none`. Use this as the source of truth when planning §3 and editing §4+Output is one line per slide: `<slide_basename>: id1, id2, id3` — default+chrome groups (`bg` / `*-header` / `*-footer` / `*-decor` / `nav` /+`watermark` / `logo` / `pagenumber`) are excluded from the ordinary target+list. Use this as the source of truth when planning §3 and editing §4— **do not read the full scaffold file unless you need it as an editingstarting point**.+An explicit sidecar entry may override only the marker-free legacy id-name+heuristic. A group carrying `data-pptx-layer` or an explicit static+role/placeholder marker can never animate, even when it is named explicitly.+If `animations.json` does not exist and you want a starting file to edit:```bash@@ -124,7 +128,7 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project_path>| `appear` | Visibility flip without motion || `fade` | Neutral entrance || `fly` | Fly in from bottom |-| `cut` | Cut in from left |+| `cut` | Legacy compatibility key; preserve its registered tuple exactly || `zoom` | Scale/zoom entrance || `wipe` | Wipe entrance || `split` | Split/barn entrance |@@ -145,7 +149,7 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project_path>| `swivel` | Swivel entrance || `auto` | Map effect from group id (chart→wipe, card-/step-/pillar-→fly, title/takeaway→fade); image-like ids (hero/figure-/image/img-/kpi) cycle zoom/dissolve/circle/box/diamond/wheel for visual variation; unmatched ids cycle fade/wipe/fly/zoom || `mixed` | Legacy 16-effect cycle by group order (first group fades, rest cycle the larger pool) |-| `random` | Random effect per animated group, sampled from the legacy pool |+| `random` | Stable seeded effect per animated group; `--conversion-trace` records resolved effects when diagnostics are enabled |**Start modes**:@@ -166,18 +170,25 @@ even when the values match `defaults`. This makes per-page rhythm visibleat a glance without mentally merging the inheritance chain. Group-leveloverrides remain opt-in — list only the groups that genuinely diverge fromthe slide's `animation` block. Chrome groups stay out (the exporter pins-them to `none`).+them to `none` by default). Name a legacy chrome-like id only when the user+explicitly wants that content animated and the SVG has no explicit structural+layer, role, or placeholder marker.++> Note: version-1 legacy sidecars may omit fields inside a listed slide and+> inherit them from `defaults`; the loader preserves that compatibility. This+> workflow writes complete new slide blocks, and validation still requires+> every current SVG stem to be present under `slides`.-`defaults` is still required: it supplies values for any slide not yet-present in `slides` (rare, e.g. mid-edit drafts) and acts as the single-source for the deck-wide baseline you copy into each slide block.+`defaults` is still required: it supplies the legacy inheritance baseline and+the deck-wide values copied into every complete new slide block.**Forbidden**:- Omitting a slide that exists in `svg_output/` — every produced slide must appear under `slides`- Writing a slide block with only `groups` and no `transition`/`animation`- Enumerating every content group in a slide just to restate the slide-level default effect-- Listing chrome groups (`bg`, `*-header`, `*-footer`, `*-decor`, `nav`, `watermark`, `logo`, `pagenumber`)+- Listing a group with `data-pptx-layer` or an explicit static role/placeholder marker+- Listing a legacy chrome-like id without an explicit, reviewed intent to override the name heuristic| Field | Behavior ||---|---|@@ -190,7 +201,7 @@ source for the deck-wide baseline you copy into each slide block.| `groups.<id>.effect` | Object-specific entrance effect, `auto`, `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; vary when semantic weight or pacing calls for it |+| `duration` | Per-group schedule duration in seconds; `appear` stays a 1ms visibility flip and uses this value only for subsequent `after-previous` spacing |**Canonical example — every slide carries explicit transition + animation;groups appear only when they diverge**:@@ -233,7 +244,7 @@ groups appear only when they diverge**:Notes:- `02_agenda` repeats `defaults` verbatim — this is intentional under the new rule so per-page rhythm is auditable in one read.- `03_market` and `07_hero_quote` only list the groups that diverge; `title`, `footer`, `bg`, `header` etc. are not enumerated.-- Chrome groups are never listed; the exporter pins them to `none`.+- Structural chrome groups are never listed. Legacy id-only chrome groups remain omitted unless an explicit reviewed override is required.**Forbidden — SVG pollution**: do not add `data-*` animation attributes to SVG files. Animation customization belongs in `animations.json`.@@ -251,7 +262,11 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project_path>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`. Unknown transition effects, NaN/Infinity, non-positive transition duration, and negative automatic advance fail validation; they never fall back to `fade`. A `defaults.transition.auto_advance` value participates in normal defaults resolution.+**Validation**: the exported native PPTX must reflect the object-level overrides. `--animation none` still disables all per-element animation and overrides `animations.json`. Unknown animation effects/modes/triggers; boolean, NaN, or Infinity numeric values; non-positive durations; negative delay/stagger; invalid order; missing slides/groups; and structural-layer targets fail validation. Transition validation remains strict as well. None of these failures substitutes a fallback effect or silently drops a requested target.++Generated export performs semantic read-back per slide, comparing row order, trigger, target, resolved effect tuple, duration, and offset. It then validates timing-tree placement, `p:cTn` ids, and `p:spTgt` references across the packaged PPTX. Stable `random` choices appear in the conversion trace when export enables `--conversion-trace`. Narration merges audio into the existing timing tree and must preserve these rows.++Direct-PPTX routes are preserve-only for object animation: they compare the source object-animation fingerprint before and after allowed edits, run structural package validation, and do not write, normalize, or claim ownership of effects. See [`pptx-animations.md`](../scripts/docs/pptx-animations.md) for the exact compatibility and OOXML contract.---@@ -265,3 +280,4 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path>- [x] Transition and object durations were chosen intentionally for the deck's pacing- [x] `animation_config.py validate` passed- [x] PPTX re-export completed with custom animation overrides+- [x] Generated animation semantic read-back and package validation passed