Skip to content

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

feat(svg-to-pptx): validate reusable template layout contracts

hugohe34d62cf09db7e
diff --git a/docs/technical-design.md b/docs/technical-design.md
index bfae986d..09f419fb 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -456,7 +456,9 @@ These direct routes share some analysis primitives with the main pipeline, espec
**Why reusable layouts require explicit SVG metadata.** `--pptx-structure template` is the opt-in path for a generated deck that must remain reusable as a PowerPoint template. The final slide SVGs declare a layout key at the root, mark only direct root children as master/layout layers, and attach typed placeholder semantics to the slide-local prototypes that should become layout placeholders. Export validates that shared master and same-key layout declarations are structurally and visually identical, then emits real layout parts and `p:ph` references while leaving every unmarked object slide-local. This is deterministic structure compilation, not visual-template inference.
-**Why template-mode Master text styles are deliberately narrow.** Template export requires the locked `typography.title` and `typography.body` sizes, then writes the title size to every Master `p:titleStyle` level and the body size to every `p:bodyStyle` / `p:otherStyle` level. The patch changes only `p:txStyles//a:defRPr@sz`; direct run sizes on generated slides remain unchanged, so the authored SVG still controls initial rendering. Missing title/body locks fail template export, while `baseline`, `preserve`, and `flat` retain their previous behavior.
+**Why template-mode text defaults are split between Master and Layout.** Template export writes the locked `typography.title` size to every Master `p:titleStyle` level and the locked `typography.body` size to every `p:bodyStyle` / `p:otherStyle` level. Each generated Layout text placeholder additionally copies its prototype's first direct run size into `a:lstStyle/a:lvl1pPr/a:defRPr@sz` while retaining the prompt's direct size. This preserves layout-specific scale when level-one placeholder text is inserted or reset; direct runs on generated Slides remain unchanged. Missing title/body locks fail template export, while `baseline`, `preserve`, and `flat` retain their previous behavior.
+
+**Why template output is read back before publication.** Metadata preflight can prove the authoring contract but cannot prove that package serialization preserved every relationship and registration. Template mode therefore reopens the temporary PPTX and validates the Slide → Layout → Master graph, Layout identity, placeholder type/effective index, reusable frame, and prompt/level-one sizes. Only a package that passes is moved to the requested output; the other structure modes are unchanged.
**Why reusable templates rebuild explicit SVG structure.** `pptx_template_import.py` emits layered Master/Layout/Slide references plus source structure facts. `create-template` uses those inputs to rebuild one clean Master and semantic Layouts as complete, explicitly annotated SVG pages; it does not package the original PPTX. Strict use keeps the selected Layout contract, while adaptive use may create a new Layout under the same Master. Both export through deterministic `template` mode. Legacy `preserve` remains readable for existing projects only. Raw PPTX plus one-off generated content still routes to `template-fill-pptx`.
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 725055ed..9886222c 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -456,7 +456,9 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。在转换器已实
**为什么可复用版式必须依赖显式 SVG 元数据。** `--pptx-structure template` 是生成型 deck 需要继续作为 PowerPoint 模板复用时的 opt-in 路径。最终 slide SVG 在根节点声明 layout key,只允许根节点的直接子元素标记 master/layout layer,并在应成为版式占位框的 slide-local 原型上附加类型语义。导出器会验证共享 master 与同 key layout 的声明在结构和视觉上完全一致,再生成真实 layout part 与 `p:ph` 引用;所有未标记对象仍保持 slide-local。这是确定性的结构编译,不是根据视觉相似度猜模板。
-**为什么 template 模式只做窄范围的母版文字样式补强。** Template 导出要求 `typography.title` 与 `typography.body` 两个锁定字号,把 title 写入母版 `p:titleStyle` 的全部层级,把 body 写入 `p:bodyStyle` / `p:otherStyle` 的全部层级。补丁只修改 `p:txStyles//a:defRPr@sz`;生成页面中的直接 run 字号保持不变,因此初始渲染仍由作者 SVG 控制。缺少 title/body 锁会让 template 导出失败,`baseline`、`preserve`、`flat` 则保持原有行为。
+**为什么 template 模式把文字默认值分在 Master 与 Layout 两层。** Template 导出把锁定的 `typography.title` 字号写入 Master `p:titleStyle` 的全部层级,把 `typography.body` 字号写入 `p:bodyStyle` / `p:otherStyle` 的全部层级。每个生成的 Layout 文字占位符还会把原型首个直接 run 的字号写入 `a:lstStyle/a:lvl1pPr/a:defRPr@sz`,同时保留提示文字的直接字号。这样,一级占位符文字在插入或重置后仍继承版式特定的字号;生成 Slide 上的直接 run 保持不变。缺少 title/body 锁会让 template 导出失败,`baseline`、`preserve`、`flat` 则维持原有行为。
+
+**为什么 template 导出要在发布前回读候选包。** 元数据预检可以证明作者合同成立,却不能证明 package 序列化完整保留了所有 relationship 与注册信息。因此 template 模式会重新打开临时 PPTX,校验 Slide → Layout → Master 关系链、Layout 身份、占位符类型与有效索引、可复用边界,以及提示文字和一级默认字号。只有通过读回校验的候选包才会移动到目标输出;其他结构模式不受影响。
**为什么可复用模板统一重建显式 SVG 结构。** `pptx_template_import.py` 输出分层的 Master/Layout/Slide 参考和源结构事实;`create-template` 据此重建一个干净 Master 与语义 Layout,并把它们重复标注在可独立预览的完整 SVG 中,不再封装原 PPTX。严格套用保持所选 Layout 契约,自适应使用可在同一 Master 下新建显式 Layout;两者都走确定性的 `template` 导出。`preserve` 只为旧项目保留兼容读取。
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index f4f43c77..b21cf8e6 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -814,12 +814,19 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> consistent Layout/placeholder contract.
> Template export also installs the locked `typography.title` size into every
> Master `titleStyle` level and the locked `typography.body` size into every
-> `bodyStyle` and `otherStyle` level. It changes only existing
-> `a:defRPr@sz` defaults: generated slide runs and Layout placeholder prototypes
-> keep their direct sizes, while newly inserted/reset placeholder text inherits
-> project defaults instead of Office fallback sizes. Missing or invalid locked
-> title/body sizes fail template export. Baseline, preserve, and flat modes do
-> not rewrite Master text-style sizes.
+> `bodyStyle` and `otherStyle` level. Each text-bearing Layout placeholder also
+> writes its prototype run size to `a:lstStyle/a:lvl1pPr/a:defRPr@sz`, so a
+> newly inserted or reset placeholder keeps that Layout's local size before it
+> falls back to the Master. Generated slide runs and Layout prompt runs keep
+> their direct sizes. Missing or invalid locked title/body sizes fail template
+> export. Baseline, preserve, and flat modes do not apply either text-default
+> update.
+> Before publishing the temporary PPTX, template export reopens the finished
+> package and verifies `Presentation → Master ↔ Layout ← Slide` registration,
+> named custom Layout parts and content types, collision-free placeholder
+> identities, prototype bounds, and prompt/level-one sizes. This read-back gate
+> is template-only and does not compare later same-Layout slides' local geometry
+> or direct text formatting.
> In template mode, `pptx_layouts` contains exactly one locked
> layout key/name per page; reuse a key for a shared structure instead of
> creating one key per content instance.
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index b60ccb2c..05fe67b3 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -1090,12 +1090,20 @@ size to every level in both `p:bodyStyle` and `p:otherStyle`.
| `p:bodyStyle` | `typography.body` | Every `a:defRPr@sz` |
| `p:otherStyle` | `typography.body` | Every `a:defRPr@sz` |
-**Hard rule — narrow scope**: This update changes only Master
+**Hard rule — narrow scope**: This Master update changes only Master
`p:txStyles//a:defRPr@sz`. It does not rewrite direct run sizes on generated
slides, so the initial slide rendering remains controlled by the authored SVG.
Missing `title` or `body` rows fail template export. `baseline`, `preserve`,
and `flat` modes do not apply this Master text-style update.
+**Layout level-one text-default contract**: For every text-bearing placeholder
+whose first prototype run has a direct `a:rPr@sz`, template export copies that
+size to the generated Layout prompt run and
+`p:txBody/a:lstStyle/a:lvl1pPr/a:defRPr@sz`. It does not rewrite Slide direct
+runs or Layout levels 2–9. This preserves the layout-specific size when
+level-one placeholder text is inserted or reset; placeholders without a direct
+prototype size remain unchanged.
+
| Metadata | Placement | Behavior |
|---|---|---|
| `data-pptx-layout="content"` | root `<svg>` | Binds the slide to one generated reusable layout key |
@@ -1141,13 +1149,17 @@ by this solid-background rule.
`title` is normally type-matched without an index in reconstructed layouts; if
an imported source title explicitly has one, preserve that exact index. Every
-indexed placeholder on one layout uses a unique non-negative index. Template
+indexed placeholder on one layout uses a unique OOXML UInt32 index. Template
export writes the semantic type on both the Layout and Slide placeholder
(except `obj`, whose OOXML default is already
-`obj`) so PowerPoint and `python-pptx` retain the same identity. A `date`
-placeholder also enables the layout date flag and gets a
-`datetimeFigureOut` field in the reusable Layout definition; the current
-Slide keeps its authored date content.
+`obj`) so PowerPoint and `python-pptx` retain the same identity. Date, footer,
+and slide-number placeholders enable their matching Layout `p:hf` flags; a
+date placeholder also gets a `datetimeFigureOut` field in the reusable Layout
+definition. The current Slide keeps its authored date content.
+
+Because an omitted `p:ph@idx` has the effective value `0`, an omitted-index
+title reserves `0`; no other placeholder on that Layout may use the same
+effective index.
**Placeholder prototype**: The first slide using a layout key supplies that
layout's placeholder formatting. `data-pptx-placeholder-bounds` supplies the
@@ -1155,6 +1167,20 @@ reusable frame; when omitted, the exporter uses the prototype object's native
DrawingML bounds. Repeat the same placeholder ids/types on every slide using
that layout. Actual slide content and local geometry may differ.
+**Final-package read-back gate**: After writing the temporary template-mode
+PPTX and before publishing it, export reopens the package and verifies that
+each Slide targets exactly one Layout, one layout key always resolves to the
+same part, different keys do not collapse onto one part, and every Layout is
+registered through its Master and the Presentation. It also verifies the
+Layout picker name/content type, placeholder type and effective index,
+matching `p:hf` flags, prototype-derived or explicitly overridden frame,
+direct prompt size, and level-one default size. Later slides may keep different
+slide-local geometry; only the reusable Layout frame is checked against the
+explicit/prototype contract. Any mismatch fails export without replacing the
+requested output.
+This gate applies only to `template`; `baseline`, `preserve`, and `flat` retain
+their existing behavior.
+
**Static structure consistency**: Repeat the same master element ids on every
slide and the same layout element ids on every slide sharing a layout. Their
generated OOXML must be identical within the affected master/layout group.
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index ffe5675d..b1ba1285 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -74,12 +74,13 @@ Behavior:
- Omitting `--pptx-structure` reads `spec_lock.md` and falls back to `baseline`. Baseline assigns Layout families from root `data-pptx-page-role`, keeps content Slide-local, and promotes only exact family-wide backgrounds plus exact leading structurally marked chrome; filenames and ids are compatibility fallbacks for marker-free legacy SVGs. It never infers placeholders or visual similarity. Template mode builds reusable PowerPoint structure only from explicit SVG metadata and validates every `pptx_layouts` row plus cross-slide equality. Both strict and adaptive template adherence use this mode; adaptive may introduce a new Layout key under the same Master.
- Template/preserve placeholder semantics distinguish title, subtitle, body, picture, chart, table, generic object, media, date, footer, and slide number. Reconstructed titles are normally type-matched without an index; explicit imported title indices and all other source indices are retained. Imported `subTitle`, `obj`, `media`, and `dt` identities remain distinct through `manifest.json`, `native_structure.json`, Layout XML, and Slide XML.
- Baseline/template native export reads `spec_lock.md` typography into the PowerPoint theme: `title_family` becomes the major font and `body_family` / `font_family` becomes the minor font. Matching SVG text emits `+mj-*` / `+mn-*` tokens, while unrelated emphasis/code/brand families stay concrete. Preserve mode keeps the imported source theme; flat mode keeps fixed-font diagnostic output.
-- Template mode also requires numeric `typography.title` and `typography.body` rows. It writes the title size to every Master `p:titleStyle` level and the body size to every `p:bodyStyle` / `p:otherStyle` level by changing only `a:defRPr@sz`. Direct slide-run sizes remain unchanged. Missing title/body rows fail template export; baseline, preserve, and flat modes do not apply this update.
+- Template mode also requires numeric `typography.title` and `typography.body` rows. It writes the title size to every Master `p:titleStyle` level and the body size to every `p:bodyStyle` / `p:otherStyle` level. Each generated Layout text placeholder also stores the prototype's first direct run size in `a:lstStyle/a:lvl1pPr/a:defRPr@sz` while retaining its prompt run size. Slide direct-run sizes remain unchanged. Missing title/body rows fail template export; baseline, preserve, and flat modes do not apply these updates.
- Baseline/template native export also maps canonical `spec_lock.md` color roles into the PowerPoint color scheme and emits context-safe `schemeClr` tokens for exact matches in SVG fills/text/strokes, gradients/patterns/bullets, native tables, and native-chart accent series. Local colors, inverse white/black, and effects stay concrete. Preserve mode keeps the imported source color scheme; flat mode keeps fixed-color diagnostic output.
- Preserve mode is legacy strict-only compatibility for existing projects that already carry `native_structure.json` + `source_template.pptx`. Current template creation does not emit the pair.
- Native output uses content-hash media filenames, so identical images are reused and different images cannot overwrite each other by sharing a basename.
- `[Content_Types].xml` is generated from the actual media extensions written into the PPTX. Unknown media extensions fail unless Python's `mimetypes` can identify them.
- Native export writes to a temporary file first and publishes the requested PPTX only after conversion succeeds. A failed conversion does not replace the main output file.
+- Before publishing template-mode native output, export reopens the temporary PPTX and validates the Slide → Layout → Master graph and registrations, Layout identity, placeholder identity, reusable bounds, and prompt/level-one sizes. A mismatch aborts publication; other structure modes skip this gate.
- SVG clip paths are still restricted for authored SVGs, but nested crop wrappers generated by PPTX import are mapped back to native picture crop / geometry when possible.
- Speaker notes are embedded automatically unless `--no-notes` is used
- Recorded narration is opt-in:
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 83630187..34404ce9 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
@@ -96,13 +96,17 @@ from .slide_xml import (
)
from .template_structure import (
NativeStructureContract,
+ OOXML_UINT32_MAX,
+ TEMPLATE_PLACEHOLDER_TYPES,
TemplateElementSpec,
TemplateSlideSpec,
TemplateStructureError,
match_native_placeholders,
parse_preserve_slides,
parse_template_slides,
+ template_placeholder_bindings,
)
+from .template_validation import validate_pptx_template_package
SLIDE_LAYOUT_REL_TYPE = (
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
@@ -667,7 +671,13 @@ def _next_slide_layout_id(extract_dir: Path, master_xml: str) -> int:
r'\bid="(\d{9,})"', presentation_path.read_text(encoding="utf-8")
)
)
- return max([*ids, 2147483648]) + 1
+ next_id = max([*ids, 2147483648]) + 1
+ if next_id > OOXML_UINT32_MAX:
+ raise TemplateStructureError(
+ "Cannot register another Slide Layout because the OOXML UInt32 "
+ "identifier range is exhausted"
+ )
+ return next_id
def _create_cover_layout(extract_dir: Path, master_part: str, base_layout_part: str) -> str:
@@ -1159,19 +1169,6 @@ def _promote_common_chrome_shapes_to_layouts(
return promoted
-_TEMPLATE_PLACEHOLDER_TYPES = {
- "title": "title",
- "subtitle": "subTitle",
- "body": "body",
- "picture": "pic",
- "chart": "chart",
- "table": "tbl",
- "object": "obj",
- "media": "media",
- "date": "dt",
- "footer": "ftr",
- "slide-number": "sldNum",
-}
_TEMPLATE_PLACEHOLDER_PROMPTS = {
"title": "Click to add title",
"subtitle": "Click to add subtitle",
@@ -1620,6 +1617,46 @@ def _replace_shape_xfrm(
sp_pr.insert(0, xfrm)
+def _set_layout_level_one_default_size(
+ list_style: ET.Element,
+ source_run_pr: ET.Element | None,
+) -> None:
+ """Persist the prototype run size as the Layout's level-one text default."""
+ if source_run_pr is None or source_run_pr.get("sz") is None:
+ return
+ level_tag = f"{{{DML_NS}}}lvl1pPr"
+ level_props = list_style.find(level_tag)
+ if level_props is None:
+ level_props = ET.Element(level_tag)
+ trailing_tags = {
+ f"{{{DML_NS}}}lvl{level}pPr" for level in range(2, 10)
+ }
+ trailing_tags.add(f"{{{DML_NS}}}extLst")
+ insert_at = next(
+ (
+ index
+ for index, child in enumerate(list_style)
+ if child.tag in trailing_tags
+ ),
+ len(list_style),
+ )
+ list_style.insert(insert_at, level_props)
+ default_props = level_props.find(f"{{{DML_NS}}}defRPr")
+ if default_props is None:
+ default_props = ET.Element(f"{{{DML_NS}}}defRPr")
+ ext_tag = f"{{{DML_NS}}}extLst"
+ insert_at = next(
+ (
+ index
+ for index, child in enumerate(level_props)
+ if child.tag == ext_tag
+ ),
+ len(level_props),
+ )
+ level_props.insert(insert_at, default_props)
+ default_props.set("sz", source_run_pr.get("sz", ""))
+
+
def _placeholder_text_body(
source_shape: ET.Element,
item: TemplateElementSpec,
@@ -1636,26 +1673,28 @@ def _placeholder_text_body(
if source_tx_body is not None
else None
)
+ source_run_pr = (
+ source_tx_body.find(f".//{{{DML_NS}}}rPr")
+ if source_tx_body is not None
+ else None
+ )
tx_body.append(
ET.fromstring(ET.tostring(source_body_pr, encoding="utf-8"))
if source_body_pr is not None
else ET.Element(f"{{{DML_NS}}}bodyPr")
)
- tx_body.append(
+ list_style = (
ET.fromstring(ET.tostring(source_lst_style, encoding="utf-8"))
if source_lst_style is not None
else ET.Element(f"{{{DML_NS}}}lstStyle")
)
+ _set_layout_level_one_default_size(list_style, source_run_pr)
+ tx_body.append(list_style)
paragraph = ET.SubElement(tx_body, f"{{{DML_NS}}}p")
if item.placeholder == "body":
paragraph_props = ET.SubElement(paragraph, f"{{{DML_NS}}}pPr")
ET.SubElement(paragraph_props, f"{{{DML_NS}}}buNone")
- source_run_pr = (
- source_tx_body.find(f".//{{{DML_NS}}}rPr")
- if source_tx_body is not None
- else None
- )
if item.placeholder in {"slide-number", "date"}:
field_type = (
"slidenum"
@@ -1743,7 +1782,7 @@ def _set_placeholder_theme_font_role(
return
if item.placeholder == "title":
prefix = "+mj"
- elif item.placeholder in _TEMPLATE_PLACEHOLDER_TYPES:
+ elif item.placeholder in TEMPLATE_PLACEHOLDER_TYPES:
prefix = "+mn"
else:
return
@@ -1762,7 +1801,7 @@ def _layout_placeholder_shape(
theme_font_spec: ThemeFontSpec | None = None,
) -> ET.Element:
"""Build one reusable p:sp placeholder from a prototype slide object."""
- placeholder_type = _TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
+ placeholder_type = TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
if placeholder_type is None:
raise TemplateStructureError(
f"Unsupported placeholder type: {item.placeholder!r}"
@@ -1815,7 +1854,7 @@ def _patch_slide_placeholder(
placeholder_type: str | None = None,
theme_font_spec: ThemeFontSpec | None = None,
) -> None:
- resolved_type = placeholder_type or _TEMPLATE_PLACEHOLDER_TYPES.get(
+ resolved_type = placeholder_type or TEMPLATE_PLACEHOLDER_TYPES.get(
item.placeholder or ""
)
if resolved_type is None:
@@ -1957,8 +1996,10 @@ def _apply_template_structure(
layout_path = extract_dir / layout_part
layout_rels_path = _relationships_path_for_part(extract_dir, layout_part)
- placeholder_idx = 1
- assigned_placeholder_indices: set[int] = set()
+ placeholder_bindings = {
+ binding.element.element_id: binding
+ for binding in template_placeholder_bindings(prototype)
+ }
for item in prototype.elements:
if item.layer == "layout":
_move_template_static_shape(
@@ -1977,21 +2018,8 @@ def _apply_template_structure(
raise TemplateStructureError(
f"Placeholder {item.element_id!r} cannot be a slide background"
)
- if item.placeholder == "title":
- assigned_idx = item.placeholder_idx
- else:
- assigned_idx = (
- item.placeholder_idx
- if item.placeholder_idx is not None
- else placeholder_idx
- )
- if (
- assigned_idx is not None
- and assigned_idx in assigned_placeholder_indices
- ):
- raise TemplateStructureError(
- f"Layout {layout_key!r} repeats placeholder idx {assigned_idx}"
- )
+ binding = placeholder_bindings[item.element_id]
+ assigned_idx = binding.assigned_idx
layout_placeholder = _layout_placeholder_shape(
prototype_shape,
item,
@@ -2012,9 +2040,6 @@ def _apply_template_structure(
assigned_idx,
theme_font_spec=theme_font_spec,
)
- if assigned_idx is not None:
- assigned_placeholder_indices.add(assigned_idx)
- placeholder_idx = max(placeholder_idx, assigned_idx + 1)
placeholder_count += 1
_set_template_layout_header_footer(layout_path, prototype.placeholders)
@@ -4229,6 +4254,21 @@ def create_pptx_with_native_svg(
if file_path.is_file():
arcname = file_path.relative_to(extract_dir)
zf.write(file_path, arcname)
+ if (
+ use_native_shapes
+ and pptx_structure == "template"
+ and success_count == len(svg_files)
+ ):
+ if template_specs is None:
+ raise TemplateStructureError(
+ "Template structure metadata was not parsed before validation"
+ )
+ try:
+ validate_pptx_template_package(temp_output_path, template_specs)
+ except ValueError as exc:
+ raise TemplateStructureError(
+ f"PPTX template package validation failed: {exc}"
+ ) from exc
try:
validate_pptx_transition_package(
temp_output_path,
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 fb69e84a..f4b3f367 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
@@ -56,6 +56,19 @@ _PLACEHOLDERS = frozenset({
"footer",
"slide-number",
})
+TEMPLATE_PLACEHOLDER_TYPES = {
+ "title": "title",
+ "subtitle": "subTitle",
+ "body": "body",
+ "picture": "pic",
+ "chart": "chart",
+ "table": "tbl",
+ "object": "obj",
+ "media": "media",
+ "date": "dt",
+ "footer": "ftr",
+ "slide-number": "sldNum",
+}
_TEXT_PLACEHOLDERS = frozenset({
"title",
"subtitle",
@@ -81,6 +94,7 @@ _LOCK_PAGE_RE = re.compile(r"^P(\d+)$")
PPTX_STRUCTURE_MODES = frozenset({"baseline", "template", "preserve", "flat"})
TEMPLATE_ADHERENCE_MODES = frozenset({"strict", "adaptive"})
NATIVE_STRUCTURE_SCHEMA = "ppt-master.native-structure.v1"
+OOXML_UINT32_MAX = (1 << 32) - 1
class TemplateStructureError(RuntimeError):
@@ -204,6 +218,67 @@ class TemplateSlideSpec:
)
+@dataclass(frozen=True)
+class TemplatePlaceholderBinding:
+ """Resolved PowerPoint identity for one template placeholder."""
+
+ element: TemplateElementSpec
+ placeholder_type: str
+ assigned_idx: int | None
+
+ @property
+ def effective_idx(self) -> int:
+ """Return the OOXML idx value after applying its default of zero."""
+ return self.assigned_idx if self.assigned_idx is not None else 0
+
+
+def template_placeholder_bindings(
+ spec: TemplateSlideSpec,
+) -> tuple[TemplatePlaceholderBinding, ...]:
+ """Assign deterministic, collision-free PowerPoint placeholder identities."""
+ next_idx = 1
+ used_indices: dict[int, str] = {}
+ bindings: list[TemplatePlaceholderBinding] = []
+ for item in spec.placeholders:
+ placeholder_type = TEMPLATE_PLACEHOLDER_TYPES.get(item.placeholder or "")
+ if placeholder_type is None:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: unsupported placeholder type "
+ f"{item.placeholder!r}"
+ )
+ if item.placeholder == "title" and item.placeholder_idx is None:
+ assigned_idx = None
+ else:
+ assigned_idx = (
+ item.placeholder_idx
+ if item.placeholder_idx is not None
+ else next_idx
+ )
+ effective_idx = assigned_idx if assigned_idx is not None else 0
+ if effective_idx > OOXML_UINT32_MAX:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: layout {spec.layout_key!r} placeholder "
+ f"{item.element_id!r} idx exceeds the OOXML UInt32 maximum "
+ f"{OOXML_UINT32_MAX}"
+ )
+ previous = used_indices.get(effective_idx)
+ if previous is not None:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: layout {spec.layout_key!r} gives "
+ f"placeholders {previous!r} and {item.element_id!r} the same "
+ f"effective idx {effective_idx}; omitted idx defaults to 0 in OOXML"
+ )
+ used_indices[effective_idx] = item.element_id
+ if assigned_idx is not None:
+ next_idx = max(next_idx, assigned_idx + 1)
+ bindings.append(TemplatePlaceholderBinding(
+ element=item,
+ placeholder_type=placeholder_type,
+ assigned_idx=assigned_idx,
+ ))
+ return tuple(bindings)
+
+
def _local_tag(elem: ET.Element) -> str:
return elem.tag.rsplit("}", 1)[-1] if isinstance(elem.tag, str) else ""
@@ -661,7 +736,13 @@ def _parse_placeholder_idx(
f"{svg_path.name}: {element_id} data-pptx-placeholder-idx must be "
"a non-negative integer"
)
- return int(value)
+ parsed = int(value)
+ if parsed > OOXML_UINT32_MAX:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id} data-pptx-placeholder-idx must be "
+ f"at most {OOXML_UINT32_MAX}"
+ )
+ return parsed
def _validate_placeholder_element(
@@ -945,6 +1026,7 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
by_layout.setdefault(spec.layout_key, []).append(spec)
for layout_key, layout_specs in by_layout.items():
prototype = layout_specs[0]
+ template_placeholder_bindings(prototype)
for spec in layout_specs[1:]:
if spec.layout_name != prototype.layout_name:
raise TemplateStructureError(
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
new file mode 100644
index 00000000..591415de
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_validation.py
@@ -0,0 +1,793 @@
+#!/usr/bin/env python3
+"""
+PPT Master - Template Package Validation
+
+Read a generated template-mode PPTX back and verify its reusable Layout graph.
+
+Usage:
+ Imported by svg_to_pptx.pptx_package.builder.
+
+Examples:
+ validate_pptx_template_package(Path("output.pptx"), template_specs)
+
+Dependencies:
+ None (only uses standard library and local modules)
+"""
+
+from __future__ import annotations
+
+import posixpath
+import sys
+import zipfile
+from dataclasses import dataclass
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+from xml.etree import ElementTree as ET
+
+if __name__ == "__main__":
+ if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]):
+ print(__doc__)
+ raise SystemExit(0)
+ print(
+ "Use this validator through the template-mode SVG-to-PPTX exporter.",
+ file=sys.stderr,
+ )
+ raise SystemExit(1)
+
+from ..drawingml.utils import EMU_PER_PX
+from .template_structure import (
+ OOXML_UINT32_MAX,
+ TemplatePlaceholderBinding,
+ TemplateSlideSpec,
+ TemplateStructureError,
+ template_placeholder_bindings,
+)
+
+
+PML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
+DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"
+REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+SLIDE_LAYOUT_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
+)
+SLIDE_MASTER_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"
+)
+SLIDE_LAYOUT_CONTENT_TYPE = (
+ "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"
+)
+PRESENTATION_COLLECTION_ID_MIN = 1 << 31
+
+
+@dataclass(frozen=True)
+class _Relationship:
+ rel_id: str
+ rel_type: str
+ target: str
+ target_mode: str | None
+
+
+@dataclass(frozen=True)
+class _Placeholder:
+ shape: ET.Element
+ placeholder_type: str
+ raw_type: str | None
+ idx: int
+ raw_idx: int | None
+
+
+class _PackageReader:
+ """Cache package XML while accumulating deterministic read-back errors."""
+
+ def __init__(self, package: zipfile.ZipFile, errors: list[str]) -> None:
+ self.package = package
+ self.errors = errors
+ self.names = frozenset(package.namelist())
+ self._xml_cache: dict[str, ET.Element | None] = {}
+ self._rels_cache: dict[str, tuple[_Relationship, ...]] = {}
+
+ def xml(self, part: str) -> ET.Element | None:
+ if part in self._xml_cache:
+ return self._xml_cache[part]
+ if part not in self.names:
+ self.errors.append(f"missing package part {part}")
+ self._xml_cache[part] = None
+ return None
+ try:
+ root = ET.fromstring(self.package.read(part))
+ except (KeyError, ET.ParseError) as exc:
+ self.errors.append(f"{part} is not valid XML: {exc}")
+ root = None
+ self._xml_cache[part] = root
+ return root
+
+ def relationships(self, source_part: str) -> tuple[_Relationship, ...]:
+ if source_part in self._rels_cache:
+ return self._rels_cache[source_part]
+ rels_part = _relationships_part_for(source_part)
+ root = self.xml(rels_part)
+ relationships: list[_Relationship] = []
+ seen_ids: set[str] = set()
+ if root is not None:
+ for elem in root:
+ attrs = {
+ key.rsplit("}", 1)[-1]: value
+ for key, value in elem.attrib.items()
+ }
+ rel_id = attrs.get("Id", "")
+ rel_type = attrs.get("Type", "")
+ target = attrs.get("Target", "")
+ if not rel_id or not rel_type or not target:
+ self.errors.append(
+ f"{rels_part} contains a relationship without Id, Type, or Target"
+ )
+ continue
+ if rel_id in seen_ids:
+ self.errors.append(f"{rels_part} repeats relationship id {rel_id}")
+ continue
+ seen_ids.add(rel_id)
+ relationships.append(_Relationship(
+ rel_id=rel_id,
+ rel_type=rel_type,
+ target=target,
+ target_mode=attrs.get("TargetMode"),
+ ))
+ result = tuple(relationships)
+ self._rels_cache[source_part] = result
+ return result
+
+
+def _relationships_part_for(source_part: str) -> str:
+ directory = posixpath.dirname(source_part)
+ filename = posixpath.basename(source_part)
+ return posixpath.join(directory, "_rels", f"{filename}.rels")
+
+
+def _resolve_relationship_target(
+ source_part: str,
+ relationship: _Relationship,
+ errors: list[str],
+ context: str,
+) -> str | None:
+ target_mode = (relationship.target_mode or "Internal").lower()
+ if target_mode != "internal":
+ errors.append(f"{context} relationship must be internal")
+ return None
+ raw_target = relationship.target
+ if "\\" in raw_target or any(ord(char) <= 0x20 for char in raw_target):
+ errors.append(f"{context} has invalid target {raw_target!r}")
+ return None
+ try:
+ parsed = urlsplit(raw_target)
+ except ValueError:
+ errors.append(f"{context} has invalid target {raw_target!r}")
+ return None
+ if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:
+ errors.append(f"{context} has invalid target {raw_target!r}")
+ return None
+ decoded = unquote(parsed.path)
+ if not decoded:
+ errors.append(f"{context} has an empty target")
+ return None
+ if decoded.startswith("/"):
+ candidate = decoded[1:]
+ else:
+ candidate = posixpath.join(posixpath.dirname(source_part), decoded)
+ normalized = posixpath.normpath(candidate)
+ if (
+ normalized in {"", ".", ".."}
+ or normalized.startswith("../")
+ or normalized.startswith("/")
+ ):
+ errors.append(f"{context} target escapes the package: {raw_target!r}")
+ return None
+ return normalized
+
+
+def _single_relationship_target(
+ reader: _PackageReader,
+ source_part: str,
+ rel_type: str,
+ context: str,
+) -> tuple[_Relationship, str] | None:
+ matches = [
+ relationship
+ for relationship in reader.relationships(source_part)
+ if relationship.rel_type == rel_type
+ ]
+ if len(matches) != 1:
+ reader.errors.append(
+ f"{context} must have exactly one {rel_type.rsplit('/', 1)[-1]} "
+ f"relationship, found {len(matches)}"
+ )
+ return None
+ target = _resolve_relationship_target(
+ source_part,
+ matches[0],
+ reader.errors,
+ context,
+ )
+ if target is None:
+ return None
+ return matches[0], target
+
+
+def _placeholder_for_shape(shape: ET.Element) -> ET.Element | None:
+ paths = {
+ f"{{{PML_NS}}}sp": (
+ f"{{{PML_NS}}}nvSpPr/{{{PML_NS}}}nvPr/{{{PML_NS}}}ph"
+ ),
+ f"{{{PML_NS}}}pic": (
+ f"{{{PML_NS}}}nvPicPr/{{{PML_NS}}}nvPr/{{{PML_NS}}}ph"
+ ),
+ f"{{{PML_NS}}}graphicFrame": (
+ f"{{{PML_NS}}}nvGraphicFramePr/{{{PML_NS}}}nvPr/{{{PML_NS}}}ph"
+ ),
+ }
+ path = paths.get(shape.tag)
+ return shape.find(path) if path else None
+
+
+def _read_placeholders(
+ root: ET.Element,
+ context: str,
+ errors: list[str],
+) -> dict[int, _Placeholder]:
+ sp_tree = root.find(f"{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
+ if sp_tree is None:
+ errors.append(f"{context} has no p:cSld/p:spTree")
+ return {}
+ placeholders: dict[int, _Placeholder] = {}
+ for shape in sp_tree:
+ ph = _placeholder_for_shape(shape)
+ if ph is None:
+ continue
+ raw_idx_value = ph.get("idx")
+ try:
+ raw_idx = int(raw_idx_value) if raw_idx_value is not None else None
+ except ValueError:
+ errors.append(f"{context} contains invalid placeholder idx {raw_idx_value!r}")
+ continue
+ idx = raw_idx if raw_idx is not None else 0
+ if not 0 <= idx <= OOXML_UINT32_MAX:
+ errors.append(
+ f"{context} placeholder idx {idx} is outside the OOXML UInt32 range"
+ )
+ continue
+ if idx in placeholders:
+ errors.append(f"{context} repeats effective placeholder idx {idx}")
+ continue
+ raw_type = ph.get("type")
+ placeholders[idx] = _Placeholder(
+ shape=shape,
+ placeholder_type=raw_type or "obj",
+ raw_type=raw_type,
+ idx=idx,
+ raw_idx=raw_idx,
+ )
+ return placeholders
+
+
+def _validate_placeholder_roster(
+ root: ET.Element,
+ bindings: tuple[TemplatePlaceholderBinding, ...],
+ context: str,
+ errors: list[str],
+ *,
+ is_layout: bool,
+) -> dict[int, _Placeholder]:
+ actual = _read_placeholders(root, context, errors)
+ expected = {binding.effective_idx: binding for binding in bindings}
+ if set(actual) != set(expected):
+ errors.append(
+ f"{context} placeholder idx roster is {sorted(actual)}, "
+ f"expected {sorted(expected)}"
+ )
+ for idx in sorted(set(actual).intersection(expected)):
+ placeholder = actual[idx]
+ binding = expected[idx]
+ if placeholder.placeholder_type != binding.placeholder_type:
+ errors.append(
+ f"{context} placeholder idx {idx} has type "
+ f"{placeholder.placeholder_type!r}, expected "
+ f"{binding.placeholder_type!r}"
+ )
+ if binding.assigned_idx is None:
+ if placeholder.raw_idx is not None:
+ errors.append(
+ f"{context} title placeholder must use the omitted idx=0 form"
+ )
+ elif placeholder.raw_idx != binding.assigned_idx:
+ errors.append(
+ f"{context} placeholder idx {idx} must serialize explicit idx "
+ f"{binding.assigned_idx}"
+ )
+ if is_layout and placeholder.raw_type is None:
+ errors.append(
+ f"{context} Layout placeholder idx {idx} must serialize its type"
+ )
+ if (
+ not is_layout
+ and binding.placeholder_type != "obj"
+ and placeholder.raw_type is None
+ ):
+ errors.append(
+ f"{context} Slide placeholder idx {idx} must serialize type "
+ f"{binding.placeholder_type!r}"
+ )
+ return actual
+
+
+def _validate_layout_header_footer(
+ root: ET.Element,
+ bindings: tuple[TemplatePlaceholderBinding, ...],
+ context: str,
+ errors: list[str],
+) -> None:
+ placeholder_roles = {
+ binding.element.placeholder for binding in bindings
+ }
+ expected = {
+ "hdr": False,
+ "dt": "date" in placeholder_roles,
+ "ftr": "footer" in placeholder_roles,
+ "sldNum": "slide-number" in placeholder_roles,
+ }
+ header_footer = root.find(f"{{{PML_NS}}}hf")
+ if header_footer is None:
+ if any(expected.values()):
+ errors.append(
+ f"{context} has date/footer/slide-number placeholders but no p:hf"
+ )
+ return
+ for attr, expected_value in expected.items():
+ # CT_HeaderFooter boolean attributes default to true when omitted.
+ raw_value = header_footer.get(attr, "1").lower()
+ if raw_value not in {"0", "1", "false", "true"}:
+ errors.append(f"{context} p:hf@{attr} is not a valid boolean")
+ continue
+ actual_value = raw_value in {"1", "true"}
+ if actual_value != expected_value:
+ errors.append(
+ f"{context} p:hf@{attr} is {raw_value!r}, expected "
+ f"{'1' if expected_value else '0'}"
+ )
+
+
+def _shape_bounds(
+ shape: ET.Element,
+ context: str,
+ errors: list[str],
+) -> tuple[int, int, int, int] | None:
+ if shape.tag == f"{{{PML_NS}}}graphicFrame":
+ xfrm = shape.find(f"{{{PML_NS}}}xfrm")
+ else:
+ xfrm = shape.find(f"{{{PML_NS}}}spPr/{{{DML_NS}}}xfrm")
+ if xfrm is None:
+ errors.append(f"{context} has no direct placeholder transform")
+ return None
+ off = xfrm.find(f"{{{DML_NS}}}off")
+ ext = xfrm.find(f"{{{DML_NS}}}ext")
+ if off is None or ext is None:
+ errors.append(f"{context} placeholder transform has no a:off/a:ext")
+ return None
+ try:
+ bounds = (
+ int(off.attrib["x"]),
+ int(off.attrib["y"]),
+ int(ext.attrib["cx"]),
+ int(ext.attrib["cy"]),
+ )
+ except (KeyError, ValueError):
+ errors.append(f"{context} placeholder transform is invalid")
+ return None
+ if bounds[2] <= 0 or bounds[3] <= 0:
+ errors.append(f"{context} placeholder width/height must be positive")
+ return bounds
+
+
+def _direct_text_body(shape: ET.Element) -> ET.Element | None:
+ return shape.find(f"{{{PML_NS}}}txBody")
+
+
+def _first_run_size(shape: ET.Element) -> str | None:
+ text_body = _direct_text_body(shape)
+ if text_body is None:
+ return None
+ run_props = text_body.find(f".//{{{DML_NS}}}rPr")
+ return run_props.get("sz") if run_props is not None else None
+
+
+def _level_one_default_size(shape: ET.Element) -> str | None:
+ text_body = _direct_text_body(shape)
+ if text_body is None:
+ return None
+ default_props = text_body.find(
+ f"{{{DML_NS}}}lstStyle/"
+ f"{{{DML_NS}}}lvl1pPr/"
+ f"{{{DML_NS}}}defRPr"
+ )
+ return default_props.get("sz") if default_props is not None else None
+
+
+def _content_type_overrides(
+ reader: _PackageReader,
+) -> dict[str, list[str]]:
+ root = reader.xml("[Content_Types].xml")
+ overrides: dict[str, list[str]] = {}
+ if root is None:
+ return overrides
+ for elem in root:
+ if elem.tag.rsplit("}", 1)[-1] != "Override":
+ continue
+ part_name = elem.get("PartName", "")
+ content_type = elem.get("ContentType", "")
+ if part_name and content_type:
+ overrides.setdefault(part_name, []).append(content_type)
+ return overrides
+
+
+def _validate_uint32_id_roster(
+ elements: list[ET.Element],
+ context: str,
+ errors: list[str],
+ *,
+ min_value: int = 0,
+) -> set[int]:
+ values: set[int] = set()
+ for element in elements:
+ raw_value = element.get("id")
+ try:
+ value = int(raw_value) if raw_value is not None else -1
+ except ValueError:
+ value = -1
+ if not min_value <= value <= OOXML_UINT32_MAX:
+ errors.append(
+ f"{context} contains id {raw_value!r} outside the OOXML range "
+ f"{min_value}..{OOXML_UINT32_MAX}"
+ )
+ continue
+ if value in values:
+ errors.append(f"{context} repeats numeric id {value}")
+ continue
+ values.add(value)
+ return values
+
+
+def _validate_registered_part_roster(
+ reader: _PackageReader,
+ source_part: str,
+ rel_type: str,
+ entries: list[ET.Element],
+ expected_targets: set[str],
+ context: str,
+) -> set[int]:
+ relationships = [
+ relationship
+ for relationship in reader.relationships(source_part)
+ if relationship.rel_type == rel_type
+ ]
+ targets_by_id: dict[str, str] = {}
+ ids_by_target: dict[str, list[str]] = {}
+ for relationship in relationships:
+ target = _resolve_relationship_target(
+ source_part,
+ relationship,
+ reader.errors,
+ context,
+ )
+ if target is None:
+ continue
+ targets_by_id[relationship.rel_id] = target
+ ids_by_target.setdefault(target, []).append(relationship.rel_id)
+ for target, rel_ids in sorted(ids_by_target.items()):
+ if len(rel_ids) > 1:
+ reader.errors.append(
+ f"{context} targets {target} through multiple relationships: "
+ + ", ".join(rel_ids)
+ )
+
+ actual_targets = set(targets_by_id.values())
+ if actual_targets != expected_targets:
+ missing = sorted(expected_targets - actual_targets)
+ extra = sorted(actual_targets - expected_targets)
+ reader.errors.append(
+ f"{context} registered target roster differs; missing={missing}, "
+ f"extra={extra}"
+ )
+
+ entry_rel_ids: list[str] = []
+ for entry in entries:
+ rel_id = entry.get(f"{{{REL_NS}}}id")
+ if not rel_id:
+ reader.errors.append(f"{context} contains an entry without r:id")
+ continue
+ entry_rel_ids.append(rel_id)
+ if len(entry_rel_ids) != len(set(entry_rel_ids)):
+ reader.errors.append(f"{context} repeats an entry r:id")
+ if set(entry_rel_ids) != {relationship.rel_id for relationship in relationships}:
+ reader.errors.append(
+ f"{context} entry r:id roster does not match its relationships"
+ )
+ return _validate_uint32_id_roster(
+ entries,
+ context,
+ reader.errors,
+ min_value=PRESENTATION_COLLECTION_ID_MIN,
+ )
+
+
+def _validate_presentation_master_registration(
+ reader: _PackageReader,
+ master_parts: set[str],
+) -> None:
+ presentation_part = "ppt/presentation.xml"
+ presentation_root = reader.xml(presentation_part)
+ if presentation_root is None:
+ return
+ master_id_entries = presentation_root.findall(
+ f"{{{PML_NS}}}sldMasterIdLst/{{{PML_NS}}}sldMasterId"
+ )
+ _validate_registered_part_roster(
+ reader,
+ presentation_part,
+ SLIDE_MASTER_REL_TYPE,
+ master_id_entries,
+ master_parts,
+ "Presentation p:sldMasterIdLst",
+ )
+
+
+def validate_pptx_template_package(
+ pptx_path: str | Path,
+ specs: list[TemplateSlideSpec],
+) -> None:
+ """Validate a finished template-mode PPTX against its explicit SVG contract."""
+ if not specs:
+ raise ValueError("template package validation requires at least one slide spec")
+
+ specs_by_layout: dict[str, list[TemplateSlideSpec]] = {}
+ bindings_by_layout: dict[str, tuple[TemplatePlaceholderBinding, ...]] = {}
+ try:
+ for spec in specs:
+ specs_by_layout.setdefault(spec.layout_key, []).append(spec)
+ for layout_key, layout_specs in specs_by_layout.items():
+ bindings_by_layout[layout_key] = template_placeholder_bindings(
+ layout_specs[0]
+ )
+ except TemplateStructureError as exc:
+ raise ValueError(str(exc)) from exc
+
+ errors: list[str] = []
+ path = Path(pptx_path)
+ try:
+ with zipfile.ZipFile(path) as package:
+ reader = _PackageReader(package, errors)
+ overrides = _content_type_overrides(reader)
+ layout_parts_by_key: dict[str, str] = {}
+ keys_by_layout_part: dict[str, str] = {}
+ slide_roots: dict[int, ET.Element] = {}
+
+ for spec in specs:
+ slide_part = f"ppt/slides/slide{spec.slide_num}.xml"
+ slide_root = reader.xml(slide_part)
+ if slide_root is not None:
+ slide_roots[spec.slide_num] = slide_root
+ relationship_target = _single_relationship_target(
+ reader,
+ slide_part,
+ SLIDE_LAYOUT_REL_TYPE,
+ f"Slide {spec.slide_num}",
+ )
+ if relationship_target is None:
+ continue
+ _relationship, layout_part = relationship_target
+ if not (
+ layout_part.startswith("ppt/slideLayouts/")
+ and layout_part.endswith(".xml")
+ ):
+ errors.append(
+ f"Slide {spec.slide_num} targets non-Layout part {layout_part}"
+ )
+ continue
+ reader.xml(layout_part)
+ previous_part = layout_parts_by_key.setdefault(
+ spec.layout_key,
+ layout_part,
+ )
+ if previous_part != layout_part:
+ errors.append(
+ f"layout key {spec.layout_key!r} targets both {previous_part} "
+ f"and {layout_part}"
+ )
+ previous_key = keys_by_layout_part.setdefault(
+ layout_part,
+ spec.layout_key,
+ )
+ if previous_key != spec.layout_key:
+ errors.append(
+ f"layout keys {previous_key!r} and {spec.layout_key!r} both "
+ f"target {layout_part}"
+ )
+
+ used_master_parts: set[str] = set()
+ layout_parts_by_master: dict[str, set[str]] = {}
+ for layout_key, layout_specs in specs_by_layout.items():
+ layout_part = layout_parts_by_key.get(layout_key)
+ if layout_part is None:
+ errors.append(f"layout key {layout_key!r} has no resolved Layout part")
+ continue
+ layout_root = reader.xml(layout_part)
+ if layout_root is None:
+ continue
+ if layout_root.tag != f"{{{PML_NS}}}sldLayout":
+ errors.append(f"{layout_part} is not a p:sldLayout part")
+ if layout_root.get("type") != "cust":
+ 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")
+ 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
+ if actual_name != expected_name:
+ errors.append(
+ f"{layout_part} has picker name {actual_name!r}, expected "
+ f"{expected_name!r}"
+ )
+
+ override_values = overrides.get(f"/{layout_part}", [])
+ if override_values != [SLIDE_LAYOUT_CONTENT_TYPE]:
+ errors.append(
+ f"[Content_Types].xml must declare {layout_part} exactly once "
+ f"as {SLIDE_LAYOUT_CONTENT_TYPE}"
+ )
+
+ bindings = bindings_by_layout[layout_key]
+ layout_placeholders = _validate_placeholder_roster(
+ layout_root,
+ bindings,
+ f"Layout {layout_key!r}",
+ errors,
+ is_layout=True,
+ )
+ _validate_layout_header_footer(
+ layout_root,
+ bindings,
+ f"Layout {layout_key!r}",
+ errors,
+ )
+ slide_placeholders: dict[int, dict[int, _Placeholder]] = {}
+ for spec in layout_specs:
+ slide_root = slide_roots.get(spec.slide_num)
+ if slide_root is None:
+ continue
+ slide_placeholders[spec.slide_num] = _validate_placeholder_roster(
+ slide_root,
+ bindings,
+ f"Slide {spec.slide_num}",
+ errors,
+ is_layout=False,
+ )
+
+ prototype = layout_specs[0]
+ prototype_placeholders = slide_placeholders.get(
+ prototype.slide_num,
+ {},
+ )
+ for binding in bindings:
+ idx = binding.effective_idx
+ layout_placeholder = layout_placeholders.get(idx)
+ prototype_placeholder = prototype_placeholders.get(idx)
+ if layout_placeholder is None or prototype_placeholder is None:
+ continue
+ context = (
+ f"Layout {layout_key!r} placeholder "
+ f"{binding.element.element_id!r}"
+ )
+ actual_bounds = _shape_bounds(
+ layout_placeholder.shape,
+ context,
+ errors,
+ )
+ if binding.element.placeholder_bounds is not None:
+ expected_bounds = tuple(
+ round(value * EMU_PER_PX)
+ for value in binding.element.placeholder_bounds
+ )
+ else:
+ expected_bounds = _shape_bounds(
+ prototype_placeholder.shape,
+ f"Slide {prototype.slide_num} placeholder "
+ f"{binding.element.element_id!r}",
+ errors,
+ )
+ if (
+ actual_bounds is not None
+ and expected_bounds is not None
+ and actual_bounds != expected_bounds
+ ):
+ errors.append(
+ f"{context} bounds are {actual_bounds}, expected "
+ f"{expected_bounds}"
+ )
+
+ prototype_size = _first_run_size(prototype_placeholder.shape)
+ if prototype_size is not None:
+ prompt_size = _first_run_size(layout_placeholder.shape)
+ if prompt_size != prototype_size:
+ errors.append(
+ f"{context} prompt size is {prompt_size!r}, expected "
+ f"{prototype_size!r}"
+ )
+ default_size = _level_one_default_size(
+ layout_placeholder.shape
+ )
+ if default_size != prototype_size:
+ errors.append(
+ f"{context} level-1 default size is "
+ f"{default_size!r}, expected {prototype_size!r}"
+ )
+
+ master_target = _single_relationship_target(
+ reader,
+ layout_part,
+ SLIDE_MASTER_REL_TYPE,
+ f"Layout {layout_key!r}",
+ )
+ if master_target is None:
+ continue
+ _relationship, master_part = master_target
+ if not (
+ master_part.startswith("ppt/slideMasters/")
+ and master_part.endswith(".xml")
+ ):
+ errors.append(
+ f"Layout {layout_key!r} targets non-Master part {master_part}"
+ )
+ continue
+ reader.xml(master_part)
+ used_master_parts.add(master_part)
+ layout_parts_by_master.setdefault(master_part, set()).add(
+ layout_part
+ )
+
+ layout_id_owners: dict[int, str] = {}
+ for master_part, layout_parts in sorted(layout_parts_by_master.items()):
+ master_root = reader.xml(master_part)
+ if master_root is None:
+ continue
+ layout_id_entries = master_root.findall(
+ f"{{{PML_NS}}}sldLayoutIdLst/"
+ f"{{{PML_NS}}}sldLayoutId"
+ )
+ layout_ids = _validate_registered_part_roster(
+ reader,
+ master_part,
+ SLIDE_LAYOUT_REL_TYPE,
+ layout_id_entries,
+ layout_parts,
+ f"Master {master_part} p:sldLayoutIdLst",
+ )
+ for layout_id in sorted(layout_ids):
+ previous_owner = layout_id_owners.setdefault(
+ layout_id,
+ master_part,
+ )
+ if previous_owner != master_part:
+ errors.append(
+ f"Slide Layout numeric id {layout_id} appears in both "
+ f"{previous_owner} and {master_part}"
+ )
+
+ _validate_presentation_master_registration(reader, used_master_parts)
+ except (OSError, zipfile.BadZipFile) as exc:
+ raise ValueError(f"cannot read template PPTX package {path}: {exc}") from exc
+
+ if errors:
+ details = "\n".join(f" - {error}" for error in errors)
+ raise ValueError(f"template package read-back failed:\n{details}")