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(svg-to-pptx): compile explicit template layouts

hugohe318b51e2ce687
diff --git a/docs/roadmap.md b/docs/roadmap.md
index be3f3b16..162ed946 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -82,7 +82,7 @@ The past two months' structural capability growth. Single flags / incremental po
- **`--native-objects` hardened from dormant marker to usable opt-in** — the narrow native-object exception (see Non-goals below) now emits charts and pure-text tables that keep the deck's own design instead of snapping to PowerPoint's white default theme. Classic native charts write explicit chart-area / plot-area / axis-line / gridline / label-text colors — inferred from the visible SVG fallback (largest panel `<rect>` → background, fallback text → labels, fallback strokes → axis/grid) or overridden per `style` (`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`, `"none"` for transparent); the color parser normalizes named CSS colors, `#RGB` shorthand, and `rgb()` / `rgba()` to OOXML hex; bar/column series disable negative-value fill inversion so negative bars keep their series color. The activated export is named `<name>_<ts>_native_charts.pptx` to tell it apart from the default flattened-shape export. **The default route is unchanged** — charts/tables still export as SVG-derived DrawingML shapes for cross-renderer fidelity; native objects stay the deliberate opt-in trade documented under Non-goals below
-- **Native package structure + conservative PPTX object round-trip** — native export now keeps the base package's real blank-layout relationship and defaults to a baseline master that promotes only identical backgrounds and a safe leading prefix of repeated chrome. The standalone `pptx_to_svg.py` importer emits fallback SVG plus native metadata for supported unmerged tables and classic-chart caches; exporter-canonical solid series/slice colors and exact title/subtitle structures survive a second `--native-objects` export, while unsupported table/chart semantics remain explicit fallback-only markers
+- **Native package structure + conservative PPTX object round-trip** — native export now keeps the base package's real blank-layout relationship and defaults to a baseline master that promotes only identical backgrounds and a safe leading prefix of repeated chrome. An explicit `--pptx-structure template` mode compiles declared SVG master/layout layers and typed placeholders into reusable PowerPoint layouts without visual inference; supplied PPTX templates still use the preservation-oriented `template-fill-pptx` route. The standalone `pptx_to_svg.py` importer emits fallback SVG plus native metadata for supported unmerged tables and classic-chart caches; exporter-canonical solid series/slice colors and exact title/subtitle structures survive a second `--native-objects` export, while unsupported table/chart semantics remain explicit fallback-only markers
---
diff --git a/docs/technical-design.md b/docs/technical-design.md
index aa0101e1..5b5973cd 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -429,6 +429,8 @@ These direct routes share some analysis primitives with the main pipeline, espec
**Why the default native deck has a baseline master, not inferred templates.** `svg_to_pptx.py` keeps the actual blank slide layout relationship from the base package and defaults to `--pptx-structure baseline`. Baseline promotes only low-risk shared structure: the strict-majority identical slide background (every slide must carry an explicit background, and minority slides keep their own overriding fill), plus a common leading prefix of repeated top-level SVG chrome whose exact id tokens say `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber`. Chrome promotion also requires identical generated OOXML, no slide-timing reference, and the same leading z-order across a strict majority of slides sharing the master; overlay chrome stays slide-local. Minority slides — covers and section pages — keep every shape slide-local and are rebound to a generated `Cover` layout with `showMasterSp="0"`, following the PowerPoint convention that page-type differences live in layouts under one master rather than in extra masters, so promoted chrome never leaks onto them. Image relationships for promoted chrome are copied to the slide master, base-template slide layouts no generated slide references are pruned from the package, and `pageNumber`/`slideNumber` chrome whose text exactly equals the slide's display number (honoring `firstSlideNum`) becomes an auto-updating slide-number field so reordering slides in PowerPoint renumbers pages. This gives ordinary decks real master/layout structure without guessing reusable layouts or placeholders from visual similarity.
+**Why reusable layouts require explicit SVG metadata.** `--pptx-structure template` is the opt-in path for a generated deck that must remain reusable as a PowerPoint template. The final slide SVGs declare a layout key at the root, mark only direct root children as master/layout layers, and attach typed placeholder semantics to the slide-local prototypes that should become layout placeholders. Export validates that shared master and same-key layout declarations are structurally and visually identical, then emits real layout parts and `p:ph` references while leaving every unmarked object slide-local. This is deterministic structure compilation, not visual-template inference. A supplied PPTX whose existing master/theme must survive still belongs to `template-fill-pptx`; `template` mode does not reconstruct an arbitrary source package.
+
**Why native-object reconstruction uses markers, not automatic object replacement.** The standalone `pptx_to_svg.py` importer can emit SVG fallback content plus `data-pptx-native` metadata for supported unmerged tables and conservative classic-chart caches. It retains source table-style inheritance, supported solid cell fills/basic text formatting, chart title/legend/axis titles, and plot-level data-label flags for area/bar/column/line charts when the current schema can represent them. Exporter-canonical classic charts also recover canonical solid series/slice colors and exact one- or two-paragraph title metadata. The default export still consumes fallback children as regular DrawingML shapes; only `--native-objects` activates editable PowerPoint tables/charts. Unsupported table cases — including merged cells, direct borders, non-solid fills, and mixed rich text — keep the rendered SVG table. Unsupported chart cases — including ChartEx, rotated/flipped/3D/combo charts, unsupported data-label scopes/types, custom axis semantics, trendlines/error bars, unsupported subtype options, sparse or non-finite caches, and date/formatted category axes — keep a baked preview when one exists, otherwise an explicit placeholder. Both carry `data-pptx-native-status`; the quality checker and native-object export report them as fallback-only warnings. This importer/exporter pairing is a reconstruction aid, not a preservation-route substitute for `template-fill-pptx` or `native-enhance-pptx`.
---
diff --git a/docs/zh/roadmap.md b/docs/zh/roadmap.md
index 3afa7112..9ff75a3d 100644
--- a/docs/zh/roadmap.md
+++ b/docs/zh/roadmap.md
@@ -82,7 +82,7 @@
- **`--native-objects` 从休眠 marker 硬化为可用级 opt-in** — 那条窄「原生对象」例外(见下文 Non-goals)现在导出的图表与纯文本表格会**保留 deck 自己的设计**,不再塌回 PowerPoint 的白底默认主题。classic 原生图表显式写入 chart-area / plot-area / 轴线 / 网格线 / 标签文字颜色——从可见的 SVG fallback 推断(最大面板型 `<rect>` → 背景、fallback 文字 → 标签、fallback 描边 → 轴线/网格),或用 `style` 显式覆盖(`chart_area_fill` / `plot_area_fill` / `text_color` / `axis_color` / `grid_color`,`"none"` 表透明);颜色解析把命名色、`#RGB` 简写、`rgb()` / `rgba()` 归一为 OOXML hex;bar/column 系列关掉负值反色,负值柱保持系列色。激活导出命名为 `<name>_<ts>_native_charts.pptx` 以与默认压平形状导出区分。**默认路线不变**——图表/表格仍以 SVG 派生的 DrawingML 形状导出以保跨渲染器保真;原生对象仍是下文 Non-goals 里那条刻意的 opt-in 取舍
-- **原生 package 结构 + 保守 PPTX 对象回转** — 原生导出现在保留基础 package 的真实空白版式关系,并默认使用 baseline master;只提升完全一致的背景和安全的前置重复 chrome。独立 `pptx_to_svg.py` 导入器会为受支持的未合并表格与 classic-chart cache 输出 fallback SVG 加原生元数据;由本 exporter 生成的规范纯色系列 / 切片与精确 title/subtitle 结构可经第二次 `--native-objects` 导出继续保留,无法等价表达的表格 / 图表语义则保持明确的 fallback-only marker
+- **原生 package 结构 + 保守 PPTX 对象回转** — 原生导出现在保留基础 package 的真实空白版式关系,并默认使用 baseline master;只提升完全一致的背景和安全的前置重复 chrome。显式 `--pptx-structure template` 模式会把 SVG 中声明的 master/layout layer 与有类型的 placeholder 编译成可复用 PowerPoint 版式,不做视觉推断;用户提供的 PPTX 模板仍走以保留为目标的 `template-fill-pptx` 路线。独立 `pptx_to_svg.py` 导入器会为受支持的未合并表格与 classic-chart cache 输出 fallback SVG 加原生元数据;由本 exporter 生成的规范纯色系列 / 切片与精确 title/subtitle 结构可经第二次 `--native-objects` 导出继续保留,无法等价表达的表格 / 图表语义则保持明确的 fallback-only marker
---
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 07fb328f..ab299753 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -429,6 +429,8 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。Executor 在一份
**为什么默认 native deck 使用基线母版,而不推断模板。** `svg_to_pptx.py` 会保留基础 package 中空白版式的真实关系,并默认使用 `--pptx-structure baseline`。Baseline 只提升低风险共享结构:严格多数页面完全一致的页面背景(每页都必须携带显式背景,少数派页面保留自己的背景并覆盖母版填充),以及位于 shape 序列开头(视觉后层)、且 id 精确 token 为 `logo`、`footer`、`header`、`watermark`、`chrome`、`pageNumber` 或 `slideNumber` 的重复 SVG chrome。Chrome 还必须在共享同一母版的严格多数页面上生成完全一致的 OOXML、没有被页面动画引用,并保持相同的前置 z-order;覆盖在正文之上的 chrome 继续留在 slide 本地。少数派页面(封面、章节页)的全部元素保持 slide-local,并被改绑到生成的 `Cover` 版式(`showMasterSp="0"`)——遵循 PowerPoint 的惯例:页型差异用同一母版下的版式表达而不是增加母版,因此被提升的母版 chrome 绝不会泄漏到这些页面上。被提升 chrome 的图片关系会复制到 slide master,基础模板中没有任何页面引用的 slide layout 也会从 package 中裁剪掉;`pageNumber`/`slideNumber` chrome 的文本若恰好等于该页应显示的页码(尊重 `firstSlideNum`),会转换为自动更新的 PowerPoint 页码字段,此后在 PowerPoint 中调整页序页码自动重算,其他编号方案保持字面文本不动。这样普通 deck 能获得真实的 master/layout 结构,同时不根据视觉相似度猜测可复用版式或占位符。
+**为什么可复用版式必须依赖显式 SVG 元数据。** `--pptx-structure template` 是生成型 deck 需要继续作为 PowerPoint 模板复用时的 opt-in 路径。最终 slide SVG 在根节点声明 layout key,只允许根节点的直接子元素标记 master/layout layer,并在应成为版式占位框的 slide-local 原型上附加类型语义。导出器会验证共享 master 与同 key layout 的声明在结构和视觉上完全一致,再生成真实 layout part 与 `p:ph` 引用;所有未标记对象仍保持 slide-local。这是确定性的结构编译,不是根据视觉相似度猜模板。若用户提供的是必须保留原有 master/theme 的 PPTX,仍应走 `template-fill-pptx`;`template` 模式不会重建任意来源的 package。
+
**为什么原生对象重建使用 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器会为受支持的未合并表格和保守 classic-chart cache 输出 SVG fallback,并附加 `data-pptx-native` 元数据;当现有 schema 能表达时,还会保留源表格样式继承、受支持的单元格纯色填充 / 基础文字格式,以及图表标题、图例、坐标轴标题和面积图 / 条形图 / 柱形图 / 折线图的 plot 级数据标签开关。由本 exporter 生成的规范 classic chart 还会回读规范纯色系列 / 切片,以及精确的单段或双段标题元数据。默认导出仍把 fallback 子元素当普通 DrawingML shape 处理;只有 `--native-objects` 才会启用可编辑的 PowerPoint 表格 / 图表。合并单元格、直接边框、非纯色填充、混合富文本等不支持的表格场景继续保留实际渲染的 SVG table。ChartEx、旋转 / 翻转 / 3D / 组合图表、不受支持的数据标签作用域或类型、自定义坐标轴语义、趋势线 / 误差线、不受支持的子类型参数、稀疏或非有限 cache、日期 / 格式化类别轴等不支持的图表场景,则在有 baked preview 时保留预览,否则给出明确占位符。两类对象都会写入 `data-pptx-native-status`;质量检查器和 native-object 导出将其报告为 fallback-only warning。这对 importer/exporter 是重建辅助能力,不能替代 `template-fill-pptx` 或 `native-enhance-pptx` 的保留型路线。
---
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index c5222661..012dff13 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -690,6 +690,19 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> `--pptx-structure flat` only for debugging/comparison when all generated
> backgrounds and chrome must remain slide-local.
+> **Explicit reusable template export** — pass `--pptx-structure template`
+> only when every SVG root declares `data-pptx-layout` and direct children
+> explicitly declare master/layout layers or PowerPoint placeholders. This
+> mode builds named reusable layouts and placeholder mappings; it does not
+> infer them from visual similarity. Static master/layout elements must be
+> repeated consistently in inheritance/z-order order. Chart/table placeholders
+> additionally require `--native-objects`. The metadata contract and authoring
+> example live in
+> [`references/shared-standards.md`](references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
+> Raw PPTX templates still route to `template-fill-pptx`; `template` structure
+> mode is for explicitly annotated SVG authoring, not source-package
+> preservation.
+
> **Paragraph editability vs line fidelity** — by default, mergeable dy-stacked
> paragraph blocks collapse into one editable PowerPoint text frame with multiple
> `<a:p>`, improving body-text editing and resize/reflow behavior. Add `--no-merge`
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index c0221bbc..5f89d826 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -925,6 +925,78 @@ steal plot area in PPT. Add `show_legend: true` only when the legend is needed;
**Forbidden — native marker transforms**: Do not rotate, skew, or matrix-transform native table/chart marker groups. Translate / scale is accepted; complex transforms fail export because PowerPoint native table/chart frames do not preserve arbitrary SVG transforms.
+### Explicit PPTX Master / Layout / Placeholder Metadata (Template Export)
+
+**Trigger**: Pass `--pptx-structure template`. Without that flag, the metadata
+stays visually dormant and the SVG exports through the normal baseline / flat
+path.
+
+| Metadata | Placement | Behavior |
+|---|---|---|
+| `data-pptx-layout="content"` | root `<svg>` | Binds the slide to one generated reusable layout key |
+| `data-pptx-layout-name="Title and Content"` | root `<svg>` | Sets the PowerPoint layout-picker name; defaults from the layout key |
+| `data-pptx-layer="master"` | direct visual child | Moves one repeated static object/background into the slide master |
+| `data-pptx-layer="layout"` | direct visual child | Moves one repeated static object/background into the selected layout |
+| `data-pptx-placeholder="..."` | direct visual child | Keeps actual content on the slide and maps it to a generated layout placeholder |
+| `data-pptx-placeholder-bounds="x y width height"` | placeholder element | Overrides the reusable placeholder frame in SVG user units |
+| `data-pptx-editable="false"` | master/layout element | Declares intentional editing through Master View, not Normal View |
+
+**Hard rule — explicit only**: Template export never promotes visually similar
+content by inference. Every SVG requires a root `data-pptx-layout`; every
+master/layout/placeholder element requires a unique `id` and must be a direct
+child of the root SVG.
+
+**Layer order**: Author the SVG in PowerPoint inheritance order: master elements
+first, then layout elements, then slide-local content/placeholders. Moving a
+later overlay behind slide content changes z-order, so the exporter rejects
+interleaved structure layers.
+
+| Placeholder value | SVG element | PowerPoint placeholder |
+|---|---|---|
+| `title`, `body`, `footer`, `slide-number` | direct `<text>` | `title`, `body`, `ftr`, `sldNum` |
+| `picture` | direct `<image>` or imported crop `<svg>` | `pic` |
+| `chart`, `table` | direct matching `data-pptx-native` marker group | `chart`, `tbl` |
+
+**Placeholder prototype**: The first slide using a layout key supplies that
+layout's placeholder formatting. `data-pptx-placeholder-bounds` supplies the
+reusable frame; when omitted, the exporter uses the prototype object's native
+DrawingML bounds. Repeat the same placeholder ids/types on every slide using
+that layout. Actual slide content and local geometry may differ.
+
+**Static structure consistency**: Repeat the same master element ids on every
+slide and the same layout element ids on every slide sharing a layout. Their
+generated OOXML must be identical within the affected master/layout group.
+Static structure may carry shapes, text, or images; non-image/external
+relationships are rejected. A full-canvas first rect/group may be marked as a
+master or layout background.
+
+**Native object placeholders**: `chart` / `table` placeholders require
+`--native-objects`; fallback groups contain several shapes and cannot map to one
+PowerPoint placeholder.
+
+```xml
+<svg xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 1280 720"
+ data-pptx-layout="content"
+ data-pptx-layout-name="Title and Content">
+ <rect id="master-bg" data-pptx-layer="master"
+ data-pptx-editable="false"
+ width="1280" height="720" fill="#F8FAFC"/>
+ <g id="content-rule" data-pptx-layer="layout"
+ data-pptx-editable="false">
+ <line x1="48" y1="96" x2="1232" y2="96"
+ stroke="#CBD5E1" stroke-width="2"/>
+ </g>
+ <text id="page-title" data-pptx-placeholder="title"
+ data-pptx-placeholder-bounds="80 112 1120 72"
+ x="80" y="158" font-size="40">Actual page title</text>
+ <image id="hero-image" data-pptx-placeholder="picture"
+ data-pptx-placeholder-bounds="680 210 480 320"
+ x="680" y="210" width="480" height="320"
+ href="../images/hero.png"/>
+</svg>
+```
+
### transform: rotate — Element Rotation
Rotation converts to native PPTX `<a:xfrm rot="...">`. Supported on all element types: `rect`, `circle`, `ellipse`, `line`, `path`, `polygon`, `polyline`, `image`, and `text`.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 426203a0..6143bb9f 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -118,6 +118,8 @@ python3 scripts/svg_to_pptx.py <project_path>
Native `svg_to_pptx.py` also defaults to `--pptx-structure baseline`: the generated deck keeps a standard master/layout relationship and promotes the strict-majority identical native slide background into the slide master (minority slides keep their own overriding background). A shared leading prefix of top-level SVG elements with exact chrome id tokens such as `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber` may also be promoted when its generated OOXML is identical on a strict majority of slides, it is not referenced by slide timing, and moving it behind slide-local content preserves z-order; image relationships are copied to the master. Minority slides such as covers keep every shape slide-local and are bound to a generated `Cover` layout (`showMasterSp="0"`) that hides the promoted master chrome. Baseline additionally prunes base-template slide layouts that no generated slide references, and swaps `pageNumber`/`slideNumber` chrome text for an auto-updating slide-number field when the text exactly equals the slide's display number. Use `--pptx-structure flat` when all generated backgrounds and chrome must remain slide-local for debugging or comparison.
+Use `--pptx-structure template` only when the final slide SVGs explicitly declare reusable PowerPoint structure. Each SVG names its layout with `data-pptx-layout`; direct root children may opt into master/layout layers with `data-pptx-layer`, and supported text, picture, chart, table, footer, or slide-number elements may declare `data-pptx-placeholder`. The exporter validates cross-slide consistency, creates one reusable layout per layout key, and keeps unmarked content slide-local. It never infers placeholders from visual similarity. The complete metadata contract lives in [`references/shared-standards.md`](../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
+
`pptx_to_svg.py` annotates supported unmerged tables and conservative classic-chart caches with `data-pptx-native` metadata. Source table-style inheritance, supported solid cell fills/basic text formatting, chart title/legend/axis titles, and plot-level data-label flags for area/bar/column/line charts are retained when the current schema can represent them. Tables with direct borders, non-solid fills, or mixed rich-text formatting remain fallback-only, as do charts with unsupported label scopes/types, custom axis semantics, trendlines/error bars, or subtype options. Unsupported tables keep their rendered SVG table; unsupported charts keep a baked preview or explicit placeholder. Both carry `data-pptx-native-status`, which `svg_quality_checker.py` and `svg_to_pptx.py --native-objects` report as a warning.
Exporter-canonical classic charts also recover canonical solid series/slice
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 4a446998..04f8622d 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -31,6 +31,7 @@ Convert project SVGs into PPTX.
```bash
python3 scripts/svg_to_pptx.py <project_path>
python3 scripts/svg_to_pptx.py <project_path> --native-objects
+python3 scripts/svg_to_pptx.py <project_path> --pptx-structure template # explicit SVG template metadata
python3 scripts/svg_to_pptx.py <project_path> --pptx-structure flat # structure diagnostic
# Template-import visual round-trip diagnostic only:
python3 scripts/svg_to_pptx.py <template_import_output> --only native -s svg-flat
@@ -60,6 +61,7 @@ Behavior:
`svg_final/`. Use `-s` only as an explicit diagnostic override.
- For PPTX template-import workspaces, use `-s svg-flat` when you need a visual round-trip check. The layered `svg/` tree is the machine-readable template source and intentionally does not inline inherited master / layout decoration into each slide.
- Native mode is strict about unsupported visual SVG elements: if a visual element cannot be represented or safely preserved, export fails with the SVG file, element tag, and position instead of silently dropping content.
+- `--pptx-structure template` builds reusable PowerPoint layouts only from explicit SVG metadata: root `data-pptx-layout`, direct-child `data-pptx-layer="master|layout"`, and direct-child `data-pptx-placeholder`. It validates cross-slide structure consistency and never infers layouts from visual similarity. Chart/table placeholders also require `--native-objects`; full contract: [`shared-standards.md`](../../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export).
- Native output uses content-hash media filenames, so identical images are reused and different images cannot overwrite each other by sharing a basename.
- `[Content_Types].xml` is generated from the actual media extensions written into the PPTX. Unknown media extensions fail unless Python's `mimetypes` can identify them.
- Native export writes to a temporary file first and publishes the requested PPTX only after conversion succeeds. A failed conversion does not replace the main output file.
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 6b793215..ceb83a67 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -73,6 +73,13 @@ try:
except ImportError:
_native_object_marker_warnings = None
+try:
+ from svg_to_pptx.pptx_package.template_structure import (
+ validate_template_svg as _validate_template_structure_svg,
+ )
+except ImportError:
+ _validate_template_structure_svg = None
+
try:
from svg_finalize.embed_icons import (
resolve_icon_path as _resolve_icon_path,
@@ -383,6 +390,9 @@ class SVGQualityChecker:
# 8c. Check opt-in native table/chart markers before export.
self._check_native_object_markers(root, result)
+ # 8d. Validate explicit master/layout/placeholder metadata.
+ self._check_pptx_structure_metadata(root, svg_path, result)
+
# 9. Check spec_lock drift (colors / font-family / font-size).
# Templates do not ship a spec_lock.md, so skip in template
# mode to avoid noise.
@@ -997,6 +1007,35 @@ class SVGQualityChecker:
f"data-pptx-native marker {marker_id}: {warning}"
)
+ def _check_pptx_structure_metadata(
+ self,
+ root: ET.Element,
+ svg_path: Path,
+ result: Dict,
+ ) -> None:
+ """Validate explicit template-export metadata when any is present."""
+ structure_attrs = {
+ 'data-pptx-layer',
+ 'data-pptx-layout',
+ 'data-pptx-layout-name',
+ 'data-pptx-placeholder',
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-editable',
+ }
+ if not any(
+ elem.get(attr) is not None
+ for elem in root.iter()
+ for attr in structure_attrs
+ ):
+ return
+ if _validate_template_structure_svg is None:
+ result['warnings'].append(
+ "Detected PPTX template structure metadata, but its validator "
+ "could not be imported; template export will still validate it."
+ )
+ return
+ result['errors'].extend(_validate_template_structure_svg(svg_path))
+
def _get_spec_lock(self, svg_path: Path):
"""Locate and parse spec_lock.md near the SVG. Returns dict or None.
diff --git a/skills/ppt-master/scripts/svg_to_pptx.py b/skills/ppt-master/scripts/svg_to_pptx.py
index 7befb9af..13d83aff 100644
--- a/skills/ppt-master/scripts/svg_to_pptx.py
+++ b/skills/ppt-master/scripts/svg_to_pptx.py
@@ -17,4 +17,4 @@ from svg_to_pptx import main
configure_utf8_stdio()
if __name__ == '__main__':
- main()
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 3310326b..7c1ff376 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -153,7 +153,12 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
style_overrides = _extract_inheritable_styles(elem)
elem_id = elem.get('id')
- should_animate_group = ctx.depth == 0 and elem_id and not is_chrome_id(elem_id)
+ should_animate_group = (
+ ctx.depth == 0
+ and elem_id
+ and not is_chrome_id(elem_id)
+ and not elem.get('data-pptx-layer')
+ )
visual_children = [
child for child in elem
if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
@@ -494,6 +499,14 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
}
if elem_id:
event['id'] = elem_id
+ for attr in (
+ 'data-pptx-layer',
+ 'data-pptx-placeholder',
+ 'data-pptx-placeholder-bounds',
+ ):
+ value = elem.get(attr)
+ if value is not None:
+ event[attr] = value
event.update(metadata)
ctx.trace_events.append(event)
@@ -693,7 +706,7 @@ def convert_svg_to_slide_shapes(
shapes.append(result.xml)
converted += 1
m = re.search(r'<p:cNvPr id="(\d+)"', result.xml)
- if m:
+ if m and not child.get('data-pptx-layer'):
fallback_targets.append((int(m.group(1)), tag))
else:
if tag not in _NON_VISUAL_TAGS:
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 f1e88d58..88762358 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
@@ -27,6 +27,7 @@ from pptx import Presentation
from pptx.util import Emu
from ..drawingml.converter import convert_svg_to_slide_shapes
+from ..drawingml.utils import EMU_PER_PX
from .dimensions import (
CANVAS_FORMATS,
get_slide_dimensions, get_pixel_dimensions,
@@ -58,6 +59,12 @@ from .slide_xml import (
ANIMATIONS_AVAILABLE, TRANSITIONS,
create_slide_xml_with_svg, create_slide_rels_xml,
)
+from .template_structure import (
+ TemplateElementSpec,
+ TemplateSlideSpec,
+ TemplateStructureError,
+ parse_template_slides,
+)
# Re-import create_transition_xml only if available
try:
@@ -116,6 +123,20 @@ class PptxStructureContext:
) from exc
+@dataclass
+class _TemplateRuntimeSlide:
+ """Parsed slide package state used by explicit template structure export."""
+
+ spec: TemplateSlideSpec
+ slide_path: Path
+ rels_path: Path
+ tree: ET.ElementTree
+ root: ET.Element
+ rels: dict[str, dict[str, str]]
+ shapes: dict[str, ET.Element]
+ shape_ids_by_svg_id: dict[str, list[str]]
+
+
def _relationship_attrs(elem: ET.Element) -> dict[str, str]:
return {key.rsplit("}", 1)[-1]: value for key, value in elem.attrib.items()}
@@ -390,6 +411,27 @@ def _trace_chrome_shape_ids(
return result
+def _trace_native_shape_ids(
+ trace: dict[str, Any] | None,
+) -> dict[str, list[str]]:
+ """Map every traced SVG id to generated top-level shape ids."""
+ result: dict[str, list[str]] = {}
+ if not trace:
+ return result
+ for event in trace.get("events", []):
+ if event.get("decision") != "native":
+ continue
+ svg_id = event.get("id")
+ shape_id = event.get("shape_id")
+ if not svg_id or shape_id is None:
+ continue
+ shape_ids = result.setdefault(str(svg_id), [])
+ normalized = str(shape_id)
+ if normalized not in shape_ids:
+ shape_ids.append(normalized)
+ return result
+
+
def _shape_id(elem: ET.Element) -> str | None:
for cnv in elem.iter(f"{{{PML_NS}}}cNvPr"):
return cnv.attrib.get("id")
@@ -486,12 +528,12 @@ def _ensure_relationship(
return _append_relationship(rels_path, rel_type, target)
-def _copy_shape_relationships_to_master(
+def _copy_shape_relationships_to_part(
elem: ET.Element,
slide_rels: dict[str, dict[str, str]],
- master_rels_path: Path,
+ target_rels_path: Path,
) -> ET.Element:
- """Clone a shape and retarget supported relationship ids to the master."""
+ """Clone a shape and retarget supported relationship ids to another part."""
clone = ET.fromstring(ET.tostring(elem, encoding="utf-8"))
for node in clone.iter():
for attr_name, value in list(node.attrib.items()):
@@ -501,7 +543,7 @@ def _copy_shape_relationships_to_master(
if not rel:
raise RuntimeError(f"Missing slide relationship for {value}")
new_rid = _ensure_relationship(
- master_rels_path,
+ target_rels_path,
rel["Type"],
rel["Target"],
)
@@ -509,6 +551,15 @@ def _copy_shape_relationships_to_master(
return clone
+def _copy_shape_relationships_to_master(
+ elem: ET.Element,
+ slide_rels: dict[str, dict[str, str]],
+ master_rels_path: Path,
+) -> ET.Element:
+ """Clone a shape and retarget supported relationship ids to the master."""
+ return _copy_shape_relationships_to_part(elem, slide_rels, master_rels_path)
+
+
def _next_master_shape_id(master_xml: str) -> int:
ids = [
int(match)
@@ -536,6 +587,24 @@ def _append_shape_to_master(master_path: Path, elem: ET.Element) -> None:
)
+def _append_shape_to_part(part_path: Path, elem: ET.Element) -> None:
+ """Append a top-level shape to a master/layout spTree with fresh ids."""
+ tree = ET.parse(part_path)
+ root = tree.getroot()
+ sp_tree = root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
+ if sp_tree is None:
+ raise RuntimeError(f"PPTX part has no p:spTree: {part_path}")
+ existing_ids = [
+ int(cnv.attrib["id"])
+ for cnv in root.iter(f"{{{PML_NS}}}cNvPr")
+ if cnv.attrib.get("id", "").isdigit()
+ ]
+ clone = ET.fromstring(ET.tostring(elem, encoding="utf-8"))
+ _renumber_shape_ids(clone, max(existing_ids, default=1) + 1)
+ sp_tree.append(clone)
+ _write_xml_tree(part_path, tree)
+
+
def _write_xml_tree(path: Path, tree: ET.ElementTree) -> None:
tree.write(path, encoding="utf-8", xml_declaration=True)
@@ -632,6 +701,90 @@ def _create_cover_layout(extract_dir: Path, master_part: str, base_layout_part:
return posixpath.relpath(new_layout_part, "ppt/slides")
+def _create_template_layout(
+ extract_dir: Path,
+ master_part: str,
+ base_layout_part: str,
+ layout_name: str,
+) -> tuple[str, str]:
+ """Clone a clean custom layout and register it under its slide master.
+
+ Returns ``(slide_relationship_target, package_part)``.
+ """
+ base_layout_path = extract_dir / base_layout_part
+ tree = ET.parse(base_layout_path)
+ root = tree.getroot()
+ root.set("type", "cust")
+ root.set("preserve", "1")
+ root.set("showMasterSp", "1")
+
+ c_sld = root.find(f"{{{PML_NS}}}cSld")
+ if c_sld is None:
+ raise RuntimeError(f"Slide layout has no p:cSld: {base_layout_part}")
+ c_sld.set("name", layout_name)
+ sp_tree = c_sld.find(f"{{{PML_NS}}}spTree")
+ if sp_tree is None:
+ raise RuntimeError(f"Slide layout has no p:spTree: {base_layout_part}")
+ for child in list(sp_tree):
+ if child.tag in _TOP_LEVEL_SHAPE_TAGS:
+ sp_tree.remove(child)
+
+ layout_num = _next_layout_part_number(extract_dir)
+ new_layout_part = f"ppt/slideLayouts/slideLayout{layout_num}.xml"
+ new_layout_path = extract_dir / new_layout_part
+ _write_xml_tree(new_layout_path, tree)
+
+ base_rels_path = _relationships_path_for_part(extract_dir, base_layout_part)
+ new_rels_path = _relationships_path_for_part(extract_dir, new_layout_part)
+ new_rels_path.parent.mkdir(exist_ok=True)
+ new_rels_path.write_text(
+ base_rels_path.read_text(encoding="utf-8"),
+ encoding="utf-8",
+ )
+
+ master_path = extract_dir / master_part
+ master_rels_path = _relationships_path_for_part(extract_dir, master_part)
+ layout_target = posixpath.relpath(new_layout_part, posixpath.dirname(master_part))
+ rel_id = _append_relationship(master_rels_path, SLIDE_LAYOUT_REL_TYPE, layout_target)
+ master_xml = master_path.read_text(encoding="utf-8")
+ layout_id = _next_slide_layout_id(extract_dir, master_xml)
+ entry = f'<p:sldLayoutId id="{layout_id}" r:id="{rel_id}"/>'
+ if "</p:sldLayoutIdLst>" not in master_xml:
+ raise RuntimeError(f"Slide master has no sldLayoutIdLst: {master_part}")
+ master_path.write_text(
+ master_xml.replace(
+ "</p:sldLayoutIdLst>",
+ f"{entry}</p:sldLayoutIdLst>",
+ 1,
+ ),
+ encoding="utf-8",
+ )
+
+ content_types_path = extract_dir / "[Content_Types].xml"
+ content_types_path.write_text(
+ _add_content_type_override(
+ content_types_path.read_text(encoding="utf-8"),
+ new_layout_part,
+ "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",
+ ),
+ encoding="utf-8",
+ )
+ return posixpath.relpath(new_layout_part, "ppt/slides"), new_layout_part
+
+
+def _clear_master_placeholder_shapes(master_path: Path) -> None:
+ """Remove base-template placeholders before installing an explicit template."""
+ tree = ET.parse(master_path)
+ root = tree.getroot()
+ sp_tree = root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
+ if sp_tree is None:
+ raise RuntimeError(f"Slide master has no p:spTree: {master_path}")
+ for child in list(sp_tree):
+ if child.find(f".//{{{PML_NS}}}ph") is not None:
+ sp_tree.remove(child)
+ _write_xml_tree(master_path, tree)
+
+
def _set_slide_layout_target(rels_path: Path, target: str) -> None:
"""Point a slide's layout relationship at a different layout part."""
content = rels_path.read_text(encoding="utf-8")
@@ -651,6 +804,561 @@ def _set_slide_layout_target(rels_path: Path, target: str) -> None:
rels_path.write_text(new_content, encoding="utf-8")
+_TEMPLATE_PLACEHOLDER_TYPES = {
+ "title": "title",
+ "body": "body",
+ "picture": "pic",
+ "chart": "chart",
+ "table": "tbl",
+ "footer": "ftr",
+ "slide-number": "sldNum",
+}
+_TEMPLATE_PLACEHOLDER_PROMPTS = {
+ "title": "Click to add title",
+ "body": "Click to add text",
+ "picture": "Click to add picture",
+ "chart": "Click to add chart",
+ "table": "Click to add table",
+ "footer": "Footer",
+}
+
+
+def _template_runtime_slides(
+ extract_dir: Path,
+ specs: list[TemplateSlideSpec],
+ conversion_traces: list[dict[str, Any]] | None,
+) -> list[_TemplateRuntimeSlide]:
+ """Load slide XML state and join it with SVG-to-shape trace ids."""
+ if not conversion_traces:
+ raise TemplateStructureError(
+ "Template export requires native conversion traces for every slide"
+ )
+ trace_by_slide = {
+ int(trace.get("slide_num", 0)): trace
+ for trace in conversion_traces
+ if trace.get("slide_num") is not None
+ }
+ states: list[_TemplateRuntimeSlide] = []
+ for spec in specs:
+ trace = trace_by_slide.get(spec.slide_num)
+ if trace is None:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: missing native conversion trace"
+ )
+ slide_path = extract_dir / "ppt" / "slides" / f"slide{spec.slide_num}.xml"
+ rels_path = (
+ extract_dir
+ / "ppt"
+ / "slides"
+ / "_rels"
+ / f"slide{spec.slide_num}.xml.rels"
+ )
+ tree = ET.parse(slide_path)
+ root = tree.getroot()
+ states.append(_TemplateRuntimeSlide(
+ spec=spec,
+ slide_path=slide_path,
+ rels_path=rels_path,
+ tree=tree,
+ root=root,
+ rels=_read_relationships(rels_path),
+ shapes=_top_level_shapes_by_id(root),
+ shape_ids_by_svg_id=_trace_native_shape_ids(trace),
+ ))
+ return states
+
+
+def _template_shape_for_item(
+ state: _TemplateRuntimeSlide,
+ item: TemplateElementSpec,
+) -> ET.Element | None:
+ """Resolve one metadata item to its generated top-level DrawingML shape."""
+ shape_ids = [
+ shape_id
+ for shape_id in state.shape_ids_by_svg_id.get(item.element_id, [])
+ if shape_id in state.shapes
+ ]
+ if len(shape_ids) == 1:
+ return state.shapes[shape_ids[0]]
+ if not shape_ids and item.layer and item.order == 0 and item.tag in {"rect", "g"}:
+ if _extract_slide_background_xml(
+ state.slide_path.read_text(encoding="utf-8")
+ ):
+ return None
+ if not shape_ids:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: metadata element {item.element_id!r} "
+ "did not produce one top-level native shape"
+ )
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: metadata element {item.element_id!r} "
+ f"resolved to {len(shape_ids)} top-level shapes; use one direct SVG element"
+ )
+
+
+def _slide_sp_tree(state: _TemplateRuntimeSlide) -> ET.Element:
+ sp_tree = state.root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
+ if sp_tree is None:
+ raise RuntimeError(f"Slide has no p:spTree: {state.slide_path}")
+ return sp_tree
+
+
+def _remove_template_shape(
+ state: _TemplateRuntimeSlide,
+ shape: ET.Element,
+) -> None:
+ sp_tree = _slide_sp_tree(state)
+ if shape not in list(sp_tree):
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: structure shape is not slide-local"
+ )
+ sp_tree.remove(shape)
+
+
+def _move_template_background(
+ states: list[_TemplateRuntimeSlide],
+ target_path: Path,
+) -> None:
+ backgrounds = [
+ _extract_slide_background_xml(state.slide_path.read_text(encoding="utf-8"))
+ for state in states
+ ]
+ if not backgrounds or any(background is None for background in backgrounds):
+ raise TemplateStructureError(
+ "Template background metadata must resolve to an explicit background "
+ "on every affected slide"
+ )
+ canonical_backgrounds = set()
+ for background in backgrounds:
+ if background is None:
+ continue
+ wrapper = ET.fromstring(
+ f'<root xmlns:p="{PML_NS}" xmlns:a="{DML_NS}">{background}</root>'
+ )
+ canonical_backgrounds.add(
+ ET.tostring(list(wrapper)[0], encoding="utf-8")
+ )
+ if len(canonical_backgrounds) != 1:
+ slide_names = ", ".join(state.spec.svg_path.name for state in states)
+ raise TemplateStructureError(
+ f"Explicit template background differs across slides: {slide_names}"
+ )
+ background_xml = backgrounds[0]
+ if background_xml is None:
+ raise TemplateStructureError("Template background is unexpectedly empty")
+ target_xml = target_path.read_text(encoding="utf-8")
+ updated = _put_background_on_master(target_xml, background_xml)
+ if updated is None:
+ raise TemplateStructureError(
+ f"Cannot install explicit background on {target_path.name}"
+ )
+ target_path.write_text(updated, encoding="utf-8")
+ for state in states:
+ c_sld = state.root.find(f"{{{PML_NS}}}cSld")
+ background = (
+ c_sld.find(f"{{{PML_NS}}}bg") if c_sld is not None else None
+ )
+ if c_sld is None or background is None:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: explicit background disappeared "
+ "during template structure assembly"
+ )
+ c_sld.remove(background)
+
+
+def _move_template_static_shape(
+ states: list[_TemplateRuntimeSlide],
+ item: TemplateElementSpec,
+ target_path: Path,
+ target_rels_path: Path,
+) -> None:
+ shapes = [_template_shape_for_item(state, item) for state in states]
+ if any(shape is None for shape in shapes):
+ if not all(shape is None for shape in shapes):
+ raise TemplateStructureError(
+ f"{item.element_id}: structure item is a background on only some slides"
+ )
+ _move_template_background(states, target_path)
+ return
+
+ resolved_shapes = [shape for shape in shapes if shape is not None]
+ canonical = {
+ _canonical_shape_xml(shape, state.rels)
+ for state, shape in zip(states, resolved_shapes)
+ }
+ if len(canonical) != 1:
+ slide_names = ", ".join(state.spec.svg_path.name for state in states)
+ raise TemplateStructureError(
+ f"Explicit structure element {item.element_id!r} differs across slides: "
+ f"{slide_names}"
+ )
+ for state, shape in zip(states, resolved_shapes):
+ shape_id = _shape_id(shape)
+ if shape_id and shape_id in _timing_shape_ids(state.root):
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: structure element {item.element_id!r} "
+ "is referenced by slide timing"
+ )
+ if not _shape_relationships_supported(shape, state.rels):
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: structure element {item.element_id!r} "
+ "uses a non-image or external relationship"
+ )
+
+ prototype_state = states[0]
+ prototype_shape = resolved_shapes[0]
+ target_shape = _copy_shape_relationships_to_part(
+ prototype_shape,
+ prototype_state.rels,
+ target_rels_path,
+ )
+ _append_shape_to_part(target_path, target_shape)
+ for state, shape in zip(states, resolved_shapes):
+ _remove_template_shape(state, shape)
+
+
+def _shape_bounds_emu(
+ shape: ET.Element,
+ override_px: tuple[float, float, float, float] | None,
+) -> tuple[int, int, int, int]:
+ if override_px is not None:
+ x, y, width, height = override_px
+ return tuple(
+ round(value * EMU_PER_PX)
+ for value in (x, y, width, height)
+ )
+
+ xfrm = shape.find(f"{{{PML_NS}}}spPr/{{{DML_NS}}}xfrm")
+ if xfrm is None:
+ xfrm = shape.find(f"{{{PML_NS}}}xfrm")
+ if xfrm is None:
+ raise TemplateStructureError(
+ "Placeholder shape has no directly readable DrawingML transform; "
+ "set data-pptx-placeholder-bounds"
+ )
+ off = xfrm.find(f"{{{DML_NS}}}off")
+ ext = xfrm.find(f"{{{DML_NS}}}ext")
+ if off is None or ext is None:
+ raise TemplateStructureError("Placeholder transform has no a:off/a:ext")
+ try:
+ return (
+ int(off.attrib["x"]),
+ int(off.attrib["y"]),
+ int(ext.attrib["cx"]),
+ int(ext.attrib["cy"]),
+ )
+ except (KeyError, ValueError) as exc:
+ raise TemplateStructureError("Placeholder transform is invalid") from exc
+
+
+def _replace_shape_xfrm(
+ sp_pr: ET.Element,
+ bounds: tuple[int, int, int, int],
+) -> None:
+ for existing in list(sp_pr):
+ if existing.tag == f"{{{DML_NS}}}xfrm":
+ sp_pr.remove(existing)
+ x, y, width, height = bounds
+ xfrm = ET.Element(f"{{{DML_NS}}}xfrm")
+ ET.SubElement(xfrm, f"{{{DML_NS}}}off", {"x": str(x), "y": str(y)})
+ ET.SubElement(
+ xfrm,
+ f"{{{DML_NS}}}ext",
+ {"cx": str(width), "cy": str(height)},
+ )
+ sp_pr.insert(0, xfrm)
+
+
+def _placeholder_text_body(
+ source_shape: ET.Element,
+ item: TemplateElementSpec,
+) -> ET.Element:
+ tx_body = ET.Element(f"{{{PML_NS}}}txBody")
+ source_tx_body = source_shape.find(f"{{{PML_NS}}}txBody")
+ source_body_pr = (
+ source_tx_body.find(f"{{{DML_NS}}}bodyPr")
+ if source_tx_body is not None
+ else None
+ )
+ source_lst_style = (
+ source_tx_body.find(f"{{{DML_NS}}}lstStyle")
+ if source_tx_body is not None
+ else None
+ )
+ tx_body.append(
+ ET.fromstring(ET.tostring(source_body_pr, encoding="utf-8"))
+ if source_body_pr is not None
+ else ET.Element(f"{{{DML_NS}}}bodyPr")
+ )
+ tx_body.append(
+ ET.fromstring(ET.tostring(source_lst_style, encoding="utf-8"))
+ if source_lst_style is not None
+ else ET.Element(f"{{{DML_NS}}}lstStyle")
+ )
+
+ paragraph = ET.SubElement(tx_body, f"{{{DML_NS}}}p")
+ source_run_pr = (
+ source_tx_body.find(f".//{{{DML_NS}}}rPr")
+ if source_tx_body is not None
+ else None
+ )
+ if item.placeholder == "slide-number":
+ field = ET.SubElement(
+ paragraph,
+ f"{{{DML_NS}}}fld",
+ {"id": f"{{{str(uuid.uuid4()).upper()}}}", "type": "slidenum"},
+ )
+ if source_run_pr is not None:
+ field.append(ET.fromstring(ET.tostring(source_run_pr, encoding="utf-8")))
+ ET.SubElement(field, f"{{{DML_NS}}}t").text = "‹#›"
+ else:
+ run = ET.SubElement(paragraph, f"{{{DML_NS}}}r")
+ if source_run_pr is not None:
+ run.append(ET.fromstring(ET.tostring(source_run_pr, encoding="utf-8")))
+ ET.SubElement(run, f"{{{DML_NS}}}t").text = _TEMPLATE_PLACEHOLDER_PROMPTS.get(
+ item.placeholder or "",
+ "Click to add content",
+ )
+ ET.SubElement(paragraph, f"{{{DML_NS}}}endParaRPr", {"lang": "en-US"})
+ return tx_body
+
+
+def _layout_placeholder_shape(
+ source_shape: ET.Element,
+ item: TemplateElementSpec,
+ placeholder_idx: int,
+) -> ET.Element:
+ """Build one reusable p:sp placeholder from a prototype slide object."""
+ placeholder_type = _TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
+ if placeholder_type is None:
+ raise TemplateStructureError(
+ f"Unsupported placeholder type: {item.placeholder!r}"
+ )
+ bounds = _shape_bounds_emu(source_shape, item.placeholder_bounds)
+ shape = ET.Element(f"{{{PML_NS}}}sp")
+ nv_sp_pr = ET.SubElement(shape, f"{{{PML_NS}}}nvSpPr")
+ ET.SubElement(
+ nv_sp_pr,
+ f"{{{PML_NS}}}cNvPr",
+ {"id": "2", "name": f"{item.element_id} Placeholder"},
+ )
+ c_nv_sp_pr = ET.SubElement(nv_sp_pr, f"{{{PML_NS}}}cNvSpPr")
+ ET.SubElement(c_nv_sp_pr, f"{{{DML_NS}}}spLocks", {"noGrp": "1"})
+ nv_pr = ET.SubElement(nv_sp_pr, f"{{{PML_NS}}}nvPr")
+ placeholder_attrs = {"type": placeholder_type}
+ if item.placeholder != "title":
+ placeholder_attrs["idx"] = str(placeholder_idx)
+ ET.SubElement(nv_pr, f"{{{PML_NS}}}ph", placeholder_attrs)
+
+ source_sp_pr = (
+ source_shape.find(f"{{{PML_NS}}}spPr")
+ if source_shape.tag == f"{{{PML_NS}}}sp"
+ else None
+ )
+ if source_sp_pr is not None:
+ sp_pr = ET.fromstring(ET.tostring(source_sp_pr, encoding="utf-8"))
+ else:
+ sp_pr = ET.Element(f"{{{PML_NS}}}spPr")
+ geometry = ET.SubElement(sp_pr, f"{{{DML_NS}}}prstGeom", {"prst": "rect"})
+ ET.SubElement(geometry, f"{{{DML_NS}}}avLst")
+ ET.SubElement(sp_pr, f"{{{DML_NS}}}noFill")
+ line = ET.SubElement(sp_pr, f"{{{DML_NS}}}ln")
+ ET.SubElement(line, f"{{{DML_NS}}}noFill")
+ _replace_shape_xfrm(sp_pr, bounds)
+ shape.append(sp_pr)
+ shape.append(_placeholder_text_body(source_shape, item))
+ return shape
+
+
+def _patch_slide_placeholder(
+ shape: ET.Element,
+ item: TemplateElementSpec,
+ placeholder_idx: int,
+) -> None:
+ placeholder_type = _TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
+ if placeholder_type is None:
+ raise TemplateStructureError(
+ f"Unsupported placeholder type: {item.placeholder!r}"
+ )
+ nv_paths = {
+ f"{{{PML_NS}}}sp": f"{{{PML_NS}}}nvSpPr/{{{PML_NS}}}nvPr",
+ f"{{{PML_NS}}}pic": f"{{{PML_NS}}}nvPicPr/{{{PML_NS}}}nvPr",
+ f"{{{PML_NS}}}graphicFrame": (
+ f"{{{PML_NS}}}nvGraphicFramePr/{{{PML_NS}}}nvPr"
+ ),
+ }
+ nv_path = nv_paths.get(shape.tag)
+ if nv_path is None:
+ raise TemplateStructureError(
+ f"Placeholder {item.element_id!r} converted to unsupported "
+ f"DrawingML element {shape.tag.rsplit('}', 1)[-1]!r}; text/picture/"
+ "native chart/table placeholders must remain one top-level object"
+ )
+ nv_pr = shape.find(nv_path)
+ if nv_pr is None:
+ raise TemplateStructureError(
+ f"Placeholder {item.element_id!r} has no non-visual properties"
+ )
+ for existing in list(nv_pr):
+ if existing.tag == f"{{{PML_NS}}}ph":
+ nv_pr.remove(existing)
+ placeholder_attrs = (
+ {"type": placeholder_type}
+ if item.placeholder == "title"
+ else {"idx": str(placeholder_idx)}
+ )
+ ph = ET.Element(f"{{{PML_NS}}}ph", placeholder_attrs)
+ ext_tag = f"{{{PML_NS}}}extLst"
+ insert_at = next(
+ (idx for idx, child in enumerate(nv_pr) if child.tag == ext_tag),
+ len(nv_pr),
+ )
+ nv_pr.insert(insert_at, ph)
+
+
+def _set_template_layout_header_footer(
+ layout_path: Path,
+ placeholders: tuple[TemplateElementSpec, ...],
+) -> None:
+ """Enable declared footer fields for slides newly created from the layout."""
+ kinds = {item.placeholder for item in placeholders}
+ if not kinds.intersection({"footer", "slide-number"}):
+ return
+ tree = ET.parse(layout_path)
+ root = tree.getroot()
+ hf = root.find(f"{{{PML_NS}}}hf")
+ if hf is None:
+ hf = ET.Element(f"{{{PML_NS}}}hf")
+ trailing_tags = {
+ f"{{{PML_NS}}}timing",
+ f"{{{PML_NS}}}transition",
+ f"{{{PML_NS}}}extLst",
+ }
+ insert_at = next(
+ (idx for idx, child in enumerate(root) if child.tag in trailing_tags),
+ len(root),
+ )
+ root.insert(insert_at, hf)
+ hf.set("hdr", "0")
+ hf.set("dt", "0")
+ hf.set("ftr", "1" if "footer" in kinds else "0")
+ hf.set("sldNum", "1" if "slide-number" in kinds else "0")
+ _write_xml_tree(layout_path, tree)
+
+
+def _apply_template_structure(
+ extract_dir: Path,
+ structure: PptxStructureContext,
+ specs: list[TemplateSlideSpec],
+ conversion_traces: list[dict[str, Any]] | None,
+ *,
+ verbose: bool = False,
+) -> None:
+ """Materialize explicit SVG master/layout/placeholder metadata into OOXML."""
+ states = _template_runtime_slides(extract_dir, specs, conversion_traces)
+ states_by_slide = {state.spec.slide_num: state for state in states}
+
+ master_items = specs[0].master_elements
+ states_by_master: dict[str, list[_TemplateRuntimeSlide]] = {}
+ for state in states:
+ master_part = structure.slide_master_part(state.spec.slide_num)
+ states_by_master.setdefault(master_part, []).append(state)
+ for master_part, master_states in states_by_master.items():
+ master_path = extract_dir / master_part
+ master_rels_path = _relationships_path_for_part(extract_dir, master_part)
+ _clear_master_placeholder_shapes(master_path)
+ for item in master_items:
+ _move_template_static_shape(
+ master_states,
+ item,
+ master_path,
+ master_rels_path,
+ )
+
+ specs_by_layout: dict[str, list[TemplateSlideSpec]] = {}
+ for spec in specs:
+ specs_by_layout.setdefault(spec.layout_key, []).append(spec)
+ placeholder_count = 0
+ layout_shape_count = 0
+ for layout_key, layout_specs in specs_by_layout.items():
+ layout_states = [states_by_slide[spec.slide_num] for spec in layout_specs]
+ master_parts = {
+ structure.slide_master_part(spec.slide_num) for spec in layout_specs
+ }
+ if len(master_parts) != 1:
+ raise TemplateStructureError(
+ f"Layout {layout_key!r} spans multiple slide masters; use distinct "
+ "layout keys per master"
+ )
+ master_part = next(iter(master_parts))
+ prototype = layout_specs[0]
+ base_target = structure.slide_layout_target(prototype.slide_num)
+ base_layout_part = _resolve_package_target(
+ f"ppt/slides/slide{prototype.slide_num}.xml",
+ base_target,
+ )
+ layout_target, layout_part = _create_template_layout(
+ extract_dir,
+ master_part,
+ base_layout_part,
+ prototype.layout_name,
+ )
+ layout_path = extract_dir / layout_part
+ layout_rels_path = _relationships_path_for_part(extract_dir, layout_part)
+
+ placeholder_idx = 1
+ for item in prototype.elements:
+ if item.layer == "layout":
+ _move_template_static_shape(
+ layout_states,
+ item,
+ layout_path,
+ layout_rels_path,
+ )
+ layout_shape_count += 1
+ continue
+ if not item.placeholder:
+ continue
+ prototype_shape = _template_shape_for_item(layout_states[0], item)
+ if prototype_shape is None:
+ raise TemplateStructureError(
+ f"Placeholder {item.element_id!r} cannot be a slide background"
+ )
+ layout_placeholder = _layout_placeholder_shape(
+ prototype_shape,
+ item,
+ placeholder_idx,
+ )
+ _append_shape_to_part(layout_path, layout_placeholder)
+ for state in layout_states:
+ shape = _template_shape_for_item(state, item)
+ if shape is None:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: placeholder {item.element_id!r} "
+ "did not produce a shape"
+ )
+ _patch_slide_placeholder(shape, item, placeholder_idx)
+ if item.placeholder != "title":
+ placeholder_idx += 1
+ placeholder_count += 1
+
+ _set_template_layout_header_footer(layout_path, prototype.placeholders)
+ for state in layout_states:
+ _set_slide_layout_target(state.rels_path, layout_target)
+
+ for state in states:
+ _write_xml_tree(state.slide_path, state.tree)
+
+ if verbose:
+ print(
+ " Template structure: "
+ f"{len(specs_by_layout)} layout(s), "
+ f"{len(master_items)} master element(s), "
+ f"{layout_shape_count} layout element(s), "
+ f"{placeholder_count} placeholder definition(s)"
+ )
+
+
def _promote_common_chrome_shapes_to_masters(
extract_dir: Path,
structure: PptxStructureContext,
@@ -945,6 +1653,7 @@ def _convert_page_number_texts_to_fields(
slide_count: int,
conversion_traces: list[dict[str, Any]] | None,
*,
+ context: str = "Baseline",
verbose: bool = False,
) -> int:
"""Replace literal page-number chrome text with auto-updating fields.
@@ -985,7 +1694,10 @@ def _convert_page_number_texts_to_fields(
converted += 1
if verbose and converted:
- print(f" Baseline slide-number fields: converted {converted} page number(s)")
+ print(
+ f" {context} slide-number fields: "
+ f"converted {converted} page number(s)"
+ )
return converted
@@ -1767,7 +2479,8 @@ def create_pptx_with_native_svg(
conversion_trace_path: Optional JSON path for native conversion diagnostics.
pptx_structure: PPTX structure strategy. ``baseline`` promotes safe
shared native backgrounds and leading chrome to slide masters;
- ``flat`` keeps generated backgrounds/chrome slide-local.
+ ``template`` consumes explicit SVG master/layout/placeholder
+ metadata; ``flat`` keeps generated structure slide-local.
Returns:
Whether all slides were successfully created.
@@ -1779,8 +2492,26 @@ def create_pptx_with_native_svg(
# Native shapes mode takes priority over compat mode
if use_native_shapes:
use_compat_mode = False
- if pptx_structure not in {"baseline", "flat"}:
+ if pptx_structure not in {"baseline", "template", "flat"}:
raise ValueError(f"Unsupported pptx_structure: {pptx_structure}")
+ template_specs = (
+ parse_template_slides(svg_files)
+ if use_native_shapes and pptx_structure == "template"
+ else None
+ )
+ if template_specs is not None and not native_objects:
+ native_placeholders = sorted({
+ item.placeholder
+ for spec in template_specs
+ for item in spec.placeholders
+ if item.placeholder in {"chart", "table"}
+ })
+ if native_placeholders:
+ kinds = ", ".join(str(kind) for kind in native_placeholders)
+ raise TemplateStructureError(
+ f"Template {kinds} placeholder(s) require --native-objects so each "
+ "marker becomes one native PowerPoint object"
+ )
# Check compatibility mode dependencies
renderer_name, renderer_status, renderer_hint = get_png_renderer_info()
@@ -1906,7 +2637,9 @@ def create_pptx_with_native_svg(
mixed_animation_offset = 0
conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
structure_trace: list[dict[str, Any]] | None = (
- [] if use_native_shapes and pptx_structure == "baseline" else None
+ []
+ if use_native_shapes and pptx_structure in {"baseline", "template"}
+ else None
)
for i, svg_path in enumerate(svg_files, 1):
@@ -2279,6 +3012,36 @@ def create_pptx_with_native_svg(
verbose=verbose,
)
+ if (
+ use_native_shapes
+ and pptx_structure == "template"
+ and success_count == len(svg_files)
+ ):
+ _convert_page_number_texts_to_fields(
+ extract_dir,
+ len(svg_files),
+ conversion_trace if conversion_trace is not None else structure_trace,
+ context="Template",
+ verbose=verbose,
+ )
+ if template_specs is None:
+ raise TemplateStructureError(
+ "Template structure metadata was not parsed before export"
+ )
+ _apply_template_structure(
+ extract_dir,
+ structure,
+ template_specs,
+ conversion_trace if conversion_trace is not None else structure_trace,
+ verbose=verbose,
+ )
+ _prune_unused_slide_layouts(
+ extract_dir,
+ structure,
+ len(svg_files),
+ verbose=verbose,
+ )
+
# Update [Content_Types].xml
content_types_path = extract_dir / '[Content_Types].xml'
with open(content_types_path, 'r', encoding='utf-8') as f:
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 70af1e2d..78034de9 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
@@ -31,6 +31,7 @@ from .discovery import find_svg_files, find_notes_files
from .builder import create_pptx_with_native_svg
from .narration import NARRATION_EXTENSIONS, find_narration_files, probe_audio_duration
from .slide_xml import TRANSITIONS
+from .template_structure import TemplateStructureError
from ..animation_config import load_animation_config, validate_animation_config
try:
@@ -211,12 +212,18 @@ Recorded narration:
'groups export through their SVG fallback children. When set, '
'the default-flow export is named <project>_<ts>_native_charts.pptx '
'to tell it apart from a plain shape export.')
- parser.add_argument('--pptx-structure', choices=['baseline', 'flat'], default='baseline',
- help='PPTX structure strategy for native export. baseline (default) '
- 'keeps a standard master/layout package and promotes identical '
- 'native slide backgrounds plus a safe leading prefix of repeated '
- 'chrome to the slide master; flat leaves generated backgrounds '
- 'and chrome slide-local for debugging/comparison.')
+ parser.add_argument(
+ '--pptx-structure',
+ choices=['baseline', 'template', 'flat'],
+ default='baseline',
+ help=(
+ 'PPTX structure strategy for native export. baseline (default) keeps '
+ 'a standard master/layout package and promotes safe repeated background/'
+ 'chrome; template consumes explicit data-pptx-layout/layer/placeholder '
+ 'metadata to build reusable layouts; flat leaves generated structure '
+ 'slide-local for debugging/comparison.'
+ ),
+ )
parser.add_argument('--svg-snapshot', action='store_true', default=False,
help='Also emit the SVG-rendered snapshot pptx alongside '
'the native pptx in exports/ (named '
@@ -670,16 +677,20 @@ Recorded narration:
print(f" Output file: {native_path}")
print()
- ok = create_pptx_with_native_svg(
- output_path=native_path,
- use_native_shapes=True,
- svg_files=native_files,
- conversion_trace_path=(
- native_path.with_name(native_path.name + '.trace.json')
- if args.conversion_trace else None
- ),
- **shared_kwargs,
- )
+ try:
+ ok = create_pptx_with_native_svg(
+ output_path=native_path,
+ use_native_shapes=True,
+ svg_files=native_files,
+ conversion_trace_path=(
+ native_path.with_name(native_path.name + '.trace.json')
+ if args.conversion_trace else None
+ ),
+ **shared_kwargs,
+ )
+ except TemplateStructureError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
success = success and ok
# --- SVG image reference version ---
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py
new file mode 100644
index 00000000..43f50543
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py
@@ -0,0 +1,394 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Template Structure Metadata
+
+Parse and validate explicit SVG metadata consumed by template-mode PPTX export.
+
+Usage:
+ Imported by svg_to_pptx.pptx_package.builder and svg_quality_checker.py.
+
+Examples:
+ parse_template_slides([Path("projects/demo/svg_output/01_cover.svg")])
+
+Dependencies:
+ None (only uses standard library)
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from dataclasses import dataclass
+from pathlib import Path
+from xml.etree import ElementTree as ET
+
+
+_NON_VISUAL_TAGS = frozenset({"defs", "title", "desc", "metadata", "style"})
+_STRUCTURE_ATTRS = frozenset({
+ "data-pptx-layer",
+ "data-pptx-layout",
+ "data-pptx-layout-name",
+ "data-pptx-placeholder",
+ "data-pptx-placeholder-bounds",
+ "data-pptx-editable",
+})
+_LAYERS = frozenset({"master", "layout"})
+_PLACEHOLDERS = frozenset({
+ "title",
+ "body",
+ "picture",
+ "chart",
+ "table",
+ "footer",
+ "slide-number",
+})
+_TEXT_PLACEHOLDERS = frozenset({"title", "body", "footer", "slide-number"})
+_LAYOUT_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
+
+
+class TemplateStructureError(RuntimeError):
+ """Reject invalid or ambiguous template-structure metadata."""
+
+
+@dataclass(frozen=True)
+class TemplateElementSpec:
+ """One direct SVG child carrying explicit PPTX structure metadata."""
+
+ element_id: str
+ order: int
+ tag: str
+ layer: str | None = None
+ placeholder: str | None = None
+ placeholder_bounds: tuple[float, float, float, float] | None = None
+
+ def contract_signature(self) -> tuple[object, ...]:
+ """Return metadata that must agree across slides sharing a structure."""
+ return (
+ self.element_id,
+ self.tag,
+ self.layer,
+ self.placeholder,
+ self.placeholder_bounds,
+ )
+
+
+@dataclass(frozen=True)
+class TemplateSlideSpec:
+ """Explicit structure contract parsed from one SVG slide."""
+
+ slide_num: int
+ svg_path: Path
+ layout_key: str
+ layout_name: str
+ elements: tuple[TemplateElementSpec, ...]
+
+ @property
+ def master_elements(self) -> tuple[TemplateElementSpec, ...]:
+ return tuple(item for item in self.elements if item.layer == "master")
+
+ @property
+ def layout_elements(self) -> tuple[TemplateElementSpec, ...]:
+ return tuple(item for item in self.elements if item.layer == "layout")
+
+ @property
+ def placeholders(self) -> tuple[TemplateElementSpec, ...]:
+ return tuple(item for item in self.elements if item.placeholder)
+
+ @property
+ def layout_contract(self) -> tuple[tuple[object, ...], ...]:
+ return tuple(
+ item.contract_signature()
+ for item in self.elements
+ if item.layer == "layout" or item.placeholder
+ )
+
+
+def _local_tag(elem: ET.Element) -> str:
+ return elem.tag.rsplit("}", 1)[-1] if isinstance(elem.tag, str) else ""
+
+
+def _parse_placeholder_bounds(
+ raw: str | None,
+ *,
+ svg_path: Path,
+ element_id: str,
+) -> tuple[float, float, float, float] | None:
+ if raw is None:
+ return None
+ parts = [part for part in re.split(r"[\s,]+", raw.strip()) if part]
+ if len(parts) != 4:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} data-pptx-placeholder-bounds must be "
+ "'x y width height'"
+ )
+ try:
+ x, y, width, height = (float(part) for part in parts)
+ except ValueError as exc:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} placeholder bounds must be numeric"
+ ) from exc
+ if not all(math.isfinite(value) for value in (x, y, width, height)):
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} placeholder bounds must be finite"
+ )
+ if width <= 0 or height <= 0:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} placeholder width/height must be positive"
+ )
+ return x, y, width, height
+
+
+def _validate_placeholder_element(
+ elem: ET.Element,
+ placeholder: str,
+ *,
+ svg_path: Path,
+ element_id: str,
+) -> None:
+ tag = _local_tag(elem)
+ if placeholder in _TEXT_PLACEHOLDERS and tag != "text":
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} placeholder '{placeholder}' must be "
+ "declared on a direct <text> element"
+ )
+ if placeholder == "picture" and tag not in {"image", "svg"}:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} picture placeholder must be declared "
+ "on a direct <image> or nested crop <svg> element"
+ )
+ if placeholder in {"chart", "table"}:
+ native_kind = (elem.get("data-pptx-native") or "").strip().lower()
+ if tag != "g" or native_kind != placeholder:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} placeholder '{placeholder}' must be "
+ f"a direct <g data-pptx-native=\"{placeholder}\"> marker"
+ )
+
+
+def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
+ """Parse one SVG's explicit template layout and structure elements."""
+ try:
+ root = ET.parse(svg_path).getroot()
+ except (OSError, ET.ParseError) as exc:
+ raise TemplateStructureError(
+ f"{svg_path.name}: unable to parse SVG structure metadata: {exc}"
+ ) from exc
+
+ if _local_tag(root) != "svg":
+ raise TemplateStructureError(f"{svg_path.name}: root element must be <svg>")
+
+ layout_key = (root.get("data-pptx-layout") or "").strip()
+ if not layout_key:
+ raise TemplateStructureError(
+ f"{svg_path.name}: template export requires root data-pptx-layout"
+ )
+ if not _LAYOUT_KEY_RE.fullmatch(layout_key):
+ raise TemplateStructureError(
+ f"{svg_path.name}: invalid data-pptx-layout {layout_key!r}; use 1-64 "
+ "ASCII letters, digits, dots, underscores, or hyphens"
+ )
+ layout_name = (root.get("data-pptx-layout-name") or "").strip()
+ if not layout_name:
+ layout_name = re.sub(r"[-_.]+", " ", layout_key).strip().title() or layout_key
+
+ illegal_root_attrs = sorted(
+ attr for attr in _STRUCTURE_ATTRS
+ if (
+ attr not in {"data-pptx-layout", "data-pptx-layout-name"}
+ and root.get(attr) is not None
+ )
+ )
+ if illegal_root_attrs:
+ raise TemplateStructureError(
+ f"{svg_path.name}: root <svg> cannot use {', '.join(illegal_root_attrs)}"
+ )
+
+ id_counts: dict[str, int] = {}
+ for elem in root.iter():
+ element_id = elem.get("id")
+ if element_id:
+ id_counts[element_id] = id_counts.get(element_id, 0) + 1
+ duplicate_ids = sorted(element_id for element_id, count in id_counts.items() if count > 1)
+ if duplicate_ids:
+ raise TemplateStructureError(
+ f"{svg_path.name}: duplicate SVG id(s) are not allowed in template mode: "
+ + ", ".join(duplicate_ids)
+ )
+
+ direct_children = set(root)
+ for elem in root.iter():
+ if elem is root or elem in direct_children:
+ continue
+ nested_attrs = sorted(attr for attr in _STRUCTURE_ATTRS if elem.get(attr) is not None)
+ if nested_attrs:
+ element_id = elem.get("id") or _local_tag(elem) or "<unnamed>"
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} uses template metadata below the SVG "
+ "root; structure metadata is allowed only on direct children"
+ )
+
+ elements: list[TemplateElementSpec] = []
+ phase = "master"
+ visual_order = 0
+ for elem in root:
+ tag = _local_tag(elem)
+ if tag in _NON_VISUAL_TAGS:
+ continue
+
+ element_id = (elem.get("id") or "").strip()
+ layer_raw = elem.get("data-pptx-layer")
+ layer = (layer_raw or "").strip().lower() or None
+ placeholder_raw = elem.get("data-pptx-placeholder")
+ placeholder = (
+ (placeholder_raw or "").strip().lower() or None
+ )
+ bounds_raw = elem.get("data-pptx-placeholder-bounds")
+ editable_raw = elem.get("data-pptx-editable")
+
+ if (
+ elem.get("data-pptx-layout") is not None
+ or elem.get("data-pptx-layout-name") is not None
+ ):
+ raise TemplateStructureError(
+ f"{svg_path.name}: data-pptx-layout and data-pptx-layout-name belong "
+ "on the root <svg> only"
+ )
+ if layer and layer not in _LAYERS:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has unsupported "
+ f"data-pptx-layer={layer!r}"
+ )
+ if layer_raw is not None and layer is None:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has empty data-pptx-layer"
+ )
+ if placeholder and placeholder not in _PLACEHOLDERS:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has unsupported "
+ f"data-pptx-placeholder={placeholder!r}"
+ )
+ if placeholder_raw is not None and placeholder is None:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has empty "
+ "data-pptx-placeholder"
+ )
+ if layer and placeholder:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} cannot be both a static "
+ "master/layout layer and a content placeholder"
+ )
+ if bounds_raw is not None and not placeholder:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has placeholder bounds without "
+ "data-pptx-placeholder"
+ )
+ if (layer or placeholder) and not element_id:
+ raise TemplateStructureError(
+ f"{svg_path.name}: direct <{tag}> with template metadata requires an id"
+ )
+ if editable_raw is not None:
+ if not layer or editable_raw.strip().lower() != "false":
+ raise TemplateStructureError(
+ f"{svg_path.name}: data-pptx-editable currently supports only "
+ "'false' on master/layout layer elements"
+ )
+
+ if layer == "master":
+ if phase != "master":
+ raise TemplateStructureError(
+ f"{svg_path.name}: master layer element {element_id} must precede "
+ "all layout and slide-local content"
+ )
+ elif layer == "layout":
+ if phase == "slide":
+ raise TemplateStructureError(
+ f"{svg_path.name}: layout layer element {element_id} must precede "
+ "all slide-local content"
+ )
+ phase = "layout"
+ else:
+ phase = "slide"
+
+ if placeholder:
+ _validate_placeholder_element(
+ elem,
+ placeholder,
+ svg_path=svg_path,
+ element_id=element_id,
+ )
+ placeholder_bounds = _parse_placeholder_bounds(
+ bounds_raw,
+ svg_path=svg_path,
+ element_id=element_id or tag,
+ )
+
+ if layer or placeholder:
+ elements.append(TemplateElementSpec(
+ element_id=element_id,
+ order=visual_order,
+ tag=tag,
+ layer=layer,
+ placeholder=placeholder,
+ placeholder_bounds=placeholder_bounds,
+ ))
+ visual_order += 1
+
+ return TemplateSlideSpec(
+ slide_num=slide_num,
+ svg_path=svg_path,
+ layout_key=layout_key,
+ layout_name=layout_name,
+ elements=tuple(elements),
+ )
+
+
+def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
+ """Parse a deck and enforce cross-slide master/layout contracts."""
+ specs = [
+ parse_template_slide(svg_path, slide_num)
+ for slide_num, svg_path in enumerate(svg_files, start=1)
+ ]
+ if not specs:
+ raise TemplateStructureError("Template export requires at least one SVG slide")
+
+ expected_master = tuple(
+ item.contract_signature() for item in specs[0].master_elements
+ )
+ for spec in specs[1:]:
+ actual_master = tuple(
+ item.contract_signature() for item in spec.master_elements
+ )
+ if actual_master != expected_master:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: master layer contract differs from "
+ f"{specs[0].svg_path.name}; every template slide must repeat the same "
+ "explicit master elements in the same order"
+ )
+
+ by_layout: dict[str, list[TemplateSlideSpec]] = {}
+ for spec in specs:
+ by_layout.setdefault(spec.layout_key, []).append(spec)
+ for layout_key, layout_specs in by_layout.items():
+ prototype = layout_specs[0]
+ for spec in layout_specs[1:]:
+ if spec.layout_name != prototype.layout_name:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: layout {layout_key!r} uses name "
+ f"{spec.layout_name!r}, expected {prototype.layout_name!r}"
+ )
+ if spec.layout_contract != prototype.layout_contract:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: layout {layout_key!r} structure differs "
+ f"from prototype {prototype.svg_path.name}; repeat the same layout "
+ "layers and placeholder ids/types in the same order"
+ )
+ return specs
+
+
+def validate_template_svg(svg_path: Path) -> list[str]:
+ """Return per-file template metadata errors for quality-check integration."""
+ try:
+ parse_template_slide(svg_path, 1)
+ except TemplateStructureError as exc:
+ return [str(exc)]
+ return []
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index 1f49d867..7688f5c2 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -320,6 +320,7 @@ Mirror mode does **not** invoke the "reconstruct into clean SVG" pathway. The sp
1. `design_spec.md` — **personality only**. Required sections: Template Overview, Color Scheme, Signature Design Elements, Page Roster (matching the actual SVG files on disk). Skip Typography / Assets / Placeholder Overrides when they would just restate defaults. Declare brief frontmatter for `register_template.py`. **Do not** restate generic SVG constraints, layout pattern libraries, font-size ratio bands, the canonical placeholder table, or content methodology — those are sourced from `shared-standards.md` / `design_spec_reference.md` / `strategist.md` and are already in the downstream reader's context. Full scope rule and skeleton: [template-designer.md §1](../references/template-designer.md#1-must-generate-design_specmd).
2. Page roster — see [Page Roster](../references/template-designer.md#page-roster) for `standard` / `fidelity` / `mirror` mode rosters, variant naming, and TOC handling
3. Placeholder vocabulary — pages should adopt the conventional names (`{{TITLE}}`, `{{CONTENT_AREA}}`, ...) when they fit. Full reference: [Placeholder Reference](../references/template-designer.md#4-placeholder-reference-canonical-convention-overridable-per-template). When a template style legitimately needs different vocabulary (consulting → `{{KEY_MESSAGE}}`, branded cover → `{{BRAND_LOGO}}`), declare a `placeholders:` block in `design_spec.md` frontmatter so the registrar and quality checker treat it as the template's authoritative contract. **Avoid** one-off indexed families such as `{{CHAPTER_01_TITLE}}` — use the indexed TOC pattern instead.
+ - `{{...}}` placeholders are the authoring contract used to generate final slide content; they are not PowerPoint `p:ph` objects. If the downstream deliverable must expose reusable PowerPoint layouts, the final generated slide SVGs must separately follow the explicit `data-pptx-layout` / `data-pptx-layer` / `data-pptx-placeholder` contract in [shared standards](../references/shared-standards.md#explicit-pptx-master--layout--placeholder-metadata-template-export) and export with `--pptx-structure template`.
4. Template assets (optional) — Logos / PNG / JPG / reference SVG bundled with the template package
---