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(template-authoring): materialize deterministic mirror templates

hugohe3e8eca9865f63
diff --git a/AGENTS.md b/AGENTS.md
index a9cb6f73..37f902a4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -73,6 +73,8 @@ python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --d
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
# Explicit create-template normalization: selected complex <g> -> one SVG picture asset / <image>
python3 skills/ppt-master/scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<workspace>/picture-assets" --inplace
+# Type A create-template mirror: validated authoring IR -> deterministic structured template workspace
+python3 skills/ppt-master/scripts/mirror_template_materialize.py "<import_workspace>" "<empty_template_workspace>"
# create-template review deck (workspace root may be global or project-scoped)
python3 skills/ppt-master/scripts/template_preview_pptx.py <template_workspace>
python3 skills/ppt-master/scripts/animation_config.py scaffold <project_path> # optional, only for custom object-level animation
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.md
index ab15fd26..0282efe0 100644
--- a/docs/powerpoint-svg-mapping.md
+++ b/docs/powerpoint-svg-mapping.md
@@ -58,7 +58,7 @@ See [`canvas-formats.md`](../skills/ppt-master/references/canvas-formats.md) for
| Template-backed deck structure | `pptx_structure.mode: structured` plus explicit Master/Layout/page assignments | Declared `p:sldMaster`, `p:sldLayout`, registrations, and slide parentage | `Native-stable` within the explicit structure contract | The exporter never guesses a Master, Layout, or placeholder topology |
| Slide Master | Root Master identity plus atomic `data-pptx-layer="master"` objects; one validated compact authored-preset `<g>` counts as one semantic atom | Reusable Master part and picker identity | Source structure is restored by template/import workflows | Master atoms must be direct, stable, and identical across their slides; ordinary or expanded authored groups do not qualify |
| Slide Layout | Root Layout identity plus atomic `data-pptx-layer="layout"` objects; one validated compact authored-preset `<g>` counts as one semantic atom | Reusable Layout part under one Master | Source Layouts can be restored; adaptive authoring may allocate a new Layout | Reuse a Layout key only when its fixed atoms and slot contract are identical; ordinary or expanded authored groups do not qualify |
-| Imported inherited-shape visibility | PPTX `p:sld@showMasterSp` and `p:sldLayout@showMasterSp`; layered analysis records normalized source booleans outside visible SVG | No new generated-authoring marker; source-preserving workflows retain the package fields | `Native-stable` for imported visual/analysis facts: Slide false hides Layout and Master shapes; Layout false hides only Master shapes | Backgrounds, Slide-local objects, placeholder inheritance, part SVGs, and parent relationships remain intact; flat import omits only the suppressed inherited shapes |
+| Imported inherited-shape visibility | Layered analysis records normalized source booleans; a materialized structured mirror writes exact lowercase root `data-pptx-show-inherited-shapes` and `data-pptx-show-master-shapes` | Restored `p:sld@showMasterSp` and `p:sldLayout@showMasterSp` | `Native-stable`: Slide false hides Layout and Master shapes; Layout false hides only Master shapes | Omission means true; every page using one Layout key must agree on the Layout value. Backgrounds, Slide-local objects, placeholder inheritance, parts, and parent relationships remain intact |
| Strict template Layout | Selected prototype contract | Existing declared Layout topology is preserved | `Native-stable` when the page follows the prototype | Fixed Layout atoms and slot structure may not change |
| Adaptive template Layout | Selected Master plus an explicit current or newly declared Layout | A new Layout identity may be created when reusable structure changes | `Native-stable` after the lock and page mapping are updated | Never mutate a reused Layout key silently |
| Slide background fill outside structured mode | First eligible full-canvas `<rect>`, direct or in a simple single-child group, with a registered solid, linear/radial gradient, or preset-pattern fill | Native slide `p:bg` | Fidelity follows the corresponding paint row below | Transform, filter, clip, rounding, visible stroke, or an unmapped fill prevents promotion |
@@ -68,6 +68,7 @@ See [`canvas-formats.md`](../skills/ppt-master/references/canvas-formats.md) for
| Title placeholder | Structured slot group with one text carrier | Layout and slide `p:ph` of type `title` | `Native-stable` | Carrier count, bounds, type, and effective index must match the Layout contract |
| Subtitle placeholder | Structured slot group with one text carrier | `p:ph` type `subTitle` | `Native-stable` | Same slot rules as title |
| Body placeholder | Structured slot group with one text carrier | `p:ph` type `body` | `Native-stable` | A multiline carrier remains one text frame |
+| Imported mirror text-placeholder frame | Positive source `data-pptx-frame="x y width height"` on the slot's `<text>` carrier, separate from the slot's reusable bounds | The Slide carrier keeps that exact `a:xfrm`; text remains editable and source hard breaks remain explicit paragraphs | `Native-stable` within supported imported text | `data-pptx-placeholder-bounds` still owns the Layout default and may differ; authored standard/fidelity slots do not duplicate bounds into this frame |
| Date, footer, and slide-number placeholders | Structured text slots | `p:ph` types `dt`, `ftr`, and `sldNum`, with matching Layout header/footer flags | `Native-stable` | Placeholder indices must be unique and legal |
| Picture placeholder | Structured slot with one image or supported crop carrier | `p:ph` type `pic` | `Native-stable` within the picture contract | The slot must contain exactly one compatible direct carrier |
| Chart or table placeholder | Structured slot with one matching native-object carrier | `p:ph` type `chart` or `tbl` | `Native-stable` only on native Chart/Table export | Requires valid JSON metadata and `--native-charts-and-tables` |
diff --git a/docs/templates-guide.md b/docs/templates-guide.md
index 331d1812..7f2cb00e 100644
--- a/docs/templates-guide.md
+++ b/docs/templates-guide.md
@@ -174,6 +174,19 @@ This is the most easily confused decision when deriving a template.
**About native PowerPoint shapes**: the lossless import SVG stays immutable in the temporary analysis workspace as native-payload backing. Template creation uses the lightweight editable `authoring-svg/` IR and its source-ref/hash manifest. Authored modes use project-canonical SVG and compact authored-preset groups only for exact registered preset matches. Mirror materializes final template SVGs from the IR, reusing converter-supported payload only for unchanged Slide-local/slot refs; fixed Master/Layout layers remain direct atoms, unsupported or edited objects keep the current SVG fallback, and final templates contain no IR-only refs.
+For a PPTX-backed Type A mirror, that final step is one deterministic command:
+
+```bash
+python3 skills/ppt-master/scripts/mirror_template_materialize.py \
+ "<import_workspace>" "<empty_template_workspace>"
+```
+
+It validates the IR manifest, immutable source hashes, complete native graph,
+visibility facts, and imported-vector closure before atomically publishing the
+source-ordered SVG roster and its `icons/imported/` / `images/` assets. It never
+uses `svg-flat/` as the template source and never generates `design_spec.md`;
+the designer writes that brief against the published roster.
+
**Mirror graph boundary**: mirror preserves the complete supported source Master/Layout graph. It emits one complete prototype per source slide and one definition-only `layout_<layout_key>.svg` prototype for every source Layout unused by those slides. The latter registers in PowerPoint through the independent Layout roster without becoming a published page; its parent Master is retained with it. Preflight stops only when required source facts or supported geometry are missing, never merely because a Layout is unused.
**How mirror is consumed**: the Strategist picks one mirror page per project page, and the Executor copies that complete SVG and edits visible text in place while preserving decoration, sprite crops, geometry, and the normalized structured declarations. Mirror preserves supported appearance, not the source PPTX group-editing hierarchy.
diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.md
index be36fea6..e331bd82 100644
--- a/docs/zh/powerpoint-svg-mapping.md
+++ b/docs/zh/powerpoint-svg-mapping.md
@@ -58,7 +58,7 @@ PowerPoint 意图
| 基于模板的演示文稿结构 | `pptx_structure.mode: structured` 加显式 Master/Layout/页面分配 | 声明的 `p:sldMaster`、`p:sldLayout`、注册与 Slide 父子关系 | 在显式结构合同内为 `Native-stable` | 导出器绝不猜测 Master、Layout 或占位符拓扑 |
| 幻灯片母版 | 根 Master 身份加原子级 `data-pptx-layer="master"` 对象;一个校验通过的 compact authored-preset `<g>` 计为一个 semantic atom | 可复用 Master part 与 picker 身份 | 源结构由模板/导入工作流恢复 | Master atom 必须为直接、稳定对象,并在所属页面间一致;普通组或 expanded authored 组不具备该资格 |
| 幻灯片版式 | 根 Layout 身份加原子级 `data-pptx-layer="layout"` 对象;一个校验通过的 compact authored-preset `<g>` 计为一个 semantic atom | 某个 Master 下的可复用 Layout part | 可恢复源 Layout;adaptive 创作可分配新 Layout | 仅当固定 atom 和 slot 合同完全相同时才复用 Layout key;普通组或 expanded authored 组不具备该资格 |
-| 回导的继承图形可见性 | PPTX 的 `p:sld@showMasterSp` 与 `p:sldLayout@showMasterSp`;分层分析在可见 SVG 之外记录规范化的源布尔值 | 不新增生成侧创作 marker;源保留工作流保留包字段 | 对回导视觉与分析事实为 `Native-stable`:Slide 为 false 时隐藏 Layout 与 Master 图形;Layout 为 false 时只隐藏 Master 图形 | 背景、Slide-local 对象、占位符继承、独立 part SVG 与父子关系保持不变;flat 回导只省略被抑制的继承图形 |
+| 回导的继承图形可见性 | 分层分析记录规范化源布尔值;物化后的 structured mirror 在根写入精确小写的 `data-pptx-show-inherited-shapes` 与 `data-pptx-show-master-shapes` | 恢复 `p:sld@showMasterSp` 与 `p:sldLayout@showMasterSp` | `Native-stable`:Slide 为 false 时隐藏 Layout 与 Master 图形;Layout 为 false 时只隐藏 Master 图形 | 省略即 true;使用同一 Layout key 的页面必须使用相同 Layout 值。背景、Slide-local 对象、占位符继承、part 与父子关系保持不变 |
| strict 模板 Layout | 选中的原型合同 | 保留现有已声明 Layout 拓扑 | 页面遵循原型时为 `Native-stable` | 不得改变固定 Layout atom 和 slot 结构 |
| adaptive 模板 Layout | 选定 Master 加显式的当前或新声明 Layout | 可在可复用结构变化时创建新 Layout 身份 | 更新 lock 与页面映射后为 `Native-stable` | 绝不默默改变已复用 Layout key |
| structured 模式以外的 Slide 背景填充 | 第一个合格的全幅 `<rect>`,可直接位于根下或位于简单单子组中,使用已登记纯色、线性/径向渐变或预设图案填充 | Slide 的原生 `p:bg` | 保真度遵循下文对应 paint 行 | transform、filter、clip、圆角、可见 stroke 或未映射 fill 会阻止提升 |
@@ -68,6 +68,7 @@ PowerPoint 意图
| 标题占位符 | 含一个文本 carrier 的结构化 slot 组 | Layout 和 Slide 的 `title` 类型 `p:ph` | `Native-stable` | carrier 数量、边界、类型与有效 index 必须与 Layout 合同一致 |
| 副标题占位符 | 含一个文本 carrier 的结构化 slot 组 | `subTitle` 类型 `p:ph` | `Native-stable` | 与标题相同的 slot 规则 |
| 正文占位符 | 含一个文本 carrier 的结构化 slot 组 | `body` 类型 `p:ph` | `Native-stable` | 多行 carrier 仍必须是一个文本框 |
+| mirror 回导文本占位符的 Slide frame | slot 的 `<text>` carrier 保留正数源 `data-pptx-frame="x y width height"`,并与 slot 的可复用 bounds 分开 | Slide carrier 保持该精确 `a:xfrm`;文字仍可编辑,源硬换行保留为显式段落 | 在受支持回导文本范围内为 `Native-stable` | `data-pptx-placeholder-bounds` 仍只定义 Layout 默认 frame,二者可以不同;standard/fidelity 创作不得为复制 bounds 而添加此 frame |
| 日期、页脚与页码占位符 | 结构化文本 slot | `dt`、`ftr` 与 `sldNum` 类型 `p:ph`,带匹配的 Layout 页眉/页脚标志 | `Native-stable` | 占位符 index 必须唯一且合法 |
| 图片占位符 | 含一个图片或受支持 crop carrier 的结构化 slot | `pic` 类型 `p:ph` | 在图片合同内为 `Native-stable` | slot 必须恰好含一个兼容的直接 carrier |
| 图表或表格占位符 | 含一个匹配原生对象 carrier 的结构化 slot | `chart` 或 `tbl` 类型 `p:ph` | 仅原生 Chart/Table 导出时为 `Native-stable` | 需要合法 JSON metadata 与 `--native-charts-and-tables` |
diff --git a/docs/zh/templates-guide.md b/docs/zh/templates-guide.md
index f46e16f7..493b18b1 100644
--- a/docs/zh/templates-guide.md
+++ b/docs/zh/templates-guide.md
@@ -174,6 +174,18 @@ PPT Master 的“模板”是一份**结构 + 风格**的预设包:每张 SVG
**关于 PowerPoint 原生形状**:完整导入 SVG 作为原生载荷后备留在临时分析工作区且保持不可变;模板创建使用轻量、可编辑的 `authoring-svg/` IR 及其 source-ref/hash manifest。创作模式使用项目规范化 SVG,只有精确匹配已登记 preset 时才使用 compact authored-preset 组。Mirror 从 IR 物化最终模板 SVG,只为未改且 hash 匹配的 Slide-local/slot ref 恢复转换器已支持的载荷;固定 Master/Layout 层保持直接原子,不支持或已修改的对象保留当前 SVG fallback,最终模板不包含 IR 专用 ref。
+对于 PPTX 来源的 Type A mirror,最终物化统一使用一个确定性命令:
+
+```bash
+python3 skills/ppt-master/scripts/mirror_template_materialize.py \
+ "<import_workspace>" "<empty_template_workspace>"
+```
+
+它会先校验 IR manifest、不可变来源 hash、完整原生图谱、可见性事实和
+导入向量闭包,再原子发布按源顺序排列的 SVG roster 及
+`icons/imported/`、`images/` 素材。它不会把 `svg-flat/` 当成模板来源,
+也不会生成 `design_spec.md`;设计角色必须针对物化后的 roster 编写该简报。
+
**Mirror 图谱边界**:mirror 保留完整且受支持的来源 Master/Layout 图谱。它为每张来源 Slide 输出一个完整原型,并为未被任何来源 Slide 使用的 Layout 额外输出一个定义专用的 `layout_<layout_key>.svg`。后者通过独立 Layout roster 注册进 PowerPoint,不会变成发布页面;其父 Master 也随之保留。预检只在必要来源事实或受支持几何缺失时停止,不会仅因 Layout 未使用而停止。
**`mirror` 模板怎么消费**:Strategist 为每个项目页选择一张 mirror 参考,Executor 复制完整 SVG 并原位修改可见文字,同时保留装饰、精灵图裁剪、几何坐标和全部 `data-pptx-*` 结构声明。
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 0d80a5f6..0f91556b 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -1757,8 +1757,12 @@ Every new SVG project declares one deterministic route. Free-design and brand-on
**Template behavior**: Strict preserves the selected prototype's declared Master/Layout/slot contract. Adaptive retains its Master and may allocate a new Layout key/name only when fixed Layout atoms or slot topology/bounds change; update the lock during authoring. Mirror-created prototypes preserve restored source identity, literal paint, typography, effects, atomic geometry, and referenced assets. `standard` / `fidelity` never make source topology authoritative; mirror does not synthesize a replacement topology.
-Imported inherited-shape visibility is an analysis fact, not generated SVG
-authoring syntax; see
+Imported inherited-shape visibility remains an immutable analysis fact until a
+structured mirror is materialized. The final mirror root carries that fact with
+the two optional canonical booleans below so export can restore the source
+package fields without inferring visibility from which shapes happen to be
+present. Authored `standard` / `fidelity` templates normally omit both and use
+the default `true`. See
[`powerpoint-svg-mapping.md`](../../../docs/powerpoint-svg-mapping.md) §2 and
[`conversion.md`](../scripts/docs/conversion.md#pptx_to_svgpy).
@@ -1795,6 +1799,8 @@ prototype size remain unchanged.
| `data-pptx-master-name="Default Master"` | root `<svg>` | Sets the Master picker/display name |
| `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-show-master-shapes="false"` | root `<svg>` | Accepts exact lowercase `true` or `false` and restores the assigned Layout's `p:sldLayout@showMasterSp`; every SVG using the same Layout key must repeat the same value; omission means `true` |
+| `data-pptx-show-inherited-shapes="false"` | root `<svg>` | Accepts exact lowercase `true` or `false` and restores this Slide's `p:sld@showMasterSp`; `false` hides inherited Layout and Master shapes without removing backgrounds, placeholders, parts, or parent relationships; omission means `true` |
| `data-pptx-layer="master"` | direct semantic atom | Moves one repeated static object/background into the named Slide Master; ordinary `<g>` is forbidden, while one validated compact authored-preset `<g>` (§1.5) is an atomic exception |
| `data-pptx-layer="layout"` | direct semantic atom | Moves one repeated static object/background into the selected Layout; ordinary `<g>` is forbidden, while one validated compact authored-preset `<g>` (§1.5) is an atomic exception |
| `data-pptx-layer="slide"` | direct full-canvas solid `<rect>` only | Writes a one-page override as Slide `p:bg` |
@@ -1805,7 +1811,7 @@ prototype size remain unchanged.
| `data-pptx-placeholder-binding="proxy"` | composite `object` slot `<g>` only | Keeps the visible group ordinary and creates one hidden transparent binding proxy |
| `data-pptx-editable="false"` | master/layout element or slide background | Declares intentional editing outside ordinary slide content |
-**Hard rule — explicit only**: On a structured deck/layout template route, every SVG requires the four root Master/Layout identity attributes. Every Master/Layout atom and slot requires a unique stable `id` and is a direct root child. Layouts with zero slots are valid. `data-pptx-layout-kind`, `distilled`, and `utility` are legacy metadata and fail the structured contract. Flat free-design/brand-only pages omit the entire interface.
+**Hard rule — explicit only**: On a structured deck/layout template route, every SVG requires the four root Master/Layout identity attributes. Optional inherited-shape visibility uses only exact lowercase `true` / `false`; other spellings fail, and omission means `true`. Every Master/Layout atom and slot requires a unique stable `id` and is a direct root child. Layouts with zero slots are valid. `data-pptx-layout-kind`, `distilled`, and `utility` are legacy metadata and fail the structured contract. Flat free-design/brand-only pages omit the entire interface, including the visibility attributes.
**Layer order**: Author the SVG in PowerPoint paint order: Master background,
Layout background, optional Slide background, remaining Master atoms, remaining Layout atoms,
@@ -1842,6 +1848,14 @@ several line shapes as one
PowerPoint placeholder prototype/binding. Leave strict-line text Slide-local
when separate frames are the required result.
+For a materialized mirror, an imported text carrier may additionally keep the
+source shape's positive `data-pptx-frame="x y width height"`. That frame owns
+the Slide carrier `a:xfrm`; the converter reconstructs text-body insets from the
+visible SVG anchor/baseline instead of shrinking the shape to glyph bounds.
+`data-pptx-placeholder-bounds` remains the reusable Layout default and may
+legitimately differ. Do not add `data-pptx-frame` to an authored
+`standard` / `fidelity` carrier merely to duplicate its Layout bounds.
+
**Blank text carrier**: Leave a marked text carrier empty or whitespace-only
when the placeholder must remain visually blank. Export materializes one
invisible U+200B run so the carrier still becomes a native PowerPoint text
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 1c1928a2..ebd79147 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -45,7 +45,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
+| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
@@ -82,6 +82,7 @@ python3 scripts/pptx_template_import.py <template.pptx>
python3 scripts/pptx_template_import.py <template.pptx> --manifest-only
python3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode both
python3 scripts/svg_authoring_view.py <imported-svg-or-dir> -o <output-dir> --projection-kind layered
+python3 scripts/mirror_template_materialize.py <import_workspace> <empty_template_workspace>
python3 scripts/template_preview_pptx.py <template_workspace>
python3 scripts/template_preview_pptx.py <legacy_template_workspace> --visual-only
```
@@ -99,6 +100,19 @@ The full imported SVG remains unchanged as native-payload backing. Template
creation edits the IR and materializes validated `templates/*.svg`; the IR
directory itself is not a final template or direct release export source.
+`mirror_template_materialize.py` is the deterministic Type A mirror compiler.
+It consumes only the layered `authoring-svg/` IR as editable input, validates
+its manifest against immutable `svg/`, `native_structure.json`,
+`svg/inheritance.json`, `source_template.pptx`, and any extracted-vector
+inventory, then publishes a complete structured template roster atomically.
+Unchanged supported Slide-local/slot refs may recover native payload; edited
+refs keep their current SVG fallback. Fixed Master/Layout wrappers are expanded
+mechanically into direct atoms, source visibility flags become canonical root
+metadata, and imported vectors are copied once to `icons/imported/`. Bitmap
+assets go to `images/`; other referenced source assets go to
+`templates/assets/`. The destination must be empty, and the command does not
+write `templates/design_spec.md`; Template_Designer owns that authored brief.
+
`template_preview_pptx.py` reads a template workspace, exports every `templates/*.svg` prototype as one structured review slide, and verifies the resulting Master/Layout package. This is an on-demand review action: its default output is `exports/<template_id>_template_preview.pptx`, and that directory need not exist before the command runs. It refuses an existing output unless an intentional re-export passes `--force`. `--visual-only` is an explicit migration aid for legacy SVG rosters: it creates a slide-local visual review deck without validating or claiming a reusable Master/Layout contract. This diagnostic path does not require a project `spec_lock.md`; it may retain generic theme/text defaults inside its clean one-Master/one-Layout shell. New structured templates use the default mode when a review deck is requested.
Template fill (direct PPTX, no SVG conversion):
@@ -153,6 +167,7 @@ Create-template/source normalization (optional; never part of automatic export):
python3 scripts/extract_svg_assets.py <layered_svg_dir> --icons-dir <icons_dir> --icon-namespace imported --inplace --id-prefix layered
python3 scripts/extract_svg_assets.py <flat_svg_dir> --icons-dir <icons_dir> --icon-namespace imported --reuse-inventory <layered_inventory.json> --inplace --id-prefix flat
python3 scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<picture_assets_dir>" --inplace # optional create-template normalization: one selected group -> one SVG picture
+python3 scripts/mirror_template_materialize.py <import_workspace> <empty_template_workspace> # Type A mirror only
```
`extract_svg_assets.py` fingerprints each extracted subtree before generated-ID
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 8e41b198..feb3c5fc 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -80,6 +80,45 @@ restore the authoring-manifest mapping. A rerun on an
already rewritten namespaced projection inventories those references and does
not progressively extract their remaining parent or sibling geometry.
+## `mirror_template_materialize.py`
+
+Compile one Type A PPTX import workspace into a deterministic structured mirror
+template after the layered authoring IR has been reviewed and edited:
+
+```bash
+python3 scripts/mirror_template_materialize.py \
+ <import_workspace> <empty_template_workspace>
+```
+
+The command treats `<import_workspace>/authoring-svg/` as the sole editable
+source. It validates the layered authoring manifest, immutable lossless SVG
+hashes, source PPTX hash, complete Master/Layout/Slide graph, inheritance
+visibility facts, source-ref closure, and extracted-vector inventory before it
+writes anything. It refuses a non-empty destination and stages the whole result
+before atomic publication, so a failed preflight cannot leave a partial
+template.
+
+Materialization preserves source page order and emits one definition-only
+`layout_<layout_key>.svg` for every source Layout unused by all source Slides.
+It mechanically expands fixed Master/Layout group wrappers into direct atoms,
+rehydrates only unchanged converter-supported Slide-local/slot refs, keeps the
+current SVG fallback for edited refs, restores explicit text hard breaks, and
+removes every IR-only source ref. Source `p:sldLayout@showMasterSp` and
+`p:sld@showMasterSp` facts become canonical root
+`data-pptx-show-master-shapes` and
+`data-pptx-show-inherited-shapes` booleans. An imported text placeholder keeps
+its authoritative native frame on the `<text data-pptx-frame>` carrier so the
+Slide-local frame can differ from the reusable Layout bounds without collapsing
+to glyph bounds.
+
+The output routes reusable vectors once to `icons/imported/`, bitmaps to
+`images/`, and other referenced files to `templates/assets/`. The JSON report
+is written to stdout only. The command intentionally does not create
+`templates/design_spec.md`; Template_Designer writes that personality and page
+roster after materialization. This compiler is for Type A mirror restoration,
+not `standard` / `fidelity`, loose Type B SVGs, ordinary generation, finalize,
+or export.
+
## `extract_svg_pictures.py`
Normalize one deliberately selected complex SVG object into one PowerPoint
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
new file mode 100644
index 00000000..8e74c3d3
--- /dev/null
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -0,0 +1,2315 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Mirror Template Materializer
+
+Materialize a deterministic structured SVG template workspace from one Type A
+PPTX import workspace. The editable authoring IR is the only authoring input;
+lossless SVG files are consulted solely to restore unchanged supported source
+objects. Final templates and imported vectors contain no IR-only source refs.
+
+Usage:
+ python3 scripts/mirror_template_materialize.py \
+ <import_workspace> <template_workspace>
+
+Dependencies:
+ None (standard library and sibling PPT Master modules only).
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import copy
+import hashlib
+import json
+import math
+import os
+import re
+import sys
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Iterable
+from urllib.parse import unquote, urlsplit, urlunsplit
+from xml.etree import ElementTree as ET
+
+from console_encoding import configure_utf8_stdio
+from pptx_shapes import svg_preset_preview_fingerprint
+from svg_authoring_view import (
+ AUTHORING_MANIFEST_NAME,
+ AUTHORING_SCHEMA,
+ SOURCE_REF_ATTRIBUTE,
+ semantic_subtree_sha256,
+)
+from svg_to_pptx.pptx_package.template_structure import (
+ TemplateStructureError,
+ parse_template_slides,
+)
+
+configure_utf8_stdio()
+
+SVG_NS = "http://www.w3.org/2000/svg"
+XLINK_NS = "http://www.w3.org/1999/xlink"
+XML_NS = "http://www.w3.org/XML/1998/namespace"
+NATIVE_STRUCTURE_SCHEMA = "ppt-master.native-structure.v1"
+VECTOR_INVENTORY_SCHEMA = "vector_asset_inventory.v1"
+IMPORTED_ICON_NAMESPACE = "imported"
+
+ET.register_namespace("", SVG_NS)
+ET.register_namespace("xlink", XLINK_NS)
+
+_NON_VISUAL_TAGS = frozenset({"defs", "desc", "metadata", "style", "title"})
+_BITMAP_EXTENSIONS = frozenset({
+ ".avif",
+ ".bmp",
+ ".gif",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".tif",
+ ".tiff",
+ ".webp",
+})
+_INHERITED_PRESENTATION_ATTRIBUTES = frozenset({
+ "color",
+ "fill",
+ "fill-opacity",
+ "font-family",
+ "font-size",
+ "font-style",
+ "font-weight",
+ "letter-spacing",
+ "paint-order",
+ "shape-rendering",
+ "stroke",
+ "stroke-dasharray",
+ "stroke-dashoffset",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "stroke-miterlimit",
+ "stroke-opacity",
+ "stroke-width",
+ "text-anchor",
+ "text-decoration",
+ "word-spacing",
+})
+_AGGREGATE_GROUP_ATTRIBUTES = frozenset({
+ "clip-path",
+ "filter",
+ "mask",
+ "mix-blend-mode",
+ "opacity",
+})
+_URL_REFERENCE_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"\s]+)\1\s*\)")
+_CSS_ID_RE = re.compile(r"#([A-Za-z_][A-Za-z0-9_.:-]*)")
+_SAFE_KEY_RE = re.compile(r"[^A-Za-z0-9_.-]+")
+
+
+class MirrorMaterializationError(RuntimeError):
+ """Reject incomplete, ambiguous, or unsafe mirror materialization input."""
+
+
+@dataclass(frozen=True)
+class SourceRefRecord:
+ source_path: tuple[int, ...]
+ initial_authoring_subtree_sha256: str
+
+
+@dataclass(frozen=True)
+class AuthoringDocument:
+ name: str
+ authoring_path: Path
+ source_path: Path
+ source_sha256: str
+ source_refs: dict[str, SourceRefRecord]
+
+
+@dataclass(frozen=True)
+class VectorAssetRecord:
+ icon: str
+ asset_path: Path
+ origin_document: str
+ expected_sha256: str
+ source_refs: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class SlotPlan:
+ slot_id: str
+ semantic_role: str
+ placeholder_type: str | None
+ idx: int | None
+ shape_id: str
+ bounds: tuple[float, float, float, float]
+
+
+@dataclass
+class RestorationStats:
+ rehydrated_refs: int = 0
+ fallback_refs: int = 0
+ structural_refs: int = 0
+ detached_connector_endpoints: int = 0
+
+ def merge(self, other: "RestorationStats") -> None:
+ self.rehydrated_refs += other.rehydrated_refs
+ self.fallback_refs += other.fallback_refs
+ self.structural_refs += other.structural_refs
+ self.detached_connector_endpoints += other.detached_connector_endpoints
+
+ def as_dict(self) -> dict[str, int]:
+ return {
+ "rehydrated_refs": self.rehydrated_refs,
+ "fallback_refs": self.fallback_refs,
+ "structural_refs": self.structural_refs,
+ "detached_connector_endpoints": self.detached_connector_endpoints,
+ }
+
+
+@dataclass
+class MaterializedFile:
+ relative_path: Path
+ payload: bytes
+
+
+def _local_name(name: object) -> str:
+ return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""
+
+
+def _sha256_bytes(payload: bytes) -> str:
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _sha256_file(path: Path) -> str:
+ return _sha256_bytes(path.read_bytes())
+
+
+def _load_json(path: Path, *, context: str) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except OSError as exc:
+ raise MirrorMaterializationError(f"Cannot read {context}: {path}: {exc}") from exc
+ except json.JSONDecodeError as exc:
+ raise MirrorMaterializationError(
+ f"Invalid JSON in {context}: {path}: {exc}"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise MirrorMaterializationError(f"{context} must be a JSON object: {path}")
+ return payload
+
+
+def _require_list(value: object, *, context: str) -> list[Any]:
+ if not isinstance(value, list):
+ raise MirrorMaterializationError(f"{context} must be a list")
+ return value
+
+
+def _require_string(value: object, *, context: str) -> str:
+ if not isinstance(value, str) or not value.strip():
+ raise MirrorMaterializationError(f"{context} must be a non-empty string")
+ return value.strip()
+
+
+def _require_boolean(value: object, *, context: str) -> bool:
+ if not isinstance(value, bool):
+ raise MirrorMaterializationError(f"{context} must be a boolean")
+ return value
+
+
+def _resolve_inside(root: Path, relative: str, *, context: str) -> Path:
+ parsed = urlsplit(relative)
+ if parsed.scheme or parsed.netloc or Path(parsed.path).is_absolute():
+ raise MirrorMaterializationError(f"{context} must be a relative path: {relative}")
+ resolved = (root / unquote(parsed.path)).resolve()
+ try:
+ resolved.relative_to(root.resolve())
+ except ValueError as exc:
+ raise MirrorMaterializationError(
+ f"{context} escapes its declared root: {relative}"
+ ) from exc
+ return resolved
+
+
+def _parse_svg(path: Path) -> ET.Element:
+ parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True, insert_pis=True))
+ try:
+ root = ET.fromstring(path.read_bytes(), parser=parser)
+ except (OSError, ET.ParseError) as exc:
+ raise MirrorMaterializationError(f"Cannot parse SVG {path}: {exc}") from exc
+ if _local_name(root.tag) != "svg":
+ raise MirrorMaterializationError(f"SVG root is not <svg>: {path}")
+ return root
+
+
+def _source_element(root: ET.Element, path: tuple[int, ...]) -> ET.Element:
+ element = root
+ try:
+ for index in path:
+ element = list(element)[index]
+ except (IndexError, TypeError) as exc:
+ raise MirrorMaterializationError(
+ f"Source-ref path no longer resolves: {list(path)}"
+ ) from exc
+ return element
+
+
+def _source_identity(element: ET.Element) -> str | None:
+ scope = element.get("data-pptx-shape-scope")
+ shape_id = element.get("data-pptx-shape-id")
+ if not scope or not shape_id:
+ return None
+ return f"{scope}:{shape_id}"
+
+
+def _load_authoring_documents(
+ workspace: Path,
+) -> tuple[Path, dict[str, AuthoringDocument]]:
+ authoring_root = workspace / "authoring-svg"
+ manifest_path = authoring_root / AUTHORING_MANIFEST_NAME
+ manifest = _load_json(manifest_path, context="authoring manifest")
+ if manifest.get("schema") != AUTHORING_SCHEMA:
+ raise MirrorMaterializationError(
+ f"Unsupported authoring manifest schema: {manifest.get('schema')!r}"
+ )
+ if manifest.get("projection_kind") != "layered":
+ raise MirrorMaterializationError(
+ "Mirror materialization requires projection_kind='layered'"
+ )
+ if manifest.get("authoring_root") != ".":
+ raise MirrorMaterializationError("authoring_manifest.json authoring_root must be '.'")
+ if manifest.get("source_ref_attribute") != SOURCE_REF_ATTRIBUTE:
+ raise MirrorMaterializationError(
+ "authoring_manifest.json uses an unsupported source-ref attribute"
+ )
+
+ source_root_raw = _require_string(
+ manifest.get("source_root"),
+ context="authoring_manifest.json source_root",
+ )
+ source_root = (authoring_root / source_root_raw).resolve()
+ expected_source_root = (workspace / "svg").resolve()
+ if source_root != expected_source_root:
+ raise MirrorMaterializationError(
+ "Type A mirror authoring manifest must resolve source_root to "
+ f"{expected_source_root}, found {source_root}"
+ )
+
+ documents_raw = _require_list(
+ manifest.get("documents"),
+ context="authoring_manifest.json documents",
+ )
+ documents: dict[str, AuthoringDocument] = {}
+ for index, raw in enumerate(documents_raw):
+ if not isinstance(raw, dict):
+ raise MirrorMaterializationError(f"documents[{index}] must be an object")
+ authoring_name = _require_string(
+ raw.get("authoring"),
+ context=f"documents[{index}].authoring",
+ )
+ source_name = _require_string(
+ raw.get("source"),
+ context=f"documents[{index}].source",
+ )
+ if authoring_name in documents:
+ raise MirrorMaterializationError(
+ f"Duplicate authoring manifest document: {authoring_name}"
+ )
+ authoring_path = _resolve_inside(
+ authoring_root,
+ authoring_name,
+ context=f"documents[{index}].authoring",
+ )
+ source_path = _resolve_inside(
+ source_root,
+ source_name,
+ context=f"documents[{index}].source",
+ )
+ if not authoring_path.is_file() or authoring_path.suffix.lower() != ".svg":
+ raise MirrorMaterializationError(
+ f"Authoring SVG is missing: {authoring_path}"
+ )
+ if not source_path.is_file() or source_path.suffix.lower() != ".svg":
+ raise MirrorMaterializationError(f"Lossless source SVG is missing: {source_path}")
+
+ expected_source_sha = _require_string(
+ raw.get("source_sha256"),
+ context=f"documents[{index}].source_sha256",
+ )
+ actual_source_sha = _sha256_file(source_path)
+ if actual_source_sha != expected_source_sha:
+ raise MirrorMaterializationError(
+ f"Lossless source SVG changed: {source_path.name}; expected "
+ f"{expected_source_sha}, found {actual_source_sha}"
+ )
+
+ refs_raw = raw.get("source_refs")
+ if not isinstance(refs_raw, dict):
+ raise MirrorMaterializationError(
+ f"documents[{index}].source_refs must be an object"
+ )
+ refs: dict[str, SourceRefRecord] = {}
+ source_root_element = _parse_svg(source_path)
+ for source_ref, ref_raw in refs_raw.items():
+ if not isinstance(source_ref, str) or not isinstance(ref_raw, dict):
+ raise MirrorMaterializationError(
+ f"Invalid source-ref record in {authoring_name}"
+ )
+ path_raw = ref_raw.get("source_path")
+ if not (
+ isinstance(path_raw, list)
+ and all(isinstance(item, int) and item >= 0 for item in path_raw)
+ ):
+ raise MirrorMaterializationError(
+ f"{authoring_name} source ref {source_ref!r} has invalid source_path"
+ )
+ initial_hash = _require_string(
+ ref_raw.get("initial_authoring_subtree_sha256"),
+ context=f"{authoring_name} source ref {source_ref!r} hash",
+ )
+ source_path_tuple = tuple(path_raw)
+ source_element = _source_element(source_root_element, source_path_tuple)
+ if _source_identity(source_element) != source_ref:
+ raise MirrorMaterializationError(
+ f"{authoring_name} source ref {source_ref!r} resolves to "
+ f"{_source_identity(source_element)!r}"
+ )
+ refs[source_ref] = SourceRefRecord(source_path_tuple, initial_hash)
+
+ documents[authoring_name] = AuthoringDocument(
+ name=authoring_name,
+ authoring_path=authoring_path,
+ source_path=source_path,
+ source_sha256=expected_source_sha,
+ source_refs=refs,
+ )
+
+ actual_authoring_files = {
+ path.relative_to(authoring_root).as_posix()
+ for path in authoring_root.rglob("*.svg")
+ if path.is_file()
+ }
+ if actual_authoring_files != set(documents):
+ raise MirrorMaterializationError(
+ "Authoring manifest/file roster differs; missing="
+ f"{sorted(set(documents) - actual_authoring_files)}, extra="
+ f"{sorted(actual_authoring_files - set(documents))}"
+ )
+ if manifest.get("file_count") != len(documents):
+ raise MirrorMaterializationError(
+ "authoring_manifest.json file_count does not match documents"
+ )
+ expected_ref_count = sum(len(document.source_refs) for document in documents.values())
+ if manifest.get("source_ref_count") != expected_ref_count:
+ raise MirrorMaterializationError(
+ "authoring_manifest.json source_ref_count does not match documents"
+ )
+ return authoring_root, documents
+
+
+def _load_vector_assets(
+ workspace: Path,
+ documents: dict[str, AuthoringDocument],
+) -> dict[str, VectorAssetRecord]:
+ inventory_path = workspace / "authoring-svg_vector_asset_inventory.json"
+ if not inventory_path.exists():
+ return {}
+ inventory = _load_json(inventory_path, context="vector asset inventory")
+ if inventory.get("schema") != VECTOR_INVENTORY_SCHEMA:
+ raise MirrorMaterializationError(
+ f"Unsupported vector inventory schema: {inventory.get('schema')!r}"
+ )
+ if inventory.get("icon_namespace") != IMPORTED_ICON_NAMESPACE:
+ raise MirrorMaterializationError(
+ "Mirror vector inventory must use icon_namespace='imported'"
+ )
+ icons_root = workspace / "icons"
+ records: dict[str, VectorAssetRecord] = {}
+ for index, raw in enumerate(
+ _require_list(inventory.get("assets"), context="vector inventory assets")
+ ):
+ if not isinstance(raw, dict):
+ raise MirrorMaterializationError(f"vector assets[{index}] must be an object")
+ icon = _require_string(raw.get("icon"), context=f"assets[{index}].icon")
+ asset = _require_string(raw.get("asset"), context=f"assets[{index}].asset")
+ origin = _require_string(raw.get("svg"), context=f"assets[{index}].svg")
+ if not icon.startswith(f"{IMPORTED_ICON_NAMESPACE}/"):
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} is outside imported/ namespace"
+ )
+ if icon in records:
+ raise MirrorMaterializationError(f"Duplicate vector asset id: {icon}")
+ if origin not in documents:
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} names unknown origin document {origin!r}"
+ )
+ asset_path = _resolve_inside(
+ icons_root,
+ asset,
+ context=f"vector asset {icon!r}",
+ )
+ if not asset_path.is_file() or asset_path.suffix.lower() != ".svg":
+ raise MirrorMaterializationError(f"Vector asset is missing: {asset_path}")
+ expected_sha256 = _require_string(
+ raw.get("asset_sha256"),
+ context=f"vector asset {icon!r} asset_sha256",
+ )
+ actual_sha256 = _sha256_file(asset_path)
+ if actual_sha256 != expected_sha256:
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} changed; expected {expected_sha256}, "
+ f"found {actual_sha256}"
+ )
+ refs_raw = _require_list(
+ raw.get("source_refs", []),
+ context=f"vector asset {icon!r} source_refs",
+ )
+ if not all(isinstance(item, str) and item for item in refs_raw):
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} source_refs must be strings"
+ )
+ records[icon] = VectorAssetRecord(
+ icon=icon,
+ asset_path=asset_path,
+ origin_document=origin,
+ expected_sha256=expected_sha256,
+ source_refs=tuple(refs_raw),
+ )
+ if inventory.get("asset_count") != len(records):
+ raise MirrorMaterializationError("Vector inventory asset_count is stale")
+ return records
+
+
+def _source_ref_counts(root: ET.Element) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for element in root.iter():
+ source_ref = element.get(SOURCE_REF_ATTRIBUTE)
+ if source_ref:
+ counts[source_ref] = counts.get(source_ref, 0) + 1
+ return counts
+
+
+def _imported_icon_refs(root: ET.Element) -> set[str]:
+ return {
+ value
+ for element in root.iter()
+ if (value := (element.get("data-icon") or "").strip())
+ if value.startswith(f"{IMPORTED_ICON_NAMESPACE}/")
+ }
+
+
+def _validate_source_ref_closure(
+ documents: dict[str, AuthoringDocument],
+ vector_assets: dict[str, VectorAssetRecord],
+) -> set[str]:
+ direct_counts: dict[str, dict[str, int]] = {}
+ referenced_icons: set[str] = set()
+ for name, document in documents.items():
+ root = _parse_svg(document.authoring_path)
+ direct_counts[name] = _source_ref_counts(root)
+ referenced_icons.update(_imported_icon_refs(root))
+
+ unknown_icons = sorted(referenced_icons - set(vector_assets))
+ if unknown_icons:
+ raise MirrorMaterializationError(
+ "Authoring SVG references missing imported vector asset(s): "
+ + ", ".join(unknown_icons)
+ )
+
+ asset_counts_by_document: dict[str, dict[str, int]] = {
+ name: {} for name in documents
+ }
+ for icon in sorted(referenced_icons):
+ record = vector_assets[icon]
+ root = _parse_svg(record.asset_path)
+ counts = _source_ref_counts(root)
+ if set(counts) != set(record.source_refs):
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} source-ref inventory is stale; expected "
+ f"{sorted(record.source_refs)}, found {sorted(counts)}"
+ )
+ duplicate_refs = sorted(ref for ref, count in counts.items() if count != 1)
+ if duplicate_refs:
+ raise MirrorMaterializationError(
+ f"Vector asset {icon!r} contains duplicate source refs: "
+ + ", ".join(duplicate_refs)
+ )
+ origin_counts = asset_counts_by_document[record.origin_document]
+ for source_ref, count in counts.items():
+ origin_counts[source_ref] = origin_counts.get(source_ref, 0) + count
+
+ for name, document in documents.items():
+ combined = dict(direct_counts[name])
+ for source_ref, count in asset_counts_by_document[name].items():
+ combined[source_ref] = combined.get(source_ref, 0) + count
+ expected = set(document.source_refs)
+ actual = set(combined)
+ duplicates = sorted(ref for ref, count in combined.items() if count != 1)
+ if actual != expected or duplicates:
+ raise MirrorMaterializationError(
+ f"{name} source-ref closure differs from its manifest; missing="
+ f"{sorted(expected - actual)}, extra={sorted(actual - expected)}, "
+ f"duplicates={duplicates}"
+ )
+ return referenced_icons
+
+
+def _load_native_graph(workspace: Path) -> dict[str, Any]:
+ native_path = workspace / "native_structure.json"
+ native = _load_json(native_path, context="native structure")
+ if native.get("schema") != NATIVE_STRUCTURE_SCHEMA:
+ raise MirrorMaterializationError(
+ f"Unsupported native structure schema: {native.get('schema')!r}"
+ )
+ source = native.get("source")
+ if not isinstance(source, dict):
+ raise MirrorMaterializationError("native_structure.json source must be an object")
+ template_name = _require_string(
+ source.get("templateFile"),
+ context="native_structure.json source.templateFile",
+ )
+ template_path = _resolve_inside(
+ workspace,
+ template_name,
+ context="native source template",
+ )
+ if not template_path.is_file():
+ raise MirrorMaterializationError(f"Native source template is missing: {template_path}")
+ expected_sha = _require_string(
+ source.get("sha256"),
+ context="native_structure.json source.sha256",
+ )
+ actual_sha = _sha256_file(template_path)
+ if actual_sha != expected_sha:
+ raise MirrorMaterializationError(
+ f"Native source template changed; expected {expected_sha}, found {actual_sha}"
+ )
+
+ slide_size = native.get("slideSize")
+ if not isinstance(slide_size, dict):
+ raise MirrorMaterializationError("native_structure.json slideSize is missing")
+ for field in ("width_px", "height_px"):
+ value = slide_size.get(field)
+ if not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
+ raise MirrorMaterializationError(f"native slideSize.{field} must be positive")
+ return native
+
+
+def _load_inheritance(workspace: Path) -> dict[str, Any]:
+ return _load_json(workspace / "svg" / "inheritance.json", context="inheritance graph")
+
+
+def _validate_graph_roster(
+ native: dict[str, Any],
+ inheritance: dict[str, Any],
+ documents: dict[str, AuthoringDocument],
+) -> None:
+ masters = _require_list(native.get("masters"), context="native masters")
+ layouts = _require_list(native.get("layouts"), context="native layouts")
+ slides = _require_list(native.get("slides"), context="native slides")
+ inheritance_masters_raw = _require_list(
+ inheritance.get("masters"),
+ context="inheritance masters",
+ )
+ master_file_by_part = {
+ _require_string(item.get("partPath"), context="inheritance Master partPath"):
+ _require_string(item.get("file"), context="inheritance Master file")
+ for item in inheritance_masters_raw
+ if isinstance(item, dict)
+ }
+ for index, master in enumerate(masters):
+ if not isinstance(master, dict):
+ raise MirrorMaterializationError(f"native masters[{index}] must be an object")
+ package_part = _require_string(
+ master.get("packagePart"),
+ context=f"native masters[{index}].packagePart",
+ )
+ svg_file = master_file_by_part.get(package_part)
+ if svg_file is None:
+ raise MirrorMaterializationError(
+ f"Native Master part {package_part!r} has no inheritance SVG file"
+ )
+ master["svgFile"] = svg_file
+ expected_files: set[str] = set()
+ for collection, field in (
+ (masters, "svgFile"),
+ (layouts, "svgFile"),
+ (slides, "layeredSvgFile"),
+ ):
+ for index, item in enumerate(collection):
+ if not isinstance(item, dict):
+ raise MirrorMaterializationError(f"native {field}[{index}] must be an object")
+ expected_files.add(
+ _require_string(item.get(field), context=f"native {field}[{index}]")
+ )
+ if expected_files != set(documents):
+ raise MirrorMaterializationError(
+ "Native graph and authoring document roster differ; missing="
+ f"{sorted(expected_files - set(documents))}, extra="
+ f"{sorted(set(documents) - expected_files)}"
+ )
+
+ inherited_masters = {
+ _require_string(item.get("file"), context="inheritance master file")
+ for item in inheritance_masters_raw
+ if isinstance(item, dict)
+ }
+ inherited_layouts = {
+ _require_string(item.get("file"), context="inheritance layout file"): item
+ for item in _require_list(inheritance.get("layouts"), context="inheritance layouts")
+ if isinstance(item, dict)
+ }
+ inherited_slides = {
+ int(item.get("index")): item
+ for item in _require_list(inheritance.get("slides"), context="inheritance slides")
+ if isinstance(item, dict) and isinstance(item.get("index"), int)
+ }
+ if inherited_masters != {item["svgFile"] for item in masters}:
+ raise MirrorMaterializationError("Inheritance Master roster differs from native graph")
+ if set(inherited_layouts) != {item["svgFile"] for item in layouts}:
+ raise MirrorMaterializationError("Inheritance Layout roster differs from native graph")
+ if set(inherited_slides) != {int(item["index"]) for item in slides}:
+ raise MirrorMaterializationError("Inheritance Slide roster differs from native graph")
+
+ master_file_by_key = {item["key"]: item["svgFile"] for item in masters}
+ layout_file_by_key = {item["key"]: item["svgFile"] for item in layouts}
+ for layout in layouts:
+ inherited = inherited_layouts[layout["svgFile"]]
+ if inherited.get("master") != master_file_by_key.get(layout.get("masterKey")):
+ raise MirrorMaterializationError(
+ f"Layout {layout.get('key')!r} Master parent differs across native facts"
+ )
+ inherited_visibility = _require_boolean(
+ inherited.get("showMasterShapes"),
+ context=f"inheritance Layout {layout.get('key')!r} showMasterShapes",
+ )
+ native_visibility = _require_boolean(
+ layout.get("showMasterShapes"),
+ context=f"native Layout {layout.get('key')!r} showMasterShapes",
+ )
+ if inherited_visibility != native_visibility:
+ raise MirrorMaterializationError(
+ f"Layout {layout.get('key')!r} showMasterShapes differs across facts"
+ )
+ for slide in slides:
+ inherited = inherited_slides[int(slide["index"])]
+ if inherited.get("layout") != layout_file_by_key.get(slide.get("layoutKey")):
+ raise MirrorMaterializationError(
+ f"Slide {slide.get('index')} Layout parent differs across native facts"
+ )
+ if inherited.get("master") != master_file_by_key.get(slide.get("masterKey")):
+ raise MirrorMaterializationError(
+ f"Slide {slide.get('index')} Master parent differs across native facts"
+ )
+ inherited_visibility = _require_boolean(
+ inherited.get("showInheritedShapes"),
+ context=f"inheritance Slide {slide.get('index')} showInheritedShapes",
+ )
+ native_visibility = _require_boolean(
+ slide.get("showInheritedShapes"),
+ context=f"native Slide {slide.get('index')} showInheritedShapes",
+ )
+ if inherited_visibility != native_visibility:
+ raise MirrorMaterializationError(
+ f"Slide {slide.get('index')} showInheritedShapes differs across facts"
+ )
+
+
+def _absolutize_local_hrefs(root: ET.Element, base_dir: Path) -> None:
+ for element in root.iter():
+ for attribute in ("href", f"{{{XLINK_NS}}}href"):
+ value = element.get(attribute)
+ if not value or value.startswith("#"):
+ continue
+ parsed = urlsplit(value)
+ if parsed.scheme or parsed.netloc or not parsed.path:
+ continue
+ absolute = (base_dir / unquote(parsed.path)).resolve().as_posix()
+ element.set(
+ attribute,
+ urlunsplit(("", "", absolute, parsed.query, parsed.fragment)),
+ )
+
+
+def _rehydrate_tree(
+ root: ET.Element,
+ document: AuthoringDocument,
+ *,
+ excluded_refs: set[str],
+) -> RestorationStats:
+ source_root = _parse_svg(document.source_path)
+ stats = RestorationStats()
+
+ def restore(element: ET.Element) -> ET.Element:
+ source_ref = element.get(SOURCE_REF_ATTRIBUTE)
+ record = document.source_refs.get(source_ref or "")
+ if source_ref and record is None:
+ raise MirrorMaterializationError(
+ f"{document.name} contains unknown source ref {source_ref!r}"
+ )
+ if source_ref and source_ref in excluded_refs:
+ stats.structural_refs += 1
+ elif source_ref and record is not None:
+ actual_hash = semantic_subtree_sha256(
+ element,
+ ignored_attributes=frozenset({SOURCE_REF_ATTRIBUTE}),
+ )
+ if actual_hash == record.initial_authoring_subtree_sha256:
+ restored = copy.deepcopy(_source_element(source_root, record.source_path))
+ _absolutize_local_hrefs(restored, document.source_path.parent)
+ stats.rehydrated_refs += 1
+ return restored
+ stats.fallback_refs += 1
+
+ children = list(element)
+ for index, child in enumerate(children):
+ replacement = restore(child)
+ if replacement is child:
+ continue
+ replacement.tail = child.tail
+ element.remove(child)
+ element.insert(index, replacement)
+ return element
+
+ restore(root)
+ return stats
+
+
+def _line_groups(text: ET.Element) -> list[list[ET.Element]]:
+ """Return direct tspan runs grouped by their imported visual line."""
+ groups: list[list[ET.Element]] = []
+ for tspan in text:
+ if _local_name(tspan.tag) != "tspan":
+ return []
+ raw_dy = _optional_float(tspan.get("dy"))
+ starts_line = (
+ not groups
+ or tspan.get("x") is not None
+ or tspan.get("y") is not None
+ or (raw_dy is not None and abs(raw_dy) > 1e-9)
+ )
+ if starts_line:
+ groups.append([tspan])
+ else:
+ groups[-1].append(tspan)
+ return groups
+
+
+def _normalized_text(value: str) -> str:
+ return " ".join(value.split())
+
+
+def _text_body_segments(metadata: ET.Element) -> list[list[str]] | None:
+ if metadata.get("data-pptx-encoding") != "base64":
+ return None
+ try:
+ payload = base64.b64decode((metadata.text or "").strip(), validate=True)
+ text_body = ET.fromstring(payload)
+ except (ValueError, ET.ParseError):
+ return None
+
+ paragraphs: list[list[str]] = []
+ for paragraph in text_body:
+ if _local_name(paragraph.tag) != "p":
+ continue
+ segments = [""]
+ for child in paragraph:
+ tag = _local_name(child.tag)
+ if tag == "br":
+ segments.append("")
+ elif tag in {"r", "fld"}:
+ segments[-1] += "".join(
+ node.text or ""
+ for node in child.iter()
+ if _local_name(node.tag) == "t"
+ )
+ paragraphs.append(segments)
+ return paragraphs
+
+
+def _mark_explicit_breaks(
+ authored_element: ET.Element,
+ source_element: ET.Element,
+) -> None:
+ metadata = next(
+ (
+ child
+ for child in source_element
+ if _local_name(child.tag) == "metadata"
+ and child.get("data-pptx-part") == "txbody"
+ ),
+ None,
+ )
+ if metadata is None:
+ return
+ paragraphs = _text_body_segments(metadata)
+ if paragraphs is None:
+ return
+ authored_texts = [
+ child for child in authored_element if _local_name(child.tag) == "text"
+ ]
+ if len(authored_texts) != len(paragraphs):
+ return
+
+ pending: list[ET.Element] = []
+ for text, segments in zip(authored_texts, paragraphs):
+ groups = _line_groups(text)
+ if not groups:
+ if len(segments) > 1:
+ return
+ continue
+ line_texts = [
+ _normalized_text(
+ "".join(text for node in group for text in node.itertext())
+ )
+ for group in groups
+ ]
+ cursor = 0
+ for segment_index, segment in enumerate(segments):
+ target = _normalized_text(segment)
+ combined = ""
+ start = cursor
+ while cursor < len(line_texts):
+ combined = _normalized_text(" ".join((combined, line_texts[cursor])))
+ cursor += 1
+ if combined == target:
+ break
+ if target and not target.startswith(combined):
+ return
+ if combined != target:
+ return
+ if segment_index > 0 and start < len(groups):
+ pending.append(groups[start][0])
+ if cursor != len(groups):
+ return
+ for tspan in pending:
+ tspan.set("data-paragraph-soft-break", "0")
+
+
+def _annotate_unchanged_explicit_text_breaks(
+ root: ET.Element,
+ document: AuthoringDocument,
+ excluded_refs: set[str],
+) -> None:
+ """Recover native a:br semantics without restoring a stale txBody."""
+ if not excluded_refs:
+ return
+ source_root = _parse_svg(document.source_path)
+ for element in root.iter():
+ source_ref = element.get(SOURCE_REF_ATTRIBUTE)
+ record = document.source_refs.get(source_ref or "")
+ if source_ref not in excluded_refs or record is None:
+ continue
+ actual_hash = semantic_subtree_sha256(
+ element,
+ ignored_attributes=frozenset({SOURCE_REF_ATTRIBUTE}),
+ )
+ if actual_hash != record.initial_authoring_subtree_sha256:
+ continue
+ _mark_explicit_breaks(
+ element,
+ _source_element(source_root, record.source_path),
+ )
+
+
+def _prepared_document(
+ document: AuthoringDocument,
+ *,
+ excluded_refs: set[str],
+) -> tuple[ET.Element, RestorationStats]:
+ root = _parse_svg(document.authoring_path)
+ _absolutize_local_hrefs(root, document.authoring_path.parent)
+ stats = _rehydrate_tree(root, document, excluded_refs=excluded_refs)
+ _annotate_unchanged_explicit_text_breaks(root, document, excluded_refs)
+ return root, stats
+
+
+def _safe_prefix(value: str) -> str:
+ normalized = _SAFE_KEY_RE.sub("-", value).strip("-.")
+ return normalized or "node"
+
+
+def _namespace_ids(root: ET.Element, prefix: str) -> None:
+ mapping: dict[str, str] = {}
+ for element in root.iter():
+ element_id = element.get("id")
+ if element_id:
+ mapping[element_id] = f"{prefix}{_safe_prefix(element_id)}"
+ for element in root.iter():
+ element_id = element.get("id")
+ if element_id:
+ element.set("id", mapping[element_id])
+ for name, value in list(element.attrib.items()):
+ if name == "id":
+ continue
+ if value.startswith("#") and value[1:] in mapping:
+ element.set(name, f"#{mapping[value[1:]]}")
+ continue
+ rewritten = _URL_REFERENCE_RE.sub(
+ lambda match: f"url(#{mapping.get(match.group(2), match.group(2))})",
+ value,
+ )
+ if name.rsplit("}", 1)[-1] in {"aria-describedby", "aria-labelledby"}:
+ rewritten = " ".join(mapping.get(token, token) for token in rewritten.split())
+ element.set(name, rewritten)
+ if _local_name(element.tag) == "style" and element.text:
+ element.text = _CSS_ID_RE.sub(
+ lambda match: f"#{mapping.get(match.group(1), match.group(1))}",
+ element.text,
+ )
+
+
+def _parse_style(value: str | None) -> dict[str, str]:
+ declarations: dict[str, str] = {}
+ for raw in (value or "").split(";"):
+ if ":" not in raw:
+ continue
+ name, declaration = raw.split(":", 1)
+ if name.strip() and declaration.strip():
+ declarations[name.strip().lower()] = declaration.strip()
+ return declarations
+
+
+def _style_text(declarations: dict[str, str]) -> str:
+ return ";".join(f"{name}:{value}" for name, value in declarations.items())
+
+
+def _hidden(element: ET.Element) -> bool:
+ style = _parse_style(element.get("style"))
+ display = (element.get("display") or style.get("display") or "").strip().lower()
+ visibility = (
+ element.get("visibility") or style.get("visibility") or ""
+ ).strip().lower()
+ opacity = (element.get("opacity") or style.get("opacity") or "").strip()
+ if display == "none" or visibility in {"hidden", "collapse"}:
+ return True
+ try:
+ return bool(opacity) and float(opacity) <= 0
+ except ValueError:
+ return False
+
+
+def _paint_value(element: ET.Element, name: str) -> str | None:
+ value = element.get(name)
+ if value is not None:
+ return value.strip().lower()
+ return _parse_style(element.get("style")).get(name)
+
+
+def _visible_leaf(element: ET.Element) -> bool:
+ if _hidden(element):
+ return False
+ tag = _local_name(element.tag)
+ if tag in _NON_VISUAL_TAGS:
+ return False
+ if tag in {"g", "svg", "a"}:
+ return any(_visible_leaf(child) for child in element)
+ if tag in {"rect", "image", "foreignObject"}:
+ for dimension in ("width", "height"):
+ raw = element.get(dimension)
+ if raw is not None:
+ try:
+ if float(raw) <= 0:
+ return False
+ except ValueError:
+ pass
+ return True
+ if tag in {"line", "polyline"}:
+ stroke = _paint_value(element, "stroke")
+ return stroke not in {None, "none", "transparent"}
+ if tag in {"path", "polygon", "circle", "ellipse"}:
+ fill = _paint_value(element, "fill")
+ stroke = _paint_value(element, "stroke")
+ return not (
+ fill in {"none", "transparent"}
+ and stroke in {None, "none", "transparent"}
+ )
+ if tag == "text":
+ return bool("".join(element.itertext()).strip())
+ return True
+
+
+def _merge_group_inheritance(parent: ET.Element, child: ET.Element) -> None:
+ for name in _INHERITED_PRESENTATION_ATTRIBUTES:
+ if parent.get(name) is not None and child.get(name) is None:
+ child.set(name, parent.get(name, ""))
+ parent_style = _parse_style(parent.get("style"))
+ child_style = _parse_style(child.get("style"))
+ if parent_style:
+ merged = dict(parent_style)
+ merged.update(child_style)
+ child.set("style", _style_text(merged))
+ parent_transform = (parent.get("transform") or "").strip()
+ child_transform = (child.get("transform") or "").strip()
+ if parent_transform:
+ child.set(
+ "transform",
+ " ".join(item for item in (parent_transform, child_transform) if item),
+ )
+
+
+def _flatten_fixed_group(group: ET.Element, *, context: str) -> list[ET.Element]:
+ visible_children = [child for child in group if _visible_leaf(child)]
+ group_style = _parse_style(group.get("style"))
+ aggregate_attrs = {
+ name for name in _AGGREGATE_GROUP_ATTRIBUTES if group.get(name) is not None
+ }
+ aggregate_attrs.update(
+ name
+ for name in _AGGREGATE_GROUP_ATTRIBUTES
+ if name in group_style
+ )
+ if len(visible_children) > 1 and aggregate_attrs:
+ raise MirrorMaterializationError(
+ f"{context} cannot expand a multi-child group with aggregate effect(s): "
+ + ", ".join(sorted(aggregate_attrs))
+ )
+
+ atoms: list[ET.Element] = []
+ for child in visible_children:
+ child_style = _parse_style(child.get("style"))
+ conflicting_aggregate_attrs = {
+ name
+ for name in aggregate_attrs
+ if child.get(name) is not None or name in child_style
+ }
+ if conflicting_aggregate_attrs:
+ raise MirrorMaterializationError(
+ f"{context} cannot collapse nested aggregate effect(s): "
+ + ", ".join(sorted(conflicting_aggregate_attrs))
+ )
+ item = copy.deepcopy(child)
+ _merge_group_inheritance(group, item)
+ for name in aggregate_attrs:
+ if group.get(name) is not None:
+ item.set(name, group.get(name, ""))
+ if _local_name(item.tag) == "g":
+ atoms.extend(_flatten_fixed_group(item, context=context))
+ else:
+ atoms.append(item)
+ if len(atoms) == 1:
+ atom = atoms[0]
+ for name in ("data-pptx-frame", "data-pptx-object", "data-pptx-prst"):
+ if group.get(name) is not None and atom.get(name) is None:
+ atom.set(name, group.get(name, ""))
+ return atoms
+
+
+def _fixed_atoms(
+ root: ET.Element,
+ *,
+ scope: str,
+ key: str,
+) -> list[ET.Element]:
+ atoms: list[ET.Element] = []
+ serial = 0
+ for child in root:
+ tag = _local_name(child.tag)
+ if tag in _NON_VISUAL_TAGS or child.get("data-ph-type") is not None:
+ continue
+ if not _visible_leaf(child):
+ continue
+ if tag == "g":
+ expanded = _flatten_fixed_group(
+ child,
+ context=f"{scope} {key} element {child.get('id') or '<g>'}",
+ )
+ else:
+ expanded = [copy.deepcopy(child)]
+ source_ref = child.get(SOURCE_REF_ATTRIBUTE)
+ source_token = source_ref.split(":", 1)[-1] if source_ref else str(serial + 1)
+ for part, atom in enumerate(expanded, start=1):
+ serial += 1
+ atom.set(
+ "id",
+ f"{scope}-{_safe_prefix(key)}-{_safe_prefix(source_token)}-{part}",
+ )
+ atom.set("data-pptx-layer", scope)
+ atom.set("data-pptx-editable", "false")
+ atom.attrib.pop("data-ph-type", None)
+ atoms.append(atom)
+ return atoms
+
+
+def _frame(element: ET.Element | None) -> tuple[float, float, float, float] | None:
+ if element is None:
+ return None
+ raw = (element.get("data-pptx-frame") or "").replace(",", " ").split()
+ if len(raw) != 4:
+ return None
+ try:
+ values = tuple(float(item) for item in raw)
+ except ValueError:
+ return None
+ if not all(math.isfinite(item) for item in values) or values[2] <= 0 or values[3] <= 0:
+ return None
+ return values
+
+
+def _element_by_ref(root: ET.Element, source_ref: str) -> ET.Element | None:
+ matches = [
+ element
+ for element in root.iter()
+ if element.get(SOURCE_REF_ATTRIBUTE) == source_ref
+ ]
+ if len(matches) > 1:
+ raise MirrorMaterializationError(f"Duplicate source ref in document: {source_ref}")
+ return matches[0] if matches else None
+
+
+def _placeholder_guide_by_semantic(
+ root: ET.Element,
+ semantic_role: str,
+) -> ET.Element | None:
+ matches = []
+ for element in root.iter():
+ placeholder_type = element.get("data-ph-type")
+ if not placeholder_type:
+ continue
+ if _semantic_role({"type": placeholder_type}) == semantic_role:
+ matches.append(element)
+ return matches[0] if len(matches) == 1 else None
+
+
+def _placeholder_idx(raw: object) -> int | None:
+ if raw is None:
+ return None
+ try:
+ value = int(str(raw))
+ except ValueError as exc:
+ raise MirrorMaterializationError(f"Invalid placeholder idx: {raw!r}") from exc
+ if value < 0:
+ raise MirrorMaterializationError(f"Placeholder idx must be non-negative: {raw!r}")
+ return value
+
+
+def _semantic_role(placeholder: dict[str, Any]) -> str:
+ role = str(placeholder.get("semanticRole") or "").strip()
+ placeholder_type = str(placeholder.get("type") or "").strip()
+ mapping = {
+ "ctrTitle": "title",
+ "title": "title",
+ "subTitle": "subtitle",
+ "body": "body",
+ "dt": "date",
+ "ftr": "footer",
+ "sldNum": "slide-number",
+ "pic": "picture",
+ "chart": "chart",
+ "tbl": "table",
+ "media": "media",
+ "obj": "object",
+ }
+ normalized = role or mapping.get(placeholder_type, "object")
+ if normalized not in {
+ "title",
+ "subtitle",
+ "body",
+ "picture",
+ "chart",
+ "table",
+ "object",
+ "media",
+ "date",
+ "footer",
+ "slide-number",
+ }:
+ raise MirrorMaterializationError(
+ f"Unsupported placeholder semantic role: {normalized!r}"
+ )
+ return normalized
+
+
+def _placeholder_match(
+ candidate: dict[str, Any],
+ target: dict[str, Any],
+) -> bool:
+ candidate_idx = _placeholder_idx(candidate.get("idx"))
+ target_idx = _placeholder_idx(target.get("idx"))
+ if candidate_idx == target_idx and _semantic_role(candidate) == _semantic_role(target):
+ return True
+ return (
+ candidate_idx == target_idx
+ and str(candidate.get("type") or "") == str(target.get("type") or "")
+ )
+
+
+def _placeholder_with_semantic_fallback(
+ candidates: Iterable[dict[str, Any]],
+ target: dict[str, Any],
+) -> dict[str, Any] | None:
+ candidate_list = list(candidates)
+ exact = [item for item in candidate_list if _placeholder_match(item, target)]
+ if len(exact) == 1:
+ return exact[0]
+ if len(exact) > 1:
+ raise MirrorMaterializationError(
+ f"Ambiguous placeholder identity for semantic role {_semantic_role(target)!r}"
+ )
+ semantic = [
+ item
+ for item in candidate_list
+ if _semantic_role(item) == _semantic_role(target)
+ ]
+ return semantic[0] if len(semantic) == 1 else None
+
+
+def _native_geometry(placeholder: dict[str, Any]) -> tuple[float, float, float, float] | None:
+ geometry = placeholder.get("geometry")
+ if not isinstance(geometry, dict):
+ return None
+ try:
+ values = tuple(float(geometry[name]) for name in ("x", "y", "width", "height"))
+ except (KeyError, TypeError, ValueError):
+ return None
+ if not all(math.isfinite(item) for item in values) or values[2] <= 0 or values[3] <= 0:
+ return None
+ return values
+
+
+def _slot_plans(
+ layout: dict[str, Any],
+ layout_root: ET.Element,
+ source_slides: list[dict[str, Any]],
+ slide_roots: dict[int, ET.Element],
+ master: dict[str, Any],
+ master_root: ET.Element,
+) -> list[SlotPlan]:
+ plans: list[SlotPlan] = []
+ placeholders = _require_list(
+ layout.get("placeholders", []),
+ context=f"layout {layout.get('key')} placeholders",
+ )
+ master_placeholders = _require_list(
+ master.get("placeholders", []),
+ context=f"master {master.get('key')} placeholders",
+ )
+ for raw in placeholders:
+ if not isinstance(raw, dict):
+ raise MirrorMaterializationError(
+ f"Layout {layout.get('key')} placeholder must be an object"
+ )
+ shape_id = _require_string(
+ raw.get("shapeId"),
+ context=f"layout {layout.get('key')} placeholder shapeId",
+ )
+ bounds = _frame(_element_by_ref(layout_root, f"layout:{shape_id}"))
+ if bounds is None:
+ for slide in source_slides:
+ matching = next(
+ (
+ item
+ for item in slide.get("placeholders", [])
+ if isinstance(item, dict) and _placeholder_match(item, raw)
+ ),
+ None,
+ )
+ if matching is None:
+ continue
+ slide_element = _element_by_ref(
+ slide_roots[int(slide["index"])],
+ f"slide:{matching['shapeId']}",
+ )
+ bounds = _frame(slide_element) or _native_geometry(matching)
+ if bounds is not None:
+ break
+ if bounds is None:
+ matching_master = _placeholder_with_semantic_fallback(
+ (item for item in master_placeholders if isinstance(item, dict)),
+ raw,
+ )
+ if matching_master is not None:
+ master_element = _element_by_ref(
+ master_root,
+ f"master:{matching_master['shapeId']}",
+ )
+ bounds = _frame(master_element) or _native_geometry(matching_master)
+ else:
+ bounds = _frame(
+ _placeholder_guide_by_semantic(master_root, _semantic_role(raw))
+ )
+ bounds = bounds or _native_geometry(raw)
+ if bounds is None:
+ raise MirrorMaterializationError(
+ f"Layout {layout.get('key')!r} placeholder {shape_id!r} has no "
+ "positive deterministic bounds in Layout, Slide, Master, or native facts"
+ )
+ plans.append(SlotPlan(
+ slot_id=f"slot-{_safe_prefix(str(layout['key']))}-{_safe_prefix(shape_id)}",
+ semantic_role=_semantic_role(raw),
+ placeholder_type=(str(raw.get("type")) if raw.get("type") is not None else None),
+ idx=_placeholder_idx(raw.get("idx")),
+ shape_id=shape_id,
+ bounds=bounds,
+ ))
+ effective_indices = [plan.idx if plan.idx is not None else 0 for plan in plans]
+ if len(effective_indices) != len(set(effective_indices)):
+ raise MirrorMaterializationError(
+ f"Layout {layout.get('key')!r} has duplicate effective placeholder idx values"
+ )
+ return plans
+
+
+def _copy_text_carrier(source: ET.Element | None) -> ET.Element | None:
+ if source is None:
+ return None
+ texts = [element for element in source.iter() if _local_name(element.tag) == "text"]
+ if not texts:
+ return None
+ if len(texts) == 1:
+ carrier = copy.deepcopy(texts[0])
+ else:
+ carrier = ET.Element(f"{{{SVG_NS}}}text", dict(texts[0].attrib))
+ previous_y = _optional_float(texts[0].get("y"))
+ first_output = True
+ for text_index, text in enumerate(texts):
+ text_y = _optional_float(text.get("y"))
+ text_children = [
+ child for child in text if _local_name(child.tag) == "tspan"
+ ]
+ if text_children:
+ for child_index, child in enumerate(text_children):
+ tspan = copy.deepcopy(child)
+ tspan.attrib.pop("y", None)
+ if first_output:
+ tspan.attrib.pop("x", None)
+ elif child_index == 0 and text_y is not None and previous_y is not None:
+ tspan.set("x", text.get("x", texts[0].get("x", "0")))
+ tspan.set("dy", _format_number(text_y - previous_y))
+ if text_index > 0 and child_index == 0:
+ tspan.set("data-paragraph-soft-break", "0")
+ carrier.append(tspan)
+ first_output = False
+ elif text.text:
+ attrs: dict[str, str] = {}
+ if not first_output and text_y is not None and previous_y is not None:
+ attrs["x"] = text.get("x", texts[0].get("x", "0"))
+ attrs["dy"] = _format_number(text_y - previous_y)
+ if text_index > 0:
+ attrs["data-paragraph-soft-break"] = "0"
+ tspan = ET.SubElement(carrier, f"{{{SVG_NS}}}tspan", attrs)
+ tspan.text = text.text
+ first_output = False
+ if text_y is not None:
+ previous_y = text_y
+ carrier.attrib.pop("id", None)
+ _normalize_mergeable_tspans(carrier)
+ source_frame = _frame(source)
+ if source_frame is not None:
+ carrier.set(
+ "data-pptx-frame",
+ " ".join(_format_number(value) for value in source_frame),
+ )
+ carrier.set("data-pptx-placeholder-carrier", "true")
+ return carrier
+
+
+def _normalize_mergeable_tspans(text: ET.Element) -> None:
+ """Mark the first line of a positional text block for paragraph merging."""
+ tspans = [child for child in text if _local_name(child.tag) == "tspan"]
+ if len(tspans) < 2 or not any(
+ any(tspan.get(name) is not None for name in ("x", "y", "dy"))
+ for tspan in tspans
+ ):
+ return
+ first = tspans[0]
+ if first.get("x") is None and text.get("x") is not None:
+ first.set("x", text.get("x", ""))
+ if first.get("y") is None and first.get("dy") is None:
+ first.set("dy", "0")
+
+
+def _blank_text_carrier(
+ plan: SlotPlan,
+ layout_guide: ET.Element | None,
+ master_guide: ET.Element | None,
+) -> ET.Element:
+ carrier = _copy_text_carrier(layout_guide)
+ if carrier is None:
+ carrier = _copy_text_carrier(master_guide)
+ if carrier is None:
+ x, y, _width, height = plan.bounds
+ carrier = ET.Element(
+ f"{{{SVG_NS}}}text",
+ {
+ "x": _format_number(x),
+ "y": _format_number(y + min(height, 24)),
+ "font-size": "18",
+ "fill": "#000000",
+ "data-pptx-placeholder-carrier": "true",
+ },
+ )
+ carrier.text = None
+ for child in list(carrier):
+ carrier.remove(child)
+ if carrier.get("data-pptx-frame") is None:
+ carrier.set(
+ "data-pptx-frame",
+ " ".join(_format_number(value) for value in plan.bounds),
+ )
+ carrier.set("data-pptx-placeholder-carrier", "true")
+ return carrier
+
+
+def _format_number(value: float) -> str:
+ return f"{value:.8f}".rstrip("0").rstrip(".") or "0"
+
+
+def _optional_float(value: str | None) -> float | None:
+ if value is None:
+ return None
+ try:
+ parsed = float(value)
+ except ValueError:
+ return None
+ return parsed if math.isfinite(parsed) else None
+
+
+def _slot_wrapper(
+ plan: SlotPlan,
+ source: ET.Element | None,
+ *,
+ layout_guide: ET.Element | None,
+ master_guide: ET.Element | None,
+) -> tuple[ET.Element, list[ET.Element]]:
+ wrapper = ET.Element(
+ f"{{{SVG_NS}}}g",
+ {
+ "id": plan.slot_id,
+ "data-pptx-placeholder": plan.semantic_role,
+ "data-pptx-placeholder-bounds": " ".join(
+ _format_number(item) for item in plan.bounds
+ ),
+ },
+ )
+ if plan.idx is not None:
+ wrapper.set("data-pptx-placeholder-idx", str(plan.idx))
+
+ extras: list[ET.Element] = []
+ if plan.semantic_role in {
+ "title",
+ "subtitle",
+ "body",
+ "date",
+ "footer",
+ "slide-number",
+ }:
+ carrier = _copy_text_carrier(source)
+ if carrier is None:
+ carrier = _blank_text_carrier(plan, layout_guide, master_guide)
+ if source is not None:
+ for child in source:
+ if _local_name(child.tag) == "text" or not _visible_leaf(child):
+ continue
+ extra = copy.deepcopy(child)
+ extra.attrib.pop("data-pptx-placeholder-carrier", None)
+ extras.append(extra)
+ wrapper.append(carrier)
+ return wrapper, extras
+
+ if plan.semantic_role == "object":
+ proxy_source = source
+ if proxy_source is None:
+ proxy_source = layout_guide
+ if proxy_source is None:
+ proxy_source = master_guide
+ if proxy_source is None:
+ raise MirrorMaterializationError(
+ f"Object slot {plan.slot_id!r} has no visible proxy source"
+ )
+ visible = [copy.deepcopy(child) for child in proxy_source if _visible_leaf(child)]
+ if not visible:
+ raise MirrorMaterializationError(
+ f"Object slot {plan.slot_id!r} has no visible proxy content"
+ )
+ wrapper.set("data-pptx-placeholder-binding", "proxy")
+ for child in visible:
+ wrapper.append(child)
+ return wrapper, extras
+
+ expected_tags = {
+ "picture": {"image", "svg"},
+ "media": {"image", "svg"},
+ "chart": {"g"},
+ "table": {"g"},
+ }[plan.semantic_role]
+ carrier_source = source or layout_guide
+ candidates = [
+ element
+ for element in (carrier_source.iter() if carrier_source is not None else [])
+ if _local_name(element.tag) in expected_tags and _visible_leaf(element)
+ ]
+ if len(candidates) != 1:
+ raise MirrorMaterializationError(
+ f"Slot {plan.slot_id!r} requires exactly one visible "
+ f"{plan.semantic_role} carrier, found {len(candidates)}"
+ )
+ carrier = copy.deepcopy(candidates[0])
+ if plan.semantic_role in {"chart", "table"}:
+ marker = carrier.get("data-pptx-replace-with")
+ if marker != plan.semantic_role:
+ raise MirrorMaterializationError(
+ f"Slot {plan.slot_id!r} {plan.semantic_role} carrier lacks native marker"
+ )
+ carrier.set("data-pptx-placeholder-carrier", "true")
+ wrapper.append(carrier)
+ return wrapper, extras
+
+
+def _strip_source_refs(root: ET.Element) -> None:
+ for element in root.iter():
+ element.attrib.pop(SOURCE_REF_ATTRIBUTE, None)
+ element.attrib.pop("data-ph-type", None)
+
+
+def _is_full_canvas_rect(
+ element: ET.Element,
+ width: float,
+ height: float,
+) -> bool:
+ if _local_name(element.tag) != "rect":
+ return False
+ try:
+ values = tuple(
+ float(element.get(name, default))
+ for name, default in (
+ ("x", "0"),
+ ("y", "0"),
+ ("width", "0"),
+ ("height", "0"),
+ )
+ )
+ except ValueError:
+ return False
+ fill = _paint_value(element, "fill")
+ return (
+ math.isclose(values[0], 0, abs_tol=0.01)
+ and math.isclose(values[1], 0, abs_tol=0.01)
+ and math.isclose(values[2], width, abs_tol=0.01)
+ and math.isclose(values[3], height, abs_tol=0.01)
+ and fill not in {None, "none", "transparent"}
+ )
+
+
+def _non_visual_nodes(roots: Iterable[ET.Element]) -> tuple[ET.Element | None, list[ET.Element]]:
+ definitions: list[ET.Element] = []
+ styles: list[ET.Element] = []
+ for root in roots:
+ for child in root:
+ tag = _local_name(child.tag)
+ if tag == "defs":
+ definitions.extend(copy.deepcopy(list(child)))
+ elif tag == "style":
+ styles.append(copy.deepcopy(child))
+ defs_node = ET.Element(f"{{{SVG_NS}}}defs") if definitions else None
+ if defs_node is not None:
+ for definition in definitions:
+ defs_node.append(definition)
+ return defs_node, styles
+
+
+def _slide_placeholder_map(slide: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ return {
+ f"slide:{item['shapeId']}": item
+ for item in slide.get("placeholders", [])
+ if isinstance(item, dict) and item.get("shapeId") is not None
+ }
+
+
+def _matching_slide_placeholder(
+ slide: dict[str, Any],
+ layout_placeholder: dict[str, Any],
+) -> dict[str, Any] | None:
+ matches = [
+ item
+ for item in slide.get("placeholders", [])
+ if isinstance(item, dict) and _placeholder_match(item, layout_placeholder)
+ ]
+ if len(matches) > 1:
+ raise MirrorMaterializationError(
+ f"Slide {slide.get('index')} ambiguously matches Layout placeholder "
+ f"{layout_placeholder.get('shapeId')}"
+ )
+ return matches[0] if matches else None
+
+
+def _compose_template(
+ *,
+ native: dict[str, Any],
+ master: dict[str, Any],
+ layout: dict[str, Any],
+ master_root: ET.Element,
+ layout_root: ET.Element,
+ slide: dict[str, Any] | None,
+ slide_root: ET.Element | None,
+ slot_plans: list[SlotPlan],
+) -> ET.Element:
+ width = float(native["slideSize"]["width_px"])
+ height = float(native["slideSize"]["height_px"])
+ root = ET.Element(
+ f"{{{SVG_NS}}}svg",
+ {
+ "version": "1.1",
+ "width": _format_number(width),
+ "height": _format_number(height),
+ "viewBox": f"0 0 {_format_number(width)} {_format_number(height)}",
+ "data-pptx-master": str(master["key"]),
+ "data-pptx-master-name": str(master["name"]),
+ "data-pptx-layout": str(layout["key"]),
+ "data-pptx-layout-name": str(layout["name"]),
+ "data-pptx-show-master-shapes": str(
+ _require_boolean(
+ layout.get("showMasterShapes"),
+ context=f"Layout {layout.get('key')!r} showMasterShapes",
+ )
+ ).lower(),
+ "data-pptx-show-inherited-shapes": str(
+ _require_boolean(
+ slide.get("showInheritedShapes"),
+ context=f"Slide {slide.get('index')} showInheritedShapes",
+ )
+ if slide
+ else True
+ ).lower(),
+ },
+ )
+
+ roots = [master_root, layout_root]
+ if slide_root is not None:
+ roots.append(slide_root)
+ defs, styles = _non_visual_nodes(roots)
+ if defs is not None:
+ root.append(defs)
+ for style in styles:
+ root.append(style)
+
+ master_atoms = _fixed_atoms(master_root, scope="master", key=str(master["key"]))
+ layout_atoms = _fixed_atoms(layout_root, scope="layout", key=str(layout["key"]))
+ master_backgrounds = [
+ atom for atom in master_atoms if _is_full_canvas_rect(atom, width, height)
+ ]
+ layout_backgrounds = [
+ atom for atom in layout_atoms if _is_full_canvas_rect(atom, width, height)
+ ]
+ master_shapes = [atom for atom in master_atoms if atom not in master_backgrounds]
+ layout_shapes = [atom for atom in layout_atoms if atom not in layout_backgrounds]
+
+ slide_backgrounds: list[ET.Element] = []
+ slide_content: list[ET.Element] = []
+ source_placeholder_elements: dict[str, ET.Element] = {}
+ if slide_root is not None and slide is not None:
+ placeholder_refs = _slide_placeholder_map(slide)
+ for index, child in enumerate(slide_root):
+ if _local_name(child.tag) in _NON_VISUAL_TAGS:
+ continue
+ source_ref = child.get(SOURCE_REF_ATTRIBUTE)
+ if source_ref in placeholder_refs:
+ source_placeholder_elements[source_ref] = child
+ continue
+ item = copy.deepcopy(child)
+ if _is_full_canvas_rect(item, width, height):
+ item.set("id", item.get("id") or f"slide-{slide['index']}-background")
+ item.set("data-pptx-layer", "slide")
+ item.set("data-pptx-editable", "false")
+ slide_backgrounds.append(item)
+ else:
+ item.set("id", item.get("id") or f"slide-{slide['index']}-node-{index + 1}")
+ slide_content.append(item)
+ if len(slide_backgrounds) > 1:
+ raise MirrorMaterializationError(
+ f"Slide {slide['index']} has more than one full-canvas solid background"
+ )
+
+ layout_placeholders = {
+ str(item["shapeId"]): item
+ for item in layout.get("placeholders", [])
+ if isinstance(item, dict) and item.get("shapeId") is not None
+ }
+ master_placeholders = [
+ item for item in master.get("placeholders", []) if isinstance(item, dict)
+ ]
+ slots: list[ET.Element] = []
+ slot_extras: list[ET.Element] = []
+ for plan in slot_plans:
+ layout_placeholder = layout_placeholders[plan.shape_id]
+ layout_guide = _element_by_ref(layout_root, f"layout:{plan.shape_id}")
+ master_placeholder = _placeholder_with_semantic_fallback(
+ master_placeholders,
+ layout_placeholder,
+ )
+ master_guide = (
+ _element_by_ref(master_root, f"master:{master_placeholder['shapeId']}")
+ if master_placeholder is not None
+ else _placeholder_guide_by_semantic(
+ master_root,
+ plan.semantic_role,
+ )
+ )
+ source_element = None
+ if slide is not None:
+ slide_placeholder = _matching_slide_placeholder(slide, layout_placeholder)
+ if slide_placeholder is not None:
+ source_element = source_placeholder_elements.get(
+ f"slide:{slide_placeholder['shapeId']}"
+ )
+ if source_element is None:
+ raise MirrorMaterializationError(
+ f"Slide {slide['index']} placeholder {slide_placeholder['shapeId']} "
+ "is missing from its authoring SVG"
+ )
+ wrapper, extras = _slot_wrapper(
+ plan,
+ source_element,
+ layout_guide=layout_guide,
+ master_guide=master_guide,
+ )
+ slots.append(wrapper)
+ slot_extras.extend(extras)
+
+ for element in (
+ *master_backgrounds,
+ *layout_backgrounds,
+ *slide_backgrounds,
+ *master_shapes,
+ *layout_shapes,
+ *slide_content,
+ *slot_extras,
+ *slots,
+ ):
+ _strip_source_refs(element)
+ root.append(element)
+ _strip_source_refs(root)
+ return root
+
+
+def _page_type(slide: dict[str, Any]) -> str:
+ raw = str(slide.get("pageType") or "").strip().lower()
+ mapping = {
+ "cover_candidate": "cover",
+ "toc_candidate": "toc",
+ "chapter_candidate": "chapter",
+ "content_candidate": "content",
+ "ending_candidate": "ending",
+ }
+ return mapping.get(raw, "content")
+
+
+def _serialize_svg(root: ET.Element) -> bytes:
+ payload = ET.tostring(root, encoding="utf-8", xml_declaration=False)
+ return payload if payload.endswith(b"\n") else payload + b"\n"
+
+
+def _refresh_preset_preview_hashes(root: ET.Element) -> None:
+ """Rebind imported preset guards after deterministic SVG ID namespacing."""
+ for element in root.iter():
+ if (
+ _local_name(element.tag) == "g"
+ and element.get("data-pptx-object") in {"shape", "connector"}
+ and element.get("data-pptx-prst") is not None
+ and element.get("data-pptx-preview-sha256") is not None
+ ):
+ fingerprint = svg_preset_preview_fingerprint(element)
+ element.set("data-pptx-preview-sha256", fingerprint)
+ for descendant in element.iter():
+ if descendant.get("data-pptx-preview-sha256") is not None:
+ descendant.set("data-pptx-preview-sha256", fingerprint)
+
+
+def _sanitize_connector_references(root: ET.Element) -> int:
+ """Drop endpoint bindings whose native target is absent from this SVG tree."""
+ identities = {
+ (
+ element.get("data-pptx-shape-scope"),
+ element.get("data-pptx-shape-id"),
+ )
+ for element in root.iter()
+ if element.get("data-pptx-shape-scope")
+ and element.get("data-pptx-shape-id")
+ }
+ detached: set[tuple[str, str, str]] = set()
+ for element in root.iter():
+ connector_scope = element.get("data-pptx-shape-scope") or "unknown"
+ connector_id = element.get("data-pptx-shape-id") or element.get("id") or "unknown"
+ for endpoint in ("start", "end"):
+ target_id_attr = f"data-pptx-{endpoint}-shape-id"
+ target_id = element.get(target_id_attr)
+ if target_id is None:
+ continue
+ target_scope = element.get(
+ f"data-pptx-{endpoint}-shape-scope",
+ connector_scope,
+ )
+ if (target_scope, target_id) in identities:
+ continue
+ detached.add((connector_scope, connector_id, endpoint))
+ for suffix in ("shape-id", "shape-scope", "site"):
+ element.attrib.pop(f"data-pptx-{endpoint}-{suffix}", None)
+ return len(detached)
+
+
+def _local_asset_path(value: str, base_dir: Path) -> Path | None:
+ if not value or value.startswith("#"):
+ return None
+ parsed = urlsplit(value)
+ if parsed.scheme == "file":
+ return Path(unquote(parsed.path)).resolve()
+ if parsed.scheme or parsed.netloc or not parsed.path:
+ return None
+ path = Path(unquote(parsed.path))
+ return path.resolve() if path.is_absolute() else (base_dir / path).resolve()
+
+
+def _detected_bitmap_extension(path: Path) -> str | None:
+ header = path.read_bytes()[:32]
+ if header.startswith(b"\x89PNG\r\n\x1a\n"):
+ return ".png"
+ if header.startswith(b"\xff\xd8\xff"):
+ return ".jpg"
+ if header.startswith((b"GIF87a", b"GIF89a")):
+ return ".gif"
+ if header.startswith(b"BM"):
+ return ".bmp"
+ if header.startswith((b"II*\x00", b"MM\x00*")):
+ return ".tiff"
+ if len(header) >= 12 and header[:4] == b"RIFF" and header[8:12] == b"WEBP":
+ return ".webp"
+ return None
+
+
+def _rewrite_packaged_assets(
+ root: ET.Element,
+ *,
+ source_base: Path,
+ final_svg_path: Path,
+ template_workspace: Path,
+ asset_sources: dict[Path, Path],
+) -> None:
+ for element in root.iter():
+ for attribute in ("href", f"{{{XLINK_NS}}}href"):
+ value = element.get(attribute)
+ if value is None:
+ continue
+ source = _local_asset_path(value, source_base)
+ if source is None:
+ continue
+ if not source.is_file():
+ raise MirrorMaterializationError(
+ f"Referenced local asset is missing: {source}"
+ )
+ detected_extension = _detected_bitmap_extension(source)
+ if detected_extension is not None:
+ source_suffix = source.suffix.lower()
+ equivalent_suffixes = (
+ {".jpg", ".jpeg"}
+ if detected_extension == ".jpg"
+ else {detected_extension}
+ )
+ packaged_name = (
+ source.name
+ if source_suffix in equivalent_suffixes
+ else f"{source.stem}{detected_extension}"
+ )
+ relative_target = Path("images") / packaged_name
+ elif source.suffix.lower() in _BITMAP_EXTENSIONS:
+ relative_target = Path("images") / source.name
+ else:
+ relative_target = Path("templates") / "assets" / source.name
+ previous = asset_sources.get(relative_target)
+ if previous is not None and _sha256_file(previous) != _sha256_file(source):
+ raise MirrorMaterializationError(
+ f"Asset basename collision with different content: {source.name}"
+ )
+ asset_sources[relative_target] = source
+ target = template_workspace / relative_target
+ relative_href = os.path.relpath(target, final_svg_path.parent).replace(os.sep, "/")
+ parsed = urlsplit(value)
+ element.set(
+ attribute,
+ urlunsplit(("", "", relative_href, parsed.query, parsed.fragment)),
+ )
+
+
+def _materialize_icon(
+ record: VectorAssetRecord,
+ document: AuthoringDocument,
+) -> tuple[ET.Element, RestorationStats]:
+ actual_sha256 = _sha256_file(record.asset_path)
+ if actual_sha256 != record.expected_sha256:
+ raise MirrorMaterializationError(
+ f"Vector asset {record.icon!r} changed during materialization; "
+ f"expected {record.expected_sha256}, found {actual_sha256}"
+ )
+ root = _parse_svg(record.asset_path)
+ _absolutize_local_hrefs(root, record.asset_path.parent)
+ stats = _rehydrate_tree(root, document, excluded_refs=set())
+ _strip_source_refs(root)
+ return root, stats
+
+
+def _ensure_no_source_refs(path: Path) -> None:
+ root = _parse_svg(path)
+ refs = sorted(_source_ref_counts(root))
+ if refs:
+ raise MirrorMaterializationError(
+ f"Materialized file still contains source refs: {path}: {refs[:5]}"
+ )
+
+
+def _preflight_output(
+ import_workspace: Path,
+ template_workspace: Path,
+ relative_files: Iterable[Path],
+) -> None:
+ import_resolved = import_workspace.resolve()
+ output_resolved = template_workspace.resolve()
+ try:
+ output_resolved.relative_to(import_resolved)
+ except ValueError:
+ pass
+ else:
+ raise MirrorMaterializationError(
+ "Template workspace must not be inside the import workspace"
+ )
+ try:
+ import_resolved.relative_to(output_resolved)
+ except ValueError:
+ pass
+ else:
+ raise MirrorMaterializationError(
+ "Import workspace must not be inside the template workspace"
+ )
+
+ templates_root = template_workspace / "templates"
+ if templates_root.exists():
+ if not templates_root.is_dir():
+ raise MirrorMaterializationError(
+ f"Template output is not a directory: {templates_root}"
+ )
+ existing = sorted(path for path in templates_root.iterdir())
+ if existing:
+ raise MirrorMaterializationError(
+ f"Template output must be empty before mirror materialization: "
+ f"{templates_root}; first entry: {existing[0].name}"
+ )
+ collisions = [
+ template_workspace / relative
+ for relative in relative_files
+ if os.path.lexists(template_workspace / relative)
+ ]
+ if collisions:
+ raise MirrorMaterializationError(
+ f"Output file already exists: {collisions[0]}"
+ )
+
+
+def _nearest_existing_directory(path: Path) -> Path:
+ candidate = path
+ while not candidate.exists():
+ if candidate.parent == candidate:
+ break
+ candidate = candidate.parent
+ if not candidate.is_dir():
+ raise MirrorMaterializationError(f"Output parent is not a directory: {candidate}")
+ return candidate
+
+
+def _ensure_directory(path: Path, created: list[Path]) -> None:
+ missing: list[Path] = []
+ candidate = path
+ while not candidate.exists():
+ if os.path.lexists(candidate):
+ raise MirrorMaterializationError(
+ f"Output parent is not a directory: {candidate}"
+ )
+ missing.append(candidate)
+ candidate = candidate.parent
+ if not candidate.is_dir():
+ raise MirrorMaterializationError(f"Output parent is not a directory: {candidate}")
+ for directory in reversed(missing):
+ directory.mkdir()
+ created.append(directory)
+
+
+def _publish_files(
+ template_workspace: Path,
+ staged_root: Path,
+ relative_files: list[Path],
+) -> None:
+ created_dirs: list[Path] = []
+ published: list[Path] = []
+ try:
+ for relative in relative_files:
+ target = template_workspace / relative
+ _ensure_directory(target.parent, created_dirs)
+ staging_device = staged_root.stat().st_dev
+ for relative in relative_files:
+ target = template_workspace / relative
+ if target.parent.stat().st_dev != staging_device:
+ raise MirrorMaterializationError(
+ f"Cannot atomically publish across filesystems: {target}"
+ )
+ if os.path.lexists(target):
+ raise MirrorMaterializationError(
+ f"Output appeared while mirror files were staged: {target}"
+ )
+ for relative in relative_files:
+ target = template_workspace / relative
+ (staged_root / relative).replace(target)
+ published.append(target)
+ except (OSError, MirrorMaterializationError) as exc:
+ rollback_errors: list[str] = []
+ for path in reversed(published):
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as rollback_exc:
+ rollback_errors.append(f"could not remove {path}: {rollback_exc}")
+ for directory in reversed(created_dirs):
+ try:
+ directory.rmdir()
+ except OSError:
+ pass
+ if rollback_errors:
+ raise MirrorMaterializationError(
+ f"Mirror publish failed ({exc}); rollback was incomplete: "
+ + "; ".join(rollback_errors)
+ ) from exc
+ raise MirrorMaterializationError(f"Mirror publish failed: {exc}") from exc
+
+
+def materialize_mirror_template(
+ import_workspace: Path,
+ template_workspace: Path,
+) -> dict[str, Any]:
+ """Validate one Type A import graph and publish its mirror SVG contract."""
+ authoring_root, documents = _load_authoring_documents(import_workspace)
+ vector_assets = _load_vector_assets(import_workspace, documents)
+ referenced_icons = _validate_source_ref_closure(documents, vector_assets)
+ native = _load_native_graph(import_workspace)
+ inheritance = _load_inheritance(import_workspace)
+ _validate_graph_roster(native, inheritance, documents)
+
+ masters = {item["key"]: item for item in native["masters"]}
+ layouts = {item["key"]: item for item in native["layouts"]}
+ slides = sorted(native["slides"], key=lambda item: int(item["index"]))
+ if [int(item["index"]) for item in slides] != list(range(1, len(slides) + 1)):
+ raise MirrorMaterializationError(
+ "Mirror source slide indexes must be contiguous and start at 1"
+ )
+
+ prepared_masters: dict[str, ET.Element] = {}
+ prepared_layouts: dict[str, ET.Element] = {}
+ prepared_slides: dict[int, ET.Element] = {}
+ total_stats = RestorationStats()
+ for key, master in masters.items():
+ document = documents[master["svgFile"]]
+ root, stats = _prepared_document(
+ document,
+ excluded_refs=set(document.source_refs),
+ )
+ _namespace_ids(root, f"m-{_safe_prefix(str(key))}-")
+ prepared_masters[key] = root
+ total_stats.merge(stats)
+ for key, layout in layouts.items():
+ document = documents[layout["svgFile"]]
+ root, stats = _prepared_document(
+ document,
+ excluded_refs=set(document.source_refs),
+ )
+ _namespace_ids(root, f"l-{_safe_prefix(str(key))}-")
+ prepared_layouts[key] = root
+ total_stats.merge(stats)
+ for slide in slides:
+ index = int(slide["index"])
+ document = documents[slide["layeredSvgFile"]]
+ placeholder_refs = {
+ f"slide:{item['shapeId']}"
+ for item in slide.get("placeholders", [])
+ if isinstance(item, dict) and item.get("shapeId") is not None
+ }
+ root, stats = _prepared_document(document, excluded_refs=placeholder_refs)
+ _namespace_ids(root, f"s-{index:03d}-")
+ prepared_slides[index] = root
+ total_stats.merge(stats)
+
+ slides_by_layout: dict[str, list[dict[str, Any]]] = {key: [] for key in layouts}
+ for slide in slides:
+ slides_by_layout[str(slide["layoutKey"])].append(slide)
+
+ plans_by_layout: dict[str, list[SlotPlan]] = {}
+ for key, layout in layouts.items():
+ master_key = str(layout["masterKey"])
+ plans_by_layout[key] = _slot_plans(
+ layout,
+ prepared_layouts[key],
+ slides_by_layout[key],
+ prepared_slides,
+ masters[master_key],
+ prepared_masters[master_key],
+ )
+
+ materialized_roots: list[tuple[Path, ET.Element]] = []
+ for slide in slides:
+ index = int(slide["index"])
+ layout = layouts[str(slide["layoutKey"])]
+ master = masters[str(slide["masterKey"])]
+ filename = Path("templates") / f"{index:03d}_{_page_type(slide)}.svg"
+ root = _compose_template(
+ native=native,
+ master=master,
+ layout=layout,
+ master_root=prepared_masters[str(master["key"])],
+ layout_root=prepared_layouts[str(layout["key"])],
+ slide=slide,
+ slide_root=prepared_slides[index],
+ slot_plans=plans_by_layout[str(layout["key"])],
+ )
+ materialized_roots.append((filename, root))
+
+ unused_layouts = [
+ layout for key, layout in layouts.items() if not slides_by_layout[key]
+ ]
+ for layout in sorted(unused_layouts, key=lambda item: str(item["key"])):
+ master = masters[str(layout["masterKey"])]
+ filename = Path("templates") / f"layout_{layout['key']}.svg"
+ root = _compose_template(
+ native=native,
+ master=master,
+ layout=layout,
+ master_root=prepared_masters[str(master["key"])],
+ layout_root=prepared_layouts[str(layout["key"])],
+ slide=None,
+ slide_root=None,
+ slot_plans=plans_by_layout[str(layout["key"])],
+ )
+ materialized_roots.append((filename, root))
+
+ asset_sources: dict[Path, Path] = {}
+ files: list[MaterializedFile] = []
+ for relative_path, root in materialized_roots:
+ final_path = template_workspace / relative_path
+ _rewrite_packaged_assets(
+ root,
+ source_base=authoring_root,
+ final_svg_path=final_path,
+ template_workspace=template_workspace,
+ asset_sources=asset_sources,
+ )
+ total_stats.detached_connector_endpoints += _sanitize_connector_references(root)
+ _refresh_preset_preview_hashes(root)
+ files.append(MaterializedFile(relative_path, _serialize_svg(root)))
+
+ for icon in sorted(referenced_icons):
+ record = vector_assets[icon]
+ icon_root, stats = _materialize_icon(
+ record,
+ documents[record.origin_document],
+ )
+ total_stats.merge(stats)
+ relative_path = Path("icons") / f"{icon}.svg"
+ final_path = template_workspace / relative_path
+ _rewrite_packaged_assets(
+ icon_root,
+ source_base=record.asset_path.parent,
+ final_svg_path=final_path,
+ template_workspace=template_workspace,
+ asset_sources=asset_sources,
+ )
+ total_stats.detached_connector_endpoints += _sanitize_connector_references(
+ icon_root
+ )
+ _refresh_preset_preview_hashes(icon_root)
+ files.append(MaterializedFile(relative_path, _serialize_svg(icon_root)))
+
+ for relative_target, source in sorted(asset_sources.items()):
+ files.append(MaterializedFile(relative_target, source.read_bytes()))
+ relative_files = [item.relative_path for item in files]
+ if len(relative_files) != len(set(relative_files)):
+ raise MirrorMaterializationError("Materializer produced duplicate output paths")
+ _preflight_output(import_workspace, template_workspace, relative_files)
+
+ staging_parent = _nearest_existing_directory(template_workspace.parent)
+ with tempfile.TemporaryDirectory(
+ prefix=".mirror-template-materialize-",
+ dir=staging_parent,
+ ) as temporary:
+ staged_root = Path(temporary) / "staged"
+ for item in files:
+ target = staged_root / item.relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(item.payload)
+
+ template_paths = sorted(
+ staged_root / relative
+ for relative, _root in materialized_roots
+ )
+ try:
+ parse_template_slides(template_paths)
+ except TemplateStructureError as exc:
+ raise MirrorMaterializationError(
+ f"Materialized structured SVG contract is invalid: {exc}"
+ ) from exc
+ for relative in relative_files:
+ if relative.suffix.lower() == ".svg":
+ _ensure_no_source_refs(staged_root / relative)
+ _publish_files(
+ template_workspace,
+ staged_root,
+ sorted(relative_files, key=lambda item: item.as_posix()),
+ )
+
+ return {
+ "schema": "ppt-master.mirror-materialization-report.v1",
+ "import_workspace": str(import_workspace),
+ "template_workspace": str(template_workspace),
+ "source_slide_indexes": [int(item["index"]) for item in slides],
+ "source_slide_count": len(slides),
+ "master_count": len(masters),
+ "layout_count": len(layouts),
+ "unused_layout_count": len(unused_layouts),
+ "template_svg_count": len(materialized_roots),
+ "imported_vector_count": len(referenced_icons),
+ "packaged_asset_count": len(asset_sources),
+ "restoration": total_stats.as_dict(),
+ "files": [
+ item.relative_path.as_posix()
+ for item in sorted(files, key=lambda item: item.relative_path.as_posix())
+ ],
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Materialize a deterministic mirror template from one PPTX import "
+ "workspace's layered authoring IR."
+ )
+ )
+ parser.add_argument(
+ "import_workspace",
+ type=Path,
+ help="Type A PPTX import workspace containing authoring-svg/ and native facts",
+ )
+ parser.add_argument(
+ "template_workspace",
+ type=Path,
+ help="Empty template workspace destination (templates/ must be absent or empty)",
+ )
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ import_workspace = args.import_workspace.resolve()
+ template_workspace = args.template_workspace.resolve()
+ if not import_workspace.is_dir():
+ print(f"Error: import workspace does not exist: {import_workspace}", file=sys.stderr)
+ return 1
+ try:
+ report = materialize_mirror_template(import_workspace, template_workspace)
+ except (MirrorMaterializationError, OSError) as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index f764ee6d..74676e9b 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -107,7 +107,7 @@ def _stable_tag_name(tag: object) -> str:
raise ValueError(f"Unsupported XML node type in source object: {tag!r}")
-def _subtree_sha256(
+def semantic_subtree_sha256(
element: ET.Element,
*,
ignored_attributes: frozenset[str] = frozenset(),
@@ -212,7 +212,7 @@ def _index_initial_authoring_references(
if reference is None:
raise ValueError(f"Unknown authoring source reference: {source_ref}")
seen.add(source_ref)
- reference.initial_authoring_subtree_sha256 = _subtree_sha256(
+ reference.initial_authoring_subtree_sha256 = semantic_subtree_sha256(
element,
ignored_attributes=frozenset({SOURCE_REF_ATTRIBUTE}),
)
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 29d68361..3cb9fcf3 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -397,6 +397,13 @@ def _classify_paragraph_block(
and not _starts_with_list_marker(line_groups[idx])
and abs(line_font_sizes[idx] - line_font_sizes[idx - 1]) <= 1e-6
)
+ explicit_soft_break = line_groups[idx][0].get(
+ PARAGRAPH_SOFT_BREAK_ATTR
+ )
+ if explicit_soft_break == "0":
+ is_soft = False
+ elif explicit_soft_break == "1":
+ is_soft = True
extras.append(0.0 if is_soft else extra)
soft_breaks.append(is_soft)
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 418ef207..d1fd3716 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -446,8 +446,13 @@ _PPTX_ROOT_STRUCTURE_ATTRS = (
'data-pptx-layout',
'data-pptx-layout-name',
)
+_PPTX_ROOT_VISIBILITY_ATTRS = (
+ 'data-pptx-show-master-shapes',
+ 'data-pptx-show-inherited-shapes',
+)
_PPTX_STRUCTURE_ATTRS = frozenset({
*_PPTX_ROOT_STRUCTURE_ATTRS,
+ *_PPTX_ROOT_VISIBILITY_ATTRS,
'data-pptx-layer',
'data-pptx-layout-kind',
'data-pptx-placeholder',
@@ -635,6 +640,12 @@ def _local_pptx_structure_errors(
f"{svg_path.name}: structured SVG root is missing "
+ ', '.join(missing)
)
+ for attr in _PPTX_ROOT_VISIBILITY_ATTRS:
+ raw = root.get(attr)
+ if raw is not None and raw not in {'true', 'false'}:
+ errors.append(
+ f"{svg_path.name}: root {attr} must be exactly 'true' or 'false'"
+ )
parent_by_id = {
id(child): parent
@@ -648,7 +659,10 @@ def _local_pptx_structure_errors(
if elem is not root:
nested_root_attrs = [
- attr for attr in _PPTX_ROOT_STRUCTURE_ATTRS
+ attr for attr in (
+ *_PPTX_ROOT_STRUCTURE_ATTRS,
+ *_PPTX_ROOT_VISIBILITY_ATTRS,
+ )
if elem.get(attr) is not None
]
if nested_root_attrs:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index 1fc1585a..9125bc5e 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -2815,7 +2815,9 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
text_height = font_size * 1.5
padding = _textbox_padding(font_size)
- # Adjust position based on text-anchor
+ # Adjust position based on text-anchor. This first box follows the visible
+ # glyph baseline and remains useful for reconstructing imported text-body
+ # insets when data-pptx-frame supplies the owning PowerPoint shape frame.
if text_anchor == 'middle':
box_x = x - text_width / 2 - padding
elif text_anchor == 'end':
@@ -2827,6 +2829,36 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
box_w = text_width + padding * 2
box_h = text_height + padding
+ visual_box_x = box_x
+ visual_box_y = box_y
+ exact_text_frame = None
+ exact_text_insets: tuple[float, float, float] | None = None
+ if elem.get('data-pptx-frame') is not None:
+ _preset, _guides, exact_text_frame = _parse_preset_geometry_metadata(elem)
+ if exact_text_frame is None:
+ raise ValueError('data-pptx-frame did not resolve to a text frame')
+ raw_frame_x, raw_frame_y, raw_frame_w, raw_frame_h = exact_text_frame
+ frame_x_1 = ctx_x(raw_frame_x, ctx)
+ frame_x_2 = ctx_x(raw_frame_x + raw_frame_w, ctx)
+ frame_y_1 = ctx_y(raw_frame_y, ctx)
+ frame_y_2 = ctx_y(raw_frame_y + raw_frame_h, ctx)
+ box_x = min(frame_x_1, frame_x_2)
+ box_y = min(frame_y_1, frame_y_2)
+ box_w = abs(frame_x_2 - frame_x_1)
+ box_h = abs(frame_y_2 - frame_y_1)
+ top_inset = visual_box_y - box_y
+ if text_anchor == 'start':
+ left_inset = x - box_x
+ right_inset = 0.0
+ elif text_anchor == 'end':
+ left_inset = 0.0
+ right_inset = box_x + box_w - x
+ else:
+ center_delta = x - (box_x + box_w / 2)
+ left_inset = max(0.0, center_delta * 2)
+ right_inset = max(0.0, -center_delta * 2)
+ exact_text_insets = (left_inset, top_inset, right_inset)
+
text_transform = elem.get('transform', '')
text_operations = (
parse_transform_operations(text_transform)
@@ -2941,7 +2973,11 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
off_x = px_to_emu(box_x)
off_y = px_to_emu(box_y)
- ext_cx = drawingml_text_frame_width_emu(text_width, font_size)
+ ext_cx = (
+ px_to_emu(box_w)
+ if exact_text_frame is not None
+ else drawingml_text_frame_width_emu(text_width, font_size)
+ )
ext_cy = px_to_emu(box_h)
if ext_cx < 1 or ext_cy < 1:
raise ValueError(
@@ -2951,13 +2987,28 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
validate_ooxml_xfrm(off_x, off_y, ext_cx, ext_cy)
validate_text_run_advances(runs)
+ # Imported text carriers with data-pptx-frame retain the source shape frame
+ # instead of shrinking to glyph bounds. Reconstruct insets from the SVG
+ # anchor/baseline so the visible text stays at its imported position while
+ # remaining ordinary editable DrawingML text.
+ if exact_text_frame is not None:
+ if exact_text_insets is None:
+ raise ValueError('data-pptx-frame text insets were not resolved')
+ left_inset, top_inset, right_inset = exact_text_insets
+ body_pr_xml = (
+ '<a:bodyPr wrap="square" '
+ f'lIns="{px_to_emu(left_inset)}" '
+ f'tIns="{px_to_emu(top_inset)}" '
+ f'rIns="{px_to_emu(right_inset)}" bIns="0" '
+ 'anchor="t" anchorCtr="0">\n<a:noAutofit/>\n</a:bodyPr>'
+ )
# Paragraph mode: wrap="square" so text reflows when the user resizes,
# but NO spAutoFit — otherwise PowerPoint expands the frame to fit a
# long joined-up <a:p> on one line, blowing past the canvas. The cx we
# write below is the longest source SVG line without single-line renderer
# headroom; PowerPoint wraps long paragraphs inside this design width.
# Single-line text keeps wrap="none" + spAutoFit for tight fidelity.
- if paragraph_runs is not None:
+ elif paragraph_runs is not None:
body_pr_xml = (
'<a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" '
'anchor="t" anchorCtr="0"/>'
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index 58664c0c..c2626dca 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -1072,6 +1072,21 @@ def _contains_thick_circle(elem: ET.Element, thick_circle_ids: set[int]) -> bool
)
+def _is_unit_axis_reflection(
+ operations: tuple[tuple[str, tuple[float, ...]], ...],
+) -> bool:
+ """Return whether a transform is translation plus an unscaled axis flip."""
+ matrix = _transform_operations_matrix(operations)
+ a, b, c, d, _e, _f = matrix
+ return (
+ abs(b) <= 1e-9
+ and abs(c) <= 1e-9
+ and math.isclose(abs(a), 1.0, abs_tol=1e-9)
+ and math.isclose(abs(d), 1.0, abs_tol=1e-9)
+ and (a < 0 or d < 0)
+ )
+
+
def _transform_semantic_error(
elem: ET.Element,
operations: tuple[tuple[str, tuple[float, ...]], ...],
@@ -1115,6 +1130,12 @@ def _transform_semantic_error(
f'{label} contains a thick-circle arc shorthand; ancestor '
'transforms must be translate-only'
)
+ if _is_unit_axis_reflection(operations):
+ # Imported PowerPoint groups encode flipH/flipV as a translate /
+ # unit-scale / translate list. The converter distributes that
+ # signed unit scale to child geometry and text positions without
+ # scaling font metrics, so this exact no-shear case is lossless.
+ return None
if supports_full_project_transform(elem):
if 'matrix' in names and _contains_rounded_rect(elem):
return (
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 f22fc873..12be4729 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
@@ -2309,8 +2309,14 @@ def _placeholder_text_body(
if source_body_pr is not None
else ET.Element(f"{{{DML_NS}}}bodyPr")
)
- source_bounds = _shape_bounds_emu(source_shape, None)
target_bounds = _shape_bounds_emu(source_shape, item.placeholder_bounds)
+ try:
+ source_bounds = _shape_bounds_emu(source_shape, None)
+ except TemplateStructureError:
+ # Composite proxy content may compile to p:grpSp, whose transform is
+ # intentionally not reused for the Layout's synthetic p:sp carrier.
+ # The explicit design-zone bounds remain the authoritative frame.
+ source_bounds = target_bounds
_normalize_placeholder_body_properties(
body_pr,
source_bounds,
@@ -2705,6 +2711,7 @@ def _apply_explicit_layout_structure(
master_part,
base_layout_part,
prototype.layout_name,
+ show_master_shapes=prototype.layout_show_master_shapes,
)
layout_path = extract_dir / layout_part
layout_rels_path = _relationships_path_for_part(extract_dir, layout_part)
@@ -2793,6 +2800,10 @@ def _apply_explicit_layout_structure(
)
expected_backgrounds.update(slide_backgrounds)
for state in states:
+ state.root.set(
+ "showMasterSp",
+ "1" if state.spec.slide_show_inherited_shapes else "0",
+ )
_write_xml_tree(state.slide_path, state.tree)
expected_backgrounds.setdefault(
f"ppt/slides/slide{state.spec.slide_num}.xml",
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
index 1203a61c..8ae7e895 100644
--- 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
@@ -51,6 +51,8 @@ _STRUCTURE_ATTRS = frozenset({
"data-pptx-layout-name",
"data-pptx-master",
"data-pptx-master-name",
+ "data-pptx-show-inherited-shapes",
+ "data-pptx-show-master-shapes",
"data-pptx-placeholder",
"data-pptx-placeholder-binding",
"data-pptx-placeholder-bounds",
@@ -300,6 +302,8 @@ class TemplateSlideSpec:
master_name: str
layout_key: str
layout_name: str
+ layout_show_master_shapes: bool
+ slide_show_inherited_shapes: bool
elements: tuple[TemplateElementSpec, ...]
@property
@@ -1194,6 +1198,23 @@ def _structure_attrs(elem: ET.Element) -> list[str]:
return sorted(attr for attr in _STRUCTURE_ATTRS if elem.get(attr) is not None)
+def _parse_root_boolean(
+ root: ET.Element,
+ attribute: str,
+ *,
+ svg_path: Path,
+) -> bool:
+ """Parse one optional root boolean with a backward-compatible true default."""
+ raw = root.get(attribute)
+ if raw is None:
+ return True
+ if raw not in {"true", "false"}:
+ raise TemplateStructureError(
+ f"{svg_path.name}: root {attribute} must be exactly 'true' or 'false'"
+ )
+ return raw == "true"
+
+
def parse_template_slide(
svg_path: Path,
slide_num: int,
@@ -1274,6 +1295,16 @@ def parse_template_slide(
)
if not layout_name:
layout_name = re.sub(r"[-_.]+", " ", layout_key).strip().title() or layout_key
+ layout_show_master_shapes = _parse_root_boolean(
+ root,
+ "data-pptx-show-master-shapes",
+ svg_path=svg_path,
+ )
+ slide_show_inherited_shapes = _parse_root_boolean(
+ root,
+ "data-pptx-show-inherited-shapes",
+ svg_path=svg_path,
+ )
if structured and root.get("data-pptx-layout-kind") is not None:
raise TemplateStructureError(
f"{svg_path.name}: data-pptx-layout-kind is obsolete; the root "
@@ -1288,6 +1319,8 @@ def parse_template_slide(
"data-pptx-layout-name",
"data-pptx-master",
"data-pptx-master-name",
+ "data-pptx-show-inherited-shapes",
+ "data-pptx-show-master-shapes",
}
and root.get(attr) is not None
)
@@ -1338,10 +1371,12 @@ def parse_template_slide(
or elem.get("data-pptx-layout-name") is not None
or elem.get("data-pptx-master") is not None
or elem.get("data-pptx-master-name") is not None
+ or elem.get("data-pptx-show-inherited-shapes") is not None
+ or elem.get("data-pptx-show-master-shapes") is not None
):
raise TemplateStructureError(
- f"{svg_path.name}: Master/Layout identity attributes belong on "
- "the root <svg> only"
+ f"{svg_path.name}: Master/Layout identity and visibility "
+ "attributes belong on the root <svg> only"
)
if layer and layer not in _LAYERS:
raise TemplateStructureError(
@@ -1609,6 +1644,8 @@ def parse_template_slide(
master_name=master_name,
layout_key=layout_key,
layout_name=layout_name,
+ layout_show_master_shapes=layout_show_master_shapes,
+ slide_show_inherited_shapes=slide_show_inherited_shapes,
elements=tuple(elements),
)
return spec
@@ -1660,6 +1697,16 @@ def _validate_template_slide_contracts(
f"belongs to Master {spec.master_key!r}, expected "
f"{prototype.master_key!r}"
)
+ if (
+ spec.layout_show_master_shapes
+ != prototype.layout_show_master_shapes
+ ):
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: layout {layout_key!r} uses "
+ "data-pptx-show-master-shapes="
+ f"{str(spec.layout_show_master_shapes).lower()}, expected "
+ f"{str(prototype.layout_show_master_shapes).lower()}"
+ )
if spec.layout_contract != prototype.layout_contract:
raise TemplateStructureError(
f"{spec.svg_path.name}: layout {layout_key!r} structure differs "
@@ -2601,7 +2648,9 @@ def template_prototype_errors(
== _prototype_placeholder_contract(prototype)
)
layout_contract_same = (
- tuple(item.contract_signature() for item in spec.layout_elements)
+ spec.layout_show_master_shapes
+ == prototype.layout_show_master_shapes
+ and tuple(item.contract_signature() for item in spec.layout_elements)
== tuple(
item.contract_signature() for item in prototype.layout_elements
)
@@ -2676,6 +2725,15 @@ def template_prototype_errors(
f"{prototype.layout_name!r} to {spec.layout_name!r}; assign a "
"new key and name to the evolved Layout contract"
)
+ if (
+ spec.slide_show_inherited_shapes
+ != prototype.slide_show_inherited_shapes
+ ):
+ errors.append(
+ f"{spec.svg_path.name}: inherited-shape visibility differs from "
+ f"prototype {reference.svg_path.name}; keep root "
+ "data-pptx-show-inherited-shapes unchanged"
+ )
if not placeholder_contract_same:
if adherence == "strict":
errors.append(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py
index 82fd22fd..77e12601 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py
@@ -963,6 +963,22 @@ def validate_pptx_template_package(
slide_root = reader.xml(slide_part)
if slide_root is not None:
slide_roots[spec.slide_num] = slide_root
+ raw_show_inherited = (
+ slide_root.get("showMasterSp", "1").strip().lower()
+ )
+ if raw_show_inherited not in {"0", "1", "false", "true"}:
+ errors.append(
+ f"{slide_part} showMasterSp is not a valid boolean"
+ )
+ elif (
+ (raw_show_inherited in {"1", "true"})
+ != spec.slide_show_inherited_shapes
+ ):
+ errors.append(
+ f"{slide_part} showMasterSp={raw_show_inherited}, "
+ "expected "
+ f"{str(spec.slide_show_inherited_shapes).lower()}"
+ )
relationship_target = _single_relationship_target(
reader,
slide_part,
@@ -1034,11 +1050,22 @@ def validate_pptx_template_package(
errors.append(f"{layout_part} must have type='cust'")
if layout_root.get("preserve") != "1":
errors.append(f"{layout_part} must have preserve='1'")
- if layout_root.get("showMasterSp", "1").lower() not in {
- "1",
- "true",
- }:
- errors.append(f"{layout_part} must show its Master shape tree")
+ raw_show_master = (
+ layout_root.get("showMasterSp", "1").strip().lower()
+ )
+ if raw_show_master not in {"0", "1", "false", "true"}:
+ errors.append(
+ f"{layout_part} showMasterSp is not a valid boolean"
+ )
+ elif (
+ (raw_show_master in {"1", "true"})
+ != prototype.layout_show_master_shapes
+ ):
+ errors.append(
+ f"{layout_part} showMasterSp={raw_show_master}, "
+ "expected "
+ f"{str(prototype.layout_show_master_shapes).lower()}"
+ )
c_sld = layout_root.find(f"{{{PML_NS}}}cSld")
expected_name = layout_specs[0].layout_name
actual_name = c_sld.get("name") if c_sld is not None else None
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index b532a8c2..7305befc 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -140,6 +140,13 @@ Each bundle contains editable SVGs plus `authoring_manifest.json`. The projectio
`authoring-svg/` is the canonical editable IR for template creation. The lossless trees are read only by materialization when an unchanged referenced object needs supported native payload or fallback evidence. Do not edit or copy the lossless SVGs directly. The IR is not a finished template directory and must be materialized into validated `<template_workspace>/templates/*.svg` before preview or export.
+For a Type A `mirror`, final materialization is owned by
+`mirror_template_materialize.py`; never assemble the structured output by
+copying lossless SVGs or `svg-flat/` pages into `templates/`. The command runs
+only after the confirmed IR edits and vector-readability pass described below.
+`standard` / `fidelity` remain newly authored Template_Designer output and do
+not use this compiler.
+
**Vector illustration readability pass**:
Factor large decorative vector groups out of the lightweight IR documents so the model-facing SVGs stay readable while export remains native shapes. Never run this in place on the lossless import SVGs:
@@ -200,7 +207,7 @@ does not turn those vectors into a picture.
| Mode | Required read set |
|---|---|
| `standard` / `fidelity` | `manifest.json`, exported assets, `svg/inheritance.json`, `authoring-svg/authoring_manifest.json`, and every cleaned layered IR document (`authoring-svg/master_*.svg` / `layout_*.svg` / `slide_NN.svg`). The layered IR is the complete read surface: it covers Layouts unused by any sample slide (invisible in `svg-flat/` yet still template vocabulary), and per-page composition follows from `inheritance.json`. Cleaned flat pages are optional composition spot checks, not a required second pass over the same shapes. Source topology remains non-binding; the two modes differ in output design (`fidelity` designs a broader roster covering the useful visual range), not in read coverage. |
-| `mirror` | `manifest.json`, `native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_manifest.json`, every cleaned layered Master/Layout/Slide IR document, and every cleaned flat slide IR document. Edit and select objects only through the IR; materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
+| `mirror` | `manifest.json`, `native_structure.json`, `svg/inheritance.json`, `authoring-svg/authoring_manifest.json`, and every cleaned layered Master/Layout/Slide IR document. The layered `authoring-svg/` tree is the sole editable and materialization input. Cleaned `authoring-svg-flat/` slides are optional visual composition checks only; never edit or feed them into template materialization. Materialization may resolve unchanged refs against the matching lossless backing without placing opaque payload in model context. |
Use `summary.md` only for orientation. Use screenshots or the original PPTX only for visual cross-checking. Do not bulk-read opaque lossless payload into model context.
@@ -418,8 +425,8 @@ If the input source is type A, pass the following internal package to the role:
- `summary.md` (orientation only)
- exported `assets/`
- `*_vector_asset_inventory.json`, when the vector readability pass extracted assets; do not bulk-read `icons/imported/*.svg`
-- editable IR documents and manifests from `authoring-svg/` and `authoring-svg-flat/`
-- for `mirror` only, matching immutable `svg/` / `svg-flat/` payload backing plus `svg/inheritance.json`
+- editable layered IR documents and manifest from `authoring-svg/`; optional `authoring-svg-flat/` is a visual cross-check only and never a template materialization input
+- for `mirror` only, matching immutable `svg/` payload backing plus `svg/inheritance.json`; immutable `svg-flat/` remains an optional visual cross-check
- optional screenshots, if available
For type B, pass the cleaned SVG file list from the analysis workspace, `*_vector_asset_inventory.json` if extraction ran, any companion `design_spec.md` / `spec_lock.md`, and the analysis notes. Do not bulk-read extracted vectors; open individual `icons/imported/*.svg` files only when needed.
@@ -433,6 +440,24 @@ The role interprets the package according to replication mode:
| `standard` / `fidelity` | Newly authored SVGs based on the confirmed brief and visual references | Design an intentional new Master/Layout/slot system. Source topology is neither preserved nor distilled into the output. |
| `mirror` | Editable `authoring-svg/` IR plus native-structure facts and lossless payload backing | Restore source pages, Master/Layout identities and parentage, placeholder identity/bounds, ownership, and supported native-object metadata one-to-one. Materialization resolves unchanged source refs; it does not copy the lossless tree as the editable source. |
+For Type A `mirror`, materialize the reviewed layered IR into an empty template
+workspace with the deterministic compiler:
+
+```bash
+python3 skills/ppt-master/scripts/mirror_template_materialize.py \
+ "<import_workspace>" "<template_workspace>"
+```
+
+The destination `templates/` directory must be absent or empty. Before
+publication, the command verifies the layered manifest and source-ref closure,
+lossless SVG and source-PPTX hashes, complete native/inheritance graph, and
+extracted-vector inventory. It then stages and publishes the entire roster in
+one operation. It emits source-ordered page SVGs, unused-Layout definition
+SVGs, `icons/imported/`, and referenced `images/` / `templates/assets/`; it does
+not create `design_spec.md`. Template_Designer writes that file from the
+confirmed brief and the materialized roster before Step 5. A rerun targets a
+new empty workspace rather than overwriting a partially reviewed template.
+
**Hard rule — mode-specific authorship**: `standard` and `fidelity` author new
project-canonical SVG documents. When one registered PowerPoint preset exactly
expresses one complete object, they use the compact canonical
@@ -482,7 +507,7 @@ Downstream, both template-adherence choices use `pptx_structure.mode: structured
**Mirror-mode restoration contract** (type A or B): when `Replication mode: mirror`, the Template_Designer role:
-1. **Restores one output SVG per source page** in `<template_workspace>/templates/`. Edit and normalize the matching `authoring-svg/` IR document, then materialize it with the authoring manifest, native structure facts, and immutable payload backing. Preserve source Master/Layout keys and picker names, Layout parentage, slide assignment, placeholder type/index/bounds, ownership, paint order, and supported native metadata. Mechanical namespace, root-declaration, asset-path, and fixed-layer group normalization is allowed only when source ownership and appearance remain unchanged.
+1. **Restores one output SVG per source page** in `<template_workspace>/templates/`. Edit and normalize the matching `authoring-svg/` IR document, then materialize it with the authoring manifest, native structure facts, and immutable payload backing. Type A must use `mirror_template_materialize.py`; do not hand-copy or independently rebuild its graph. Preserve source Master/Layout keys and picker names, Layout parentage, slide assignment, placeholder type/index/bounds, inherited-shape visibility, ownership, paint order, and supported native metadata. Mechanical namespace, root-declaration, asset-path, and fixed-layer group normalization is allowed only when source ownership and appearance remain unchanged.
- Type A authoring source: `<import_workspace>/authoring-svg/` plus its `authoring_manifest.json`; `<import_workspace>/svg/`, `<import_workspace>/svg-flat/`, `svg/inheritance.json`, and `native_structure.json` provide payload and structural backing
- Type B authoring source: `<svg_analysis_workspace>/authoring-svg/` plus its manifest; the complete explicit source SVG contract is immutable backing
- For every source Layout unused by all source slides, additionally materialize one definition-only SVG named `layout_<layout_key>.svg` from its layered authoring IR document and payload backing. It carries the exact root identity, fixed atoms, and placeholder contract but is not a generated page assignment. Use source placeholder prompts/carriers; do not invent business content. This definition SVG lets downstream export register the Layout and any otherwise-unused parent Master without retaining an internal carrier slide.
@@ -517,7 +542,7 @@ becomes the prototype Slide placeholder, while
| Generic text entry | General `body` and text-carried `object` slots begin at the upper-left, use left paragraph alignment, and wrap inside the full frame. Title/subtitle alignment follows the authored composition. |
| Centered exceptions | Center alignment is reserved for semantically short focal content such as KPI values, short process nodes, hero statements, and compact takeaways. Record a template-wide exception in `design_spec.md §IV` when it is part of the layout grammar. |
| Review Slide binding | `template_preview_pptx.py` sizes each authored Slide carrier to the same complete frame as its registered Layout placeholder. A review deck whose Slide carrier is only the prompt text's tight box fails Step 6. |
-| Mirror boundary | `mirror` preserves source Slide carrier geometry exactly; do not normalize it to the Layout frame when the source intentionally overrides that frame. |
+| Mirror boundary | `mirror` preserves source Slide carrier geometry exactly; the materializer places the authoritative source `data-pptx-frame` on its text carrier and keeps `data-pptx-placeholder-bounds` as the reusable Layout default. Do not normalize one to the other when the source intentionally overrides that frame. |
---
@@ -566,9 +591,10 @@ This checker validates the authoring contract, not the compiled OOXML package. T
- [ ] `standard` / `fidelity` output SVGs and their Master/Layout/slot contracts were newly authored without preserving or distilling source topology
- [ ] Every additional authored Master represents a distinct reusable design family, not one Layout or an equivalent duplicate; every declared Master owns at least one emitted Layout and every declared Layout has at least one emitted prototype
- [ ] Mirror output preserves source slide order, Master/Layout identity and parentage, placeholder facts, and ownership; fixed-layer group expansion is mechanical and pixel-equivalent, and the Source Restoration Map lists every source slide
+- [ ] Mirror roots preserve source inherited-shape visibility with canonical lowercase `data-pptx-show-master-shapes` and `data-pptx-show-inherited-shapes`; same-key Layouts agree on the former, while each Slide retains its own latter value
- [ ] Mirror preflight covered the complete source graph; each unused Layout has one `layout_<layout_key>.svg` definition prototype and each otherwise-unused Master is retained through at least one such Layout
- [ ] For `standard` / `fidelity`, no duplicate-Layout-contract warning remains; mirror may keep equivalent source Layout identities when the restoration map explains them
-- [ ] All template-creation edits used the authoring IR; mirror materialization validated its manifest, reused only converter-supported payload for hash-matching Slide-local/slot refs, stripped IR-only source-ref metadata, and kept fixed Master/Layout visuals as direct atoms
+- [ ] All template-creation edits used the authoring IR; Type A mirror used `mirror_template_materialize.py`, validated its manifest/hash/graph/source-ref closure before atomic publication, reused only converter-supported payload for hash-matching Slide-local/slot refs, stripped IR-only source-ref metadata, and kept fixed Master/Layout visuals as direct atoms
- [ ] If any SVG references an extracted vector, it uses `data-icon="imported/<name>"` and the sole SVG asset exists at `<template_workspace>/icons/imported/<name>.svg`; `templates/icons/` does not exist and no separate illustration embedding script was added
- [ ] For `fidelity` mode: every sprite-sheet asset retains its nested `<svg viewBox=...>` crop wrapper; no image whose file aspect differs from its on-page aspect was flattened to a bare `<image>`
- [ ] For `mirror` mode: source-page SVG count equals source page count, while additional files are exactly the required `layout_<layout_key>.svg` definitions for unused source Layouts; source-page filenames follow the `<NNN>_<page_type>.svg` convention; **no new `{{...}}` authoring placeholders were inserted into restored source-page SVGs**; §V Page Roster lists every emitted file and marks definition-only prototypes explicitly