Skip to content

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

feat(pptx-transitions): unify transition behavior across export routes

hugohe384765307f9f0
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 3f8e85ee..46a5a23e 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -812,11 +812,11 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> claiming editability.
**Optional animation flags** (page transitions are on by default; per-element entrance is off by default — turn it on only when the user asks for it):
-- `-t <effect>` — page transition. Default `fade`. Options: `fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random` / `none`.
+- `-t <effect>` — page transition. Default `fade`. Options: `fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random` / `none`. `none` removes only the visual transition; an explicit automatic advance remains valid.
- `-a <effect>` — per-element entrance animation. **Default `none`** — pages appear as a whole, no auto-firing element builds (the unsolicited cascade reads as the "AI deck" tell). Opt in with `auto` (map effect from group id: chart→wipe, card-/step-/pillar-→fly, title/takeaway→fade; image-like ids `hero` / `figure-` / `image` / `img-` / `kpi` cycle a richer pool — zoom / dissolve / circle / box / diamond / wheel — so multiple images vary across the deck), a specific effect like `fade`, or `mixed` for the legacy 16-effect cycle. Requires top-level `<g id="...">` groups (already required by Executor).
- `--animation-trigger {on-click,with-previous,after-previous}` — Start mode (matches PowerPoint's animation-pane Start dropdown). Default `after-previous` (click-free cascade; pace via `--animation-stagger`). Use `on-click` for presenter-paced reveals, or `with-previous` for all-at-once.
- `--animation-config <path>` — optional object-level sidecar. Default: `<project_path>/animations.json` when present.
-- `--auto-advance <seconds>` — kiosk-style auto-play.
+- `--auto-advance <seconds>` — kiosk-style auto-play. Click remains enabled, so click or timer may advance the slide.
**Optional custom animations** (only when the user asks to tune animation order/effects/timing for specific objects):
diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.md
index 95f3ccc5..af350727 100644
--- a/skills/ppt-master/references/animations.md
+++ b/skills/ppt-master/references/animations.md
@@ -6,7 +6,7 @@ PPT Master's exported PPTX supports **page transitions** (slide-to-slide) and **
| Layer | Default | Why |
|---|---|---|
-| Page transition | `fade`, 0.4s | Calm baseline that suits most decks |
+| Page transition | CLI: `fade`, 0.4s | Calm baseline that suits most decks; the public Python builder retains its legacy 0.5s default |
| Per-element animation | **`none` (off)** | A page appears as a whole. Auto-firing element builds are an unsolicited "AI deck" tell, so element entrance is opt-in. Turn it on with `-a auto` (or another effect): effects map from group id (chart→wipe, card-/step-/pillar-→fly, title/takeaway→fade); image-like ids (`hero` / `figure-` / `image` / `img-` / `kpi`) cycle a richer visual pool (zoom / dissolve / circle / box / diamond / wheel) so multiple images vary across the deck; unmatched ids cycle a small fade/wipe/fly/zoom pool |
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`.
@@ -28,13 +28,19 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project>
python3 skills/ppt-master/scripts/svg_to_pptx.py <project>
```
-Minimal sidecar:
+Single-slide sidecar excerpt (repeat the complete slide block for every SVG in `svg_output/`):
```json
{
"version": 1,
+ "defaults": {
+ "transition": { "effect": "fade", "duration": 0.4 },
+ "animation": { "effect": "auto", "duration": 0.4, "stagger": 0.5, "trigger": "after-previous" }
+ },
"slides": {
"03_market": {
+ "transition": { "effect": "fade", "duration": 0.4 },
+ "animation": { "effect": "auto", "duration": 0.4, "stagger": 0.5, "trigger": "after-previous" },
"groups": {
"title": { "effect": "fade", "order": 1 },
"chart": { "effect": "wipe", "order": 2, "duration": 0.6 },
@@ -62,20 +68,25 @@ Rules:
# Pick a different effect
python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -t push --transition-duration 0.6
-# Disable
+# Remove the visual transition
python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -t none
# Auto-advance every 5 seconds (kiosk-style playback)
python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --auto-advance 5
+
+# Auto-advance with no visual transition
+python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -t none --auto-advance 5
```
Available effects: `fade`, `push`, `wipe`, `split`, `strips`, `cover`, `random`.
Flags:
-- `-t/--transition` — effect name, or `none` to disable. Default: `fade`.
+- `-t/--transition` — effect name, or `none` for no visual transition. Default: `fade`. `none` does not remove an explicitly configured automatic advance.
- `--transition-duration` — seconds, default `0.4`.
-- `--auto-advance` — seconds; omit for presenter-controlled advance.
+- `--auto-advance` — seconds; click remains enabled, so the slide advances on click or when the timer expires. Omit for presenter-controlled advance.
+
+**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
@@ -103,7 +114,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation mixed \
--animation-stagger 0.7 --animation-duration 0.5
# All groups animate in unison on slide entry
-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 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:
@@ -144,12 +155,13 @@ Executors should wrap logical sections in `<g id>` regardless of whether you pla
- **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.
- **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
| Goal | Command |
|---|---|
-| Disable transitions | `-t none` |
+| Remove visual transition | `-t none` |
| Change transition effect | `-t push` (or any from the list above) |
| Slower transition | `--transition-duration 0.8` |
| Auto-play | `--auto-advance 5` |
@@ -160,4 +172,7 @@ Executors should wrap logical sections in `<g id>` regardless of whether you pla
| Slower per-element reveal | `--animation-duration 0.5` |
| Wider gap in after-previous | `--animation-stagger 0.7` |
-See also: [`scripts/docs/svg-pipeline.md`](../scripts/docs/svg-pipeline.md) for the full `svg_to_pptx.py` reference.
+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.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 1bd0d10f..75ee5e78 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -46,6 +46,7 @@ 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) |
| 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 |
@@ -163,6 +164,7 @@ python3 scripts/update_repo.py --skip-pip
- [Conversion Tools](./docs/conversion.md)
- [Project Tools](./docs/project.md)
- [SVG Pipeline Tools](./docs/svg-pipeline.md)
+- [PPTX Transition Core](./docs/pptx-transitions.md)
- [Image Tools](./docs/image.md)
- [Troubleshooting](./docs/troubleshooting.md)
- [Skill Entry](../SKILL.md)
diff --git a/skills/ppt-master/scripts/animation_config.py b/skills/ppt-master/scripts/animation_config.py
index b3a08847..cd7ee2c5 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: E402
build_group_listing,
load_animation_config,
validate_animation_config,
+ validate_transition_config,
write_scaffold,
)
@@ -111,6 +112,11 @@ 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)
+ 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:
diff --git a/skills/ppt-master/scripts/docs/pptx-transitions.md b/skills/ppt-master/scripts/docs/pptx-transitions.md
new file mode 100644
index 00000000..cab55402
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/pptx-transitions.md
@@ -0,0 +1,148 @@
+# PPTX Transition Core
+
+The shared transition core owns page-transition vocabulary, slide-advance
+semantics, OOXML mutation, MCE preservation, package timing enablement, and
+read-back validation for every PPTX route.
+
+## 1. Ownership
+
+| Concern | Owner |
+|---|---|
+| Page transition registry | scripts/pptx_transitions.py |
+| In-slide object animation | scripts/pptx_animations.py |
+| Generated PPTX adapter | svg_to_pptx/pptx_package/builder.py |
+| Template Fill adapter | template_fill_pptx/transitions.py |
+| Native Enhance adapter | native_narration_pptx.py |
+| Public workflow | references/animations.md |
+
+**Hard rule**: adapters resolve route policy, then call the shared core. They
+must not build, replace, or patch a transition with route-local XML or regex.
+
+---
+
+## 2. Domain Model
+
+| Layer | Meaning | OOXML |
+|---|---|---|
+| Enter | How the current slide appears from the preceding slide | Transition effect child plus duration |
+| Advance | How the current slide leaves for the next slide | advClick and advTm |
+
+Enter policy:
+
+| Policy | Behavior |
+|---|---|
+| preserve | Keep the source visual transition, including unknown extensions |
+| replace | Write the requested supported effect |
+| none | Write no visual effect |
+
+Advance mode:
+
+| Mode | Behavior |
+|---|---|
+| preserve | Keep source advClick and advTm |
+| click | Click advance only |
+| after | Timed advance only |
+| both | Click or timed advance, whichever occurs first |
+| narration | Timed advance from audio duration plus padding; click disabled |
+
+**Hard rule**: enter=none may coexist with a timed advance. The valid result is
+a timing-only p:transition with no visual-effect child.
+
+---
+
+## 3. Compatibility Contract
+
+The Phase 1 registry preserves the established seven effects:
+
+| Effect | Required child and attributes |
+|---|---|
+| fade | p:fade |
+| push | p:push dir=r |
+| wipe | p:wipe dir=r |
+| split | p:split orient=horz dir=out |
+| strips | p:strips dir=rd |
+| cover | p:cover dir=r |
+| random | p:random |
+
+**Hard rule — no downgrade**:
+
+- Never rename or remove an established effect.
+- Never omit its established direction or split attributes.
+- Reject an unknown requested effect; never substitute fade.
+- Preserve an unknown source effect when the route selects preserve.
+- A future PowerPoint extension counts as successful only when the primary
+ Choice contains the requested effect. A fallback alone is not success.
+
+---
+
+## 4. Route Mapping
+
+| Route | Default enter | Default advance | Compatibility note |
+|---|---|---|---|
+| Generated PPTX CLI | fade, 0.4s | click | auto-advance maps to both |
+| Recorded narration | Preserve resolved enter | narration | none remains visually none |
+| Template Fill v1 | fade, 0.5s | click | keep preserves source; legacy advance_after maps to both |
+| Native Enhance v1 | Confirmed plan effect | Confirmed timing module | Disabled transitions preserve unless the v1 plan explicitly selected none |
+
+Template Fill and Native Enhance keep their v1 route defaults in Phase 1.
+The public `create_pptx_with_native_svg` Python API also retains its legacy
+0.5s default; the CLI explicitly passes 0.4s. Changing a default policy is a
+separate migration decision.
+
+---
+
+## 5. OOXML Rules
+
+**Slide child order**:
+
+~~~text
+p:cSld
+p:clrMapOvr
+p:transition or transition mc:AlternateContent
+p:timing
+p:extLst
+~~~
+
+One slide may contain at most one logical transition carrier:
+
+- one direct p:transition; or
+- one root-level mc:AlternateContent whose Choice/Fallback branches contain
+ p:transition.
+
+Mutation rules:
+
+| Operation | Direct transition | AlternateContent |
+|---|---|---|
+| preserve | Leave unchanged | Leave wrapper and branches unchanged |
+| advance-only | Patch direct attributes | Patch Choice and Fallback identically |
+| replace | Replace the direct carrier | Remove the whole wrapper, then write one carrier |
+| none | Remove visual carrier; retain timing-only carrier when needed | Remove the whole wrapper; retain timing-only carrier when needed |
+
+**MCE prefix rule**: Requires and Ignorable values contain textual prefix
+names. Serialization must retain bindings for those exact names. Renaming an
+effect prefix without updating these attributes corrupts compatibility.
+
+**Package timing rule**: when a route writes advTm, set
+ppt/presProps.xml p:presentationPr/p:showPr useTimings=1. Do not write showPr
+into ppt/presentation.xml.
+
+---
+
+## 6. Validation and Read-Back
+
+Reject:
+
+- unknown effect names;
+- non-finite values, including NaN and Infinity;
+- duration less than or equal to zero;
+- negative advance or narration padding;
+- booleans passed as numeric API values;
+- multiple logical transition carriers;
+- unresolved MCE Requires or Ignorable prefixes.
+
+Read-back must report the primary Choice effect separately from the fallback.
+It must also report carrier type, duration, click mode, and automatic advance
+time. Package validation must run after writing, not only before mutation.
+
+Use inline smoke commands and gitignored projects/_smoke_* artifacts. Do not
+add a tests directory or test_*.py files.
diff --git a/skills/ppt-master/scripts/native_narration_pptx.py b/skills/ppt-master/scripts/native_narration_pptx.py
index 691397eb..78f846a2 100644
--- a/skills/ppt-master/scripts/native_narration_pptx.py
+++ b/skills/ppt-master/scripts/native_narration_pptx.py
@@ -42,7 +42,15 @@ 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 TRANSITIONS, create_transition_xml # noqa: E402
+from pptx_transitions import ( # noqa: E402
+ AdvanceUpdate,
+ EnterUpdate,
+ TRANSITIONS,
+ apply_slide_motion_xml,
+ set_directory_use_timings,
+ validate_pptx_transition_package,
+ validate_seconds,
+)
from svg_to_pptx.pptx_package.builder import ( # noqa: E402
_add_default_content_type,
_append_relationship,
@@ -55,7 +63,6 @@ from svg_to_pptx.pptx_package.narration import ( # noqa: E402
IMAGE_REL_TYPE,
MEDIA_REL_TYPE,
NARRATION_EXTENSIONS,
- apply_recorded_timing,
inject_narration,
next_shape_id,
probe_audio_duration,
@@ -96,6 +103,20 @@ def _sanitize_slug(value: str) -> str:
return slug or "native_enhance"
+def _positive_seconds_arg(value: str) -> float:
+ try:
+ return validate_seconds(value, "transition duration", allow_zero=False)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError(str(exc)) from exc
+
+
+def _non_negative_seconds_arg(value: str) -> float:
+ try:
+ return validate_seconds(value, "narration padding", allow_zero=True)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError(str(exc)) from exc
+
+
def _read_json(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
@@ -276,39 +297,6 @@ def _add_notes_content_types(content_types: str, note_indices: set[int]) -> str:
return content_types
-def _set_transition_only(slide_xml: str, effect: str, duration: float) -> str:
- transition_xml = create_transition_xml(effect=effect, duration=duration)
- if re.search(r"<p:transition\b[^>]*/>", slide_xml):
- return re.sub(r"\s*<p:transition\b[^>]*/>", "\n" + transition_xml, slide_xml, count=1)
- if re.search(r"<p:transition\b[^>]*>.*?</p:transition>", slide_xml, re.S):
- return re.sub(
- r"\s*<p:transition\b[^>]*>.*?</p:transition>",
- "\n" + transition_xml,
- slide_xml,
- count=1,
- flags=re.S,
- )
- if "<p:timing>" in slide_xml:
- return slide_xml.replace("<p:timing>", transition_xml + "\n <p:timing>", 1)
- return slide_xml.replace("</p:sld>", transition_xml + "\n</p:sld>", 1)
-
-
-def _apply_recorded_timing_without_transition(slide_xml: str, advance_after: float) -> str:
- adv_ms = max(1, int(advance_after * 1000))
- transition_xml = f' <p:transition advTm="{adv_ms}"/>'
- slide_xml = re.sub(r"\s*<p:transition\b[^>]*/>", "", slide_xml, count=1)
- slide_xml = re.sub(
- r"\s*<p:transition\b[^>]*>.*?</p:transition>",
- "",
- slide_xml,
- count=1,
- flags=re.S,
- )
- if "<p:timing>" in slide_xml:
- return slide_xml.replace("<p:timing>", transition_xml + "\n <p:timing>", 1)
- return slide_xml.replace("</p:sld>", transition_xml + "\n</p:sld>", 1)
-
-
def _apply_notes(extract_dir: Path, slide: SlidePart, note_md: Path) -> None:
notes_text = markdown_to_plain_text(note_md.read_text(encoding="utf-8"))
if not notes_text:
@@ -346,10 +334,10 @@ def _apply_audio(
slide: SlidePart,
audio_path: Path,
*,
- transition: str,
- transition_duration: float,
+ enter: EnterUpdate,
+ timings_enabled: bool,
narration_padding: float,
-) -> None:
+) -> bool:
media_dir = extract_dir / "ppt" / "media"
media_dir.mkdir(parents=True, exist_ok=True)
@@ -380,20 +368,25 @@ def _apply_audio(
poster_rid=poster_rid,
)
- duration = probe_audio_duration(audio_path)
- if duration is None:
- raise RuntimeError(f"Unable to read narration duration with ffprobe: {audio_path}")
- advance_after = duration + narration_padding
- if transition == "none":
- slide_xml = _apply_recorded_timing_without_transition(slide_xml, advance_after)
- else:
- slide_xml = apply_recorded_timing(
+ advance = AdvanceUpdate(mode="preserve")
+ if timings_enabled:
+ duration = probe_audio_duration(audio_path)
+ if duration is None:
+ raise RuntimeError(f"Unable to read narration duration with ffprobe: {audio_path}")
+ advance = AdvanceUpdate(
+ mode="narration",
+ after=duration + narration_padding,
+ )
+
+ wrote_advance = False
+ if enter.policy != "preserve" or timings_enabled:
+ slide_xml, wrote_advance = apply_slide_motion_xml(
slide_xml,
- advance_after=advance_after,
- transition_duration=transition_duration,
- transition_effect=transition,
+ enter=enter,
+ advance=advance,
)
slide_xml_path.write_text(slide_xml, encoding="utf-8")
+ return timings_enabled and wrote_advance
def _update_content_types(extract_dir: Path, note_indices: set[int], audio_exts: set[str]) -> None:
@@ -441,6 +434,32 @@ def _enabled_modules(plan: dict) -> set[str]:
return enabled
+def _resolve_enter_update(
+ *,
+ cli_effect: str | None,
+ configured_effect: object,
+ transitions_enabled: bool,
+ duration: float,
+) -> EnterUpdate:
+ if cli_effect is None and not transitions_enabled:
+ if configured_effect == "none":
+ return EnterUpdate(policy="none", effect=None, duration=duration)
+ return EnterUpdate(policy="preserve", duration=duration)
+
+ effect = cli_effect if cli_effect is not None else configured_effect
+ if not isinstance(effect, str):
+ raise ValueError(f"transition effect must be a string: {effect!r}")
+ if effect == "none":
+ return EnterUpdate(policy="none", effect=None, duration=duration)
+ if effect not in TRANSITIONS:
+ valid = ", ".join(sorted(TRANSITIONS))
+ raise ValueError(
+ f"unknown transition effect {effect!r}; valid effects: {valid}, none"
+ )
+
+ return EnterUpdate(policy="replace", effect=effect, duration=duration)
+
+
def _plan_confirmed(plan: dict) -> bool:
return plan.get("status") == "confirmed"
@@ -661,32 +680,64 @@ def apply_project(args: argparse.Namespace) -> int:
return 1
modules = _enabled_modules(plan)
- transitions_cfg = (
- plan.get("modules", {}).get("transitions", {})
- if isinstance(plan.get("modules"), dict)
- else {}
- )
- timings_cfg = (
- plan.get("modules", {}).get("timings", {})
- if isinstance(plan.get("modules"), dict)
- else {}
- )
- transition = (
- args.transition
- or transitions_cfg.get("effect")
- or transition_cfg.get("effect")
- or "fade"
- )
- transition_duration = (
- args.transition_duration
- or transitions_cfg.get("duration")
- or float(transition_cfg.get("duration") or 0.5)
- )
- narration_padding = (
- args.narration_padding
- if args.narration_padding is not None
- else float(timings_cfg.get("narration_padding") or 0.4)
- )
+ modules_cfg = plan.get("modules") if isinstance(plan.get("modules"), dict) else {}
+ transitions_cfg = modules_cfg.get("transitions", {})
+ if not isinstance(transitions_cfg, dict):
+ transitions_cfg = {}
+ timings_cfg = modules_cfg.get("timings", {})
+ if not isinstance(timings_cfg, dict):
+ timings_cfg = {}
+
+ if "effect" in transitions_cfg:
+ configured_effect = transitions_cfg["effect"]
+ elif "effect" in transition_cfg:
+ configured_effect = transition_cfg["effect"]
+ else:
+ configured_effect = "fade"
+
+ if args.transition_duration is not None:
+ raw_transition_duration = args.transition_duration
+ elif "duration" in transitions_cfg:
+ raw_transition_duration = transitions_cfg["duration"]
+ elif "duration" in transition_cfg:
+ raw_transition_duration = transition_cfg["duration"]
+ else:
+ raw_transition_duration = 0.5
+
+ if args.narration_padding is not None:
+ raw_narration_padding = args.narration_padding
+ elif "narration_padding" in timings_cfg:
+ raw_narration_padding = timings_cfg["narration_padding"]
+ else:
+ raw_narration_padding = 0.4
+
+ try:
+ if args.transition is not None or "transitions" in modules:
+ transition_duration = validate_seconds(
+ raw_transition_duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ else:
+ transition_duration = 0.5
+ if "timings" in modules:
+ narration_padding = validate_seconds(
+ raw_narration_padding,
+ "narration padding",
+ allow_zero=True,
+ )
+ else:
+ narration_padding = 0.4
+ enter_update = _resolve_enter_update(
+ cli_effect=args.transition,
+ configured_effect=configured_effect,
+ transitions_enabled="transitions" in modules,
+ duration=transition_duration,
+ )
+ except ValueError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
apply_transition_without_audio = (
args.apply_transition_without_audio
or bool(transitions_cfg.get("apply_without_audio"))
@@ -710,6 +761,7 @@ def apply_project(args: argparse.Namespace) -> int:
audio_exts: set[str] = set()
audio_count = 0
transition_only_count = 0
+ wrote_auto_advance = False
for slide in slides:
note = _note_path(notes_dir, slide.index)
if "notes" in modules and note:
@@ -718,33 +770,55 @@ def apply_project(args: argparse.Namespace) -> int:
audio = _audio_path(audio_dir, slide.index)
if "audio" in modules and audio:
- _apply_audio(
+ wrote_auto_advance = _apply_audio(
extract_dir,
slide,
audio,
- transition=transition if "transitions" in modules else "none",
- transition_duration=transition_duration,
- narration_padding=narration_padding if "timings" in modules else 0,
- )
+ enter=enter_update,
+ timings_enabled="timings" in modules,
+ narration_padding=narration_padding,
+ ) or wrote_auto_advance
audio_exts.add(audio.suffix.lower())
audio_count += 1
continue
if (
- "transitions" in modules
- and apply_transition_without_audio
- and transition != "none"
+ apply_transition_without_audio
+ and enter_update.policy != "preserve"
):
slide_xml_path = extract_dir / slide.part_name
slide_xml = slide_xml_path.read_text(encoding="utf-8")
+ slide_xml, _uses_timings = apply_slide_motion_xml(
+ slide_xml,
+ enter=enter_update,
+ advance=AdvanceUpdate(mode="preserve"),
+ )
slide_xml_path.write_text(
- _set_transition_only(slide_xml, transition, transition_duration),
+ slide_xml,
encoding="utf-8",
)
transition_only_count += 1
_update_content_types(extract_dir, note_indices, audio_exts)
- _zip_dir(extract_dir, output_path)
+ if wrote_auto_advance:
+ set_directory_use_timings(extract_dir)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(
+ prefix="native-enhance-output-",
+ dir=output_path.parent,
+ ) as output_tmp:
+ candidate_path = Path(output_tmp) / output_path.name
+ _zip_dir(extract_dir, candidate_path)
+ try:
+ validate_pptx_transition_package(
+ candidate_path,
+ require_use_timings=wrote_auto_advance,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f"PPTX transition package validation failed: {exc}"
+ ) from exc
+ candidate_path.replace(output_path)
print(f"Output: {output_path}", file=sys.stderr)
print(f"Notes applied: {len(note_indices)}", file=sys.stderr)
@@ -813,8 +887,8 @@ def build_parser() -> argparse.ArgumentParser:
init.add_argument("--project-dir", default=None, help="explicit project directory")
init.add_argument("--projects-root", default="projects", help="projects root (default: projects)")
init.add_argument("--transition", default="fade", choices=sorted(TRANSITIONS.keys()))
- init.add_argument("--transition-duration", type=float, default=0.5)
- init.add_argument("--narration-padding", type=float, default=0.4)
+ init.add_argument("--transition-duration", type=_positive_seconds_arg, default=0.5)
+ init.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=0.4)
init.add_argument(
"--apply-transition-without-audio",
action="store_true",
@@ -825,8 +899,8 @@ def build_parser() -> argparse.ArgumentParser:
plan = subparsers.add_parser("plan", help="draft an enhancement module plan")
plan.add_argument("project_path", help="native enhancement project directory")
plan.add_argument("--transition", default="fade", choices=sorted(TRANSITIONS.keys()) + ["none"])
- plan.add_argument("--transition-duration", type=float, default=0.5)
- plan.add_argument("--narration-padding", type=float, default=0.4)
+ plan.add_argument("--transition-duration", type=_positive_seconds_arg, default=0.5)
+ plan.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=0.4)
plan.add_argument(
"--apply-transition-without-audio",
action="store_true",
@@ -839,8 +913,8 @@ def build_parser() -> argparse.ArgumentParser:
apply.add_argument("-o", "--output", default=None, help="output .pptx path")
apply.add_argument("--overwrite", action="store_true", help="overwrite output if it exists")
apply.add_argument("--transition", default=None, choices=sorted(TRANSITIONS.keys()) + ["none"])
- apply.add_argument("--transition-duration", type=float, default=None)
- apply.add_argument("--narration-padding", type=float, default=None)
+ apply.add_argument("--transition-duration", type=_positive_seconds_arg, default=None)
+ apply.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=None)
apply.add_argument("--force", action="store_true", help="apply without a confirmed enhancement plan")
apply.add_argument(
"--apply-transition-without-audio",
diff --git a/skills/ppt-master/scripts/pptx_animations.py b/skills/ppt-master/scripts/pptx_animations.py
index 565f5d68..c82d1144 100644
--- a/skills/ppt-master/scripts/pptx_animations.py
+++ b/skills/ppt-master/scripts/pptx_animations.py
@@ -43,96 +43,11 @@ import argparse
from typing import Optional, Dict, Any
from console_encoding import configure_utf8_stdio
+from pptx_transitions import TRANSITIONS, create_transition_xml
configure_utf8_stdio()
-# ============================================================================
-# Transition effect definitions
-# ============================================================================
-
-TRANSITIONS: Dict[str, Dict[str, Any]] = {
- 'fade': {
- 'name': 'Fade',
- 'element': 'fade',
- 'attrs': {},
- },
- 'push': {
- 'name': 'Push',
- 'element': 'push',
- 'attrs': {'dir': 'r'}, # Push from right
- },
- 'wipe': {
- 'name': 'Wipe',
- 'element': 'wipe',
- 'attrs': {'dir': 'r'}, # Wipe from right
- },
- 'split': {
- 'name': 'Split',
- 'element': 'split',
- 'attrs': {'orient': 'horz', 'dir': 'out'},
- },
- 'strips': {
- 'name': 'Strips',
- 'element': 'strips',
- 'attrs': {'dir': 'rd'}, # Diagonal wipe from bottom-right
- },
- 'cover': {
- 'name': 'Cover',
- 'element': 'cover',
- 'attrs': {'dir': 'r'},
- },
- 'random': {
- 'name': 'Random',
- 'element': 'random',
- 'attrs': {},
- },
-}
-
-def create_transition_xml(
- effect: str = 'fade',
- duration: float = 0.5,
- advance_after: Optional[float] = None
-) -> str:
- """
- Generate a slide transition effect XML fragment
-
- Args:
- effect: Transition effect name (fade/push/wipe/split/strips/cover/random)
- duration: Transition duration (seconds, precise to milliseconds)
- advance_after: Auto-advance interval (seconds); None means manual advance
-
- Returns:
- A <p:transition> element string insertable into slide XML
- """
- if effect not in TRANSITIONS:
- effect = 'fade'
-
- trans_info = TRANSITIONS[effect]
- element_name = trans_info['element']
- attrs = trans_info['attrs']
-
- # Build dur attribute (milliseconds, precise control via Office 2010 extension)
- dur_ms = int(duration * 1000)
- dur_attr = f' p14:dur="{dur_ms}" xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main"'
-
- # Build auto-advance attribute
- adv_attr = ''
- if advance_after is not None:
- adv_tm = int(advance_after * 1000) # Convert to milliseconds
- adv_attr = f' advTm="{adv_tm}"'
-
- # Build effect element attributes
- effect_attrs = ' '.join(f'{k}="{v}"' for k, v in attrs.items())
- if effect_attrs:
- effect_attrs = ' ' + effect_attrs
-
- # Generate XML
- return f''' <p:transition{dur_attr}{adv_attr}>
- <p:{element_name}{effect_attrs}/>
- </p:transition>'''
-
-
# ============================================================================
# Entrance animation definitions
# ============================================================================
diff --git a/skills/ppt-master/scripts/pptx_transitions.py b/skills/ppt-master/scripts/pptx_transitions.py
new file mode 100644
index 00000000..80ef4ed8
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_transitions.py
@@ -0,0 +1,1356 @@
+#!/usr/bin/env python3
+"""
+PPT Master - PPTX Transition Core
+
+Provide one strict transition registry plus shared OOXML read/write helpers for
+generated slides, template-filled PPTX files, and native PPTX enhancement.
+See references/animations.md for the public workflow and
+scripts/docs/pptx-transitions.md for the OOXML contract.
+
+Usage:
+ Import from PPT Master PPTX builders and direct-package workflows.
+
+Examples:
+ from pptx_transitions import AdvanceUpdate, EnterUpdate, apply_slide_motion
+
+Dependencies:
+ lxml (preferred for prefix-preserving source-PPTX mutation)
+"""
+
+from __future__ import annotations
+
+import io
+import math
+import posixpath
+import re
+import zipfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, MutableMapping
+from xml.etree import ElementTree as ET
+from xml.sax.saxutils import quoteattr
+
+try:
+ from lxml import etree as LET
+except ImportError:
+ LET = None
+
+
+PML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
+P14_NS = "http://schemas.microsoft.com/office/powerpoint/2010/main"
+MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
+CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+
+PRESENTATION_PROPS_PART = "ppt/presProps.xml"
+PRESENTATION_RELS_PART = "ppt/_rels/presentation.xml.rels"
+CONTENT_TYPES_PART = "[Content_Types].xml"
+PRESENTATION_PROPS_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps"
+)
+PRESENTATION_PROPS_CONTENT_TYPE = (
+ "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"
+)
+
+DEFAULT_TRANSITION = "fade"
+DEFAULT_TRANSITION_DURATION = 0.4
+MAX_OOXML_MILLISECONDS = 4_294_967_295
+
+
+TRANSITIONS: dict[str, dict[str, Any]] = {
+ "fade": {
+ "name": "Fade",
+ "element": "fade",
+ "attrs": {},
+ },
+ "push": {
+ "name": "Push",
+ "element": "push",
+ "attrs": {"dir": "r"},
+ },
+ "wipe": {
+ "name": "Wipe",
+ "element": "wipe",
+ "attrs": {"dir": "r"},
+ },
+ "split": {
+ "name": "Split",
+ "element": "split",
+ "attrs": {"orient": "horz", "dir": "out"},
+ },
+ "strips": {
+ "name": "Strips",
+ "element": "strips",
+ "attrs": {"dir": "rd"},
+ },
+ "cover": {
+ "name": "Cover",
+ "element": "cover",
+ "attrs": {"dir": "r"},
+ },
+ "random": {
+ "name": "Random",
+ "element": "random",
+ "attrs": {},
+ },
+}
+
+
+for _prefix, _uri in (("p", PML_NS), ("p14", P14_NS), ("mc", MC_NS)):
+ try:
+ ET.register_namespace(_prefix, _uri)
+ except (AttributeError, ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class EnterUpdate:
+ """Describe how the current slide's visual transition enters."""
+
+ policy: str = "replace"
+ effect: str | None = DEFAULT_TRANSITION
+ duration: float = DEFAULT_TRANSITION_DURATION
+
+
+@dataclass(frozen=True)
+class AdvanceUpdate:
+ """Describe how the current slide advances to the next slide."""
+
+ mode: str = "preserve"
+ after: float | None = None
+
+
+@dataclass(frozen=True)
+class TransitionSummary:
+ """Read-back summary of one slide's logical transition slot."""
+
+ carrier: str
+ logical_count: int
+ effect: str | None = None
+ effect_namespace: str | None = None
+ fallback_effect: str | None = None
+ fallback_effect_namespace: str | None = None
+ duration_ms: int | None = None
+ speed: str | None = None
+ advance_on_click: bool | None = None
+ advance_after_ms: int | None = None
+
+
+def _qn(namespace: str, tag: str) -> str:
+ return f"{{{namespace}}}{tag}"
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1]
+
+
+def _namespace_name(tag: str) -> str | None:
+ if tag.startswith("{") and "}" in tag:
+ return tag[1:].split("}", 1)[0]
+ return None
+
+
+def _value_repr(value: object) -> str:
+ try:
+ return repr(value)
+ except Exception:
+ return f"<{type(value).__name__}>"
+
+
+def validate_seconds(
+ value: object,
+ field: str,
+ *,
+ allow_zero: bool,
+) -> float:
+ """Return a finite seconds value or raise a field-specific error."""
+ display_value = _value_repr(value)
+ if isinstance(value, bool):
+ raise ValueError(f"{field} must be a finite number, not {display_value}")
+ try:
+ number = float(value)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise ValueError(
+ f"{field} must be a finite number: {display_value}"
+ ) from exc
+ if not math.isfinite(number):
+ raise ValueError(f"{field} must be finite: {display_value}")
+ if allow_zero:
+ if number < 0:
+ raise ValueError(f"{field} must be non-negative: {display_value}")
+ elif number <= 0:
+ raise ValueError(f"{field} must be greater than zero: {display_value}")
+ return number
+
+
+def normalize_transition_effect(effect: object, *, allow_none: bool = True) -> str | None:
+ """Return a known transition effect without silently changing it."""
+ if effect is None or effect == "none":
+ if allow_none:
+ return None
+ raise ValueError("transition effect is required")
+ if not isinstance(effect, str):
+ raise ValueError(f"transition effect must be a string: {effect!r}")
+ if effect not in TRANSITIONS:
+ valid = ", ".join(sorted(TRANSITIONS))
+ raise ValueError(
+ f"unknown transition effect {effect!r}; valid effects: {valid}, none"
+ )
+ return effect
+
+
+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 _effect_xml(effect: str) -> tuple[str, str]:
+ info = TRANSITIONS[effect]
+ attrs = " ".join(
+ f'{key}="{value}"'
+ for key, value in info.get("attrs", {}).items()
+ )
+ suffix = f" {attrs}" if attrs else ""
+ return str(info["element"]), suffix
+
+
+def create_transition_xml(
+ effect: str | None = DEFAULT_TRANSITION,
+ duration: float = 0.5,
+ advance_after: float | None = None,
+ advance_on_click: bool | None = None,
+) -> str:
+ """Build a legacy-compatible direct p:transition XML fragment."""
+ normalized_effect = normalize_transition_effect(effect)
+ attrs: list[str] = []
+ if normalized_effect is not None:
+ duration_ms = _seconds_to_ms(
+ duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ attrs.extend((
+ f'p14:dur="{duration_ms}"',
+ f'xmlns:p14="{P14_NS}"',
+ ))
+ if advance_on_click is not None:
+ if not isinstance(advance_on_click, bool):
+ raise ValueError(
+ "transition advance_on_click must be a boolean or None"
+ )
+ attrs.append(f'advClick="{1 if advance_on_click else 0}"')
+ if advance_after is not None:
+ advance_ms = _seconds_to_ms(
+ advance_after,
+ "transition advance_after",
+ allow_zero=True,
+ )
+ attrs.append(f'advTm="{advance_ms}"')
+
+ if normalized_effect is None and not attrs:
+ return ""
+
+ attr_text = " " + " ".join(attrs) if attrs else ""
+ if normalized_effect is None:
+ return f" <p:transition{attr_text}/>"
+
+ element_name, effect_attrs = _effect_xml(normalized_effect)
+ return (
+ f" <p:transition{attr_text}>\n"
+ f" <p:{element_name}{effect_attrs}/>\n"
+ " </p:transition>"
+ )
+
+
+def _is_lxml_element(element: object) -> bool:
+ return LET is not None and isinstance(element, LET._Element)
+
+
+def _new_element(
+ context: Any,
+ tag: str,
+ *,
+ nsmap: dict[str, str] | None = None,
+) -> Any:
+ if _is_lxml_element(context):
+ return LET.Element(tag, nsmap=nsmap)
+ return ET.Element(tag)
+
+
+def _build_transition_element(
+ context: Any,
+ *,
+ effect: str | None,
+ duration: float,
+ advance_after: float | None,
+ advance_on_click: bool | None,
+) -> Any | None:
+ normalized_effect = normalize_transition_effect(effect)
+ if (
+ normalized_effect is None
+ and advance_after is None
+ and advance_on_click is not False
+ ):
+ return None
+
+ nsmap = {"p": PML_NS}
+ if normalized_effect is not None:
+ nsmap["p14"] = P14_NS
+ transition = _new_element(
+ context,
+ _qn(PML_NS, "transition"),
+ nsmap=nsmap,
+ )
+
+ if normalized_effect is not None:
+ duration_ms = _seconds_to_ms(
+ duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ transition.set(_qn(P14_NS, "dur"), str(duration_ms))
+ if advance_on_click is not None:
+ if not isinstance(advance_on_click, bool):
+ raise ValueError(
+ "transition advance_on_click must be a boolean or None"
+ )
+ transition.set("advClick", "1" if advance_on_click else "0")
+ if advance_after is not None:
+ transition.set(
+ "advTm",
+ str(
+ _seconds_to_ms(
+ advance_after,
+ "transition advance_after",
+ allow_zero=True,
+ )
+ ),
+ )
+
+ if normalized_effect is not None:
+ info = TRANSITIONS[normalized_effect]
+ child = _new_element(context, _qn(PML_NS, str(info["element"])))
+ for key, value in info.get("attrs", {}).items():
+ child.set(key, str(value))
+ transition.append(child)
+ return transition
+
+
+def _transition_elements(carrier: Any) -> list[Any]:
+ if carrier.tag == _qn(PML_NS, "transition"):
+ return [carrier]
+ return [
+ element
+ for element in carrier.iter()
+ if element.tag == _qn(PML_NS, "transition")
+ ]
+
+
+def transition_carriers(slide_root: Any) -> list[Any]:
+ """Return root-level direct or AlternateContent transition carriers."""
+ carriers: list[Any] = []
+ for child in list(slide_root):
+ if child.tag == _qn(PML_NS, "transition"):
+ carriers.append(child)
+ continue
+ if child.tag != _qn(MC_NS, "AlternateContent"):
+ continue
+ if _transition_elements(child):
+ carriers.append(child)
+ return carriers
+
+
+def _primary_and_fallback(carrier: Any) -> tuple[Any | None, Any | None]:
+ if carrier.tag == _qn(PML_NS, "transition"):
+ return carrier, None
+
+ primary = None
+ fallback = None
+ for child in list(carrier):
+ transitions = _transition_elements(child)
+ if not transitions:
+ continue
+ if child.tag == _qn(MC_NS, "Choice") and primary is None:
+ primary = transitions[0]
+ elif child.tag == _qn(MC_NS, "Fallback") and fallback is None:
+ fallback = transitions[0]
+ if primary is None:
+ transitions = _transition_elements(carrier)
+ primary = transitions[0] if transitions else None
+ return primary, fallback
+
+
+def _effect_identity(transition: Any | None) -> tuple[str | None, str | None]:
+ if transition is None:
+ return None, None
+ for child in list(transition):
+ if child.tag == _qn(PML_NS, "sndAc"):
+ continue
+ return _local_name(child.tag), _namespace_name(child.tag)
+ return None, None
+
+
+def _int_attribute(element: Any | None, *names: str) -> int | None:
+ if element is None:
+ return None
+ for name in names:
+ raw = element.get(name)
+ if raw is None:
+ continue
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return None
+ return None
+
+
+def _bool_attribute(element: Any, name: str, default: bool) -> bool:
+ raw = element.get(name)
+ if raw is None:
+ return default
+ return str(raw).strip().lower() not in {"0", "false", "off", "no"}
+
+
+def read_slide_transition(slide_root: Any) -> TransitionSummary:
+ """Read the primary transition without mistaking fallback for success."""
+ carriers = transition_carriers(slide_root)
+ if not carriers:
+ return TransitionSummary(carrier="none", logical_count=0)
+
+ carrier = carriers[0]
+ primary, fallback = _primary_and_fallback(carrier)
+ effect, effect_namespace = _effect_identity(primary)
+ fallback_effect, fallback_namespace = _effect_identity(fallback)
+ carrier_name = (
+ "alternate-content"
+ if carrier.tag == _qn(MC_NS, "AlternateContent")
+ else "direct"
+ )
+ duration_ms = _int_attribute(
+ primary,
+ _qn(P14_NS, "dur"),
+ "dur",
+ )
+ advance_after_ms = _int_attribute(primary, "advTm")
+ return TransitionSummary(
+ carrier=carrier_name if len(carriers) == 1 else "multiple",
+ logical_count=len(carriers),
+ effect=effect,
+ effect_namespace=effect_namespace,
+ fallback_effect=fallback_effect,
+ fallback_effect_namespace=fallback_namespace,
+ duration_ms=duration_ms,
+ speed=primary.get("spd") if primary is not None else None,
+ advance_on_click=(
+ _bool_attribute(primary, "advClick", True)
+ if primary is not None
+ else None
+ ),
+ advance_after_ms=advance_after_ms,
+ )
+
+
+def _captured_advance(carriers: list[Any]) -> tuple[bool | None, float | None]:
+ if not carriers:
+ return None, None
+ primary, _fallback = _primary_and_fallback(carriers[0])
+ if primary is None:
+ return None, None
+ click = (
+ _bool_attribute(primary, "advClick", True)
+ if primary.get("advClick") is not None
+ else None
+ )
+ advance_ms = _int_attribute(primary, "advTm")
+ after = advance_ms / 1000 if advance_ms is not None else None
+ return click, after
+
+
+def _resolve_advance(
+ update: AdvanceUpdate,
+ *,
+ preserved_click: bool | None,
+ preserved_after: float | None,
+) -> tuple[bool | None, float | None]:
+ valid_modes = {"preserve", "click", "after", "both", "narration"}
+ if update.mode not in valid_modes:
+ raise ValueError(
+ f"unknown slide advance mode {update.mode!r}; "
+ f"valid modes: {', '.join(sorted(valid_modes))}"
+ )
+ if update.mode == "preserve":
+ return preserved_click, preserved_after
+ if update.mode == "click":
+ return True, None
+ if update.after is None:
+ raise ValueError(f"slide advance mode {update.mode!r} requires 'after'")
+ after = validate_seconds(
+ update.after,
+ "slide advance after",
+ allow_zero=True,
+ )
+ if update.mode == "both":
+ return True, after
+ return False, after
+
+
+def _set_advance_attributes(
+ transition: Any,
+ *,
+ advance_on_click: bool | None,
+ advance_after: float | None,
+) -> None:
+ if advance_on_click is None:
+ transition.attrib.pop("advClick", None)
+ else:
+ transition.set("advClick", "1" if advance_on_click else "0")
+ if advance_after is None:
+ transition.attrib.pop("advTm", None)
+ else:
+ transition.set(
+ "advTm",
+ str(
+ _seconds_to_ms(
+ advance_after,
+ "slide advance after",
+ allow_zero=True,
+ )
+ ),
+ )
+
+
+def _insert_transition_carrier(slide_root: Any, carrier: Any) -> None:
+ children = list(slide_root)
+ for index, child in enumerate(children):
+ if child.tag in {
+ _qn(PML_NS, "timing"),
+ _qn(PML_NS, "extLst"),
+ }:
+ slide_root.insert(index, carrier)
+ return
+
+ clr_map = None
+ for child in children:
+ if child.tag == _qn(PML_NS, "clrMapOvr"):
+ clr_map = child
+ if clr_map is not None:
+ slide_root.insert(list(slide_root).index(clr_map) + 1, carrier)
+ return
+ slide_root.append(carrier)
+
+
+def _apply_slide_motion_unchecked(
+ slide_root: Any,
+ *,
+ enter: EnterUpdate,
+ advance: AdvanceUpdate,
+) -> bool:
+ """Apply one resolved enter/advance update and return whether advTm remains."""
+ valid_policies = {"preserve", "replace", "none"}
+ if enter.policy not in valid_policies:
+ raise ValueError(
+ f"unknown transition enter policy {enter.policy!r}; "
+ f"valid policies: {', '.join(sorted(valid_policies))}"
+ )
+
+ carriers = transition_carriers(slide_root)
+ if len(carriers) > 1:
+ raise ValueError(
+ "slide contains multiple logical transition carriers; "
+ "refusing to preserve or replace an ambiguous source"
+ )
+
+ preserved_click, preserved_after = _captured_advance(carriers)
+ advance_on_click, advance_after = _resolve_advance(
+ advance,
+ preserved_click=preserved_click,
+ preserved_after=preserved_after,
+ )
+
+ if enter.policy == "preserve":
+ if advance.mode == "preserve":
+ return any(
+ transition.get("advTm") is not None
+ for carrier in carriers
+ for transition in _transition_elements(carrier)
+ )
+ if carriers:
+ for transition in _transition_elements(carriers[0]):
+ _set_advance_attributes(
+ transition,
+ advance_on_click=advance_on_click,
+ advance_after=advance_after,
+ )
+ return advance_after is not None
+
+ transition = _build_transition_element(
+ slide_root,
+ effect=None,
+ duration=enter.duration,
+ advance_after=advance_after,
+ advance_on_click=advance_on_click,
+ )
+ if transition is not None:
+ _insert_transition_carrier(slide_root, transition)
+ return advance_after is not None
+
+ effect = (
+ normalize_transition_effect(enter.effect, allow_none=False)
+ if enter.policy == "replace"
+ else None
+ )
+ duration = validate_seconds(
+ enter.duration,
+ "transition duration",
+ allow_zero=False,
+ )
+
+ if carriers:
+ slide_root.remove(carriers[0])
+
+ transition = _build_transition_element(
+ slide_root,
+ effect=effect,
+ duration=duration,
+ advance_after=advance_after,
+ advance_on_click=advance_on_click,
+ )
+ if transition is not None:
+ _insert_transition_carrier(slide_root, transition)
+ return advance_after is not None
+
+
+def _visual_identity(summary: TransitionSummary) -> tuple[Any, ...]:
+ return (
+ summary.carrier,
+ summary.logical_count,
+ summary.effect,
+ summary.effect_namespace,
+ summary.fallback_effect,
+ summary.fallback_effect_namespace,
+ summary.duration_ms,
+ summary.speed,
+ )
+
+
+def _validate_applied_motion(
+ slide_root: Any,
+ *,
+ before: TransitionSummary,
+ enter: EnterUpdate,
+ advance: AdvanceUpdate,
+) -> None:
+ errors = validate_slide_transition_structure(slide_root)
+ after = read_slide_transition(slide_root)
+
+ if enter.policy == "preserve":
+ if before.logical_count and _visual_identity(after) != _visual_identity(before):
+ errors.append("preserve policy changed the source visual transition")
+ elif not before.logical_count and after.effect is not None:
+ errors.append("preserve policy added a visual transition")
+ elif enter.policy == "replace":
+ effect = normalize_transition_effect(enter.effect, allow_none=False)
+ expected_duration = _seconds_to_ms(
+ enter.duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ if (
+ after.carrier != "direct"
+ or after.logical_count != 1
+ or after.effect != TRANSITIONS[effect]["element"]
+ or after.effect_namespace != PML_NS
+ or after.fallback_effect is not None
+ or after.duration_ms != expected_duration
+ ):
+ errors.append(
+ f"replace policy read-back does not match effect {effect!r}"
+ )
+ carriers = transition_carriers(slide_root)
+ if carriers:
+ primary, _fallback = _primary_and_fallback(carriers[0])
+ effect_children = [
+ child
+ for child in (list(primary) if primary is not None else [])
+ if child.tag != _qn(PML_NS, "sndAc")
+ ]
+ if effect_children:
+ actual_attrs = effect_children[0].attrib
+ for name, value in TRANSITIONS[effect].get("attrs", {}).items():
+ if actual_attrs.get(name) != str(value):
+ errors.append(
+ f"replace policy wrote invalid {effect} {name} attribute"
+ )
+ elif enter.policy == "none":
+ if after.effect is not None or after.fallback_effect is not None:
+ errors.append("none policy retained a visual transition")
+
+ preserved_click = (
+ before.advance_on_click
+ if before.advance_on_click is not None
+ else True
+ )
+ preserved_after = (
+ before.advance_after_ms / 1000
+ if before.advance_after_ms is not None
+ else None
+ )
+ expected_click, expected_after = _resolve_advance(
+ advance,
+ preserved_click=preserved_click,
+ preserved_after=preserved_after,
+ )
+ actual_click = (
+ after.advance_on_click
+ if after.advance_on_click is not None
+ else True
+ )
+ actual_after_ms = after.advance_after_ms
+ expected_after_ms = (
+ _seconds_to_ms(
+ expected_after,
+ "transition advance_after",
+ allow_zero=True,
+ )
+ if expected_after is not None
+ else None
+ )
+ if actual_click != expected_click or actual_after_ms != expected_after_ms:
+ errors.append("transition advance read-back does not match the requested mode")
+ if advance.mode != "preserve":
+ for carrier in transition_carriers(slide_root):
+ for transition in _transition_elements(carrier):
+ branch_click = _bool_attribute(transition, "advClick", True)
+ branch_after_ms = _int_attribute(transition, "advTm")
+ if (
+ branch_click != expected_click
+ or branch_after_ms != expected_after_ms
+ ):
+ errors.append(
+ "transition fallback advance does not match the requested mode"
+ )
+ break
+
+ if errors:
+ raise ValueError("; ".join(errors))
+
+
+def apply_slide_motion(
+ slide_root: Any,
+ *,
+ enter: EnterUpdate,
+ advance: AdvanceUpdate,
+) -> bool:
+ """Apply and immediately read back one resolved transition update."""
+ before = read_slide_transition(slide_root)
+ uses_timings = _apply_slide_motion_unchecked(
+ slide_root,
+ enter=enter,
+ advance=advance,
+ )
+ _validate_applied_motion(
+ slide_root,
+ before=before,
+ enter=enter,
+ advance=advance,
+ )
+ return uses_timings
+
+
+def _xml_declaration(source: str) -> str:
+ match = re.match(r"\s*(<\?xml[^?]*\?>)", source)
+ return match.group(1) if match else ""
+
+
+def _serialize_lxml_like(root: Any, source: str) -> str:
+ body = LET.tostring(root, encoding="unicode", pretty_print=False)
+ declaration = _xml_declaration(source)
+ return f"{declaration}\n{body}" if declaration else body
+
+
+def namespace_bindings(xml_data: str | bytes) -> dict[str, str]:
+ """Return source prefix bindings without changing the document."""
+ data = xml_data.encode("utf-8") if isinstance(xml_data, str) else xml_data
+ bindings: dict[str, str] = {}
+ for _event, (prefix, uri) in ET.iterparse(
+ io.BytesIO(data),
+ events=("start-ns",),
+ ):
+ bindings[prefix or ""] = uri
+ return bindings
+
+
+def register_source_namespaces(xml_data: str | bytes) -> dict[str, str]:
+ """Register source prefixes before stdlib ElementTree re-serialization."""
+ bindings = namespace_bindings(xml_data)
+ for prefix, uri in bindings.items():
+ if prefix == "xml":
+ continue
+ try:
+ ET.register_namespace(prefix, uri)
+ except (AttributeError, ValueError):
+ continue
+ return bindings
+
+
+def parse_source_xml(xml_data: str | bytes) -> ET.Element:
+ """Parse XML after registering its original namespace prefixes."""
+ data = xml_data.encode("utf-8") if isinstance(xml_data, str) else xml_data
+ register_source_namespaces(data)
+ return ET.fromstring(data)
+
+
+def _required_mce_prefixes(root: Any) -> set[str]:
+ prefixes = set(str(root.get(_qn(MC_NS, "Ignorable")) or "").split())
+ for element in root.iter():
+ if element.tag == _qn(MC_NS, "Choice"):
+ prefixes.update(str(element.get("Requires") or "").split())
+ return {prefix for prefix in prefixes if prefix}
+
+
+def _inject_root_namespace_declarations(
+ xml_data: bytes,
+ *,
+ bindings: dict[str, str],
+ prefixes: set[str],
+) -> bytes:
+ text = xml_data.decode("utf-8")
+ declaration_end = text.find("?>")
+ root_start = text.find("<", declaration_end + 2 if declaration_end >= 0 else 0)
+ root_end = text.find(">", root_start)
+ if root_start < 0 or root_end < 0:
+ raise ValueError("unable to locate serialized XML root element")
+
+ opening = text[root_start:root_end]
+ declarations: list[str] = []
+ for prefix in sorted(prefixes):
+ uri = bindings.get(prefix)
+ if not uri:
+ raise ValueError(
+ f"MCE prefix {prefix!r} has no namespace binding in source XML"
+ )
+ if re.search(rf"\bxmlns:{re.escape(prefix)}\s*=", opening):
+ continue
+ declarations.append(f" xmlns:{prefix}={quoteattr(uri)}")
+ if declarations:
+ text = text[:root_end] + "".join(declarations) + text[root_end:]
+ return text.encode("utf-8")
+
+
+def validate_mce_prefixes(xml_data: str | bytes) -> list[str]:
+ """Return unresolved MCE Requires/Ignorable prefix errors."""
+ if LET is None:
+ return []
+ data = xml_data.encode("utf-8") if isinstance(xml_data, str) else xml_data
+ try:
+ root = LET.fromstring(data)
+ except LET.XMLSyntaxError as exc:
+ return [f"invalid XML: {exc}"]
+
+ errors: list[str] = []
+ ignorable = str(root.get(_qn(MC_NS, "Ignorable")) or "").split()
+ for prefix in ignorable:
+ if prefix not in root.nsmap:
+ errors.append(f"mc:Ignorable prefix is not bound: {prefix}")
+ for choice in root.iter(_qn(MC_NS, "Choice")):
+ for prefix in str(choice.get("Requires") or "").split():
+ if prefix not in choice.nsmap:
+ errors.append(f"mc:Choice Requires prefix is not bound: {prefix}")
+ return errors
+
+
+def serialize_source_xml(root: ET.Element, source_xml: str | bytes) -> bytes:
+ """Serialize stdlib XML while retaining MCE prefix bindings."""
+ expected_transition = (
+ read_slide_transition(root)
+ if root.tag == _qn(PML_NS, "sld")
+ else None
+ )
+ source = (
+ source_xml.encode("utf-8")
+ if isinstance(source_xml, str)
+ else source_xml
+ )
+ bindings = register_source_namespaces(source)
+ prefixes = _required_mce_prefixes(root)
+ serialized = ET.tostring(root, encoding="utf-8", xml_declaration=True)
+ serialized = _inject_root_namespace_declarations(
+ serialized,
+ bindings=bindings,
+ prefixes=prefixes,
+ )
+ errors = validate_mce_prefixes(serialized)
+ if expected_transition is not None:
+ errors.extend(validate_slide_transition_xml(serialized))
+ actual_transition = read_slide_transition_xml(serialized)
+ if actual_transition != expected_transition:
+ errors.append("slide transition changed during XML serialization")
+ if errors:
+ raise ValueError("; ".join(errors))
+ return serialized
+
+
+def apply_slide_motion_xml(
+ slide_xml: str,
+ *,
+ enter: EnterUpdate,
+ advance: AdvanceUpdate,
+) -> tuple[str, bool]:
+ """Apply motion to source XML while preserving MCE namespace prefixes."""
+ source_bytes = slide_xml.encode("utf-8")
+ if LET is not None:
+ parser = LET.XMLParser(
+ remove_blank_text=False,
+ resolve_entities=False,
+ no_network=True,
+ )
+ root = LET.fromstring(source_bytes, parser)
+ uses_timings = apply_slide_motion(
+ root,
+ enter=enter,
+ advance=advance,
+ )
+ output = _serialize_lxml_like(root, slide_xml)
+ else:
+ root = parse_source_xml(source_bytes)
+ uses_timings = apply_slide_motion(
+ root,
+ enter=enter,
+ advance=advance,
+ )
+ output = serialize_source_xml(root, source_bytes).decode("utf-8")
+
+ expected_transition = read_slide_transition(root)
+ errors = validate_slide_transition_xml(output)
+ if read_slide_transition_xml(output) != expected_transition:
+ errors.append("slide transition changed during XML serialization")
+ if errors:
+ raise ValueError("; ".join(errors))
+ return output, uses_timings
+
+
+def read_slide_transition_xml(slide_xml: str | bytes) -> TransitionSummary:
+ """Read a transition summary from raw slide XML."""
+ data = (
+ slide_xml.encode("utf-8")
+ if isinstance(slide_xml, str)
+ else slide_xml
+ )
+ if LET is not None:
+ root = LET.fromstring(data)
+ else:
+ root = parse_source_xml(data)
+ return read_slide_transition(root)
+
+
+def validate_generated_transition_xml(
+ slide_xml: str | bytes,
+ *,
+ effect: str | None,
+ duration: object,
+ advance_on_click: bool | None,
+ advance_after: object | None,
+) -> TransitionSummary:
+ """Validate a generated direct transition against its resolved settings."""
+ data = slide_xml.encode("utf-8") if isinstance(slide_xml, str) else slide_xml
+ root = LET.fromstring(data) if LET is not None else parse_source_xml(data)
+ errors = validate_slide_transition_structure(root) + validate_mce_prefixes(data)
+ summary = read_slide_transition(root)
+ normalized_effect = normalize_transition_effect(effect)
+ expected_click = True if advance_on_click is None else advance_on_click
+ if not isinstance(expected_click, bool):
+ errors.append("transition advance_on_click must be a boolean or None")
+ expected_after_ms = (
+ _seconds_to_ms(
+ advance_after,
+ "transition advance_after",
+ allow_zero=True,
+ )
+ if advance_after is not None
+ else None
+ )
+ expects_carrier = (
+ normalized_effect is not None
+ or expected_after_ms is not None
+ or expected_click is False
+ )
+
+ if not expects_carrier:
+ if summary.logical_count != 0:
+ errors.append("generated slide unexpectedly contains a transition carrier")
+ else:
+ expected_duration_ms = (
+ _seconds_to_ms(
+ duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ if normalized_effect is not None
+ else None
+ )
+ expected_effect = (
+ str(TRANSITIONS[normalized_effect]["element"])
+ if normalized_effect is not None
+ else None
+ )
+ if (
+ summary.carrier != "direct"
+ or summary.logical_count != 1
+ or summary.effect != expected_effect
+ or summary.fallback_effect is not None
+ or summary.duration_ms != expected_duration_ms
+ or summary.advance_on_click != expected_click
+ or summary.advance_after_ms != expected_after_ms
+ ):
+ errors.append("generated transition read-back does not match its settings")
+ if normalized_effect is not None:
+ carriers = transition_carriers(root)
+ if carriers:
+ primary, _fallback = _primary_and_fallback(carriers[0])
+ effect_children = [
+ child
+ for child in (list(primary) if primary is not None else [])
+ if child.tag != _qn(PML_NS, "sndAc")
+ ]
+ expected_attrs = TRANSITIONS[normalized_effect].get("attrs", {})
+ if not effect_children:
+ errors.append("generated transition has no visual effect child")
+ else:
+ for name, value in expected_attrs.items():
+ if effect_children[0].get(name) != str(value):
+ errors.append(
+ f"generated {normalized_effect} transition has "
+ f"invalid {name} attribute"
+ )
+
+ if errors:
+ raise ValueError("; ".join(errors))
+ return summary
+
+
+def validate_pptx_transition_package(
+ pptx_path: Path,
+ *,
+ require_use_timings: bool = False,
+) -> dict[str, TransitionSummary]:
+ """Read back and validate every slide transition in a written PPTX.
+
+ Return summaries keyed by package part name. Raise ``ValueError`` when the
+ ZIP, slide transition structure, MCE bindings, or required presentation
+ timing metadata is invalid.
+ """
+ errors: list[str] = []
+ summaries: dict[str, TransitionSummary] = {}
+ try:
+ with zipfile.ZipFile(pptx_path, "r") as package:
+ names = package.namelist()
+ part_counts: dict[str, int] = {}
+ for name in names:
+ part_counts[name] = part_counts.get(name, 0) + 1
+ duplicate_names = sorted(
+ name for name, count in part_counts.items() if count > 1
+ )
+ if duplicate_names:
+ errors.append(
+ "duplicate package parts: " + ", ".join(duplicate_names)
+ )
+
+ slide_names = sorted(
+ name
+ for name in names
+ if name.startswith("ppt/slides/slide")
+ and name.endswith(".xml")
+ )
+ for slide_name in slide_names:
+ slide_xml = package.read(slide_name)
+ for problem in validate_slide_transition_xml(slide_xml):
+ errors.append(f"{slide_name}: {problem}")
+ try:
+ summaries[slide_name] = read_slide_transition_xml(slide_xml)
+ except Exception as exc:
+ errors.append(f"{slide_name}: transition read-back failed: {exc}")
+
+ if require_use_timings:
+ errors.extend(_validate_package_use_timings(package, names))
+ except (OSError, zipfile.BadZipFile, KeyError, ET.ParseError) as exc:
+ errors.append(f"unable to read PPTX transition package: {exc}")
+
+ if errors:
+ raise ValueError("; ".join(errors))
+ return summaries
+
+
+def _validate_package_use_timings(
+ package: zipfile.ZipFile,
+ names: list[str],
+) -> list[str]:
+ errors: list[str] = []
+ required_parts = {
+ PRESENTATION_RELS_PART,
+ CONTENT_TYPES_PART,
+ }
+ missing = sorted(required_parts - set(names))
+ if missing:
+ return ["timed advance is missing package parts: " + ", ".join(missing)]
+
+ rels_root = ET.fromstring(package.read(PRESENTATION_RELS_PART))
+ props_part = _presentation_props_part(rels_root)
+ if props_part is None:
+ return ["presentation relationships do not reference presentation properties"]
+ if props_part not in names:
+ return [f"presentation properties part is missing: {props_part}"]
+
+ props_root = ET.fromstring(package.read(props_part))
+ show_properties = props_root.find(_qn(PML_NS, "showPr"))
+ if (
+ show_properties is None
+ or show_properties.get("useTimings") not in {"1", "true", "on"}
+ ):
+ errors.append(f"{props_part} must set p:showPr@useTimings=1")
+
+ content_root = ET.fromstring(package.read(CONTENT_TYPES_PART))
+ package_part_name = "/" + props_part.lstrip("/")
+ if not any(
+ override.get("PartName") == package_part_name
+ and override.get("ContentType") == PRESENTATION_PROPS_CONTENT_TYPE
+ for override in content_root
+ ):
+ errors.append(f"[Content_Types].xml must declare {props_part}")
+ return errors
+
+
+def validate_slide_transition_structure(slide_root: Any) -> list[str]:
+ """Return logical-carrier and schema-order errors for one slide root."""
+ errors: list[str] = []
+ children = list(slide_root)
+ carriers = transition_carriers(slide_root)
+ if len(carriers) > 1:
+ errors.append(
+ f"slide has {len(carriers)} logical transition carriers; expected at most 1"
+ )
+ if carriers:
+ carrier_index = children.index(carriers[0])
+ common_slide = next(
+ (
+ child
+ for child in children
+ if child.tag == _qn(PML_NS, "cSld")
+ ),
+ None,
+ )
+ if common_slide is None:
+ errors.append("slide with transition carrier must contain p:cSld")
+ elif carrier_index < children.index(common_slide):
+ errors.append("transition carrier must follow p:cSld")
+ color_map = next(
+ (
+ child
+ for child in children
+ if child.tag == _qn(PML_NS, "clrMapOvr")
+ ),
+ None,
+ )
+ if color_map is not None and carrier_index < children.index(color_map):
+ errors.append("transition carrier must follow p:clrMapOvr")
+ for tag in ("timing", "extLst"):
+ element = next(
+ (
+ child
+ for child in children
+ if child.tag == _qn(PML_NS, tag)
+ ),
+ None,
+ )
+ if element is not None and carrier_index > children.index(element):
+ errors.append(f"transition carrier must precede p:{tag}")
+
+ for carrier in carriers:
+ if carrier.tag != _qn(MC_NS, "AlternateContent"):
+ continue
+ choices = [
+ child
+ for child in list(carrier)
+ if child.tag == _qn(MC_NS, "Choice")
+ ]
+ if not choices:
+ errors.append("mc:AlternateContent transition must contain mc:Choice")
+ for branch_name in ("Choice", "Fallback"):
+ branches = [
+ child
+ for child in list(carrier)
+ if child.tag == _qn(MC_NS, branch_name)
+ ]
+ for branch in branches:
+ count = len(_transition_elements(branch))
+ if count != 1:
+ errors.append(
+ f"mc:{branch_name} must contain exactly one p:transition; "
+ f"found {count}"
+ )
+ return errors
+
+
+def validate_slide_transition_xml(slide_xml: str | bytes) -> list[str]:
+ """Validate raw slide transition structure and MCE prefix bindings."""
+ data = slide_xml.encode("utf-8") if isinstance(slide_xml, str) else slide_xml
+ try:
+ if LET is not None:
+ root = LET.fromstring(data)
+ else:
+ root = parse_source_xml(data)
+ except Exception as exc:
+ return [f"invalid slide XML: {exc}"]
+ return validate_slide_transition_structure(root) + validate_mce_prefixes(data)
+
+
+def _insert_show_properties(root: Any, element: Any) -> None:
+ for index, child in enumerate(list(root)):
+ if child.tag in {
+ _qn(PML_NS, "clrMru"),
+ _qn(PML_NS, "extLst"),
+ }:
+ root.insert(index, element)
+ return
+ root.append(element)
+
+
+def _next_relationship_id(rels_xml: str) -> str:
+ root = ET.fromstring(rels_xml)
+ numbers: list[int] = []
+ for relationship in root:
+ match = re.fullmatch(r"rId(\d+)", relationship.get("Id", ""))
+ if match is not None:
+ numbers.append(int(match.group(1)))
+ return f"rId{max(numbers, default=0) + 1}"
+
+
+def _presentation_props_part(rels_root: Any) -> str | None:
+ for relationship in rels_root:
+ if relationship.get("Type") != PRESENTATION_PROPS_REL_TYPE:
+ continue
+ if relationship.get("TargetMode") == "External":
+ raise ValueError("presentation properties relationship must be internal")
+ target = str(relationship.get("Target") or "").replace("\\", "/")
+ if not target:
+ raise ValueError("presentation properties relationship has no target")
+ if target.startswith("/"):
+ part_name = target.lstrip("/")
+ else:
+ part_name = posixpath.normpath(posixpath.join("ppt", target))
+ if part_name == ".." or part_name.startswith("../"):
+ raise ValueError(
+ "presentation properties relationship escapes the PPTX package"
+ )
+ return part_name
+ return None
+
+
+def _ensure_presentation_props_references(
+ parts: MutableMapping[str, bytes],
+ *,
+ props_part: str,
+) -> None:
+ rels_source = parts[PRESENTATION_RELS_PART]
+ rels_root = parse_source_xml(rels_source)
+ if _presentation_props_part(rels_root) is None:
+ ET.SubElement(
+ rels_root,
+ _qn(PACKAGE_REL_NS, "Relationship"),
+ {
+ "Id": _next_relationship_id(rels_source.decode("utf-8")),
+ "Type": PRESENTATION_PROPS_REL_TYPE,
+ "Target": "presProps.xml",
+ },
+ )
+ parts[PRESENTATION_RELS_PART] = serialize_source_xml(
+ rels_root,
+ rels_source,
+ )
+
+ content_source = parts[CONTENT_TYPES_PART]
+ content_root = parse_source_xml(content_source)
+ part_name = "/" + props_part.lstrip("/")
+ if not any(
+ override.get("PartName") == part_name
+ and override.get("ContentType") == PRESENTATION_PROPS_CONTENT_TYPE
+ for override in content_root
+ ):
+ ET.SubElement(
+ content_root,
+ _qn(CONTENT_TYPES_NS, "Override"),
+ {
+ "PartName": part_name,
+ "ContentType": PRESENTATION_PROPS_CONTENT_TYPE,
+ },
+ )
+ parts[CONTENT_TYPES_PART] = serialize_source_xml(
+ content_root,
+ content_source,
+ )
+
+
+def set_package_use_timings(
+ parts: MutableMapping[str, bytes],
+ *,
+ enabled: bool = True,
+) -> None:
+ """Set presentation-wide timing playback in ppt/presProps.xml."""
+ rels_root = parse_source_xml(parts[PRESENTATION_RELS_PART])
+ existing_props_part = _presentation_props_part(rels_root)
+ props_part = existing_props_part or PRESENTATION_PROPS_PART
+ if props_part in parts:
+ source = parts[props_part]
+ root = parse_source_xml(source)
+ else:
+ if existing_props_part is not None:
+ raise ValueError(
+ f"presentation properties part is missing: {props_part}"
+ )
+ source = (
+ f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
+ f'<p:presentationPr xmlns:p="{PML_NS}"/>'
+ ).encode("utf-8")
+ root = parse_source_xml(source)
+
+ show_properties = root.find(_qn(PML_NS, "showPr"))
+ if show_properties is None:
+ show_properties = ET.Element(_qn(PML_NS, "showPr"))
+ _insert_show_properties(root, show_properties)
+ show_properties.set("useTimings", "1" if enabled else "0")
+ parts[props_part] = serialize_source_xml(root, source)
+ _ensure_presentation_props_references(parts, props_part=props_part)
+
+
+def set_directory_use_timings(
+ extract_dir: Path,
+ *,
+ enabled: bool = True,
+) -> None:
+ """Set presentation timing playback in an extracted PPTX directory."""
+ part_names = {
+ PRESENTATION_RELS_PART,
+ CONTENT_TYPES_PART,
+ }
+ rels_source = (extract_dir / PRESENTATION_RELS_PART).read_bytes()
+ rels_root = parse_source_xml(rels_source)
+ props_part = _presentation_props_part(rels_root) or PRESENTATION_PROPS_PART
+ if (extract_dir / props_part).is_file():
+ part_names.add(props_part)
+ parts = {
+ name: (extract_dir / name).read_bytes()
+ for name in part_names
+ }
+ set_package_use_timings(parts, enabled=enabled)
+ for name, payload in parts.items():
+ path = extract_dir / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(payload)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
index 57ecf3f7..9eaedf8c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
@@ -12,11 +12,12 @@ from xml.etree import ElementTree as ET
from .drawingml.utils import SVG_NS
from .semantic_markers import is_static_page_frame
+from pptx_transitions import TRANSITIONS, validate_seconds
+
try:
- from pptx_animations import ANIMATIONS, TRANSITIONS
+ from pptx_animations import ANIMATIONS
except ImportError:
ANIMATIONS = {}
- TRANSITIONS = {}
_NON_VISUAL_TAGS = frozenset(('defs', 'title', 'desc', 'metadata', 'style'))
@@ -143,6 +144,61 @@ def _valid_transition_effect(effect: str) -> bool:
return effect == 'none' or effect in TRANSITIONS
+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', {})
+ if not isinstance(defaults, dict):
+ errors.append('animations.json field "defaults" must be an object')
+ else:
+ errors.extend(_transition_scope_errors(defaults, 'defaults'))
+
+ slides = config.get('slides', {})
+ if not isinstance(slides, dict):
+ errors.append('animations.json field "slides" must be an object')
+ return 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(
+ _transition_scope_errors(slide_cfg, f'slide "{slide_name}"')
+ )
+ return errors
+
+
+def _transition_scope_errors(scope: dict[str, Any], label: 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] = []
+ if 'effect' in transition:
+ effect = transition['effect']
+ if not isinstance(effect, str):
+ errors.append(
+ f'animations.json {label} transition effect must be a string'
+ )
+ elif not _valid_transition_effect(effect):
+ errors.append(
+ f'animations.json {label} has unknown transition effect: {effect}'
+ )
+ for field, allow_zero in (('duration', False), ('auto_advance', True)):
+ if field not in transition:
+ continue
+ try:
+ validate_seconds(
+ transition[field],
+ f'animations.json {label} transition {field}',
+ allow_zero=allow_zero,
+ )
+ except ValueError as exc:
+ errors.append(str(exc))
+ return errors
+
+
def validate_animation_config(
project_path: Path,
config: dict[str, Any] | None = None,
@@ -154,7 +210,7 @@ def validate_animation_config(
if not config:
return []
- warnings: list[str] = []
+ warnings = validate_transition_config(config)
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')
@@ -162,7 +218,8 @@ def validate_animation_config(
known_slides = set(targets_by_slide)
slides = config.get('slides', {})
if slides and not isinstance(slides, dict):
- return ['animations.json field "slides" must be an object']
+ warnings.append('animations.json field "slides" must be an object')
+ return list(dict.fromkeys(warnings))
defaults = config.get('defaults', {})
if isinstance(defaults, dict):
@@ -195,15 +252,10 @@ def validate_animation_config(
warnings.append(
f'animations.json group "{slide_name}/{group_id}" has unknown effect: {effect}'
)
- return warnings
+ return list(dict.fromkeys(warnings))
def _validate_scope_effects(scope: dict[str, Any], label: str, warnings: list[str]) -> None:
- transition = scope.get('transition', {})
- if isinstance(transition, dict):
- effect = transition.get('effect')
- if effect is not None and not _valid_transition_effect(str(effect)):
- warnings.append(f'animations.json {label} has unknown transition effect: {effect}')
animation = scope.get('animation', {})
if isinstance(animation, dict):
effect = animation.get('effect')
@@ -221,6 +273,13 @@ def build_scaffold(project_path: Path) -> dict[str, Any]:
to remind the editor that deck-wide overrides exist and most pages should
inherit them.
"""
+ transition_defaults = {'effect': 'fade', 'duration': 0.4}
+ animation_defaults = {
+ 'effect': 'auto',
+ 'duration': 0.4,
+ 'stagger': 0.5,
+ 'trigger': 'after-previous',
+ }
targets_by_slide, _anonymous = scan_project_targets(project_path)
slides: dict[str, Any] = {}
for slide_name, targets in targets_by_slide.items():
@@ -229,17 +288,16 @@ def build_scaffold(project_path: Path) -> dict[str, Any]:
if target.chrome:
continue
groups[target.group_id] = {}
- slides[slide_name] = {'groups': groups}
+ slides[slide_name] = {
+ 'transition': dict(transition_defaults),
+ 'animation': dict(animation_defaults),
+ 'groups': groups,
+ }
return {
'version': 1,
'defaults': {
- 'transition': {'effect': 'fade', 'duration': 0.4},
- 'animation': {
- 'effect': 'auto',
- 'duration': 0.4,
- 'stagger': 0.5,
- 'trigger': 'after-previous',
- },
+ 'transition': transition_defaults,
+ 'animation': animation_defaults,
},
'slides': slides,
}
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.py
index ebb57404..91b1dc30 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
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
+import math
import mimetypes
import os
import posixpath
@@ -15,7 +16,7 @@ import tempfile
import uuid
import zipfile
from concurrent.futures import ProcessPoolExecutor, as_completed
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -26,6 +27,16 @@ from xml.sax.saxutils import escape
from pptx import Presentation
from pptx.util import Emu
+from pptx_transitions import (
+ TRANSITIONS,
+ create_transition_xml,
+ normalize_transition_effect,
+ set_directory_use_timings,
+ validate_generated_transition_xml,
+ validate_pptx_transition_package,
+ validate_seconds,
+)
+
from ..drawingml.converter import convert_svg_to_slide_shapes
from ..drawingml.theme_colors import (
ThemeColorSpec,
@@ -69,7 +80,6 @@ from .narration import (
probe_audio_duration,
)
from .slide_xml import (
- ANIMATIONS_AVAILABLE, TRANSITIONS,
create_slide_xml_with_svg, create_slide_rels_xml,
)
from .template_structure import (
@@ -82,15 +92,12 @@ from .template_structure import (
parse_template_slides,
)
-# Re-import create_transition_xml only if available
try:
from pptx_animations import (
- create_transition_xml,
create_sequence_timing_xml,
pick_animation_effect,
)
except ImportError:
- create_transition_xml = None
create_sequence_timing_xml = None
pick_animation_effect = None
@@ -2762,14 +2769,21 @@ def _to_float(value: Any, default: float) -> float:
number = float(value)
except (TypeError, ValueError):
return default
- return number if number >= 0 else 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 {}
- slides = _as_dict(animation_config.get('slides'))
- return _as_dict(slides.get(svg_stem))
+ slides_value = animation_config.get('slides', {})
+ if not isinstance(slides_value, dict):
+ raise ValueError('animations.json field "slides" must be an object')
+ slide_value = slides_value.get(svg_stem, {})
+ if not isinstance(slide_value, dict):
+ raise ValueError(
+ f'animations.json slide "{svg_stem}" must be an object'
+ )
+ return slide_value
def _slide_transition_settings(
@@ -2779,15 +2793,30 @@ def _slide_transition_settings(
auto_advance: float | None,
cli_overrides: dict[str, bool],
) -> tuple[str | None, float, float | None]:
- trans_cfg = _as_dict(slide_cfg.get('transition'))
+ trans_value = slide_cfg.get('transition', {})
+ if not isinstance(trans_value, dict):
+ raise ValueError('animations.json slide transition must be an object')
+ trans_cfg = trans_value
effect = transition
if not cli_overrides.get('transition') and 'effect' in trans_cfg:
- cfg_effect = str(trans_cfg.get('effect'))
- effect = None if cfg_effect == 'none' else cfg_effect
+ raw_effect = trans_cfg['effect']
+ if not isinstance(raw_effect, str):
+ raise ValueError('animations.json transition effect must be a string')
+ cfg_effect = normalize_transition_effect(raw_effect)
+ effect = cfg_effect
if not cli_overrides.get('transition_duration'):
- duration = _to_float(trans_cfg.get('duration'), duration)
+ if 'duration' in trans_cfg:
+ duration = validate_seconds(
+ trans_cfg.get('duration'),
+ "transition duration",
+ allow_zero=False,
+ )
if not cli_overrides.get('auto_advance') and 'auto_advance' in trans_cfg:
- auto_advance = _to_float(trans_cfg.get('auto_advance'), auto_advance or 0)
+ auto_advance = validate_seconds(
+ trans_cfg.get('auto_advance'),
+ "transition auto_advance",
+ allow_zero=True,
+ )
return effect, duration, auto_advance
@@ -3487,6 +3516,7 @@ def create_pptx_with_native_svg(
notes_slides_created: set[int] = set()
narration_slides_created: set[int] = set()
audio_exts_used: set[str] = set()
+ package_uses_timings = False
mixed_animation_offset = 0
conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
structure_trace: list[dict[str, Any]] | None = (
@@ -3553,16 +3583,19 @@ def create_pptx_with_native_svg(
# to precede <p:timing> inside <p:sld>. Both use the same
# </p:sld> string-replace anchor, so transition must be
# injected first and timing second.
- if slide_transition and ANIMATIONS_AVAILABLE and create_transition_xml:
- transition_xml = '\n' + create_transition_xml(
+ if slide_transition is not None or slide_auto_advance is not None:
+ transition_fragment = create_transition_xml(
effect=slide_transition,
duration=slide_transition_duration,
advance_after=slide_auto_advance,
)
- slide_xml = slide_xml.replace(
- '</p:sld>',
- transition_xml + '\n</p:sld>',
- )
+ if transition_fragment:
+ slide_xml = slide_xml.replace(
+ '</p:sld>',
+ '\n' + transition_fragment + '\n</p:sld>',
+ )
+ if slide_auto_advance is not None:
+ package_uses_timings = True
if (slide_animation and slide_animation != 'none'
and create_sequence_timing_xml
@@ -3732,6 +3765,9 @@ def create_pptx_with_native_svg(
with open(rels_path, 'w', encoding='utf-8') as f:
f.write(rels_xml)
+ resolved_advance_after = slide_auto_advance
+ resolved_advance_on_click = True
+
# --- Process notes (shared between native and legacy mode) ---
notes_content = ''
if enable_notes:
@@ -3819,11 +3855,35 @@ def create_pptx_with_native_svg(
slide_xml,
advance_after=duration + narration_padding,
transition_duration=slide_transition_duration,
- transition_effect=slide_transition or 'fade',
+ transition_effect=slide_transition,
)
+ resolved_advance_after = duration + narration_padding
+ resolved_advance_on_click = False
+ package_uses_timings = True
slide_xml_path.write_text(slide_xml, encoding='utf-8')
narration_slides_created.add(slide_num)
+ final_slide_xml = slide_xml_path.read_text(encoding='utf-8')
+ try:
+ resolved_motion = validate_generated_transition_xml(
+ final_slide_xml,
+ effect=slide_transition,
+ duration=slide_transition_duration,
+ advance_on_click=resolved_advance_on_click,
+ advance_after=resolved_advance_after,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f'Slide {slide_num} transition validation failed: {exc}'
+ ) from exc
+
+ if 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
+ break
+
if verbose:
if use_native_shapes:
mode_str = " (Native)"
@@ -4006,6 +4066,9 @@ def create_pptx_with_native_svg(
with open(content_types_path, 'w', encoding='utf-8') as f:
f.write(content_types)
+ if package_uses_timings:
+ set_directory_use_timings(extract_dir)
+
rels_problems = _verify_internal_rels_targets(extract_dir)
if rels_problems:
details = '\n'.join(f' - {p}' for p in rels_problems)
@@ -4028,6 +4091,15 @@ def create_pptx_with_native_svg(
if file_path.is_file():
arcname = file_path.relative_to(extract_dir)
zf.write(file_path, arcname)
+ try:
+ validate_pptx_transition_package(
+ temp_output_path,
+ require_use_timings=package_uses_timings,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f'PPTX transition package validation failed: {exc}'
+ ) from exc
shutil.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.py
index 24ed6314..6814cade 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
@@ -4,6 +4,7 @@ from __future__ import annotations
import sys
import json
+import math
import shutil
import argparse
from datetime import datetime
@@ -15,6 +16,7 @@ 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_transitions import validate_seconds # noqa: E402
configure_utf8_stdio()
@@ -42,7 +44,11 @@ from .template_structure import (
parse_template_slides,
template_lock_errors,
)
-from ..animation_config import load_animation_config, validate_animation_config
+from ..animation_config import (
+ load_animation_config,
+ validate_animation_config,
+ validate_transition_config,
+)
try:
from pptx_animations import ANIMATIONS as _ANIMATIONS
@@ -236,13 +242,21 @@ Recorded narration:
number = float(value)
except ValueError as exc:
raise argparse.ArgumentTypeError(f"must be a number: {value}") from exc
+ if not math.isfinite(number):
+ raise argparse.ArgumentTypeError("must be finite")
if number < 0:
raise argparse.ArgumentTypeError("must be non-negative")
return number
+ def positive_float(value: str) -> float:
+ number = non_negative_float(value)
+ if number <= 0:
+ raise argparse.ArgumentTypeError("must be greater than zero")
+ return number
+
parser.add_argument('-t', '--transition', type=str, choices=transition_choices, default=None,
- help='Page transition effect (default: fade, use "none" to disable)')
- parser.add_argument('--transition-duration', type=non_negative_float, default=None,
+ help='Page transition effect (default: fade; "none" removes visual motion)')
+ parser.add_argument('--transition-duration', type=positive_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)')
@@ -283,7 +297,7 @@ Recorded narration:
help='Prepare PowerPoint recorded timings and narrations from a complete audio '
'directory. Default-flow exports get the _narrated name suffix '
'(<project>_<ts>_narrated.pptx) to tell them apart from silent exports.')
- parser.add_argument('--narration-padding', type=float, default=0.5,
+ parser.add_argument('--narration-padding', type=non_negative_float, default=0.5,
help='Seconds to add after each narration before auto-advance (default: 0.5)')
args = parser.parse_args(argv)
@@ -533,6 +547,15 @@ 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:
+ 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}")
@@ -540,7 +563,7 @@ Recorded narration:
print(f" [warn] {warning}")
defaults = animation_config.get('defaults', {}) if animation_config else {}
- transition_defaults = defaults.get('transition', {}) if isinstance(defaults, dict) else {}
+ transition_defaults = _as_dict(defaults.get('transition')) if isinstance(defaults, dict) else {}
animation_defaults = defaults.get('animation', {}) if isinstance(defaults, dict) else {}
transition_arg = args.transition
@@ -550,11 +573,30 @@ Recorded narration:
else transition_defaults.get('effect', 'fade')
)
transition = None if transition_effect == 'none' else transition_effect
- transition_duration = (
- args.transition_duration
- if args.transition_duration is not None
- else float(transition_defaults.get('duration', 0.4))
- )
+ try:
+ transition_duration = validate_seconds(
+ (
+ args.transition_duration
+ if args.transition_duration is not None
+ else transition_defaults.get('duration', 0.4)
+ ),
+ "transition duration",
+ allow_zero=False,
+ )
+ auto_advance = (
+ args.auto_advance
+ if args.auto_advance is not None
+ else transition_defaults.get('auto_advance')
+ )
+ if auto_advance is not None:
+ auto_advance = validate_seconds(
+ auto_advance,
+ "transition auto_advance",
+ allow_zero=True,
+ )
+ except ValueError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
animation_arg = args.animation
animation_effect = (
@@ -635,7 +677,7 @@ Recorded narration:
verbose=verbose,
transition=transition,
transition_duration=transition_duration,
- auto_advance=args.auto_advance,
+ auto_advance=auto_advance,
notes=notes,
enable_notes=enable_notes,
animation=animation,
@@ -679,7 +721,7 @@ Recorded narration:
),
**shared_kwargs,
)
- except TemplateStructureError as exc:
+ except (TemplateStructureError, ValueError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
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.py
index b43422b9..298b6e43 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
@@ -8,6 +8,13 @@ import re
import subprocess
from pathlib import Path
+from pptx_transitions import (
+ AdvanceUpdate,
+ EnterUpdate,
+ apply_slide_motion_xml,
+ read_slide_transition_xml,
+)
+
MEDIA_REL_TYPE = "http://schemas.microsoft.com/office/2007/relationships/media"
AUDIO_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"
@@ -193,6 +200,12 @@ def inject_narration(
</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)
pattern = re.compile(r'(<p:cTn\s+id="1"[^>]*>\s*<p:childTnLst>)', re.S)
@@ -209,28 +222,20 @@ def apply_recorded_timing(
transition_effect: str | None = "fade",
) -> str:
"""Set slide auto-advance timing so exported video follows narration length."""
- adv_ms = max(1, int(advance_after * 1000))
- dur_ms = max(1, int(transition_duration * 1000))
-
- transition_match = re.search(r"<p:transition\b[^>]*>", slide_xml)
- if transition_match:
- tag = transition_match.group(0)
- is_self_closing = tag.rstrip().endswith("/>")
- base_tag = tag.rstrip()
- if is_self_closing:
- base_tag = re.sub(r"\s*/>$", ">", base_tag, count=1)
- if "advTm=" in base_tag:
- new_tag = re.sub(r'\sadvTm="[^"]*"', f' advTm="{adv_ms}"', base_tag, count=1)
- else:
- new_tag = base_tag[:-1] + f' advTm="{adv_ms}">'
- if is_self_closing:
- new_tag = new_tag[:-1] + "/>"
- return slide_xml[:transition_match.start()] + new_tag + slide_xml[transition_match.end():]
-
- effect = transition_effect or "fade"
- transition_xml = f''' <p:transition p14:dur="{dur_ms}" xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" advTm="{adv_ms}">
- <p:{effect}/>
- </p:transition>'''
- if "<p:timing>" in slide_xml:
- return slide_xml.replace("<p:timing>", transition_xml + "\n <p:timing>", 1)
- return slide_xml.replace("</p:sld>", transition_xml + "\n</p:sld>", 1)
+ summary = read_slide_transition_xml(slide_xml)
+ if summary.logical_count:
+ enter = EnterUpdate(policy="preserve")
+ elif transition_effect is None or transition_effect == "none":
+ enter = EnterUpdate(policy="none")
+ else:
+ enter = EnterUpdate(
+ policy="replace",
+ effect=transition_effect,
+ duration=transition_duration,
+ )
+ updated, _uses_timings = apply_slide_motion_xml(
+ slide_xml,
+ enter=enter,
+ advance=AdvanceUpdate(mode="narration", after=advance_after),
+ )
+ return updated
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/slide_xml.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/slide_xml.py
index 04835879..0c541f1c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/slide_xml.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/slide_xml.py
@@ -2,13 +2,7 @@
from __future__ import annotations
-# Import animation module (optional)
-try:
- from pptx_animations import create_transition_xml, TRANSITIONS
- ANIMATIONS_AVAILABLE = True
-except ImportError:
- ANIMATIONS_AVAILABLE = False
- TRANSITIONS = {}
+from pptx_transitions import TRANSITIONS, create_transition_xml
def create_slide_xml_with_svg(
@@ -36,12 +30,14 @@ def create_slide_xml_with_svg(
use_compat_mode: Whether to use compatibility mode (PNG + SVG dual format).
"""
transition_xml = ''
- if transition and ANIMATIONS_AVAILABLE:
- transition_xml = '\n' + create_transition_xml(
+ if transition is not None or auto_advance is not None:
+ transition_fragment = create_transition_xml(
effect=transition,
duration=transition_duration,
advance_after=auto_advance,
)
+ if transition_fragment:
+ transition_xml = '\n' + transition_fragment
if use_compat_mode:
blip_xml = f'''<a:blip r:embed="{png_rid}">
diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.py
index 4704c1a7..c39de8ab 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py
@@ -6,11 +6,19 @@ and rebuilds the presentation slide list, relationships, and content types.
from __future__ import annotations
+import tempfile
import zipfile
from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET
+from pptx_transitions import (
+ parse_source_xml,
+ serialize_source_xml,
+ set_package_use_timings,
+ validate_pptx_transition_package,
+)
+
from .chart_fill import (
_apply_chart_edits_to_slide_package,
_max_chart_part_number,
@@ -76,6 +84,7 @@ def apply_plan(
next_chart_number = _max_chart_part_number(entries)
next_embedding_number = _max_embedding_part_number(entries)
allocate_part = _make_part_allocator(entries)
+ wrote_auto_advance = False
for offset, item in enumerate(plan_slides):
source_slide = int(item.get("source_slide", 0))
@@ -87,7 +96,8 @@ def apply_plan(
new_rels = f"ppt/slides/_rels/slide{new_slide_number}.xml.rels"
new_rid = f"rId{next_rel_number + offset}"
- slide_root = ET.fromstring(entries[source_ref.part_name])
+ source_slide_xml = entries[source_ref.part_name]
+ slide_root = parse_source_xml(source_slide_xml)
replacements = item.get("replacements", [])
if not isinstance(replacements, list):
raise RuntimeError(f"Slide {source_slide} replacements must be a list")
@@ -109,12 +119,14 @@ def apply_plan(
default_effect=transition,
default_duration=transition_duration,
)
- _set_slide_transition(
+ slide_has_auto_advance = _set_slide_transition(
slide_root,
effect=slide_effect,
duration=slide_duration,
advance_after=slide_advance,
)
+ if slide_advance is not None and slide_has_auto_advance:
+ wrote_auto_advance = True
source_rels = entries.get(source_ref.rels_name)
slide_rels_root = ET.fromstring(source_rels) if source_rels else _empty_relationships_root()
@@ -139,7 +151,13 @@ def apply_plan(
next_chart_number=next_chart_number,
next_embedding_number=next_embedding_number,
)
- entries[new_part] = _xml_bytes(slide_root)
+ try:
+ entries[new_part] = serialize_source_xml(
+ slide_root,
+ source_slide_xml,
+ )
+ except ValueError as exc:
+ raise RuntimeError(str(exc)) from exc
notes_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),
@@ -171,8 +189,32 @@ def apply_plan(
entries["ppt/_rels/presentation.xml.rels"] = _xml_bytes(pres_rels_root)
_prune_unreferenced_parts(entries, content_root)
entries["[Content_Types].xml"] = _xml_bytes(content_root)
+ if wrote_auto_advance:
+ try:
+ set_package_use_timings(entries)
+ except ValueError as exc:
+ raise RuntimeError(str(exc)) from exc
output_path.parent.mkdir(parents=True, exist_ok=True)
- with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as out:
- for name, data in entries.items():
- out.writestr(name, data)
+ with tempfile.TemporaryDirectory(
+ prefix="template-fill-pptx-",
+ dir=output_path.parent,
+ ) as temp_dir:
+ candidate_path = Path(temp_dir) / output_path.name
+ with zipfile.ZipFile(
+ candidate_path,
+ "w",
+ compression=zipfile.ZIP_DEFLATED,
+ ) as out:
+ for name, data in entries.items():
+ out.writestr(name, data)
+ try:
+ validate_pptx_transition_package(
+ candidate_path,
+ require_use_timings=wrote_auto_advance,
+ )
+ except ValueError as exc:
+ raise RuntimeError(
+ f"PPTX transition package validation failed: {exc}"
+ ) from exc
+ candidate_path.replace(output_path)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/transitions.py b/skills/ppt-master/scripts/template_fill_pptx/transitions.py
index 445494b6..868bd463 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/transitions.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/transitions.py
@@ -2,8 +2,8 @@
Native templates usually ship an empty ``<p:transition/>`` that renders as no
motion, so ``apply`` injects a default transition unless told to ``keep`` the
-source or set ``none``. Effects come from the shared ``pptx_animations``
-vocabulary so they match the SVG export path.
+source or set ``none``. Effects and OOXML mutation come from the shared
+``pptx_transitions`` core so every PPTX path uses the same writer.
"""
from __future__ import annotations
@@ -11,12 +11,13 @@ from __future__ import annotations
from typing import Any
from xml.etree import ElementTree as ET
-from .ooxml import NS, P14_NS, _qn
-
-try:
- from pptx_animations import TRANSITIONS
-except ImportError:
- TRANSITIONS = {}
+from pptx_transitions import (
+ TRANSITIONS,
+ AdvanceUpdate,
+ EnterUpdate,
+ apply_slide_motion,
+ validate_seconds,
+)
# Default page transition injected by `apply` when neither the CLI flag nor a
# per-slide plan field asks for something else. Use `keep` to preserve the
@@ -28,59 +29,52 @@ KEEP_TRANSITION = "keep"
_UNSET = object()
-def _build_transition_element(
- effect: str,
- duration: float,
- advance_after: float | None = None,
-) -> ET.Element:
- """Build a populated <p:transition> element from the shared TRANSITIONS vocabulary."""
- info = TRANSITIONS[effect]
- transition = ET.Element(_qn(NS["p"], "transition"))
- transition.set(_qn(P14_NS, "dur"), str(int(float(duration) * 1000)))
- if advance_after is not None:
- transition.set("advTm", str(int(float(advance_after) * 1000)))
- child = ET.SubElement(transition, _qn(NS["p"], info["element"]))
- for key, value in info.get("attrs", {}).items():
- child.set(key, str(value))
- return transition
-
-
def _set_slide_transition(
slide_root: ET.Element,
*,
effect: str | None,
duration: float,
advance_after: float | None = None,
-) -> None:
- """Replace the cloned slide's transition element (empty in most templates).
-
- ``effect`` of ``None`` or ``"keep"`` leaves the source transition untouched;
- ``"none"`` strips it so the slide advances with no animation. OOXML requires
- the transition to sit after ``p:clrMapOvr`` and before ``p:timing``.
+) -> bool:
+ """Apply a legacy template-fill transition through the shared core.
+
+ ``None`` and ``keep`` preserve the source transition. ``none`` removes the
+ visual transition while retaining an explicitly requested auto-advance.
+ Legacy ``advance_after`` allowed both click and timed advance, so it maps to
+ ``both`` rather than the stricter ``after`` mode. The return value reports
+ whether the resulting slide contains an automatic advance.
"""
if effect is None or effect == KEEP_TRANSITION:
- return
-
- new_element = None if effect == "none" else _build_transition_element(effect, duration, advance_after)
- existing = slide_root.find("p:transition", NS)
- if existing is not None:
- index = list(slide_root).index(existing)
- slide_root.remove(existing)
- if new_element is not None:
- slide_root.insert(index, new_element)
- return
- if new_element is None:
- return
+ enter = EnterUpdate(policy="preserve")
+ advance = AdvanceUpdate(
+ mode="preserve" if advance_after is None else "both",
+ after=advance_after,
+ )
+ elif effect == "none":
+ enter = EnterUpdate(policy="none", effect=None, duration=duration)
+ advance = AdvanceUpdate(
+ mode="click" if advance_after is None else "both",
+ after=advance_after,
+ )
+ else:
+ enter = EnterUpdate(
+ policy="replace",
+ effect=effect,
+ duration=duration,
+ )
+ advance = AdvanceUpdate(
+ mode="click" if advance_after is None else "both",
+ after=advance_after,
+ )
- timing = slide_root.find("p:timing", NS)
- if timing is not None:
- slide_root.insert(list(slide_root).index(timing), new_element)
- return
- clr_map_ovr = slide_root.find("p:clrMapOvr", NS)
- if clr_map_ovr is not None:
- slide_root.insert(list(slide_root).index(clr_map_ovr) + 1, new_element)
- return
- slide_root.append(new_element)
+ try:
+ return apply_slide_motion(
+ slide_root,
+ enter=enter,
+ advance=advance,
+ )
+ except ValueError as exc:
+ raise RuntimeError(str(exc)) from exc
def _resolve_slide_transition(
@@ -98,11 +92,19 @@ def _resolve_slide_transition(
duration = raw.get("duration", default_duration)
advance_after = raw.get("advance_after")
else:
- effect = str(raw)
+ effect = None if raw is None else str(raw)
duration = default_duration
advance_after = None
if effect is not None and effect not in ("none", KEEP_TRANSITION) and effect not in TRANSITIONS:
raise RuntimeError(
f"Unknown transition effect '{effect}'. Valid: {', '.join(sorted(TRANSITIONS))}, none, {KEEP_TRANSITION}"
)
- return effect, float(duration), advance_after
+ try:
+ resolved_duration = validate_seconds(
+ duration,
+ "transition duration",
+ allow_zero=False,
+ )
+ except ValueError as exc:
+ raise RuntimeError(str(exc)) from exc
+ return effect, resolved_duration, advance_after
diff --git a/skills/ppt-master/workflows/customize-animations.md b/skills/ppt-master/workflows/customize-animations.md
index 9c4cd345..78fa0568 100644
--- a/skills/ppt-master/workflows/customize-animations.md
+++ b/skills/ppt-master/workflows/customize-animations.md
@@ -99,7 +99,7 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project_path>
| Effect | Behavior |
|---|---|
-| `none` | Disable page transition |
+| `none` | Remove visual page transition; timed advance may remain |
| `fade` | Neutral default for technical decks |
| `push` | Directional slide entry |
| `wipe` | Directional reveal |
@@ -112,9 +112,9 @@ python3 skills/ppt-master/scripts/animation_config.py validate <project_path>
| Field | Behavior |
|---|---|
-| `effect` | One supported page transition effect |
-| `duration` | Transition duration in seconds |
-| `auto_advance` | Optional seconds before automatic slide advance |
+| `effect` | One supported page transition effect; `none` removes only the visual effect |
+| `duration` | Finite transition duration in seconds; must be greater than zero |
+| `auto_advance` | Optional finite non-negative seconds before automatic slide advance; click remains enabled, and this field is valid with `effect: none` |
### 3.2 Supported In-Slide Animations
@@ -251,7 +251,7 @@ 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`.
+**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.
---
diff --git a/skills/ppt-master/workflows/generate-audio.md b/skills/ppt-master/workflows/generate-audio.md
index 7bdc90f9..e36cf3a3 100644
--- a/skills/ppt-master/workflows/generate-audio.md
+++ b/skills/ppt-master/workflows/generate-audio.md
@@ -149,7 +149,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> \
If `notes_to_audio.py` errors with a missing dependency or missing provider API key, fix the prerequisite and re-run — do NOT swallow the error.
-`--recorded-narration audio` prepares PowerPoint's recorded timings and narrations: every slide must have a matching supported audio file, every duration must be readable by `ffprobe`, and object animations must not use `--animation-trigger on-click`. Use `after-previous` or `with-previous` for narrated/video export. The re-export is saved as `exports/<project_name>_<timestamp>_narrated.pptx`, telling it apart from silent exports.
+`--recorded-narration audio` prepares PowerPoint's recorded timings and narrations: every slide must have a matching supported audio file, every duration must be readable by `ffprobe`, and object animations must not use `--animation-trigger on-click`. Use `after-previous` or `with-previous` for narrated/video export. Narration changes the slide-advance layer only: the resolved page-transition effect remains unchanged, `-t none` remains visually transition-free, and narration advance disables click while using audio duration plus padding. The re-export is saved as `exports/<project_name>_<timestamp>_narrated.pptx`, telling it apart from silent exports.
---
diff --git a/skills/ppt-master/workflows/native-enhance-pptx.md b/skills/ppt-master/workflows/native-enhance-pptx.md
index f6fb3f04..4f06ea00 100644
--- a/skills/ppt-master/workflows/native-enhance-pptx.md
+++ b/skills/ppt-master/workflows/native-enhance-pptx.md
@@ -129,6 +129,18 @@ Present the plan to the user before generating notes or audio:
**⛔ BLOCKING**: Stop here and wait for explicit user confirmation. Do not generate notes, generate audio, or patch the PPTX until the user confirms the module plan.
+**Transition/timing ownership**:
+
+| Confirmed state | Enter transition | Slide advance |
+|---|---|---|
+| Transitions enabled with an effect | Replace with that exact effect and duration | Preserve unless timings is enabled |
+| Transitions disabled with a non-`none` configured effect | Preserve the source effect, including unknown `AlternateContent` | Preserve unless timings is enabled |
+| Explicit `none` | Remove the visual effect | Preserve, or write timing-only advance when timings is enabled |
+| Timings enabled with audio | Keep the resolved enter policy | Use audio duration plus narration padding; click disabled |
+| Timings disabled | Apply the confirmed enter policy only | Do not run `ffprobe`; do not add/change `advTm` or `useTimings` |
+
+**Hard rule — no silent downgrade**: a requested supported effect must be written with its established direction/variant attributes. Unknown requested effects fail; unknown source effects are preserved when the transition module is disabled.
+
After confirmation, update `<project>/analysis/enhancement_plan.json`:
```json
@@ -254,9 +266,14 @@ python3 skills/ppt-master/scripts/native_enhance_pptx.py apply "<project>" \
--transition fade \
--transition-duration 0.5 \
--narration-padding 0.4 \
+ --apply-transition-without-audio \
--overwrite
```
+Without `--apply-transition-without-audio` (or the matching confirmed-plan
+field), the resolved enter policy is applied while processing slides with
+audio; slides without audio keep their source transition.
+
Patch scope:
| Package area | Append/update |
@@ -266,6 +283,7 @@ Patch scope:
| `ppt/slides/_rels/slideN.xml.rels` | Relationships for notes/audio/media/poster |
| `ppt/media/` | Narration audio and transparent poster |
| `ppt/slides/slideN.xml` | Hidden autoplay audio shape and page timing |
+| `ppt/presProps.xml` | `showPr useTimings=1` only when this run writes automatic slide advance |
| `[Content_Types].xml` | Required content types |
**Hard rule**: Do not modify existing slide shapes, text bodies, images, chart data, master/layout parts, or existing non-target relationships.
@@ -291,6 +309,8 @@ Check:
| Notes | Present on intended slides |
| Audio media | Present under `ppt/media/` when generated |
| Auto-play | Narrated slides advance by audio duration |
+| Transition | Requested effect remains exact; preserved `AlternateContent` keeps its primary and fallback branches |
+| Timings disabled | Source `advTm` and package `useTimings` are not changed |
```markdown
## ✅ Native PPTX Enhancement V1 Complete
diff --git a/skills/ppt-master/workflows/template-fill-pptx.md b/skills/ppt-master/workflows/template-fill-pptx.md
index 3e0184b2..d1973ae7 100644
--- a/skills/ppt-master/workflows/template-fill-pptx.md
+++ b/skills/ppt-master/workflows/template-fill-pptx.md
@@ -192,7 +192,7 @@ The plan structure:
| `layout_rationale` | Human review aid for page selection. Include `layout_pattern`, `why_fit`, and `risk`; it is not a mechanical checker gate. |
| `accepted_warnings` | Optional audit trail for warnings the user or agent explicitly accepts. `check-plan` warnings remain non-blocking; errors must be fixed. |
| `notes` | Optional spoken speaker notes for the filled slide — see **Speaker notes** below; write prose, not a copy of the on-slide text |
-| `transition` | Optional per-slide page transition; overrides the `apply --transition` default. Accepts an effect name (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`), `none` to strip it, or `{ "effect": "push", "duration": 0.6 }` |
+| `transition` | Optional per-slide page transition; overrides the `apply --transition` default. Accepts an effect name (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`), `none` to remove the visual effect, `keep` to preserve the source, or an object such as `{ "effect": "push", "duration": 0.6, "advance_after": 5 }` |
| `replacements` | Target by `slot_id` whenever possible; `shape_id` and `shape_name` are fallback selectors |
| `table_edits` | Optional native table cell edits; target by `table_id` whenever possible and use zero-based `row` / `col` |
| `chart_edits` | Optional native chart data edits; target by `chart_id`, set `categories`, and provide one or more `series` |
@@ -267,7 +267,7 @@ Run:
python3 skills/ppt-master/scripts/template_fill_pptx.py apply "<project_dir>/sources/<source.pptx>" "<project_dir>/analysis/fill_plan.json" -o "<project_dir>/exports/<output.pptx>"
```
-By default `apply` gives every cloned slide a `fade` transition (`0.5s`), because most native templates ship an empty `<p:transition/>` that renders as *no* motion. Override the default with `--transition <effect>` (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`) and `--transition-duration <seconds>`; pass `--transition none` for no motion, or `--transition keep` to preserve each source slide's existing transition unchanged. A per-slide `transition` field in the plan overrides whatever the CLI selects for that slide.
+By default `apply` gives every cloned slide a `fade` transition (`0.5s`), preserving the v1 route contract. Override it with `--transition <effect>` (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`) and `--transition-duration <seconds>`; pass `--transition none` for no visual motion, or `--transition keep` to preserve each source slide's existing transition unchanged. A per-slide `transition` field overrides the CLI. `advance_after` keeps click advance enabled and adds timed advance; it also works with `none` (timing-only transition) and `keep` (source effect preserved, Choice/Fallback timing updated together).
`apply` appends a timestamp automatically. For example, `-o "<project_dir>/exports/demo.pptx"` writes `demo_YYYYMMDD_HHMMSS.pptx`. If the filename already ends with `_YYYYMMDD_HHMMSS`, it is left unchanged.
@@ -278,12 +278,12 @@ The script:
| Clones selected source slides | Original slide design, relationships, images, layouts, and animations are preserved where PowerPoint supports them |
| Replaces text nodes | Text frames remain editable in PowerPoint |
| Writes `notes` fields | Speaker notes are embedded as native PowerPoint notes slides |
-| Applies `--transition` / per-slide `transition` | Populates each slide's `<p:transition>` with a native PowerPoint page transition |
+| Applies `--transition` / per-slide `transition` | Applies the requested visual-transition and slide-advance policy; `keep` may preserve no carrier and `none` may remove it |
| Rebuilds presentation slide list | Output deck contains only the planned slide sequence |
| Adds timestamp to PPTX filename | Matches the main SVG-to-PPTX export convention |
| Drops orphaned source parts | Output carries only the selected pages and the layouts / media / charts they still reference (reachability prune) |
-**Animation policy**: Template-fill preserves each cloned slide's existing object animation XML (the SVG pipeline's generated object animation defaults are not applied here). Page transitions are the one motion layer this workflow writes directly, and `apply` adds a `fade` transition by default so a filled deck is never left with the template's empty no-motion transitions; change it with `apply --transition` / a per-slide `transition` field, or opt out with `--transition keep` (preserve source) or `--transition none`. If the user asks to change object-level animation order / timing / effects, treat that as a separate direct-PPTX animation customization task.
+**Animation policy**: Template-fill preserves each cloned slide's existing object animation XML (the SVG pipeline's generated object animation defaults are not applied here). Page transitions are the one motion layer this workflow writes directly, and `apply` adds a `fade` transition by default; change it with `apply --transition` / a per-slide `transition` field, or opt out with `--transition keep` (preserve source) or `--transition none`. `keep` preserves direct and `mc:AlternateContent` transition effects without converting unknown effects to `fade`; explicit replacement removes the old logical carrier before writing one new carrier. If the user asks to change object-level animation order / timing / effects, treat that as a separate direct-PPTX animation customization task.
---