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

fix: round-trip motion overlays diff transition, advance, and animation against the import baseline; narration injects into minimal native timing, replaces its own earlier carriers, and matches imported audio by output page; notes parts are allocated by relationship and counted by content type

hugohe3a7cb7767aa54
diff --git a/skills/ppt-master/scripts/docs/narration.md b/skills/ppt-master/scripts/docs/narration.md
index 54c00a20..7950c70e 100644
--- a/skills/ppt-master/scripts/docs/narration.md
+++ b/skills/ppt-master/scripts/docs/narration.md
@@ -13,7 +13,7 @@ Tool behavior behind the [`generate-audio`](../../workflows/stages/generate-audi
```bash
python3 skills/ppt-master/scripts/notes_to_audio.py --list-voices --locale <locale> # edge
python3 skills/ppt-master/scripts/notes_to_audio.py --provider <elevenlabs|minimax|qwen|cosyvoice> --list-voices
-python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --voice <ShortName> --rate <rate> [--concurrency <N>]
+python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --voice <ShortName> --rate=<rate> [--concurrency <N>]
python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --provider elevenlabs --voice-id <id> --elevenlabs-model eleven_multilingual_v2
python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --provider minimax --voice-id <id> --minimax-model speech-2.8-hd
python3 skills/ppt-master/scripts/notes_to_audio.py <project_path> --provider qwen --voice-id <voice> --qwen-model qwen3-tts-flash --qwen-language-type Chinese
@@ -57,7 +57,8 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> --recorded-narra
# [--conversion-trace <final_narrated_trace>] native-export mix branch
```
-- `--recorded-narration audio` prepares PowerPoint's recorded timings and narrations: every slide needs a matching supported audio file with an `ffprobe`-readable duration, and object animations may not use `--animation-trigger on-click` (use `after-previous` / `with-previous`). Narration changes only the slide-advance layer — the page-transition effect is unchanged, `-t none` stays transition-free, and advance disables click while using page-start lead-in + audio duration + page-tail padding. Output is `exports/<project_name>_<timestamp>_narrated.pptx`.
+- `--recorded-narration audio` prepares PowerPoint's recorded timings and narrations: every slide needs matching supported audio with an `ffprobe`-readable duration. Both authored `on-click` / `trigger_shape` rows and preserved native click/interactive timing block recording, including source effects absent from the sidecar; diagnostics name the output stem, source slide, and shape ids. Explicitly replace or clear those effects, or author `after-previous` / `with-previous` rows. Narration preserves the transition effect (`-t none` stays transition-free) and replaces advance with click-disabled lead-in + audio duration + tail padding. Output is `exports/<project_name>_<timestamp>_narrated.pptx`.
+- Round-trip import records recognized PPT Master narration in each manifest slide's `narrationAudio` mapping; old workspaces recover it from the source package. Exact output-stem audio (including newly generated `notes_to_audio.py` output) takes priority; copies may inherit source narration. Re-recording replaces marked narration and the exact legacy off-canvas carrier, removes their exclusive timing/relationships, and allocates unused media names. Unrelated source audio remains intact.
- **Pacing**: `narration_start_floor` (default `0.8` s) and `narration_padding` (default `0.5` s) are independent. For a destination-page transition of `T` seconds the post-transition lead-in is `max(0, narration_start_floor - T)` — narration never starts during the transition and a longer transition is not stretched; the same lead-in applies to embedded narration, cue-bound object animation, subtitle offsets, and slide advance; uncued title or decorative animation keeps canonical relative timing; a floor of `0` starts narration as soon as the transition completes.
- `--inherit-motion-from` preserves source-bound deck motion from the base export report: inherited `-a none` preserves explicit objects-off, while a final Stage-2 `false` does not; only explicit all-motion-off uses `--no-animations`; invalid reports block. Text uses the default flow mode (authored line breaks in one editable no-wrap frame).
- Edit Native PPTX exports with `--roundtrip --recorded-narration audio --use-narration-timings`.
diff --git a/skills/ppt-master/scripts/docs/pptx-transitions.md b/skills/ppt-master/scripts/docs/pptx-transitions.md
index 9c729aed..c151a90a 100644
--- a/skills/ppt-master/scripts/docs/pptx-transitions.md
+++ b/skills/ppt-master/scripts/docs/pptx-transitions.md
@@ -242,7 +242,7 @@ round-trip export keeps existing object names and transition XML.
|---|---|---|---|
| Generated PPTX CLI | fade, 0.4s; no sound | click | auto-advance maps to both; an optional sidecar sound is project-local |
| Recorded narration | Preserve resolved enter | narration | none remains visually none |
-| Edit Native PPTX (`svg_to_pptx.py --roundtrip`) | preserve source | preserve source | `-t` or `animations.json` rows replace per output page as an overlay; `--use-narration-timings` derives advance from narration |
+| Edit Native PPTX (`svg_to_pptx.py --roundtrip`) | preserve source | preserve source | Compare enter, advance, and animation against the import baseline separately. `-t` or explicit slide `transition` replaces enter; omission inherits source even with importer `defaults.transition: none`. Effect-only edits retain `advClick` / `advTm`; explicit advance or `--use-narration-timings` replaces advance |
The public `create_pptx_with_native_svg` Python API retains its legacy 0.5s
default; the generated-deck CLI explicitly passes 0.4s.
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index c2422de0..118c4e65 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -888,7 +888,7 @@ Behavior:
- `--no-merge`: each dy-stacked line becomes an independent frame with its own placement.
- Detection is conservative: mixed-layout `<text>` falls back to per-line frames. Use `--reflow-text` only for resizable body copy and `--no-merge` only for independent line objects or absolute line positions.
- Native release export reads `svg_output/`; `-s <directory>` selects another project-relative SVG source. `-s final` remains an explicit diagnostic comparison against post-processed SVGs and does not change artifact ownership. `--enable-dangerous-nonconforming-svg-export` is a separate, explicitly requested flat compatibility path for either the default or selected source; it forces flat structure, restores no imported source object, and cannot combine with `--roundtrip` or `--quick-generate`.
-- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, rebuilds a page whose authoring changed, and rebuilds every output page that references a changed resource. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.
+- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, rebuilds a page whose authoring changed, and rebuilds every output page that references a changed resource. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Motion fields are compared independently with the import baseline: omitted slide `transition` preserves source motion even when importer defaults say `none`, while changed `defaults.animation` participates in animation replacement. Effect-only changes preserve source `advClick` / `advTm`; explicit advance settings or narration timings replace them. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.
- `svg_final/` may be opened directly or inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is outside the compatibility contract.
- On every SVG-authoring route, each file in `svg_output/` is the complete visible
page-design source. Templates and locks may guide authoring, but finalize/export
@@ -937,7 +937,7 @@ Behavior:
- Per-element animation applies to ordinary top-level SVG `<g id="...">` groups; each group is a PowerPoint shape-target anchor, not necessarily one Animation Pane row. Use one group per logical Slide-local content unit rather than targeting a group count
- For chrome defaults, static role/placeholder overrides, and structural exclusions, see [`animations.md`](../../references/animations.md) §5
- Start mode is set globally by `--animation-trigger`, mirroring PowerPoint's Start dropdown: `after-previous` (default, cascade with `--animation-stagger` spacing on slide entry), `on-click` (presenter-paced), or `with-previous` (all together on slide entry). A sidecar row may override it with `trigger`; the slide value is only the inherited Start mode
-- `on-click` is for live presentations only; recorded narration rejects every row that resolves to it, including a row with `trigger_shape`, because the tool does not generate object-level click timings
+- `on-click` is for live presentations only; recorded narration rejects every row that resolves to it, including `trigger_shape` and preserved native click/interactive timing that could not be reconstructed into the sidecar. Diagnostics identify the output stem, source slide, and shape ids; the tool does not generate object-level click timings
- Flat SVG roots without top-level groups fall back to at most 8 visible primitives; beyond that, animation is skipped on the slide
- Per-element animation defaults to `none`. `auto` is opt-in (`-a auto`) and maps
generic entrance effects from the group's SVG id: information-dense elements
diff --git a/skills/ppt-master/scripts/notes_to_audio.py b/skills/ppt-master/scripts/notes_to_audio.py
index 8d38d9fa..bc07147b 100644
--- a/skills/ppt-master/scripts/notes_to_audio.py
+++ b/skills/ppt-master/scripts/notes_to_audio.py
@@ -560,7 +560,12 @@ def main() -> int:
parser.add_argument("--list-common-voices", action="store_true", help="print a curated voice list and exit")
parser.add_argument("--list-voices", action="store_true", help="query provider voices and exit")
parser.add_argument("--locale", default=None, help='filter --list-voices by locale, e.g. "zh-CN"')
- args = parser.parse_args()
+ raw_args = list(sys.argv[1:])
+ # argparse otherwise interprets a separate negative percentage as an option.
+ for index in range(len(raw_args) - 2, -1, -1):
+ if raw_args[index] == "--rate" and re.fullmatch(r"-\d+(?:\.\d+)?%", raw_args[index + 1]):
+ raw_args[index:index + 2] = [f"--rate={raw_args[index + 1]}"]
+ args = parser.parse_args(raw_args)
if args.list_common_voices:
backend_edge.print_common_voices()
diff --git a/skills/ppt-master/scripts/pptx_animations.py b/skills/ppt-master/scripts/pptx_animations.py
index 598e847e..31c88e0f 100644
--- a/skills/ppt-master/scripts/pptx_animations.py
+++ b/skills/ppt-master/scripts/pptx_animations.py
@@ -3243,6 +3243,25 @@ def validate_slide_animation_structure(
return errors
+def read_slide_click_dependencies(slide_xml: str | bytes) -> tuple[int, ...]:
+ """Read native click/interactive targets without requiring supported effects."""
+ root = ET.fromstring(slide_xml)
+ targets: set[int] = set()
+ for timing in root.iter(_qn(PML_NS, 'timing')):
+ for node in timing.iter(_qn(PML_NS, 'cTn')):
+ conditions = node.findall(f"{_qn(PML_NS, 'stCondLst')}/{_qn(PML_NS, 'cond')}")
+ interactive = node.get('nodeType') in {'clickEffect', 'interactiveSeq'} or any(
+ condition.get('evt') in {'onClick', 'onDblClick', 'onMouseOver', 'onMouseOut', 'onNext', 'onPrev'}
+ for condition in conditions
+ )
+ if interactive:
+ targets.update(
+ int(value) for target in node.iter(_qn(PML_NS, 'spTgt'))
+ if (value := target.get('spid', '')).isdigit()
+ )
+ return tuple(sorted(targets))
+
+
def read_slide_animation_sequence(
slide_xml: str | bytes,
*,
diff --git a/skills/ppt-master/scripts/pptx_delivery_check.py b/skills/ppt-master/scripts/pptx_delivery_check.py
index d889c31c..701495ee 100644
--- a/skills/ppt-master/scripts/pptx_delivery_check.py
+++ b/skills/ppt-master/scripts/pptx_delivery_check.py
@@ -66,10 +66,13 @@ DRAWINGML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
PRESENTATION_NS = (
"http://schemas.openxmlformats.org/presentationml/2006/main"
)
-_SLIDE_PART_RE = re.compile(r"ppt/slides/slide[1-9]\d*\.xml")
-_NOTES_PART_RE = re.compile(r"ppt/notesSlides/notesSlide[1-9]\d*\.xml")
-_MASTER_PART_RE = re.compile(r"ppt/slideMasters/slideMaster[1-9]\d*\.xml")
-_LAYOUT_PART_RE = re.compile(r"ppt/slideLayouts/slideLayout[1-9]\d*\.xml")
+_PRESENTATION_PART_TYPES = {
+ key: f"application/vnd.openxmlformats-officedocument.presentationml.{kind}+xml"
+ for key, kind in (
+ ("slides", "slide"), ("notes", "notesSlide"),
+ ("masters", "slideMaster"), ("layouts", "slideLayout"),
+ )
+}
_MEDIA_REL_KINDS = frozenset({"audio", "image", "media", "video"})
_PPT_SAFE_FONT_ALIASES = {
"等线": "DengXian",
@@ -784,10 +787,7 @@ def audit_pptx_delivery(path: str | Path) -> dict[str, object]:
package["parts"] = {
"entries": len(file_infos),
"unique": len(part_names),
- "slides": sum(bool(_SLIDE_PART_RE.fullmatch(name)) for name in part_names),
- "notes": sum(bool(_NOTES_PART_RE.fullmatch(name)) for name in part_names),
- "masters": sum(bool(_MASTER_PART_RE.fullmatch(name)) for name in part_names),
- "layouts": sum(bool(_LAYOUT_PART_RE.fullmatch(name)) for name in part_names),
+ **dict.fromkeys(_PRESENTATION_PART_TYPES, 0),
"media": sum(
(canonical_opc_part_path(name) or "").startswith(
"ppt/media/"
@@ -832,6 +832,14 @@ def audit_pptx_delivery(path: str | Path) -> dict[str, object]:
)
defaults, overrides = _content_type_maps(archive, errors)
+ declared_types = Counter(
+ _declared_content_type_for_part(name, defaults, overrides)
+ for name in part_names
+ )
+ package["parts"].update({
+ key: declared_types[content_type]
+ for key, content_type in _PRESENTATION_PART_TYPES.items()
+ })
content_type_registry_valid = not any(
issue.get("code") in {
"missing_content_types",
diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.py
index dc452bff..083a6512 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/converter.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py
@@ -17,9 +17,11 @@ import base64
import hashlib
import json
import os
+import posixpath
import re
import shutil
import tempfile
+import zipfile
from collections.abc import Callable
from dataclasses import dataclass, field, replace
from html import unescape
@@ -57,6 +59,7 @@ from svg_to_pptx.animation_config import (
validate_animation_config_errors,
validate_transition_config,
)
+from svg_to_pptx.pptx_package.narration import narration_audio_parts
from template_import.manifest import (
count_drawable_shapes,
extract_placeholders,
@@ -1648,6 +1651,15 @@ def _write_roundtrip_manifest(
and item.get("packagePart")
}
slides: list[dict[str, object]] = []
+ narration_by_index: dict[int, str | None] = {}
+ with zipfile.ZipFile(source_path) as archive:
+ for index, native_slide in native_by_index.items():
+ part = str(native_slide["packagePart"])
+ rels_part = posixpath.join(posixpath.dirname(part), "_rels", posixpath.basename(part) + ".rels")
+ parts = narration_audio_parts(archive.read(part), archive.read(rels_part), part)
+ narration_by_index[index] = (
+ result.resource_inventory.path_map().get(parts[0]) if len(parts) == 1 else None
+ )
for slide in result.slides:
layered_path = ROUNDTRIP_LAYERED_SVG_DIR / f"slide_{slide.index:02d}.svg"
native_slide = native_by_index.get(slide.index, {})
@@ -1662,6 +1674,7 @@ def _write_roundtrip_manifest(
result.animation_config,
f"slide_{slide.index:02d}",
),
+ "narrationAudio": narration_by_index.get(slide.index),
}
referenced_svg_paths = [output_dir / layered_path]
if slide.index in flat_by_index:
@@ -1712,6 +1725,7 @@ def _write_roundtrip_manifest(
"animations": {
"file": "animations.json",
"sha256": _sha256_file(animation_path),
+ "baseline": result.animation_config,
},
"notesTotal": (
{
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 22f2d389..b971bf1f 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
@@ -43,6 +43,7 @@ from pptx_transitions import (
apply_slide_motion_xml,
create_transition_xml,
normalize_transition_effect_request,
+ read_slide_transition_xml,
serialize_source_xml,
set_directory_use_timings,
transition_carriers,
@@ -129,6 +130,7 @@ from .narration import (
narration_lead_in_seconds,
next_shape_id,
probe_audio_duration,
+ remove_narration,
)
from .slide_xml import (
create_slide_xml_with_svg, create_slide_rels_xml,
@@ -249,6 +251,7 @@ class RoundtripSlidePatch:
transition_replaced: bool
animation_changed: bool
notes_changed: bool
+ advance_changed: bool = False
@dataclass(frozen=True)
@@ -1208,9 +1211,12 @@ def _replace_roundtrip_motion(
transition_changed: bool,
transition_replaced: bool,
animation_changed: bool,
+ advance_changed: bool = True,
) -> None:
"""Replace only explicitly changed transition and animation state."""
if transition_changed and transition_replaced:
+ if not advance_changed:
+ _replace_roundtrip_transition_advance(generated_root, source_root)
generated_carriers = transition_carriers(generated_root)
if len(generated_carriers) > 1:
raise TemplateStructureError(
@@ -1294,10 +1300,12 @@ def _replace_roundtrip_transition_advance(
)
if not source_carriers:
- if generated_carriers:
- clone = ET.fromstring(
- ET.tostring(generated_carriers[0], encoding="utf-8")
- )
+ if advance_click is not None or advance_after is not None:
+ clone = ET.Element(transition_tag)
+ if advance_click is not None:
+ clone.set("advClick", advance_click)
+ if advance_after is not None:
+ clone.set("advTm", advance_after)
children = list(source_root)
insert_at = next(
(
@@ -1443,6 +1451,7 @@ def _apply_roundtrip_transition_overlay(
duration: float,
auto_advance: float | None,
replace_transition: bool,
+ advance_changed: bool = True,
) -> bool:
"""Patch only transition/advance state while preserving source timing."""
source_bytes = slide_path.read_bytes()
@@ -1464,9 +1473,12 @@ def _apply_roundtrip_transition_overlay(
effect_options=effect_options,
)
advance = (
- AdvanceUpdate(mode="click")
- if auto_advance is None
- else AdvanceUpdate(mode="both", after=auto_advance)
+ AdvanceUpdate(mode="preserve")
+ if not advance_changed else (
+ AdvanceUpdate(mode="click")
+ if auto_advance is None
+ else AdvanceUpdate(mode="both", after=auto_advance)
+ )
)
updated_xml, uses_timings = apply_slide_motion_xml(
source_xml,
@@ -1478,13 +1490,16 @@ def _apply_roundtrip_transition_overlay(
"Round-trip transition overlay changed source object animations"
)
if replace_transition:
+ original = read_slide_transition_xml(source_xml)
validate_generated_transition_xml(
updated_xml,
effect=effect,
effect_options=effect_options,
duration=duration,
- advance_on_click=True,
- advance_after=auto_advance,
+ advance_on_click=True if advance_changed else original.advance_on_click,
+ advance_after=auto_advance if advance_changed else (
+ original.advance_after_ms / 1000 if original.advance_after_ms is not None else None
+ ),
)
slide_path.write_bytes(
_preserve_roundtrip_timing_markup(
@@ -1793,6 +1808,7 @@ def _apply_roundtrip_slide_overlay(
transition_changed=patch.transition_changed,
transition_replaced=patch.transition_replaced,
animation_changed=patch.animation_changed,
+ advance_changed=patch.advance_changed,
)
restored_shape_id_map = {
generated_top_id: source_id
@@ -1868,6 +1884,18 @@ def _remove_relationships_by_type(rels_path: Path, rel_type: str) -> int:
return removed
+def _unused_part_path(directory: Path, filename: str) -> Path:
+ """Allocate a part name without overwriting any existing package member."""
+ requested = Path(filename)
+ occupied = {path.name.casefold() for path in directory.iterdir()}
+ candidate = directory / requested.name
+ suffix = 1
+ while candidate.name.casefold() in occupied:
+ candidate = directory / f"{requested.stem}_{suffix}{requested.suffix}"
+ suffix += 1
+ return candidate
+
+
def _apply_slide_notes(
extract_dir: Path,
rels_path: Path,
@@ -1878,6 +1906,24 @@ def _apply_slide_notes(
enable_notes: bool,
) -> _NotesMasterReference | None:
"""Replace one slide's notes relationship and return its notes master."""
+ existing_target = _find_relationship_target(rels_path, NOTES_SLIDE_REL_TYPE)
+ source_part = _part_name_for_relationships_path(rels_path)
+ existing_part = (
+ _resolve_package_target(source_part, existing_target) if existing_target else None
+ )
+ exclusive = existing_part is not None
+ if exclusive:
+ for other_rels in rels_path.parent.glob('*.rels'):
+ if other_rels == rels_path:
+ continue
+ other_part = _part_name_for_relationships_path(other_rels)
+ if any(
+ attrs.get('Type') == NOTES_SLIDE_REL_TYPE
+ and _resolve_package_target(other_part, attrs.get('Target', '')) == existing_part
+ for attrs in _read_relationships(other_rels).values()
+ ):
+ exclusive = False
+ break
_remove_relationships_by_type(rels_path, NOTES_SLIDE_REL_TYPE)
if not enable_notes:
return None
@@ -1888,25 +1934,29 @@ def _apply_slide_notes(
notes_master = _ensure_notes_master(extract_dir, primary_language)
notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'
notes_slides_dir.mkdir(exist_ok=True)
- notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'
+ notes_xml_path = (
+ extract_dir / existing_part if exclusive
+ else _unused_part_path(notes_slides_dir, f'notesSlide{slide_num}.xml')
+ )
+ notes_part = notes_xml_path.relative_to(extract_dir).as_posix()
notes_xml_path.write_text(
create_notes_slide_xml(slide_num, notes_text, primary_language),
encoding='utf-8',
)
- notes_rels_dir = notes_slides_dir / '_rels'
+ notes_rels_dir = notes_xml_path.parent / '_rels'
notes_rels_dir.mkdir(exist_ok=True)
- notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'
+ notes_rels_path = notes_rels_dir / f'{notes_xml_path.name}.rels'
notes_rels_path.write_text(
create_notes_slide_rels_xml(
slide_num,
- posixpath.relpath(notes_master.package_part, 'ppt/notesSlides'),
+ posixpath.relpath(notes_master.package_part, posixpath.dirname(notes_part)),
),
encoding='utf-8',
)
_ensure_relationship(
rels_path,
NOTES_SLIDE_REL_TYPE,
- f'../notesSlides/notesSlide{slide_num}.xml',
+ posixpath.relpath(notes_part, posixpath.dirname(source_part)),
)
return notes_master
@@ -6943,12 +6993,14 @@ def create_pptx_with_native_svg(
else transition
)
print(f" Transition effect: {trans_name}")
- if enable_notes and notes:
- print(f" Speaker notes: {len(notes)} page(s)")
- elif enable_notes:
- print(f" Speaker notes: Enabled (no notes files found)")
- else:
- print(f" Speaker notes: Disabled")
+ # Round-trip counts include inherited notes from the finished package.
+ if not roundtrip_export:
+ if enable_notes and notes:
+ print(f" Speaker notes: {len(notes)} page(s)")
+ elif enable_notes:
+ print(f" Speaker notes: Enabled (no notes files found)")
+ else:
+ print(f" Speaker notes: Disabled")
print()
animation_cli_overrides = animation_cli_overrides or {}
@@ -7089,6 +7141,7 @@ def create_pptx_with_native_svg(
notes_master_parts_used: set[str] = set()
notes_master_theme_parts_created: set[str] = set()
narration_slides_created: set[int] = set()
+ replaced_narration_parts: set[str] = set()
audio_exts_used: set[str] = set()
package_uses_timings = False
mixed_animation_offset = 0
@@ -7228,6 +7281,7 @@ def create_pptx_with_native_svg(
)
direct_transition_overlay = (
overlay_animation is None
+ and not slide_patch.animation_changed
and not overlay_groups
and not animation_override_requested
and overlay_transition_sound is None
@@ -7248,6 +7302,7 @@ def create_pptx_with_native_svg(
duration=overlay_transition_duration,
auto_advance=overlay_auto_advance,
replace_transition=slide_patch.transition_replaced,
+ advance_changed=slide_patch.advance_changed,
):
package_uses_timings = True
if slide_patch.notes_changed:
@@ -7791,6 +7846,13 @@ def create_pptx_with_native_svg(
resolved_advance_after = slide_auto_advance
resolved_advance_on_click = True
+ if slide_patch is not None and not slide_patch.advance_changed:
+ source_motion = read_slide_transition_xml(source_slide_bytes)
+ resolved_advance_on_click = source_motion.advance_on_click
+ resolved_advance_after = (
+ source_motion.advance_after_ms / 1000
+ if source_motion.advance_after_ms is not None else None
+ )
# --- Process notes (shared between native and legacy mode) ---
notes_changed = slide_patch is None or slide_patch.notes_changed
@@ -7826,12 +7888,24 @@ def create_pptx_with_native_svg(
rels_path = extract_dir / 'ppt' / 'slides' / '_rels' / f'slide{slide_num}.xml.rels'
ext = audio_path.suffix.lower()
- media_name = f'narration{slide_num}{ext}'
+ slide_xml, removed_rids = remove_narration(slide_xml_path.read_text(encoding='utf-8'))
+ source_relationships = _read_relationships(rels_path)
+ for rel_id in removed_rids:
+ relationship = source_relationships.get(rel_id, {})
+ if relationship.get('Target') and relationship.get('TargetMode') != 'External':
+ replaced_narration_parts.add(_resolve_package_target(
+ f'ppt/slides/slide{slide_num}.xml', relationship['Target'],
+ ))
+ _remove_relationship(rels_path, rel_id)
+ media_name = _unused_part_path(media_dir, f'narration{slide_num}{ext}').name
shutil.copy2(audio_path, media_dir / media_name)
audio_exts_used.add(ext)
poster_name = 'narration_poster.png'
poster_path = media_dir / poster_name
+ if poster_path.exists() and poster_path.read_bytes() != AUDIO_MARKER_PNG_BYTES:
+ poster_path = _unused_part_path(media_dir, poster_name)
+ poster_name = poster_path.name
if not poster_path.exists():
poster_path.write_bytes(AUDIO_MARKER_PNG_BYTES)
has_any_image = True
@@ -7853,7 +7927,6 @@ def create_pptx_with_native_svg(
f'../media/{poster_name}',
)
- slide_xml = slide_xml_path.read_text(encoding='utf-8')
narration_shape_id = next_shape_id(slide_xml)
narration_transition_duration = (
slide_transition_duration
@@ -8123,13 +8196,13 @@ def create_pptx_with_native_svg(
pruned_roundtrip_payloads = (
_prune_unreferenced_definition_payload_parts(
extract_dir,
- preserved_parts=roundtrip_source_parts,
+ preserved_parts=roundtrip_source_parts - replaced_narration_parts,
)
)
if verbose and pruned_roundtrip_payloads:
print(
" Round-trip overlay: pruned "
- f"{pruned_roundtrip_payloads} unused generated payload part(s)"
+ f"{pruned_roundtrip_payloads} unused payload part(s)"
)
if (
@@ -8233,9 +8306,15 @@ def create_pptx_with_native_svg(
_NOTES_MASTER_CONTENT_TYPE,
)
for i in sorted(notes_slides_created):
+ notes_target = _find_relationship_target(
+ extract_dir / 'ppt' / 'slides' / '_rels' / f'slide{i}.xml.rels',
+ NOTES_SLIDE_REL_TYPE,
+ )
+ if notes_target is None:
+ raise RuntimeError(f"Slide {i} lost its generated notes relationship")
content_types = _add_content_type_override(
content_types,
- f'/ppt/notesSlides/notesSlide{i}.xml',
+ '/' + _resolve_package_target(f'ppt/slides/slide{i}.xml', notes_target),
'application/vnd.openxmlformats-officedocument.presentationml.'
'notesSlide+xml',
)
@@ -8388,6 +8467,12 @@ def create_pptx_with_native_svg(
if verbose:
print()
print(f"[Done] Saved: {output_path}")
+ if roundtrip_export:
+ from pptx_to_svg.notes_import import import_speaker_notes
+ from pptx_to_svg.ooxml_loader import OoxmlPackage
+
+ with OoxmlPackage(output_path) as package:
+ print(f" Speaker notes: {len(import_speaker_notes(package))} page(s)")
for warning in permission_warnings:
print(f" [warn] {warning}")
if conversion_trace_path and conversion_trace is not None:
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 62961b29..c34bc45d 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
@@ -48,6 +48,7 @@ from pptx_animations import ( # noqa: E402
animation_seconds_to_milliseconds,
normalize_animation_effect,
normalize_animation_trigger,
+ read_slide_click_dependencies,
)
from pptx_transitions import ( # noqa: E402
DEFAULT_TRANSITION_DURATION,
@@ -503,6 +504,7 @@ def _roundtrip_slide_patches(
force_transition_replaced: bool,
force_animation_changed: bool,
force_notes_changed: bool,
+ force_advance_changed: bool = False,
) -> dict[int, RoundtripSlidePatch]:
"""Build strict source-overlay metadata for edited authoring slides."""
if authoring_report is None:
@@ -539,10 +541,20 @@ def _roundtrip_slide_patches(
animation_config,
pages,
)
- animation_defaults = _as_dict(animation_config.get("defaults"))
- default_transition_config = _as_dict(
- animation_defaults.get("transition")
- )
+ baseline = animation.get("baseline")
+ if not isinstance(baseline, dict):
+ # Older workspaces stored only a combined hash. Recover their import
+ # projection in memory from the immutable source, without publishing it.
+ from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svg
+
+ baseline = convert_pptx_to_svg(
+ source_pptx_path(project_path),
+ options=ConvertOptions(inheritance_mode="both", roundtrip=True),
+ ).animation_config
+ animation_defaults = _as_dict(_as_dict(animation_config.get("defaults")).get("animation"))
+ baseline_defaults = _as_dict(_as_dict(baseline.get("defaults")).get("animation"))
+ defaults_transition = _as_dict(_as_dict(animation_config.get("defaults")).get("transition"))
+ baseline_defaults_transition = _as_dict(_as_dict(baseline.get("defaults")).get("transition"))
documents = authoring_report.get("documents")
if not isinstance(documents, list):
@@ -574,45 +586,40 @@ def _roundtrip_slide_patches(
f"Round-trip manifest has no source slide {page.source_slide} "
"for authoring overlay"
)
- expected_animation = row.get("animationSha256")
- if not isinstance(expected_animation, str):
- raise RuntimeError(
- f"Round-trip manifest slide {page.source_slide} lacks "
- "animationSha256"
- )
- sidecar_changed = (
- slide_animation_config_sha256(
- animation_config,
- page.svg_stem,
- )
- != expected_animation
- )
slide_config = _as_dict(
_as_dict(animation_config.get("slides")).get(page.svg_stem)
)
- slide_transition_config = _as_dict(slide_config.get("transition"))
- effective_transition_config = resolve_slide_animation_config(
- default_transition_config,
- slide_transition_config,
- )
- sidecar_transition_applies = (
- bool(default_transition_config)
- or "transition" in slide_config
- )
- transition_changed = force_transition_changed or (
- sidecar_changed and sidecar_transition_applies
- )
- transition_replaced = force_transition_replaced or (
- sidecar_changed
- and sidecar_transition_applies
- and any(
- key in effective_transition_config
- for key in ("effect", "effect_options", "duration", "sound")
- )
+ baseline_slide = _as_dict(
+ _as_dict(baseline.get("slides")).get(Path(page.source_svg_name).stem)
)
+ slide_transition_config = _as_dict(slide_config.get("transition"))
+ baseline_transition = _as_dict(baseline_slide.get("transition"))
+ def _transition_key_changed(key: str) -> bool:
+ # A slide row wins; otherwise a user-edited default (different from
+ # the import baseline default) is a deck-wide request.
+ if key in slide_transition_config:
+ return slide_transition_config[key] != baseline_transition.get(key)
+ return (
+ key in defaults_transition
+ and defaults_transition[key] != baseline_defaults_transition.get(key)
+ )
+
+ transition_replaced = force_transition_replaced or any(
+ _transition_key_changed(key)
+ for key in ("effect", "effect_options", "duration", "sound")
+ )
+ advance_changed = force_advance_changed or _transition_key_changed("auto_advance")
+ transition_changed = force_transition_changed or transition_replaced or advance_changed
animation_changed = force_animation_changed or (
- sidecar_changed
- and any(key in slide_config for key in ("animation", "groups"))
+ (
+ ("animation" in slide_config or animation_defaults != baseline_defaults)
+ and resolve_slide_animation_config(animation_defaults, _as_dict(slide_config.get("animation")))
+ != resolve_slide_animation_config(baseline_defaults, _as_dict(baseline_slide.get("animation")))
+ )
+ or (
+ "groups" in slide_config
+ and _as_dict(slide_config.get("groups")) != _as_dict(baseline_slide.get("groups"))
+ )
)
motion_changed = (
force_motion_changed
@@ -650,6 +657,7 @@ def _roundtrip_slide_patches(
transition_changed=transition_changed,
transition_replaced=transition_replaced,
animation_changed=animation_changed,
+ advance_changed=advance_changed,
notes_changed=(
force_notes_changed
or _roundtrip_note_changed(project_path, row, page)
@@ -1829,13 +1837,39 @@ def _recorded_narration_on_click_slides(
animation: str | None,
animation_trigger: str,
animation_cli_overrides: dict[str, bool],
+ *,
+ roundtrip_source: Path | None = None,
+ roundtrip_pages: tuple[RoundtripPage, ...] = (),
+ roundtrip_patches: dict[int, RoundtripSlidePatch] | None = None,
) -> list[str]:
"""Return slides whose effective recorded-video animation trigger is on-click."""
if animation_cli_overrides.get('animation') and animation is None:
return []
slides_cfg = _as_dict(_as_dict(animation_config).get('slides'))
blocked: list[str] = []
+ preserved: dict[str, tuple[int, tuple[int, ...]]] = {}
+ if roundtrip_source is not None:
+ from pptx_to_svg.ooxml_loader import OoxmlPackage
+
+ with OoxmlPackage(roundtrip_source) as package:
+ for page in roundtrip_pages:
+ slide_patch = (roundtrip_patches or {}).get(page.output_index)
+ if slide_patch is not None and slide_patch.animation_changed:
+ continue
+ source = package.get_slide(page.source_slide)
+ preserved[page.svg_stem] = (
+ page.source_slide,
+ read_slide_click_dependencies(ET.tostring(source.part.xml)),
+ )
for svg_path in ref_files:
+ if svg_path.stem in preserved:
+ source_index, shape_ids = preserved[svg_path.stem]
+ if shape_ids:
+ blocked.append(
+ f"{svg_path.stem} (source slide {source_index}; shape id(s): "
+ + ', '.join(str(shape_id) for shape_id in shape_ids) + ')'
+ )
+ continue
slide_cfg = _as_dict(slides_cfg.get(svg_path.stem))
anim_cfg = _as_dict(slide_cfg.get('animation'))
@@ -2924,6 +2958,12 @@ Recorded narration:
force_transition_replaced=roundtrip_transition_replaced,
force_animation_changed=roundtrip_animation_overridden,
force_notes_changed=args.no_notes,
+ force_advance_changed=any((
+ args.auto_advance is not None,
+ args.recorded_narration is not None,
+ args.use_narration_timings,
+ args.inherit_motion_from is not None,
+ )),
)
except RuntimeError as exc:
print(f"Error: {exc}", file=sys.stderr)
@@ -3648,11 +3688,15 @@ Recorded narration:
animation,
animation_trigger,
animation_cli_overrides,
+ roundtrip_source=source_pptx_path(project_path) if args.roundtrip else None,
+ roundtrip_pages=roundtrip_pages,
+ roundtrip_patches=roundtrip_slide_patches,
)
if on_click_slides:
print(
"Error: --recorded-narration cannot be used with on-click object animations. "
- "Use --animation-trigger after-previous or --animation-trigger with-previous.",
+ "Explicitly replace or clear the reported source animations, or use "
+ "after-previous / with-previous for authored animation rows.",
file=sys.stderr,
)
for slide in on_click_slides[:20]:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
index d9232744..f2a26428 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/discovery.py
@@ -76,6 +76,10 @@ def find_notes_files(
Dict mapping SVG filename stem to notes content.
"""
notes_dir = project_path / 'notes'
+ roundtrip = (
+ (project_path / 'analysis' / 'roundtrip_manifest.json').is_file()
+ or (project_path / 'authoring-svg-flat').is_dir()
+ )
index_notes: dict[str, tuple[Path, str]] = {}
filename_notes: dict[str, tuple[Path, str]] = {}
@@ -93,7 +97,7 @@ def find_notes_files(
stem = notes_file.stem
# Try index-based matching (backward compat with slide01.md format).
- match = re.search(r'slide[_]?(\d+)', stem)
+ match = None if roundtrip else re.search(r'slide[_]?(\d+)', stem)
mapped_stem = (
svg_index_mapping.get(int(match.group(1)))
if match
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 1e5b231c..17062beb 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
@@ -4,12 +4,15 @@ from __future__ import annotations
import base64
import json
+import posixpath
import re
import subprocess
+import zipfile
from collections.abc import Iterable
from pathlib import Path
from xml.etree import ElementTree as ET
+from pptx_workspace import load_roundtrip_manifest, source_pptx_path
from pptx_transitions import (
AdvanceUpdate,
EnterUpdate,
@@ -42,6 +45,7 @@ AUDIO_CONTENT_TYPES = {
NARRATION_EXTENSIONS = tuple(AUDIO_CONTENT_TYPES.keys())
DEFAULT_NARRATION_START_FLOOR = 0.8
+NARRATION_SHAPE_PREFIX = "PPT Master narration: "
AUDIO_MARKER_SIZE_EMU = 457200 # 48 SVG px
AUDIO_MARKER_OFF_CANVAS_EMU = -AUDIO_MARKER_SIZE_EMU
@@ -86,7 +90,7 @@ def _leading_number(text: str) -> int | None:
def find_narration_files(audio_dir: Path, svg_files: list[Path]) -> dict[str, Path]:
- """Return `{svg_stem: audio_path}` matched by exact stem, normalized stem, or index."""
+ """Match exact stems, imported narration, then legacy normalized/index names."""
if not audio_dir.exists() or not audio_dir.is_dir():
return {}
@@ -104,11 +108,17 @@ def find_narration_files(audio_dir: Path, svg_files: list[Path]) -> dict[str, Pa
if number is not None:
numbered.setdefault(number, []).append(path)
+ unmatched_stems = [svg for svg in svg_files if svg.stem not in exact]
+ inherited = _roundtrip_narration_files(audio_dir, unmatched_stems) if unmatched_stems else {}
matched: dict[str, Path] = {}
claimed_by: dict[Path, str] = {}
for index, svg in enumerate(svg_files, 1):
stem = svg.stem
candidates = exact.get(stem)
+ if not candidates and stem in inherited:
+ # A page-plan copy intentionally shares its source narration file.
+ matched[stem] = inherited[stem]
+ continue
if not candidates:
candidates = normalized.get(_normalize_title(stem))
if not candidates:
@@ -134,6 +144,117 @@ def find_narration_files(audio_dir: Path, svg_files: list[Path]) -> dict[str, Pa
return matched
+def narration_shapes(root: ET.Element) -> list[ET.Element]:
+ """Identify our marked narration and the exact legacy off-canvas carrier."""
+ autoplay_ids = {
+ target.get("spid")
+ for audio in root.iter(_qn(PML_NS, "audio"))
+ for target in audio.iter(_qn(PML_NS, "spTgt"))
+ }
+ found = []
+ for picture in root.findall(f"{_qn(PML_NS, 'cSld')}/{_qn(PML_NS, 'spTree')}/{_qn(PML_NS, 'pic')}"):
+ props = picture.find(f"{_qn(PML_NS, 'nvPicPr')}/{_qn(PML_NS, 'cNvPr')}")
+ if props is None or picture.find(f".//{_qn(DRAWINGML_NS, 'audioFile')}") is None:
+ continue
+ name = props.get("name", "")
+ marked = name.startswith(NARRATION_SHAPE_PREFIX)
+ offset = picture.find(f"{_qn(PML_NS, 'spPr')}/{_qn(DRAWINGML_NS, 'xfrm')}/{_qn(DRAWINGML_NS, 'off')}")
+ extent = picture.find(f"{_qn(PML_NS, 'spPr')}/{_qn(DRAWINGML_NS, 'xfrm')}/{_qn(DRAWINGML_NS, 'ext')}")
+ legacy = (
+ re.fullmatch(r"narration[1-9]\d*\.(?:m4a|mp3|wav)", name) is not None
+ and props.get("id") in autoplay_ids
+ and offset is not None and extent is not None
+ and all(offset.get(key) == str(AUDIO_MARKER_OFF_CANVAS_EMU) for key in ("x", "y"))
+ and all(extent.get(key) == str(AUDIO_MARKER_SIZE_EMU) for key in ("cx", "cy"))
+ and picture.find(f".//{_qn(P14_NS, 'media')}") is not None
+ )
+ if marked or legacy:
+ found.append(picture)
+ return found
+
+
+def narration_audio_parts(slide_xml: bytes, rels_xml: bytes, slide_part: str) -> tuple[str, ...]:
+ """Read recognized narration targets without reconstructing source motion."""
+ relationships = {rel.get("Id"): rel for rel in ET.fromstring(rels_xml)}
+ parts = set()
+ for picture in narration_shapes(ET.fromstring(slide_xml)):
+ audio = picture.find(f".//{_qn(DRAWINGML_NS, 'audioFile')}")
+ relationship = relationships.get(audio.get(_qn(RELATIONSHIPS_NS, "link")))
+ if relationship is None or relationship.get("TargetMode") == "External":
+ continue
+ target = relationship.get("Target", "")
+ if target:
+ parts.add(posixpath.normpath(posixpath.join(posixpath.dirname(slide_part), target)).lstrip("/"))
+ return tuple(sorted(parts))
+
+
+def _roundtrip_narration_files(audio_dir: Path, svg_files: list[Path]) -> dict[str, Path]:
+ workspace = audio_dir.parent
+ manifest = load_roundtrip_manifest(workspace)
+ if manifest is None:
+ return {}
+ rows = {row["index"]: row for row in manifest["slides"]}
+ sources = {f"slide_{index:02d}": index for index in rows}
+ plan_path = workspace / "page_plan.json"
+ if plan_path.is_file():
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
+ sources = {
+ Path(page.get("svg", f"slide_{page['source_slide']:02d}.svg")).stem: page["source_slide"]
+ for page in plan["pages"]
+ }
+ resource_paths = {
+ row["packagePart"]: row["workspacePath"]
+ for row in manifest["resources"]["items"]
+ }
+ inherited = {}
+ # Legacy manifests can recover the same mapping from immutable source XML.
+ with zipfile.ZipFile(source_pptx_path(workspace)) as archive:
+ for svg in svg_files:
+ row = rows.get(sources.get(svg.stem))
+ if row is None:
+ continue
+ relative = row.get("narrationAudio")
+ if "narrationAudio" not in row:
+ part = row["sourcePart"]
+ rels = posixpath.join(posixpath.dirname(part), "_rels", posixpath.basename(part) + ".rels")
+ parts = narration_audio_parts(archive.read(part), archive.read(rels), part)
+ relative = resource_paths.get(parts[0]) if len(parts) == 1 else None
+ if not isinstance(relative, str):
+ continue
+ path = (workspace / relative).resolve()
+ if path.parent == audio_dir.resolve() and path.is_file() and path.suffix.lower() in NARRATION_EXTENSIONS:
+ inherited[svg.stem] = path
+ return inherited
+
+
+def remove_narration(slide_xml: str) -> tuple[str, set[str]]:
+ """Remove owned narration carriers/timing and return exclusively owned rIds."""
+ root = parse_source_xml(slide_xml)
+ pictures = narration_shapes(root)
+ if not pictures:
+ return slide_xml, set()
+ shape_ids = {
+ picture.find(f"{_qn(PML_NS, 'nvPicPr')}/{_qn(PML_NS, 'cNvPr')}").get("id")
+ for picture in pictures
+ }
+ relationship_ids = {
+ value for picture in pictures for node in picture.iter()
+ for key, value in node.attrib.items() if key.startswith(f"{{{RELATIONSHIPS_NS}}}") and value
+ }
+ for parent in root.iter():
+ for child in list(parent):
+ if child in pictures or (
+ child.tag == _qn(PML_NS, "audio")
+ and any(target.get("spid") in shape_ids for target in child.iter(_qn(PML_NS, "spTgt")))
+ ):
+ parent.remove(child)
+ still_used = {
+ value for node in root.iter() for key, value in node.attrib.items()
+ if key.startswith(f"{{{RELATIONSHIPS_NS}}}")
+ }
+ return serialize_source_xml(root, slide_xml).decode("utf-8"), relationship_ids - still_used
+
+
def probe_audio_duration(audio_path: Path) -> float | None:
"""Return duration in seconds using ffprobe when available."""
try:
@@ -184,7 +305,7 @@ def _create_audio_pic_element(
c_nv_pr = ET.SubElement(
nv_pic_pr,
_qn(PML_NS, "cNvPr"),
- {"id": str(shape_id), "name": shape_name},
+ {"id": str(shape_id), "name": NARRATION_SHAPE_PREFIX + shape_name},
)
ET.SubElement(
c_nv_pr,
@@ -517,6 +638,7 @@ def inject_narration(
f"{start_delay_ms} ms"
)
+ slide_xml, _removed_relationships = remove_narration(slide_xml)
root = parse_source_xml(slide_xml)
if root.tag != _qn(PML_NS, "sld"):
raise ValueError("narration source XML root must be p:sld")
@@ -568,6 +690,8 @@ def inject_narration(
_validate_root_timing_position(root, timing_anchor)
for timing in timing_branches:
timing_root = _existing_timing_root(timing)
+ if timing_root.find(_qn(PML_NS, "childTnLst")) is None:
+ ET.SubElement(timing_root, _qn(PML_NS, "childTnLst"))
child_nodes = _direct_child(
timing_root,
_qn(PML_NS, "childTnLst"),
diff --git a/skills/ppt-master/scripts/tests/test_edit_native_batch_a.py b/skills/ppt-master/scripts/tests/test_edit_native_batch_a.py
new file mode 100644
index 00000000..0875db18
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_edit_native_batch_a.py
@@ -0,0 +1,387 @@
+#!/usr/bin/env python3
+"""Regress Edit Native motion, narration, and notes overlays on small native decks.
+
+Usage: python3 -m unittest tests.test_edit_native_batch_a
+Dependencies: python-pptx and the converter's normal dependencies.
+"""
+
+from __future__ import annotations
+
+import copy
+import io
+import json
+import posixpath
+import sys
+import tempfile
+import unittest
+import wave
+import zipfile
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+from xml.etree import ElementTree as ET
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from pptx import Presentation # noqa: E402
+from pptx.enum.shapes import MSO_SHAPE # noqa: E402
+from pptx.util import Inches # noqa: E402
+
+from pptx_animations import create_sequence_timing_xml # noqa: E402
+import notes_to_audio # noqa: E402
+from pptx_delivery_check import audit_pptx_delivery # noqa: E402
+from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svg # noqa: E402
+from svg_to_pptx.pptx_package import cli, narration # noqa: E402
+from svg_to_pptx.pptx_package.discovery import find_notes_files # noqa: E402
+
+NS = {
+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',
+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
+ 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
+ 'rel': 'http://schemas.openxmlformats.org/package/2006/relationships',
+}
+MINIMAL_TIMING = (
+ '<p:timing><p:tnLst><p:par><p:cTn id="1" dur="indefinite" '
+ 'restart="never" nodeType="tmRoot"/></p:par></p:tnLst></p:timing>'
+)
+
+
+def _fragment(xml: str) -> ET.Element:
+ wrapped = '<root ' + ' '.join(f'xmlns:{k}="{v}"' for k, v in NS.items()) + '>'
+ return ET.fromstring(wrapped + xml + '</root>')[0]
+
+
+def _note(archive: zipfile.ZipFile, slide: int) -> tuple[str | None, str]:
+ part = f'ppt/slides/slide{slide}.xml'
+ rels = ET.fromstring(archive.read(f'ppt/slides/_rels/slide{slide}.xml.rels'))
+ for rel in rels:
+ if rel.get('Type', '').endswith('/notesSlide'):
+ target = posixpath.normpath(posixpath.join(posixpath.dirname(part), rel.get('Target')))
+ root = ET.fromstring(archive.read(target))
+ return target, ' '.join(node.text or '' for node in root.findall('.//a:t', NS))
+ return None, ''
+
+
+class EditNativeBatchATests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+
+ def _source(self, *, count: int = 1, timing: str = '', advance: bool = False,
+ notes: tuple[int, ...] = ()) -> Path:
+ prs = Presentation()
+ for number in range(1, count + 1):
+ slide = prs.slides.add_slide(prs.slide_layouts[6])
+ slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(1), Inches(1), Inches(2), Inches(1))
+ if number in notes:
+ slide.notes_slide.notes_text_frame.text = f'Original note for source {number}'
+ transition = _fragment('<p:transition spd="med"><p:random/></p:transition>')
+ if advance:
+ transition.set('advClick', '0')
+ transition.set('advTm', '4200')
+ # python-pptx uses lxml; append through its own parser.
+ from pptx.oxml import parse_xml
+ slide._element.append(parse_xml(ET.tostring(transition)))
+ if timing:
+ slide._element.append(parse_xml(ET.tostring(_fragment(timing))))
+ source = self.root / 'source.pptx'
+ prs.save(source)
+ return source
+
+ def _import(self, source: Path, name: str = 'workspace') -> Path:
+ project = self.root / name
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ convert_pptx_to_svg(source, project, ConvertOptions(inheritance_mode='both', roundtrip=True))
+ return project
+
+ def _export(self, project: Path, *args: str, name: str = 'result.pptx', success: bool = True):
+ output = project / name
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with redirect_stdout(stdout), redirect_stderr(stderr):
+ result = cli.main([str(project), '--roundtrip', '-o', str(output), *args])
+ if success:
+ self.assertEqual(result, 0, stdout.getvalue() + stderr.getvalue())
+ self.assertTrue(output.is_file())
+ return output, result, stdout.getvalue(), stderr.getvalue()
+
+ def _config(self, project: Path, *, slides=None, defaults=None) -> None:
+ path = project / 'animations.json'
+ config = json.loads(path.read_text(encoding='utf-8'))
+ if slides is not None:
+ config['slides'] = slides
+ if defaults is not None:
+ config.setdefault('defaults', {}).update(defaults)
+ path.write_text(json.dumps(config), encoding='utf-8')
+
+ def _audio(self, project: Path, stem: str = 'slide_01', sample: int = 0) -> Path:
+ directory = project / 'audio'
+ directory.mkdir(exist_ok=True)
+ path = directory / f'{stem}.wav'
+ with wave.open(str(path), 'wb') as audio:
+ audio.setnchannels(1)
+ audio.setsampwidth(2)
+ audio.setframerate(8000)
+ audio.writeframes(sample.to_bytes(2, 'little', signed=True) * 1600)
+ return path
+
+ def _slide(self, path: Path, number: int = 1) -> ET.Element:
+ with zipfile.ZipFile(path) as archive:
+ return ET.fromstring(archive.read(f'ppt/slides/slide{number}.xml'))
+
+ def test_a1_animation_and_default_changes_do_not_replace_source_transition(self) -> None:
+ source = self._source()
+ for name, row, defaults in (
+ ('row', {'slide_01': {'animation': {'effect': 'none'}}}, None),
+ ('default', {}, {'animation': {'effect': 'entrance_fade'}}),
+ ):
+ with self.subTest(name=name):
+ project = self._import(source, name)
+ self._config(project, slides=row, defaults=defaults)
+ output, *_ = self._export(project)
+ root = self._slide(output)
+ self.assertEqual(ET.tostring(root.find('p:transition', NS)),
+ ET.tostring(self._slide(source).find('p:transition', NS)))
+ if name == 'default':
+ self.assertIsNotNone(root.find('p:timing', NS))
+
+ def test_a1_user_edited_default_transition_replaces_deck_wide(self) -> None:
+ source = self._source()
+ project = self._import(source)
+ self._config(project, slides={}, defaults={'transition': {'effect': 'fade', 'duration': 0.4}})
+ output, *_ = self._export(project)
+ transition = self._slide(output).find('p:transition', NS)
+ self.assertIsNotNone(transition)
+ self.assertIsNotNone(transition.find('p:fade', NS))
+
+ def test_a2_explicit_none_removes_timing_and_keeps_transition_and_shapes(self) -> None:
+ source = self._source(timing=create_sequence_timing_xml([(2, 0, 'entrance_fade')]))
+ project = self._import(source)
+ self._config(project, slides={'slide_01': {'animation': {'effect': 'none'}}})
+ output, *_ = self._export(project)
+ before, after = self._slide(source), self._slide(output)
+ self.assertIsNone(after.find('p:timing', NS))
+ for xpath in ('p:transition', 'p:cSld/p:spTree'):
+ self.assertEqual(ET.tostring(before.find(xpath, NS)), ET.tostring(after.find(xpath, NS)))
+
+ def test_a1_legacy_baseline_and_unlisted_motion_are_preserved(self) -> None:
+ source = self._source(count=2, timing=create_sequence_timing_xml([(2, 0, 'entrance_fade')]))
+ project = self._import(source)
+ manifest_path = project / 'analysis/roundtrip_manifest.json'
+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
+ manifest['sidecars']['animations'].pop('baseline', None)
+ manifest_path.write_text(json.dumps(manifest), encoding='utf-8')
+ self._config(project, slides={'slide_01': {'animation': {'effect': 'none'}}})
+ output, *_ = self._export(project)
+ self.assertIsNone(self._slide(output).find('p:timing', NS))
+ self.assertEqual(ET.tostring(self._slide(output, 2)), ET.tostring(self._slide(source, 2)))
+
+ def test_a3_narration_accepts_minimal_native_timing(self) -> None:
+ project = self._import(self._source(timing=MINIMAL_TIMING))
+ self._audio(project)
+ output, *_ = self._export(project, '--recorded-narration', 'audio')
+ self.assertEqual(len(self._slide(output).findall('.//p:audio', NS)), 1)
+
+ def test_a4_preserved_unreconstructed_click_timing_blocks_recording(self) -> None:
+ timing = create_sequence_timing_xml([(2, 0, 'entrance_fade')], trigger='on-click')
+ timing = timing.replace('presetID="10"', 'presetID="999"')
+ project = self._import(self._source(timing=timing))
+ self._audio(project)
+ _, result, _, error = self._export(project, '--recorded-narration', 'audio', success=False)
+ self.assertNotEqual(result, 0)
+ self.assertIn('slide_01', error)
+ self.assertIn('source slide 1', error)
+ self.assertIn('shape', error)
+ self.assertIn('2', error)
+ self._config(project, slides={'slide_01': {'animation': {'effect': 'none'}}})
+ self._export(project, '--recorded-narration', 'audio')
+
+ def test_a5_effect_only_changes_preserve_native_advance(self) -> None:
+ source = self._source(advance=True)
+ for name, args, row in (
+ ('cli', ('-t', 'fade'), None),
+ ('sidecar', (), {'slide_01': {'transition': {'effect': 'fade', 'duration': 0.4}}}),
+ ):
+ with self.subTest(name=name):
+ project = self._import(source, name)
+ if row:
+ self._config(project, slides=row)
+ output, *_ = self._export(project, *args)
+ transition = self._slide(output).find('p:transition', NS)
+ self.assertEqual((transition.get('advClick'), transition.get('advTm')), ('0', '4200'))
+ self.assertIsNotNone(transition.find('p:fade', NS))
+
+ def test_a5_imported_narration_matches_output_stems(self) -> None:
+ project = self._import(self._source())
+ self._audio(project)
+ narrated, *_ = self._export(project, '--recorded-narration', 'audio')
+ imported = self._import(narrated, 'narrated_import')
+ matched = narration.find_narration_files(imported / 'audio', [imported / 'slide_01.svg'])
+ self.assertEqual(set(matched), {'slide_01'})
+ self._audio(imported, stem='01', sample=200)
+ self.assertEqual(
+ narration.find_narration_files(imported / 'audio', [imported / 'slide_01.svg']), matched,
+ )
+ replacement = self._audio(imported, sample=100)
+ self.assertEqual(
+ narration.find_narration_files(imported / 'audio', [imported / 'slide_01.svg']),
+ {'slide_01': replacement},
+ )
+ repeated, *_ = self._export(imported, '--recorded-narration', 'audio')
+ with zipfile.ZipFile(repeated) as archive:
+ self.assertNotIn('ppt/media/narration1.wav', archive.namelist())
+ self.assertEqual(len(self._slide(repeated).findall('.//p:audio', NS)), 1)
+
+ def test_a5_full_overlay_preserves_advance_and_explicit_advance_wins(self) -> None:
+ source = self._source(advance=True)
+ project = self._import(source)
+ self._audio(project)
+ output, *_ = self._export(project, '-t', 'none', '--narration-audio-dir', 'audio')
+ transition = self._slide(output).find('p:transition', NS)
+ self.assertEqual((transition.get('advClick'), transition.get('advTm')), ('0', '4200'))
+ self.assertEqual(list(transition), [])
+ self._config(project, slides={'slide_01': {'transition': {'auto_advance': 2.3}}})
+ output, *_ = self._export(project, name='advance.pptx')
+ transition = self._slide(output).find('p:transition', NS)
+ self.assertEqual((transition.get('advClick'), transition.get('advTm')), ('1', '2300'))
+ self.assertIsNotNone(transition.find('p:random', NS))
+
+ def test_a6_repeated_injection_replaces_owned_audio_only(self) -> None:
+ root = self._slide(self._source())
+ xml = ET.tostring(root, encoding='unicode')
+ for number in (1, 2):
+ xml = narration.inject_narration(
+ xml, shape_id=narration.next_shape_id(xml), shape_name='narration1.wav',
+ audio_rid=f'rId{number * 3}', media_rid=f'rId{number * 3 + 1}',
+ poster_rid=f'rId{number * 3 + 2}', start_delay=0.8,
+ )
+ final = ET.fromstring(xml)
+ self.assertEqual(len(final.findall('.//p:pic', NS)), 1)
+ self.assertEqual(len(final.findall('.//p:audio', NS)), 1)
+
+ def test_a6_second_export_does_not_overwrite_source_media(self) -> None:
+ project = self._import(self._source())
+ self._audio(project)
+ narrated, *_ = self._export(project, '--recorded-narration', 'audio')
+ imported = self._import(narrated, 'second')
+ # Keep an unrelated audio shape sharing the original audio part.
+ source = imported / 'sources/source.pptx'
+ with zipfile.ZipFile(source) as archive:
+ entries = {name: archive.read(name) for name in archive.namelist()}
+ root = ET.fromstring(entries['ppt/slides/slide1.xml'])
+ other = copy.deepcopy(root.find('.//p:pic', NS))
+ other.find('p:nvPicPr/p:cNvPr', NS).attrib.update(id='99', name='Unrelated sound')
+ # This shape deliberately has neither the new marker nor the legacy geometry.
+ for ext in other.findall('.//p:ext', NS):
+ if 'ppt-master' in ext.get('uri', ''):
+ other.find('.//p:extLst', NS).remove(ext)
+ other.find('p:spPr/a:xfrm/a:off', NS).set('x', '0')
+ root.find('p:cSld/p:spTree', NS).append(other)
+ other_timing = copy.deepcopy(root.find('.//p:audio', NS))
+ other_timing.find('.//p:cTn', NS).set('id', '99')
+ other_timing.find('.//p:spTgt', NS).set('spid', '99')
+ root.find('.//p:cTn[@nodeType="tmRoot"]/p:childTnLst', NS).append(other_timing)
+ entries['ppt/slides/slide1.xml'] = ET.tostring(root)
+ shared_source = self.root / 'shared_audio.pptx'
+ with zipfile.ZipFile(shared_source, 'w') as archive:
+ for name, data in entries.items():
+ archive.writestr(name, data)
+ shared = self._import(shared_source, 'shared')
+ self._audio(shared, sample=100)
+ output, *_ = self._export(shared, '--recorded-narration', 'audio')
+ with zipfile.ZipFile(output) as archive:
+ self.assertEqual(archive.read('ppt/media/narration1.wav'), entries['ppt/media/narration1.wav'])
+ final = ET.fromstring(archive.read('ppt/slides/slide1.xml'))
+ self.assertEqual(len(final.findall('.//p:pic', NS)), 2)
+ self.assertEqual(len(final.findall('.//p:audio', NS)), 2)
+ retained = next(node for node in final.findall('.//p:audio', NS)
+ if node.find('.//p:spTgt', NS).get('spid') == '99')
+ self.assertEqual(ET.tostring(retained), ET.tostring(other_timing))
+
+ def test_a7_sparse_notes_and_copied_page_are_independent(self) -> None:
+ project = self._import(self._source(count=4, notes=(3, 4)))
+ (project / 'notes/slide_01.md').write_text('New first note', encoding='utf-8')
+ output, *_ = self._export(project)
+ with zipfile.ZipFile(output) as archive:
+ self.assertIn('Original note for source 3', _note(archive, 3)[1])
+ self.assertIn('New first note', _note(archive, 1)[1])
+ authoring = project / 'authoring-svg-flat'
+ (authoring / 'copy.svg').write_bytes((authoring / 'slide_03.svg').read_bytes())
+ (project / 'page_plan.json').write_text(json.dumps({
+ 'schema': 'ppt-master.roundtrip-page-plan.v1',
+ 'pages': [{'source_slide': 3}, {'source_slide': 3, 'svg': 'copy.svg'}],
+ }), encoding='utf-8')
+ (project / 'notes/copy.md').write_text('Copy only', encoding='utf-8')
+ output, _, stdout, _ = self._export(project, name='copies.pptx')
+ self.assertIn('Speaker notes: 2 page(s)', stdout)
+ with zipfile.ZipFile(output) as archive:
+ self.assertIn('Original note for source 3', _note(archive, 1)[1])
+ self.assertIn('Copy only', _note(archive, 2)[1])
+ self.assertNotEqual(_note(archive, 1)[0], _note(archive, 2)[0])
+
+ def test_a7_shared_source_notes_allocate_a_private_part(self) -> None:
+ source = self._source(count=3, notes=(3,))
+ with zipfile.ZipFile(source) as archive:
+ entries = {name: archive.read(name) for name in archive.namelist()}
+ rels_path = 'ppt/slides/_rels/slide1.xml.rels'
+ rels = ET.fromstring(entries[rels_path])
+ ET.SubElement(rels, f"{{{NS['rel']}}}Relationship", {
+ 'Id': 'rIdNotes', 'Type': NS['r'] + '/notesSlide', 'Target': '../notesSlides/notesSlide1.xml',
+ })
+ entries[rels_path] = ET.tostring(rels)
+ with zipfile.ZipFile(source, 'w') as archive:
+ for name, data in entries.items():
+ archive.writestr(name, data)
+ project = self._import(source)
+ (project / 'notes/slide_01.md').write_text('Private first note', encoding='utf-8')
+ output, *_ = self._export(project)
+ with zipfile.ZipFile(output) as archive:
+ self.assertIn('Original note for source 3', _note(archive, 3)[1])
+ self.assertIn('Private first note', _note(archive, 1)[1])
+ self.assertNotEqual(_note(archive, 1)[0], _note(archive, 3)[0])
+
+ def test_a8_roundtrip_notes_match_stems_only(self) -> None:
+ project = self.root / 'notes_workspace'
+ (project / 'authoring-svg-flat').mkdir(parents=True)
+ (project / 'notes').mkdir()
+ for name in ('slide_03', 'slide_13'):
+ (project / 'notes' / f'{name}.md').write_text(name, encoding='utf-8')
+ roster = [project / f'slide_{number:02d}.svg' for number in (3, 4, 16)]
+ self.assertEqual(find_notes_files(project, roster), {'slide_03': 'slide_03'})
+
+ def test_a9_delivery_counts_cloned_notes_parts_by_type(self) -> None:
+ project = self._import(self._source(count=4, notes=(3, 4)))
+ authoring = project / 'authoring-svg-flat'
+ (authoring / 'copy.svg').write_bytes((authoring / 'slide_04.svg').read_bytes())
+ (project / 'page_plan.json').write_text(json.dumps({
+ 'schema': 'ppt-master.roundtrip-page-plan.v1',
+ 'pages': [{'source_slide': 4}, {'source_slide': 4, 'svg': 'copy.svg'}],
+ }), encoding='utf-8')
+ output, *_ = self._export(project)
+ report = audit_pptx_delivery(output)
+ self.assertEqual(report['package']['parts']['notes'], 2)
+ self.assertEqual(report['package']['parts']['slides'], 2)
+
+ def test_a9_arbitrary_slide_master_and_layout_part_names_are_counted(self) -> None:
+ source = self._source(notes=(1,))
+ with zipfile.ZipFile(source) as archive:
+ entries = {name: archive.read(name) for name in archive.namelist()}
+ renames = {'slide1.xml': 'customSlide.xml', 'notesSlide1.xml': 'customNotes.xml',
+ 'slideMaster1.xml': 'customMaster.xml', 'slideLayout7.xml': 'customLayout.xml'}
+ renamed = self.root / 'renamed.pptx'
+ with zipfile.ZipFile(renamed, 'w') as archive:
+ for name, data in entries.items():
+ for old, new in renames.items():
+ name = name.replace(old, new)
+ if name.endswith(('.xml', '.rels')):
+ data = data.replace(old.encode(), new.encode())
+ archive.writestr(name, data)
+ parts = audit_pptx_delivery(renamed)['package']['parts']
+ self.assertEqual((parts['slides'], parts['notes'], parts['masters'], parts['layouts']), (1, 1, 1, 11))
+
+ def test_p1_star6_negative_rate_is_accepted_without_equals(self) -> None:
+ with patch.object(sys, 'argv', ['notes_to_audio.py', '--list-common-voices', '--rate', '-5%']):
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertEqual(notes_to_audio.main(), 0)