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-to-svg): reconstruct supported slide transitions

hugohe3ad2126282f27
diff --git a/docs/faq.md b/docs/faq.md
index 8957297e..4bff06a5 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -197,6 +197,8 @@ animation is **off by default**—a page appears as a whole instead of having
elements auto-cascade in one by one. Both are controlled by `svg_to_pptx.py`
flags: `-t/--transition` for page-level and `-a/--animation` for element-level.
The object registry includes entrance, emphasis, motion-path, and exit effects.
+`pptx_to_svg.py` also reconstructs exact current-registry page transitions into
+`animations.json`; unsupported source carriers remain explicit diagnostics.
```bash
python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -t push # different transition
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index 13d3a712..2a3adea7 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -240,7 +240,7 @@ owner.
| PowerPoint feature | Owning project representation | PPTX result | Import and fidelity | Validation boundary |
|---|---|---|---|---|
| Speaker notes | `notes/<slide>.md` sidecar | Notes Slide part and relationship | `Sidecar/package` | Notes are not SVG text and do not affect page geometry |
-| Slide transition | CLI options or `animations.json` | `p:transition` | `Sidecar/package` | Unknown effects or invalid durations fail; no silent `fade` fallback |
+| Slide transition | CLI options or `animations.json` | `p:transition` | `Sidecar/package`; PPTX import reconstructs exact current-registry transitions into `animations.json` | Unknown effects or inexact carriers fail or remain diagnosed; no silent `fade` fallback |
| Object animation (entrance / emphasis / motion path / exit) | `animations.json` targeting stable top-level SVG group IDs; `effects[]` may assign several rows to one anchor | Root `p:timing` animation tree | `Sidecar/package`; the group ID is only the shape-target anchor | Static structural layers and placeholders cannot be animated |
| Narration audio | `audio/` asset plus recorded-narration export option | Media relationship, audio carrier, and timing | `Sidecar/package` | Asset, slide association, and timing must validate |
| Automatic slide advance | Explicit transition timing or narration-derived duration | `advTm`/advance behavior | `Sidecar/package` | Click-driven animation is incompatible with recorded narration |
@@ -292,6 +292,7 @@ The importer reconstructs supported PowerPoint semantics into the same project v
| Connector | Expanded line/path preview plus connector/frame/topology evidence |
| Group | `<g>` |
| Supported native table/chart | Visible fallback plus native-object metadata |
+| Supported current-registry page transition | Canonical `animations.json` row with effective options, exact duration, optional auto-advance, and supported WAV sound |
| Unsupported graphic frame or SmartArt | Explicit preview, placeholder, or unsupported status |
This is semantic projection, not a syntax round trip. Preserving validated source-package Master/Layout facts is confined to Create Template mirror and always produces a new workspace; an ordinary visual import does not infer reusable topology from slide appearance.
@@ -308,7 +309,14 @@ This is semantic projection, not a syntax round trip. Preserving validated sourc
| Unsupported slide or part background | Omit that background and continue the page/part | Stop at the first violation | Warning identifies the owning part |
| Corrupt package/XML or missing required package structure | Stop; no safe page-level recovery exists | Stop | Clean command error; no raw Python traceback |
-Every successful run writes `<output>/conversion-report.json`. The report records the mode, slide and warning counts, stable reason code, source message, chosen fallback, package part, and—when available—slide index plus shape id/name/kind. Tolerant import is therefore not silent: it maximizes usable output while making every contract recovery reviewable.
+Every successful run writes `<output>/conversion-report.json` and a canonical
+`<output>/animations.json` whose baseline transition is `none`. The report
+records the mode, slide and warning counts, owned artifacts, stable reason code,
+source message, chosen fallback, package part, and—when available—slide index
+plus shape id/name/kind. Unknown or inexact transition carriers remain explicit
+`transition-not-reconstructed` diagnostics. Tolerant import is therefore not
+silent: it maximizes usable output while making every contract recovery
+reviewable.
## 13. Validation ownership
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 9d1c2626..b0a4e60c 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -70,7 +70,7 @@ A presentation is four layers: what is on the slide, how it is arranged, how it
| Concern | Status | Notes |
|---|---|---|
-| Page transitions | Systematized | Includes on-demand transition sounds from a bundled CC0 catalog |
+| Page transitions | Systematized | Includes on-demand transition sounds from a bundled CC0 catalog; PPTX import reconstructs exact current-registry transitions into the canonical sidecar |
| Object animation | Systematized | Off by default and opt-in; per-object configuration is explicit |
| Auto-advance | Covered | Derived from narration lead-in, audio duration, and page-tail padding |
| Media playback | Covered | Narration audio and animation sounds play natively; media already present in a source deck keeps its playback settings |
diff --git a/docs/zh/faq.md b/docs/zh/faq.md
index 62a142ac..85d21245 100644
--- a/docs/zh/faq.md
+++ b/docs/zh/faq.md
@@ -189,6 +189,8 @@ carrier 与保留边界见 [PowerPoint ↔ SVG 映射指南](./powerpoint-svg-ma
一页时整页一次性呈现,不会自动逐个级联。两者都通过 `svg_to_pptx.py` 的
参数控制:`-t/--transition` 控制页级,`-a/--animation` 控制元素级。对象
注册表已经包含进入、强调、动作路径和退出效果。
+`pptx_to_svg.py` 也会把当前注册表内可精确读回的页面切换重建到
+`animations.json`;不支持的来源 carrier 会保留明确诊断。
```bash
python3 skills/ppt-master/scripts/svg_to_pptx.py <project> -t push # 换转场效果
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index 8943fa06..81dadbda 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -230,7 +230,7 @@ SVG 预览内容只负责让导出前的作者页面保持可见。
| PowerPoint 功能 | 项目中的所有者 | PPTX 结果 | 回导与保真度 | 校验边界 |
|---|---|---|---|---|
| 演讲者备注 | `notes/<slide>.md` sidecar | Notes Slide part 与 relationship | `Sidecar/package` | 备注不是 SVG 文本,不影响页面几何 |
-| 幻灯片切换 | CLI 选项或 `animations.json` | `p:transition` | `Sidecar/package` | 未知效果或非法时长失败;不默默 fallback 到 `fade` |
+| 幻灯片切换 | CLI 选项或 `animations.json` | `p:transition` | `Sidecar/package`;PPTX 回导把当前注册表内的精确切换重建到 `animations.json` | 未知效果或不精确 carrier 会失败或保留诊断;不默默 fallback 到 `fade` |
| 对象动画(进入 / 强调 / 动作路径 / 退出) | `animations.json`,目标为稳定的顶层 SVG group ID;`effects[]` 可让一个锚点拥有多条记录 | 根 `p:timing` 动画树 | `Sidecar/package`;group ID 仅为 shape target 锚点 | 静态结构层与占位符不可动画 |
| 旁白音频 | `audio/` 资产加 recorded-narration 导出选项 | media relationship、audio carrier 与 timing | `Sidecar/package` | 必须校验资产、Slide 关联与时序 |
| 幻灯片自动换页 | 显式 transition timing 或旁白派生时长 | `advTm`/换页行为 | `Sidecar/package` | 单击驱动动画与录制旁白不兼容 |
@@ -279,6 +279,7 @@ sidecar 工作流见[转场与动画](./animations.md)(技术规范源为 [`re
| 连接符 | expanded 线/path preview 加 connector/frame/topology 证据 |
| 组 | `<g>` |
| 受支持原生表格/图表 | 可见 fallback 加原生对象 metadata |
+| 当前注册表内受支持的页面切换 | 规范 `animations.json` 记录,包含有效选项、精确时长、可选自动换页与受支持 WAV 声音 |
| 不支持的 graphic frame 或 SmartArt | 显式 preview、placeholder 或 unsupported 状态 |
这是语义投影,不是语法往返。只有 Create Template mirror 可把来源包中已验证的 Master/Layout 事实保留到新工作区;普通视觉导入不会从 Slide 外观推断可复用拓扑。
@@ -295,7 +296,12 @@ sidecar 工作流见[转场与动画](./animations.md)(技术规范源为 [`re
| 不支持的 Slide 或 part 背景 | 省略该背景,继续当前页面/part | 在第一个违规点停止 | warning 标识所属 part |
| 损坏的包/XML 或缺失必需包结构 | 停止;不存在安全的页面级容错 | 停止 | 整洁的命令错误,不输出裸 Python traceback |
-每次成功转换都会写入 `<output>/conversion-report.json`。报告记录运行模式、Slide 与 warning 数量、稳定原因码、源错误消息、采用的 fallback、包 part,以及可用时的 Slide 序号和 shape id/name/kind。因此,容错导入不是静默吞错:它尽可能保留可用输出,同时让每一次合同降级都可复核。
+每次成功转换都会写入 `<output>/conversion-report.json` 和以 `none` 为
+基线切换的规范 `<output>/animations.json`。报告记录运行模式、Slide 与
+warning 数量、归属产物、稳定原因码、源错误消息、采用的 fallback、包 part,
+以及可用时的 Slide 序号和 shape id/name/kind。未知或不精确的切换 carrier
+会保留明确的 `transition-not-reconstructed` 诊断。因此,容错导入不是静默
+吞错:它尽可能保留可用输出,同时让每一次合同降级都可复核。
## 13. 校验职责
diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.md
index da73f3f3..3010fab9 100644
--- a/docs/zh/roadmap.md
+++ b/docs/zh/roadmap.md
@@ -70,7 +70,7 @@
| 关注点 | 状态 | 说明 |
|---|---|---|
-| 页面转场 | 系统化 | 含来自内置 CC0 音效库的按需转场音 |
+| 页面转场 | 系统化 | 含来自内置 CC0 音效库的按需转场音;PPTX 回导会把当前注册表内的精确转场重建到规范 sidecar |
| 对象动画 | 系统化 | 默认关闭、opt-in;逐对象配置为显式声明 |
| 自动翻页 | 已覆盖 | 由旁白起始留白、音频时长与页尾补白推导 |
| 音视频播放 | 已覆盖 | 旁白音频与动画音效原生播放;来源 deck 中已有的媒体保留其播放设置 |
diff --git a/skills/ppt-master/references/animations.md b/skills/ppt-master/references/animations.md
index 921d6648..cb09c0c4 100644
--- a/skills/ppt-master/references/animations.md
+++ b/skills/ppt-master/references/animations.md
@@ -595,6 +595,14 @@ object-animation timing before and after their allowed edits, then run
structural package validation; they do not author or normalize animation
effects.
+`pptx_to_svg.py` uses the same generated-transition read-back validator to
+project supported source `p:transition` into canonical `animations.json` rows.
+It retains the registry effect, effective options, exact duration, automatic
+advance, and supported WAV sound; the sidecar defaults to `none` so absent
+source transitions remain absent on re-export. Unknown or inexact native
+carriers stay diagnosed/direct-preserve. This is a closed PPT Master-owned
+contract, not an arbitrary OOXML transition normalizer.
+
**Validation boundary**: these checks prove PPTX timing, relationships, and
embedded sound parts. They are not final-video audio acceptance. The
native-export branch requires a triggered `video_sound_mix.py` receipt; the
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 279c268a..d9d4d7c8 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -290,6 +290,13 @@ Template `page_layouts` records authoring-input provenance, `pptx_masters` / `pp
Legacy structured/template contracts using `baseline`, `template`, `preserve`, `layout_strategy`, `data-pptx-layout-kind`, `distilled`/`utility`, direct atomic placeholders, or incomplete root Master identity must be replaced by a new workspace created through [`create-template`](../workflows/create-template.md). Generate new structured SVG pages from that workspace; do not upgrade the existing PPTX/SVG in place. Explicit flat free-design/Brand-only/Style-only projects intentionally omit root Master identity.
+`pptx_to_svg.py` also writes a canonical `animations.json` whose default
+transition is `none`. Page transitions produced by the current native
+transition registry are read back with their effective options, exact duration,
+automatic advance, and optional embedded WAV sound. Source transition XML
+outside that closed writer/read-back contract remains diagnosed rather than
+being normalized by guesswork.
+
`pptx_to_svg.py` annotates verified text-grid tables and conservative chart data with `data-pptx-replace-with` beside the visible SVG fallback and places the payload in `<metadata type="application/json">`; the parent claim selects the chart or table schema. Imported table/chart groups under this contract carry `data-pptx-import-source="pptx"`, whether active or fallback-only. Table import covers exact physical row/grid topology, canonical rectangular merges, safe solid/no-fill per-side borders, plain multi-paragraph cells, and a closed run-rich paragraph schema. Each rich run requires `text` and may use only `bold`, `italic`, `underline`, `strike`, `color`, `font_size`, one `font_family`, `lang`, and `alt_lang`. A merge must use the exact `rowSpan` / `gridSpan` / `hMerge` / `vMerge` physical topology with empty merge slaves. Presentation-only source run XML without a non-empty `effectLst` / `effectDag` normalizes; a table-cell run effect disables native replacement and adds a blocking effect diagnostic. Relationship-bearing text, extensions, line breaks, fields, tabs, bullets, broken text topology, unsafe border XML, non-solid fills, and other merge encodings remain fallback-only. For table style `{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}`, the normalized SVG fallback resolves `wholeTbl`, `firstRow`, horizontal banding, theme colors/fonts, and direct cell/run overrides; other built-in/custom style families are not implied.
Supported parsed column/bar/line/area, pie/doughnut, scatter, and bubble charts without a baked preview receive a deterministic readable fallback marked `data-pptx-fallback-kind="normalized"`. The importer additionally activates verified column/line/area combo charts, canonical OHLC stock charts, area charts with numeric date axes, verified scatter/bubble charts whose two value axes fit the closed `axes.x` / `axes.y` contract, radar charts, safe `of_pie` `serLines`, axis/title/legend normalization, and validated bar/column gap/overlap cases. Combo plots may retain independent primary/secondary category caches and workbook ranges. Both the category/value and XY contracts retain kind/position/visibility/label position/number format/min/max/major unit/reverse/major gridlines for native read-back. Scatter import derives effective `scatter_style` from uniform per-series line/marker/smooth state. The normalized XY fallback consumes only the two major-gridline flags; the C4/C5 additions do not expand the normalized renderer. `gapWidth` is accepted only as an integer in `0..500` and `overlap` only as an integer in `-100..100`; both normalize in native output, while malformed or out-of-range values fail closed. Safe common series paint forms and theme scheme colors are resolved; unknown series paint/style XML outside the explicit normalization boundaries still fails closed. Safe stock series style may pass the structural gate, but stock series, `hiLowLines`, and up-down bar local styling can still normalize under the data-object-first contract. The PowerPoint-native replacement remains allowed to normalize unmodeled no-fill/alpha/line/marker details and reports the route-level loss risk. Chart title/legend/axis titles and supported data-label flags are retained when the current schema can represent them. Fallback-only objects keep rendered SVG content or a baked chart preview and carry `data-pptx-replacement-status`, which validation and `--native-charts-and-tables` export report as a warning. An active marker without a renderer keeps `data-pptx-fallback-kind="placeholder"`; default export keeps the reconstruction-only placeholder and the native Chart/Table opt-in may still reconstruct it.
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index 5585289c..ad6e90b7 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -251,6 +251,10 @@ python3 scripts/pptx_to_svg.py deck.pptx --strict
| `layered` | Only the layered `svg/` view and inheritance metadata |
| `flat` | One self-contained slide SVG per page under `svg/` |
+Every mode also writes a canonical `animations.json`. Its default transition
+is `none`, so slides without a source transition stay transition-free when the
+workspace is exported again.
+
For Office pictures that carry both a raster compatibility preview on
`a:blip` and an editable SVG relationship in `asvg:svgBlip`, import resolves
the SVG relationship first. The raster relationship is used only when the SVG
@@ -277,8 +281,10 @@ exists. Pass `--strict` for parser development or contract verification when
the first unsupported/malformed source construct should stop conversion.
Every successful run writes `<output>/conversion-report.json`. Its stable
-top-level fields are `schemaVersion`, `source`, `mode`, `summary`, and
-`diagnostics`. Each diagnostic records a reason `code`, source `message`, chosen
+top-level fields are `schemaVersion`, `source`, `mode`, `summary`, `artifacts`,
+and `diagnostics`; `artifacts.animationConfig` and
+`artifacts.animationMedia` identify the converter-owned sidecar and transition
+sounds. Each diagnostic records a reason `code`, source `message`, chosen
`fallback`, package `part_path`, and—when available—`slide_index`, `shape_id`,
`shape_name`, and `shape_kind`. The command also prints a bounded warning
summary instead of a raw Python traceback.
@@ -289,11 +295,27 @@ retains the usable fallback/object and records the degradation; it does not
discard unrelated shapes, pages, or the entire deck.
Source `p:transition` and `p:timing` nodes are never silently implied by the
-static SVG view. Until their corresponding sidecar read-back stages are
-enabled, the importer emits `transition-not-reconstructed` and
-`animation-not-reconstructed` diagnostics with the exact source slide. Direct
-PPTX Fill/Enhance workflows remain the source-preserving route; `--strict`
-stops on the first such unreconstructed node.
+static SVG view. Supported page transitions are reconstructed in
+`animations.json`; source object timing still emits
+`animation-not-reconstructed` with the exact source slide. Direct PPTX
+Fill/Enhance workflows remain the source-preserving route for timing outside
+the closed read-back contracts; `--strict` stops on the first unreconstructed
+node.
+
+### Page-transition reverse import
+
+The importer accepts exactly the current generated-transition registry and
+validates the source carrier with the same read-back contract used after
+SVG-to-PPTX export. It reconstructs the canonical effect and all effective
+options, exact `p14:dur`, optional `advTm`, and an internal WAV transition
+sound. Sound bytes are extracted under the selected media directory with a
+content-addressed filename and referenced from the sidecar.
+
+This is a PPT Master-owned semantic loop, not a general transition normalizer.
+Unknown effects, legacy `p:transition@spd`, visual effects without exact
+`p14:dur`, `advClick="0"`, malformed carriers, and unsupported or broken sound
+relationships produce `transition-not-reconstructed` in tolerant mode;
+`--strict` stops. The converter never substitutes `fade` for those cases.
### Native formula reverse import
diff --git a/skills/ppt-master/scripts/pptx_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg.py
index 0a4859c8..d0d1e404 100644
--- a/skills/ppt-master/scripts/pptx_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg.py
@@ -11,6 +11,7 @@ Output structure (default --inheritance-mode both):
<output_dir>/
svg/ layered machine input: masters/layouts/slides
svg-flat/ self-contained visual preview slides
+ animations.json normalized transition/object-motion sidecar
<media_subdir>/ (default: assets/)
image1.png
image2.png
@@ -189,6 +190,7 @@ def main() -> int:
file=sys.stderr,
)
print(f"Output: {output_dir}")
+ print(f"Animation config: {output_dir / 'animations.json'}")
print(f"Conversion report: {output_dir / 'conversion-report.json'}")
return 0
diff --git a/skills/ppt-master/scripts/pptx_to_svg/converter.py b/skills/ppt-master/scripts/pptx_to_svg/converter.py
index 13c5aac2..697f8ff3 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/converter.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/converter.py
@@ -24,6 +24,11 @@ from html import unescape
from pathlib import Path, PurePosixPath
from urllib.parse import unquote, urlsplit
+from svg_to_pptx.animation_config import (
+ validate_animation_config_errors,
+ validate_transition_config,
+)
+
from .color_resolver import ColorPalette
from .emu_units import NS
from .import_diagnostics import ImportDiagnostic, append_diagnostic
@@ -34,6 +39,10 @@ from .ooxml_loader import (
part_show_master_sp,
)
from .slide_to_svg import assemble_part_solo, assemble_slide
+from .transition_import import (
+ TransitionImportError,
+ import_slide_transition,
+)
_CJK_THEME_SCRIPTS = frozenset({"Hans", "Hant", "Jpan", "Hang"})
@@ -41,6 +50,9 @@ _MANAGED_PRIMARY_SVG_RE = re.compile(
r"(?:slide_\d+|master_\d+_[A-Za-z0-9_-]+|layout_\d+_[A-Za-z0-9_-]+)\.svg"
)
_MANAGED_FLAT_SVG_RE = re.compile(r"slide_\d+\.svg")
+_MANAGED_TRANSITION_SOUND_RE = re.compile(
+ r"transition_sound_[0-9a-f]{16}\.wav"
+)
_SVG_HREF_RE = re.compile(
r"\b(?:href|xlink:href)\s*=\s*[\"']([^\"']+)[\"']"
)
@@ -203,6 +215,19 @@ class ConvertResult:
flat_slides: list[SlideArtifact] = field(default_factory=list)
master_themes: dict[str, dict[str, object]] = field(default_factory=dict)
diagnostics: list[ImportDiagnostic] = field(default_factory=list)
+ animation_config: dict[str, object] = field(
+ default_factory=lambda: {
+ "version": 1,
+ "defaults": {
+ "transition": {
+ "effect": "none",
+ "duration": 0.0,
+ },
+ },
+ "slides": {},
+ }
+ )
+ animation_media_files: dict[str, bytes] = field(default_factory=dict)
source_file: str = ""
strict: bool = False
@@ -325,10 +350,11 @@ def convert_pptx_to_svg(
# rendered alongside when needed.
primary_mode = "layered" if emit_layered else "flat"
for slide in pkg.iter_slides():
- _diagnose_unreconstructed_slide_features(
+ _read_back_slide_motion(
+ pkg,
slide,
- result.diagnostics,
- strict=options.strict,
+ result,
+ options,
)
slide_theme = pkg.resolve_theme(slide.master) or default_theme
slide_palette = _make_palette(
@@ -383,38 +409,74 @@ def convert_pptx_to_svg(
return result
-def _diagnose_unreconstructed_slide_features(
+def _read_back_slide_motion(
+ pkg: OoxmlPackage,
slide: SlideRef,
- diagnostics: list[ImportDiagnostic],
- *,
- strict: bool,
+ result: ConvertResult,
+ options: ConvertOptions,
) -> None:
- """Report source-owned motion that the SVG workspace cannot yet express."""
- for tag, code, label in (
- ("p:transition", "transition-not-reconstructed", "slide transition"),
- ("p:timing", "animation-not-reconstructed", "object animation timing"),
- ):
- if slide.part.xml.find(tag, NS) is None:
- continue
- message = (
- f"Source slide contains {label} that was not reconstructed "
- "in the SVG workspace"
+ """Recover supported transitions and diagnose remaining motion."""
+ try:
+ transition = import_slide_transition(
+ pkg,
+ slide,
+ media_subdir=options.media_subdir,
)
- if strict:
- raise ValueError(message)
+ except TransitionImportError as exc:
+ message = f"Slide transition was not reconstructed: {exc}"
+ if options.strict:
+ raise ValueError(message) from exc
append_diagnostic(
- diagnostics,
+ result.diagnostics,
ImportDiagnostic(
- code=code,
+ code="transition-not-reconstructed",
message=message,
fallback=(
- "keep the source PPTX for direct native preservation or "
- "author the corresponding animations.json sidecar"
+ "keep this transition in the source PPTX through direct "
+ "native preservation"
),
part_path=slide.part.path,
slide_index=slide.index,
),
)
+ else:
+ if transition is not None:
+ slides = result.animation_config["slides"]
+ if not isinstance(slides, dict):
+ raise RuntimeError("internal animations.json slides must be an object")
+ slides[f"slide_{slide.index:02d}"] = {
+ "transition": transition.config,
+ }
+ for filename, payload in transition.media_files.items():
+ existing = result.animation_media_files.get(filename)
+ if existing is not None and existing != payload:
+ raise RuntimeError(
+ "Transition sound filename collision with different bytes: "
+ f"{filename}"
+ )
+ result.animation_media_files[filename] = payload
+
+ if slide.part.xml.find("p:timing", NS) is None:
+ return
+ message = (
+ "Source slide contains object animation timing that was not "
+ "reconstructed in the SVG workspace"
+ )
+ if options.strict:
+ raise ValueError(message)
+ append_diagnostic(
+ result.diagnostics,
+ ImportDiagnostic(
+ code="animation-not-reconstructed",
+ message=message,
+ fallback=(
+ "keep the source PPTX for direct native preservation or "
+ "author the corresponding animations.json sidecar"
+ ),
+ part_path=slide.part.path,
+ slide_index=slide.index,
+ ),
+ )
def _convert_slide(
@@ -592,6 +654,42 @@ def _managed_svg_paths(output_dir: Path) -> list[Path]:
return managed
+def _managed_report_artifact_paths(output_dir: Path) -> set[Path]:
+ """Return optional artifacts owned by the previous conversion report."""
+ report_path = output_dir / "conversion-report.json"
+ if report_path.is_symlink() or not report_path.is_file():
+ return set()
+ try:
+ report = json.loads(report_path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, json.JSONDecodeError):
+ return set()
+ artifacts = report.get("artifacts")
+ if not isinstance(artifacts, dict):
+ return set()
+ if artifacts.get("animationConfig") != "animations.json":
+ return set()
+
+ managed = {Path("animations.json")}
+ animation_media = artifacts.get("animationMedia")
+ if not isinstance(animation_media, list):
+ return managed
+ for value in animation_media:
+ if not isinstance(value, str):
+ continue
+ path = Path(value)
+ if (
+ path.drive
+ or path.anchor
+ or path.is_absolute()
+ or not path.parts
+ or ".." in path.parts
+ or not _MANAGED_TRANSITION_SOUND_RE.fullmatch(path.name)
+ ):
+ continue
+ managed.add(path)
+ return managed
+
+
def _referenced_local_paths(
output_dir: Path,
svg_paths: list[Path],
@@ -783,6 +881,7 @@ def publish_staged_workspace(
}
relative_paths.update(_referenced_local_paths(output_dir, managed_svg))
relative_paths.add(Path("conversion-report.json"))
+ relative_paths.update(_managed_report_artifact_paths(output_dir))
relative_paths.update(_validated_relative_paths(managed_root_files or set()))
relative_paths.update(_validated_relative_paths(managed_relative_paths or set()))
_remove_managed_paths(candidate_dir, relative_paths)
@@ -861,6 +960,7 @@ def _write_artifact_tree(
target = svg_dir / f"slide_{art.index:02d}.svg"
target.write_text(art.svg, encoding="utf-8")
_collect_media(art.media_files)
+ _collect_media(result.animation_media_files)
# Inheritance graph alongside the layered SVGs (only meaningful when we
# actually emitted a layered view).
@@ -876,7 +976,8 @@ def _write_artifact_tree(
target.write_text(art.svg, encoding="utf-8")
_collect_media(art.media_files)
- _write_conversion_report(output_dir, result)
+ _write_animation_config(output_dir, result)
+ _write_conversion_report(output_dir, result, options)
if media_written:
media_dir.mkdir(parents=True, exist_ok=True)
for filename, blob in media_written.items():
@@ -914,8 +1015,16 @@ def _write_artifacts(
shutil.rmtree(staging_root, ignore_errors=True)
-def _write_conversion_report(output_dir: Path, result: ConvertResult) -> None:
+def _write_conversion_report(
+ output_dir: Path,
+ result: ConvertResult,
+ options: ConvertOptions,
+) -> None:
"""Write the user-visible tolerant-import report."""
+ animation_media = [
+ (PurePosixPath(options.media_subdir) / filename).as_posix()
+ for filename in sorted(result.animation_media_files)
+ ]
report = {
"schemaVersion": 1,
"source": result.source_file,
@@ -924,6 +1033,10 @@ def _write_conversion_report(output_dir: Path, result: ConvertResult) -> None:
"slides": len(result.slides),
"warnings": len(result.diagnostics),
},
+ "artifacts": {
+ "animationConfig": "animations.json",
+ "animationMedia": animation_media,
+ },
"diagnostics": [item.to_dict() for item in result.diagnostics],
}
(output_dir / "conversion-report.json").write_text(
@@ -932,6 +1045,28 @@ def _write_conversion_report(output_dir: Path, result: ConvertResult) -> None:
)
+def _write_animation_config(output_dir: Path, result: ConvertResult) -> None:
+ """Write the canonical transition/object-motion sidecar."""
+ errors = list(
+ dict.fromkeys(
+ validate_transition_config(result.animation_config)
+ + validate_animation_config_errors(result.animation_config)
+ )
+ )
+ if errors:
+ raise RuntimeError(
+ "Generated animations.json is invalid: " + "; ".join(errors)
+ )
+ (output_dir / "animations.json").write_text(
+ json.dumps(
+ result.animation_config,
+ ensure_ascii=False,
+ indent=2,
+ ) + "\n",
+ encoding="utf-8",
+ )
+
+
def _write_inheritance_json(svg_dir: Path, result: ConvertResult) -> None:
"""Record layered parentage plus source-owned shape-visibility booleans."""
layout_by_path = {art.part_path: art.filename for art in result.layouts}
diff --git a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py
index 9e8716c9..3a60a665 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py
@@ -264,13 +264,17 @@ class OoxmlPackage:
"""Load an arbitrary XML part by package path."""
return self._load_part(part_path)
- def read_media(self, part_path: str) -> bytes | None:
- """Return raw bytes of an embedded media part (e.g. ppt/media/image1.png)."""
+ def read_part_bytes(self, part_path: str) -> bytes | None:
+ """Return the unchanged bytes of one internal package part."""
assert self.zip is not None
if part_path not in self.zip.namelist():
return None
return self.zip.read(part_path)
+ def read_media(self, part_path: str) -> bytes | None:
+ """Return raw bytes of an embedded media part (e.g. ppt/media/image1.png)."""
+ return self.read_part_bytes(part_path)
+
def media_filename(self, part_path: str) -> str:
"""Last segment of the media path, e.g. 'image1.png'."""
return PurePosixPath(part_path).name
diff --git a/skills/ppt-master/scripts/pptx_to_svg/transition_import.py b/skills/ppt-master/scripts/pptx_to_svg/transition_import.py
new file mode 100644
index 00000000..c61745f2
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_to_svg/transition_import.py
@@ -0,0 +1,201 @@
+"""Import PPT Master-owned slide transitions into animations.json rows.
+
+The reverse contract accepts only source XML that passes the existing
+generated-transition read-back validator. Unknown third-party carriers remain
+outside the reconstruction claim and are handled by the caller's diagnostics.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass
+from pathlib import PurePosixPath
+
+from pptx_transitions import (
+ TransitionSummary,
+ read_slide_transition_xml,
+ validate_generated_transition_xml,
+)
+
+from .ooxml_loader import OoxmlPackage, SlideRef
+
+
+_AUDIO_RELATIONSHIP_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio"
+)
+
+
+class TransitionImportError(ValueError):
+ """Raised when a source transition is outside the reversible contract."""
+
+
+@dataclass(frozen=True)
+class TransitionImport:
+ """One canonical sidecar row plus any extracted transition sound."""
+
+ config: dict[str, object]
+ media_files: dict[str, bytes]
+
+
+@dataclass(frozen=True)
+class TransitionReadback:
+ """One validated transition before its sound relationship is resolved."""
+
+ config: dict[str, object]
+ summary: TransitionSummary
+
+
+def read_transition_config(
+ slide_xml: str | bytes,
+) -> TransitionReadback | None:
+ """Read one exact generated-transition contract from slide XML."""
+ summary = read_slide_transition_xml(slide_xml)
+ if summary.logical_count == 0:
+ return None
+ if summary.speed is not None:
+ raise TransitionImportError(
+ "legacy p:transition@spd cannot be represented exactly by "
+ "animations.json duration"
+ )
+ if summary.effect is not None and summary.canonical_effect is None:
+ raise TransitionImportError(
+ "transition effect is outside the canonical native registry"
+ )
+ if summary.canonical_effect is not None and summary.duration_ms is None:
+ raise TransitionImportError(
+ "visual transition is missing the exact p14:dur duration"
+ )
+
+ sound = _sound_expectation(summary)
+ duration = (
+ summary.duration_ms / 1000.0
+ if summary.duration_ms is not None
+ else 0.0
+ )
+ advance_after = (
+ summary.advance_after_ms / 1000.0
+ if summary.advance_after_ms is not None
+ else None
+ )
+ try:
+ validate_generated_transition_xml(
+ slide_xml,
+ effect=summary.canonical_effect,
+ effect_options=summary.effect_options,
+ duration=duration,
+ advance_on_click=summary.advance_on_click,
+ advance_after=advance_after,
+ sound=sound,
+ )
+ except ValueError as exc:
+ raise TransitionImportError(str(exc)) from exc
+ if summary.advance_on_click is not True:
+ raise TransitionImportError(
+ "advance_on_click=false is outside the animations.json "
+ "transition contract"
+ )
+
+ config: dict[str, object] = {
+ "effect": summary.canonical_effect or "none",
+ }
+ if summary.effect_options:
+ config["effect_options"] = dict(summary.effect_options)
+ if summary.canonical_effect is not None:
+ config["duration"] = duration
+ if advance_after is not None:
+ config["auto_advance"] = advance_after
+ return TransitionReadback(config=config, summary=summary)
+
+
+def import_slide_transition(
+ pkg: OoxmlPackage,
+ slide: SlideRef,
+ *,
+ media_subdir: str,
+) -> TransitionImport | None:
+ """Read one slide transition and resolve its optional WAV relationship."""
+ slide_xml = pkg.read_part_bytes(slide.part.path)
+ if slide_xml is None:
+ raise TransitionImportError(
+ f"source slide part is missing: {slide.part.path}"
+ )
+ readback = read_transition_config(slide_xml)
+ if readback is None:
+ return None
+
+ config = dict(readback.config)
+ media_files: dict[str, bytes] = {}
+ relationship_id = readback.summary.sound_relationship_id
+ if relationship_id is not None:
+ sound_path, sound_bytes = _resolve_transition_sound(
+ pkg,
+ slide,
+ relationship_id,
+ )
+ media_files[sound_path] = sound_bytes
+ config["sound"] = (
+ PurePosixPath(media_subdir) / sound_path
+ ).as_posix()
+ return TransitionImport(config=config, media_files=media_files)
+
+
+def _sound_expectation(
+ summary: TransitionSummary,
+) -> dict[str, str] | None:
+ relationship_id = summary.sound_relationship_id
+ name = summary.sound_name
+ if relationship_id is None and name is None:
+ return None
+ if not relationship_id or not name:
+ raise TransitionImportError(
+ "transition sound requires both relationship id and display name"
+ )
+ return {
+ "relationship_id": relationship_id,
+ "name": name,
+ }
+
+
+def _resolve_transition_sound(
+ pkg: OoxmlPackage,
+ slide: SlideRef,
+ relationship_id: str,
+) -> tuple[str, bytes]:
+ relationship = slide.part.rels.get(relationship_id)
+ if relationship is None:
+ raise TransitionImportError(
+ f"transition sound relationship is missing: {relationship_id}"
+ )
+ if relationship.get("external"):
+ raise TransitionImportError("transition sound relationship must be internal")
+ if relationship.get("type") != _AUDIO_RELATIONSHIP_TYPE:
+ raise TransitionImportError(
+ "transition sound relationship must use the OOXML audio type"
+ )
+ target = relationship.get("target") or ""
+ if PurePosixPath(target).suffix.lower() != ".wav":
+ raise TransitionImportError("transition sound part must use .wav")
+ payload = pkg.read_part_bytes(target)
+ if payload is None:
+ raise TransitionImportError(
+ f"transition sound part is missing: {target}"
+ )
+ if not (
+ len(payload) >= 12
+ and payload[:4] in {b"RIFF", b"RF64"}
+ and payload[8:12] == b"WAVE"
+ ):
+ raise TransitionImportError(
+ f"transition sound part is not a valid WAV file: {target}"
+ )
+ digest = hashlib.sha256(payload).hexdigest()[:16]
+ return f"transition_sound_{digest}.wav", payload
+
+
+__all__ = [
+ "TransitionImport",
+ "TransitionImportError",
+ "TransitionReadback",
+ "import_slide_transition",
+ "read_transition_config",
+]
diff --git a/skills/ppt-master/scripts/pptx_transitions.py b/skills/ppt-master/scripts/pptx_transitions.py
index 22e202eb..348c2b3e 100644
--- a/skills/ppt-master/scripts/pptx_transitions.py
+++ b/skills/ppt-master/scripts/pptx_transitions.py
@@ -2431,8 +2431,11 @@ def validate_generated_transition_xml(
for child in (list(primary) if primary is not None else [])
if child.tag != _qn(PML_NS, "sndAc")
]
- if not effect_children:
- errors.append("generated transition has no visual effect child")
+ if len(effect_children) != 1:
+ errors.append(
+ "generated transition must contain exactly one visual "
+ f"effect child; found {len(effect_children)}"
+ )
else:
for name, value in expected_attrs.items():
if effect_children[0].get(name) != str(value):