Skip to content

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

feat(pptx-layouts): compile explicit master and layout contracts

hugohe3b6f1879d60f1
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index d2fc0059..2532267e 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -15,6 +15,7 @@ import sys
import re
import json
import html
+import math
from pathlib import Path
from typing import List, Dict, Tuple
from collections import Counter, defaultdict
@@ -172,13 +173,7 @@ except ImportError:
try:
from svg_to_pptx.pptx_package.template_structure import (
TemplateStructureError as _TemplateStructureError,
- PptxLayoutReference as _PptxLayoutReference,
- PptxStructureLock as _PptxStructureLock,
- load_native_structure_contract as _load_native_structure_contract,
load_pptx_structure_lock as _load_pptx_structure_lock,
- native_structure_lock_errors as _native_structure_lock_errors,
- parse_optional_layout_slides as _parse_optional_layout_slides,
- parse_preserve_slides as _parse_preserve_structure_slides,
parse_template_slide as _parse_template_structure_slide,
parse_template_slides as _parse_template_structure_slides,
template_lock_errors as _template_lock_errors,
@@ -187,13 +182,7 @@ try:
)
except ImportError:
_TemplateStructureError = None
- _PptxLayoutReference = None
- _PptxStructureLock = None
- _load_native_structure_contract = None
_load_pptx_structure_lock = None
- _native_structure_lock_errors = None
- _parse_optional_layout_slides = None
- _parse_preserve_structure_slides = None
_parse_template_structure_slide = None
_parse_template_structure_slides = None
_template_lock_errors = None
@@ -231,6 +220,40 @@ _BARE_HEX_VALUE_RE = re.compile(
)
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
+_NON_VISUAL_SVG_TAGS = frozenset({
+ 'defs',
+ 'desc',
+ 'metadata',
+ 'style',
+ 'title',
+})
+_PPTX_ROOT_STRUCTURE_ATTRS = (
+ 'data-pptx-master',
+ 'data-pptx-master-name',
+ 'data-pptx-layout',
+ 'data-pptx-layout-name',
+)
+_PPTX_STRUCTURE_ATTRS = frozenset({
+ *_PPTX_ROOT_STRUCTURE_ATTRS,
+ 'data-pptx-layer',
+ 'data-pptx-layout-kind',
+ 'data-pptx-placeholder',
+ 'data-pptx-placeholder-binding',
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-placeholder-carrier',
+ 'data-pptx-placeholder-idx',
+})
+_PPTX_PLACEHOLDER_DETAIL_ATTRS = frozenset({
+ 'data-pptx-placeholder-binding',
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-placeholder-idx',
+})
+_PPTX_STRUCTURE_SECTION_RE = re.compile(
+ r"(?ms)^##[ \t]+pptx_structure[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
+)
+_PPTX_STRUCTURE_MODE_RE = re.compile(
+ r"(?m)^-[ \t]+mode[ \t]*:[ \t]*([^\s#]+)[ \t]*(?:#.*)?$"
+)
_SUPPORTED_FILTER_PRIMITIVES = frozenset({
'feDropShadow',
'feGaussianBlur',
@@ -245,6 +268,237 @@ _SUPPORTED_FILTER_PRIMITIVES = frozenset({
_FILTER_EFFECT_PRIMITIVES = frozenset({'feDropShadow', 'feGaussianBlur'})
+def _declared_pptx_structure_mode(project_path: Path) -> str | None:
+ """Return the explicitly locked SVG structure mode without a fallback."""
+ lock_path = project_path / 'spec_lock.md'
+ try:
+ content = lock_path.read_text(encoding='utf-8')
+ except OSError:
+ return None
+ section_match = _PPTX_STRUCTURE_SECTION_RE.search(content)
+ if section_match is None:
+ return None
+ mode_match = _PPTX_STRUCTURE_MODE_RE.search(section_match.group(1))
+ return mode_match.group(1).strip().lower() if mode_match else None
+
+
+def _placeholder_bounds_error(value: str) -> str | None:
+ """Return a concise error for invalid design-zone bounds."""
+ raw_values = [item for item in re.split(r"[\s,]+", value.strip()) if item]
+ if len(raw_values) != 4:
+ return "must contain exactly four numbers: x y width height"
+ try:
+ values = tuple(float(item) for item in raw_values)
+ except ValueError:
+ return "must contain only numeric values"
+ if not all(math.isfinite(item) for item in values):
+ return "must contain only finite values"
+ if values[2] <= 0 or values[3] <= 0:
+ return "must use positive width and height"
+ return None
+
+
+def _local_pptx_structure_errors(
+ root: ET.Element,
+ svg_path: Path,
+ *,
+ require_structure: bool,
+) -> List[str]:
+ """Validate the authoring shape of the structured SVG contract."""
+ errors: List[str] = []
+ root_values = {
+ attr: (root.get(attr) or '').strip()
+ for attr in _PPTX_ROOT_STRUCTURE_ATTRS
+ }
+ has_root_structure = any(root_values.values())
+ if require_structure or has_root_structure:
+ missing = [attr for attr, value in root_values.items() if not value]
+ if missing:
+ errors.append(
+ f"{svg_path.name}: structured SVG root is missing "
+ + ', '.join(missing)
+ )
+
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ for elem in root.iter():
+ tag = elem.tag.rsplit('}', 1)[-1]
+ element_id = elem.get('id') or f"<{tag}>"
+ parent = parent_by_id.get(id(elem))
+
+ if elem is not root:
+ nested_root_attrs = [
+ attr for attr in _PPTX_ROOT_STRUCTURE_ATTRS
+ if elem.get(attr) is not None
+ ]
+ if nested_root_attrs:
+ errors.append(
+ f"{svg_path.name}: {element_id} carries root-only metadata "
+ + ', '.join(nested_root_attrs)
+ )
+
+ if elem.get('data-pptx-layout-kind') is not None:
+ errors.append(
+ f"{svg_path.name}: data-pptx-layout-kind is a legacy distillation "
+ "attribute; restore the page to the structured contract"
+ )
+
+ layer = (elem.get('data-pptx-layer') or '').strip().lower()
+ placeholder = (elem.get('data-pptx-placeholder') or '').strip().lower()
+ if layer in {'master', 'layout'}:
+ if parent is not root:
+ errors.append(
+ f"{svg_path.name}: {element_id} data-pptx-layer={layer!r} "
+ "must be a direct child of the root <svg>"
+ )
+ if tag == 'g':
+ errors.append(
+ f"{svg_path.name}: {element_id} is a <g> marked as {layer}; "
+ "Master/Layout fixed visuals must be root-level atomic elements"
+ )
+ if placeholder:
+ errors.append(
+ f"{svg_path.name}: {element_id} cannot be both a fixed "
+ f"{layer} element and a placeholder slot"
+ )
+
+ detail_attrs = [
+ attr for attr in _PPTX_PLACEHOLDER_DETAIL_ATTRS
+ if elem.get(attr) is not None
+ ]
+ if detail_attrs and not placeholder:
+ errors.append(
+ f"{svg_path.name}: {element_id} uses placeholder detail metadata "
+ "without data-pptx-placeholder"
+ )
+
+ if placeholder:
+ if parent is not root:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} must be a "
+ "direct child of the root <svg>"
+ )
+ if tag != 'g':
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} must be a "
+ "root-level <g>"
+ )
+ if not (elem.get('id') or '').strip():
+ errors.append(
+ f"{svg_path.name}: every placeholder slot <g> requires a stable id"
+ )
+ wrapper_attrs = sorted(
+ attr.rsplit('}', 1)[-1]
+ for attr in elem.attrib
+ if attr != 'id'
+ and not attr.rsplit('}', 1)[-1].startswith('data-pptx-')
+ )
+ if wrapper_attrs:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} is an "
+ "authoring boundary and may carry only id/data-pptx-*; remove "
+ + ', '.join(wrapper_attrs)
+ )
+ bounds = (elem.get('data-pptx-placeholder-bounds') or '').strip()
+ if not bounds:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} requires "
+ "data-pptx-placeholder-bounds"
+ )
+ else:
+ bounds_error = _placeholder_bounds_error(bounds)
+ if bounds_error:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} bounds "
+ + bounds_error
+ )
+
+ binding = (
+ elem.get('data-pptx-placeholder-binding') or 'carrier'
+ ).strip().lower()
+ if binding not in {'carrier', 'proxy'}:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} has unknown "
+ f"binding {binding!r}; use carrier or proxy"
+ )
+ carrier_descendants = [
+ child for child in elem.iter()
+ if child is not elem
+ and child.get('data-pptx-placeholder-carrier') is not None
+ ]
+ visual_children = [
+ child for child in list(elem)
+ if child.tag.rsplit('}', 1)[-1] not in _NON_VISUAL_SVG_TAGS
+ ]
+ direct_carriers = [
+ child for child in visual_children
+ if (child.get('data-pptx-placeholder-carrier') or '').strip().lower()
+ == 'true'
+ ]
+ nested_carriers = [
+ child for child in carrier_descendants
+ if parent_by_id.get(id(child)) is not elem
+ ]
+ if nested_carriers:
+ names = ', '.join(
+ child.get('id') or f"<{child.tag.rsplit('}', 1)[-1]}>"
+ for child in nested_carriers
+ )
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} has nested "
+ f"carrier marker(s): {names}; the carrier must be a direct child"
+ )
+ if binding == 'carrier':
+ if len(visual_children) != 1 or len(direct_carriers) != 1:
+ errors.append(
+ f"{svg_path.name}: placeholder slot {element_id} requires "
+ "exactly one visual direct child, marked "
+ "data-pptx-placeholder-carrier=\"true\""
+ )
+ if binding == 'proxy':
+ if placeholder != 'object':
+ errors.append(
+ f"{svg_path.name}: proxy binding is allowed only for an "
+ f"object placeholder, not {placeholder!r}"
+ )
+ if carrier_descendants:
+ errors.append(
+ f"{svg_path.name}: proxy placeholder slot {element_id} must "
+ "not declare a visible placeholder carrier"
+ )
+ if not visual_children:
+ errors.append(
+ f"{svg_path.name}: proxy placeholder slot {element_id} must "
+ "contain visible Slide-local content"
+ )
+
+ carrier_value = elem.get('data-pptx-placeholder-carrier')
+ if carrier_value is not None:
+ if carrier_value.strip().lower() != 'true':
+ errors.append(
+ f"{svg_path.name}: {element_id} "
+ "data-pptx-placeholder-carrier must equal true"
+ )
+ if parent is None or not (
+ parent.get('data-pptx-placeholder') or ''
+ ).strip():
+ errors.append(
+ f"{svg_path.name}: placeholder carrier {element_id} must be a "
+ "direct child of a root placeholder slot"
+ )
+
+ if tag in _NON_VISUAL_SVG_TAGS and (layer or placeholder):
+ errors.append(
+ f"{svg_path.name}: non-visual {element_id} cannot carry "
+ "Master/Layout/placeholder ownership"
+ )
+
+ return list(dict.fromkeys(errors))
+
+
def _normalize_hex_rgb(value: str) -> str | None:
"""Normalize 3/4/6/8-digit HEX to alpha-free ``RRGGBB``."""
if not HEX_VALUE_RE.fullmatch(value):
@@ -1704,53 +1958,31 @@ class SVGQualityChecker:
svg_path: Path,
result: Dict,
) -> None:
- """Validate explicit template-export metadata when any is present."""
- structure_attrs = {
- 'data-pptx-layer',
- 'data-pptx-layout',
- 'data-pptx-layout-kind',
- 'data-pptx-layout-name',
- 'data-pptx-placeholder',
- 'data-pptx-placeholder-bounds',
- 'data-pptx-placeholder-idx',
- 'data-pptx-editable',
- }
- if not any(
+ """Validate the intrinsic structured Master/Layout SVG contract."""
+ has_structure_metadata = any(
elem.get(attr) is not None
for elem in root.iter()
- for attr in structure_attrs
- ):
+ for attr in _PPTX_STRUCTURE_ATTRS
+ )
+ require_structure = bool(
+ self.template_mode
+ or svg_path.parent.name == 'svg_output'
+ )
+ if not has_structure_metadata and not require_structure:
return
- if root.get('data-pptx-layout') is not None:
- layout_kind = (root.get('data-pptx-layout-kind') or '').strip().lower()
- if layout_kind != 'utility':
- has_placeholder = any(
- elem.get('data-pptx-placeholder') is not None
- for elem in root.iter()
- )
- has_layout_layer = any(
- elem.get('data-pptx-layer') == 'layout'
- for elem in root.iter()
- )
- if not has_placeholder and not has_layout_layer:
- result['warnings'].append(
- "Mapped page declares neither a reusable Layout layer nor a "
- "placeholder. Use a utility/freeform contract for an unselected "
- "page, or distill at least one real reusable design element."
- )
- elif not has_placeholder:
- result['warnings'].append(
- "Mapped Layout has reusable framing but no insertable placeholder. "
- "Keep it only when that static framing is the intended reusable "
- "contract."
- )
+ result['errors'].extend(_local_pptx_structure_errors(
+ root,
+ svg_path,
+ require_structure=require_structure,
+ ))
if _validate_template_structure_svg is None:
- result['warnings'].append(
- "Detected PPTX template structure metadata, but its validator "
- "could not be imported; template export will still validate it."
+ result['errors'].append(
+ "Structured PPTX metadata validator could not be imported; "
+ "the quality gate cannot verify this SVG"
)
return
result['errors'].extend(_validate_template_structure_svg(svg_path))
+ result['errors'] = list(dict.fromkeys(result['errors']))
def _check_semantic_markers(
self,
@@ -2201,72 +2433,12 @@ class SVGQualityChecker:
target_path: Path,
svg_files: List[Path],
) -> None:
- """Validate project-level layout reuse and spec_lock mappings."""
- if (
- _load_pptx_structure_lock is None
- or _parse_optional_layout_slides is None
- or _parse_template_structure_slides is None
- or _template_lock_errors is None
- or _TemplateStructureError is None
- ):
- return
+ """Validate the all-page structured lock and reusable contracts."""
project_path = self._resolve_project_path(target_path)
- try:
- structure_lock = _load_pptx_structure_lock(project_path)
- except _TemplateStructureError as exc:
- self._pptx_structure_issues.append(('error', str(exc)))
- return
-
- if (
- structure_lock is not None
- and structure_lock.mode == 'template'
- and structure_lock.layout_strategy == 'distill'
- and structure_lock.template_adherence in {'strict', 'adaptive'}
- and _parse_spec_lock is not None
- ):
- lock_path = project_path / 'spec_lock.md'
- lock = _parse_spec_lock(lock_path)
- page_layouts = lock.get('page_layouts', {})
- expected_pages = {f'P{index:02d}' for index in range(1, len(svg_files) + 1)}
- missing_pages = sorted(expected_pages - set(page_layouts))
- extra_pages = sorted(set(page_layouts) - expected_pages)
- if missing_pages:
- self._pptx_structure_issues.append((
- 'error',
- 'spec_lock.md template export requires page_layouts '
- 'rows for every generated page; missing: ' + ', '.join(missing_pages),
- ))
- if target_path.is_dir() and extra_pages:
- self._pptx_structure_issues.append((
- 'error',
- 'spec_lock.md template export page_layouts references absent '
- 'generated pages: ' + ', '.join(extra_pages),
- ))
- template_dir = project_path / 'templates'
- template_svgs = {path.stem for path in template_dir.glob('*.svg')}
- missing_templates = sorted({
- value.strip().removesuffix('.svg')
- for page, value in page_layouts.items()
- if page in expected_pages
- and value.strip().removesuffix('.svg') not in template_svgs
- })
- if missing_templates:
- self._pptx_structure_issues.append((
- 'error',
- 'spec_lock.md template export references missing '
- 'template SVG(s): ' + ', '.join(missing_templates),
- ))
-
- structure_attrs = {
- 'data-pptx-layer',
- 'data-pptx-layout',
- 'data-pptx-layout-kind',
- 'data-pptx-layout-name',
- 'data-pptx-placeholder',
- 'data-pptx-placeholder-bounds',
- 'data-pptx-placeholder-idx',
- 'data-pptx-editable',
- }
+ standard_project = bool(
+ not self.template_mode
+ and (project_path / 'svg_output').is_dir()
+ )
has_metadata = False
for svg_path in svg_files:
try:
@@ -2276,169 +2448,158 @@ class SVGQualityChecker:
if any(
elem.get(attr) is not None
for elem in root.iter()
- for attr in structure_attrs
+ for attr in _PPTX_STRUCTURE_ATTRS
):
has_metadata = True
break
- locked_mode = structure_lock.mode if structure_lock is not None else None
- structure_locked = locked_mode in {'template', 'preserve'}
- standard_project = (
- not self.template_mode
- and (project_path / 'svg_output').is_dir()
- )
- baseline_mode = not self.template_mode and (
- locked_mode == 'baseline'
- or (locked_mode is None and standard_project)
- )
- baseline_layout_locked = bool(
- baseline_mode
- and structure_lock is not None
- and structure_lock.layouts
- )
- distillation_locked = bool(
- baseline_mode
- and structure_lock is not None
- and structure_lock.layout_strategy == 'distill'
- )
- template_distillation_pending = bool(
- locked_mode == 'template'
- and structure_lock is not None
- and structure_lock.layout_strategy == 'distill'
- and not structure_lock.layouts
- )
- if template_distillation_pending:
- premature_kinds = []
- for svg_path in svg_files:
- try:
- root = ET.parse(svg_path).getroot()
- except (OSError, ET.ParseError):
- continue
- if root.get('data-pptx-layout-kind') is not None:
- premature_kinds.append(svg_path.name)
- if premature_kinds:
- self._pptx_structure_issues.append((
- 'error',
- 'template Layout distillation is still pending, but final '
- 'data-pptx-layout-kind metadata already appears on: '
- + ', '.join(premature_kinds),
- ))
- if (
- not premature_kinds
- and _parse_template_structure_slide is not None
- and _template_prototype_errors is not None
- ):
- try:
- pending_specs = [
- _parse_template_structure_slide(svg_path, index)
- for index, svg_path in enumerate(svg_files, start=1)
- ]
- except _TemplateStructureError as exc:
- self._pptx_structure_issues.append(('error', str(exc)))
- else:
- self._pptx_structure_issues.extend(
- ('error', message)
- for message in _template_prototype_errors(
- pending_specs,
- structure_lock,
- require_complete_roster=target_path.is_dir(),
- )
- )
+
+ if not standard_project and not self.template_mode and not has_metadata:
return
if (
- target_path.is_dir()
- and distillation_locked
- and (not baseline_layout_locked or not has_metadata)
+ _load_pptx_structure_lock is None
+ or _parse_template_structure_slide is None
+ or _parse_template_structure_slides is None
+ or _template_lock_errors is None
+ or _TemplateStructureError is None
):
self._pptx_structure_issues.append((
'error',
- 'post-design Layout distillation is incomplete: write a complete '
- 'spec_lock.md pptx_layouts mapping and matching root Layout metadata '
- 'for every SVG before the project quality gate',
+ 'Structured PPTX project validation is unavailable because the '
+ 'template_structure module could not be imported.',
))
return
- if not has_metadata and not structure_locked and not baseline_layout_locked:
- return
- try:
- if locked_mode == 'preserve':
- if _parse_preserve_structure_slides is None:
- return
- specs = _parse_preserve_structure_slides(svg_files)
- elif baseline_mode:
- specs = _parse_optional_layout_slides(svg_files)
- if specs is None:
- if structure_lock is not None and structure_lock.layouts:
- self._pptx_structure_issues.append((
- 'error',
- 'spec_lock.md pptx_layouts requires every baseline SVG '
- 'root to declare data-pptx-layout and '
- 'data-pptx-layout-name',
- ))
- elif has_metadata:
- _parse_template_structure_slides(svg_files)
- return
- else:
+ if self.template_mode:
+ try:
specs = _parse_template_structure_slides(svg_files)
- except _TemplateStructureError as exc:
- self._pptx_structure_issues.append(('error', str(exc)))
- return
- if baseline_mode:
- if structure_lock is None or not structure_lock.layouts:
- self._pptx_structure_issues.append((
- 'error',
- 'explicit baseline Layout metadata requires a complete '
- 'spec_lock.md pptx_layouts mapping',
- ))
+ except _TemplateStructureError as exc:
+ self._pptx_structure_issues.append(('error', str(exc)))
return
- self._pptx_structure_issues.extend(
- ('error', message)
- for message in _template_lock_errors(specs, structure_lock)
- )
self._pptx_structure_issues.extend(
('warning', message)
for message in self._duplicate_layout_key_warnings(specs)
)
return
- if not structure_locked:
- return
- self._pptx_structure_issues.extend(
- ('error', message)
- for message in _template_lock_errors(specs, structure_lock)
- )
- if (
- locked_mode == 'template'
- and structure_lock.layout_strategy == 'distill'
- and _template_prototype_errors is not None
- ):
- self._pptx_structure_issues.extend(
- ('error', message)
- for message in _template_prototype_errors(specs, structure_lock)
+
+ declared_mode = _declared_pptx_structure_mode(project_path)
+ if standard_project and declared_mode != 'structured':
+ label = repr(declared_mode) if declared_mode else (
+ 'missing (legacy implicit baseline)'
)
- if locked_mode != 'preserve':
+ self._pptx_structure_issues.append((
+ 'error',
+ 'release SVG projects require spec_lock.md '
+ f'pptx_structure.mode: structured; found {label}. Follow '
+ 'skills/ppt-master/workflows/restore-pptx-structure.md before export.',
+ ))
return
- if (
- _load_native_structure_contract is None
- or _native_structure_lock_errors is None
- ):
+
+ try:
+ structure_lock = _load_pptx_structure_lock(project_path)
+ except _TemplateStructureError as exc:
+ self._pptx_structure_issues.append(('error', str(exc)))
+ return
+ if structure_lock is None or structure_lock.mode != 'structured':
self._pptx_structure_issues.append((
'error',
- 'Preserve mode validator could not load the native structure contract.',
+ 'spec_lock.md must contain one complete '
+ 'pptx_structure.mode: structured contract.',
))
return
+ complete_roster = target_path.is_dir()
try:
- contract = _load_native_structure_contract(structure_lock)
+ if not complete_roster and target_path.is_file():
+ sibling_files = sorted(target_path.parent.glob('*.svg'))
+ resolved_target = target_path.resolve()
+ slide_num = next(
+ (
+ index
+ for index, sibling in enumerate(sibling_files, start=1)
+ if sibling.resolve() == resolved_target
+ ),
+ 1,
+ )
+ specs = [
+ _parse_template_structure_slide(target_path, slide_num)
+ ]
+ else:
+ specs = _parse_template_structure_slides(svg_files)
except _TemplateStructureError as exc:
self._pptx_structure_issues.append(('error', str(exc)))
return
- self._pptx_structure_issues.extend(
- ('error', message)
- for message in _native_structure_lock_errors(
- specs,
- structure_lock,
- contract,
+
+ if complete_roster:
+ self._pptx_structure_issues.extend(
+ ('error', message)
+ for message in _template_lock_errors(specs, structure_lock)
+ )
+ else:
+ self._pptx_structure_issues.extend(
+ ('error', message)
+ for message in self._partial_structure_lock_errors(
+ specs,
+ structure_lock,
+ )
)
+ if _template_prototype_errors is not None:
+ self._pptx_structure_issues.extend(
+ ('error', message)
+ for message in _template_prototype_errors(
+ specs,
+ structure_lock,
+ require_complete_roster=complete_roster,
+ )
+ )
+ self._pptx_structure_issues.extend(
+ ('warning', message)
+ for message in self._duplicate_layout_key_warnings(specs)
)
+ @staticmethod
+ def _partial_structure_lock_errors(specs, structure_lock) -> List[str]:
+ """Compare explicitly checked pages without requiring the full roster."""
+ references = {
+ reference.slide_num: reference
+ for reference in structure_lock.layouts
+ }
+ master_names = {
+ master.master_key: master.master_name
+ for master in structure_lock.masters
+ }
+ errors: List[str] = []
+ for spec in specs:
+ page = f"P{spec.slide_num:02d}"
+ reference = references.get(spec.slide_num)
+ if reference is None:
+ errors.append(f"spec_lock.md pptx_layouts is missing {page}")
+ continue
+ if spec.master_key != reference.master_key:
+ errors.append(
+ f"{spec.svg_path.name}: data-pptx-master={spec.master_key!r} "
+ f"does not match spec_lock {page} Master key "
+ f"{reference.master_key!r}"
+ )
+ if spec.layout_key != reference.layout_key:
+ errors.append(
+ f"{spec.svg_path.name}: data-pptx-layout={spec.layout_key!r} "
+ f"does not match spec_lock {page} layout key "
+ f"{reference.layout_key!r}"
+ )
+ if spec.layout_name != reference.layout_name:
+ errors.append(
+ f"{spec.svg_path.name}: data-pptx-layout-name="
+ f"{spec.layout_name!r} does not match spec_lock {page} "
+ f"layout name {reference.layout_name!r}"
+ )
+ expected_master_name = master_names.get(spec.master_key)
+ if expected_master_name != spec.master_name:
+ errors.append(
+ f"{spec.svg_path.name}: data-pptx-master-name="
+ f"{spec.master_name!r} does not match spec_lock Master "
+ f"{spec.master_key!r} name {expected_master_name!r}"
+ )
+ return errors
+
def _duplicate_layout_key_warnings(self, specs) -> List[str]:
"""Flag distinct layout keys whose static contracts are identical.
@@ -2446,17 +2607,23 @@ class SVGQualityChecker:
duplicate PowerPoint Layouts; the fingerprint compares the
id-insensitive layout-layer drawing plus the placeholder contract.
"""
- prototypes: Dict[str, Path] = {}
+ prototypes: Dict[Tuple[str, str], Path] = {}
for spec in specs:
- prototypes.setdefault(spec.layout_key, spec.svg_path)
+ prototypes.setdefault(
+ (getattr(spec, 'master_key', ''), spec.layout_key),
+ spec.svg_path,
+ )
if len(prototypes) < 2:
return []
fingerprint_keys: Dict[tuple, List[str]] = {}
- for layout_key, svg_path in prototypes.items():
+ for (master_key, layout_key), svg_path in prototypes.items():
fingerprint = self._layout_contract_fingerprint(svg_path)
if fingerprint is None:
continue
- fingerprint_keys.setdefault(fingerprint, []).append(layout_key)
+ fingerprint_keys.setdefault(
+ (master_key, fingerprint),
+ [],
+ ).append(layout_key)
messages = []
for keys in fingerprint_keys.values():
if len(keys) < 2:
@@ -2481,7 +2648,6 @@ class SVGQualityChecker:
root = ET.parse(str(svg_path)).getroot()
except (OSError, ET.ParseError):
return None
- layout_kind = (root.get('data-pptx-layout-kind') or '').strip().lower()
layout_parts = []
placeholder_parts = []
for child in list(root):
@@ -2493,25 +2659,24 @@ class SVGQualityChecker:
layout_parts.append(re.sub(r'\s+', ' ', xml).strip())
placeholder = child.get('data-pptx-placeholder')
if placeholder is not None:
- explicit_bounds = child.get('data-pptx-placeholder-bounds') or ''
- fallback_geometry = ()
- if not explicit_bounds and layout_kind != 'distilled':
- fallback_geometry = (
- child.get('data-pptx-text-bounds') or '',
- child.get('x') or '',
- child.get('y') or '',
- child.get('width') or '',
- child.get('height') or '',
- )
+ carrier_tags = tuple(
+ grandchild.tag.rsplit('}', 1)[-1]
+ for grandchild in list(child)
+ if (
+ grandchild.get('data-pptx-placeholder-carrier') or ''
+ ).strip().lower() == 'true'
+ )
placeholder_parts.append((
placeholder,
child.tag.rsplit('}', 1)[-1],
- explicit_bounds,
+ child.get('data-pptx-placeholder-bounds') or '',
child.get('data-pptx-placeholder-idx') or '',
- fallback_geometry,
+ (
+ child.get('data-pptx-placeholder-binding') or 'carrier'
+ ).strip().lower(),
+ carrier_tags,
))
return (
- layout_kind,
tuple(layout_parts),
tuple(sorted(placeholder_parts)),
)
@@ -2616,11 +2781,18 @@ class SVGQualityChecker:
@staticmethod
def _resolve_project_path(dir_path: Path) -> Path:
"""Resolve a checker target directory to its project root."""
- if _project_root_for_svg_path is not None and dir_path.name in _SVG_WORK_DIR_NAMES:
- return _project_root_for_svg_path(dir_path)
- if (dir_path / 'svg_output').exists() or (dir_path / 'design_spec.md').exists():
- return dir_path
- return dir_path.parent
+ candidate = dir_path.parent if dir_path.is_file() else dir_path
+ if (
+ _project_root_for_svg_path is not None
+ and candidate.name in _SVG_WORK_DIR_NAMES
+ ):
+ return _project_root_for_svg_path(candidate)
+ if (
+ (candidate / 'svg_output').exists()
+ or (candidate / 'design_spec.md').exists()
+ ):
+ return candidate
+ return candidate.parent
@staticmethod
def _split_md_table_row(line: str) -> List[str]:
@@ -2931,7 +3103,7 @@ class SVGQualityChecker:
- **Roster mismatch (orphan / missing)** is reported as an *error*: a
stale roster will produce a wrong ``layouts_index.json`` entry.
- **Explicit structure gaps** are errors: every reusable SVG declares
- its Layout and at least one direct structure/placeholder element.
+ its Master and Layout identity. Zero-placeholder Layouts are valid.
- **Placeholder gaps** are reported as *warnings*. Templates may
legitimately omit conventional placeholders or swap them out (e.g.
``{{CLOSING_MESSAGE}}`` instead of ``{{THANK_YOU}}``), and a content
@@ -2944,12 +3116,28 @@ class SVGQualityChecker:
"""
native_contract_path = dir_path / 'native_structure.json'
source_template_path = dir_path / 'source_template.pptx'
- native_contract = None
+ legacy_structure_detected = False
for svg_file in svg_files:
try:
root = ET.parse(svg_file).getroot()
except (OSError, ET.ParseError):
continue
+ if not root.get('data-pptx-master'):
+ legacy_structure_detected = True
+ self._template_issues.append((
+ 'error',
+ 'explicit_master_missing',
+ f"{svg_file.name}: reusable templates require root "
+ "data-pptx-master metadata",
+ ))
+ if not root.get('data-pptx-master-name'):
+ legacy_structure_detected = True
+ self._template_issues.append((
+ 'error',
+ 'explicit_master_name_missing',
+ f"{svg_file.name}: reusable templates require root "
+ "data-pptx-master-name metadata",
+ ))
if not root.get('data-pptx-layout'):
self._template_issues.append((
'error',
@@ -2965,25 +3153,19 @@ class SVGQualityChecker:
"data-pptx-layout-name metadata",
))
if root.get('data-pptx-layout-kind') is not None:
+ legacy_structure_detected = True
self._template_issues.append((
'error',
'deck_instance_layout_kind',
f"{svg_file.name}: reusable template prototypes must omit "
- "data-pptx-layout-kind; downstream completed pages receive "
- "distilled/utility during post-design finalization",
+ "legacy data-pptx-layout-kind metadata",
))
- has_structure_child = any(
- child.get('data-pptx-layer') in {'master', 'layout'}
- or child.get('data-pptx-placeholder')
+ if any(
+ child.get('data-pptx-placeholder') is not None
+ and child.tag.rsplit('}', 1)[-1] != 'g'
for child in list(root)
- )
- if not has_structure_child:
- self._template_issues.append((
- 'error',
- 'explicit_structure_empty',
- f"{svg_file.name}: reusable templates require at least one "
- "direct master/layout/placeholder declaration",
- ))
+ ):
+ legacy_structure_detected = True
missing_bounds = [
child.get('id') or child.tag.rsplit('}', 1)[-1]
for child in list(root)
@@ -2991,91 +3173,23 @@ class SVGQualityChecker:
and child.get('data-pptx-placeholder-bounds') is None
]
if missing_bounds:
+ legacy_structure_detected = True
self._template_issues.append((
- 'warning',
+ 'error',
'placeholder_bounds_missing',
- f"{svg_file.name}: newly created reusable templates require "
+ f"{svg_file.name}: reusable templates require "
"explicit design-zone data-pptx-placeholder-bounds; missing: "
+ ', '.join(missing_bounds),
))
- if native_contract_path.exists() != source_template_path.exists():
+ if native_contract_path.exists() or source_template_path.exists():
+ legacy_structure_detected = True
self._template_issues.append((
'error',
- 'native_structure_pair',
- "native_structure.json and source_template.pptx must be shipped together",
+ 'legacy_native_structure_pair',
+ "legacy native_structure.json/source_template.pptx template "
+ "contracts must be restored through "
+ "skills/ppt-master/workflows/restore-pptx-structure.md",
))
- elif native_contract_path.exists():
- if (
- _PptxStructureLock is None
- or _load_native_structure_contract is None
- or _TemplateStructureError is None
- ):
- self._template_issues.append((
- 'error',
- 'native_structure_validator',
- "native structure validator is unavailable",
- ))
- else:
- try:
- native_contract = _load_native_structure_contract(_PptxStructureLock(
- mode='preserve',
- source_template=source_template_path,
- native_structure=native_contract_path,
- ))
- except _TemplateStructureError as exc:
- self._template_issues.append((
- 'error',
- 'native_structure_invalid',
- str(exc),
- ))
- if (
- native_contract is not None
- and _PptxLayoutReference is not None
- and _parse_preserve_structure_slides is not None
- and _template_lock_errors is not None
- and _native_structure_lock_errors is not None
- ):
- try:
- native_specs = _parse_preserve_structure_slides(svg_files)
- native_layouts = {
- layout.key: layout for layout in native_contract.layouts
- }
- references = tuple(
- _PptxLayoutReference(
- slide_num=spec.slide_num,
- layout_key=spec.layout_key,
- layout_name=(
- native_layouts[spec.layout_key].name
- if spec.layout_key in native_layouts
- else spec.layout_name
- ),
- )
- for spec in native_specs
- )
- native_lock = _PptxStructureLock(
- mode='preserve',
- layouts=references,
- source_template=source_template_path,
- native_structure=native_contract_path,
- )
- native_errors = _template_lock_errors(native_specs, native_lock)
- native_errors.extend(_native_structure_lock_errors(
- native_specs,
- native_lock,
- native_contract,
- ))
- for message in native_errors:
- self._template_issues.append((
- 'error',
- 'native_structure_svg',
- message,
- ))
- except _TemplateStructureError as exc:
- self._template_issues.append((
- 'error',
- 'native_structure_svg',
- str(exc),
- ))
spec_path = dir_path / 'design_spec.md'
spec_text = spec_path.read_text(encoding='utf-8') if spec_path.exists() else ""
@@ -3085,12 +3199,21 @@ class SVGQualityChecker:
re.MULTILINE,
)
declared_structure_mode = mode_match.group(1).lower() if mode_match else None
- if native_contract is None and declared_structure_mode != 'template':
+ if declared_structure_mode != 'structured':
+ legacy_structure_detected = True
self._template_issues.append((
'error',
'explicit_structure_mode',
"design_spec.md frontmatter must declare "
- "native_structure_mode: template",
+ "native_structure_mode: structured",
+ ))
+ if legacy_structure_detected:
+ self._template_issues.append((
+ 'error',
+ 'legacy_structure_contract',
+ "legacy template structure detected; run "
+ "skills/ppt-master/workflows/restore-pptx-structure.md before "
+ "Step 3 consumption",
))
spec_pages = self._extract_spec_roster(spec_text) if spec_text else []
custom_contract = self._extract_frontmatter_placeholders(spec_text) if spec_text else {}
@@ -3464,8 +3587,8 @@ class SVGQualityChecker:
if not errors:
print(" No structural roster issues.")
print(" Conventional placeholder-name hints may be declared through "
- "'placeholders:' frontmatter. Bounds warnings require explicit "
- "design-zone metadata; create-template treats them as blocking.")
+ "'placeholders:' frontmatter. Placeholder bounds are mandatory "
+ "design-zone metadata.")
def _apply_aggregated_issue_counts(self):
"""Mirror project-level aggregate issues into summary counters once."""
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 0a8e3ee5..77f7bce1 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
@@ -101,7 +101,7 @@ from .template_structure import (
TemplateElementSpec,
TemplateSlideSpec,
TemplateStructureError,
- is_composite_distilled_placeholder,
+ is_proxy_placeholder,
match_native_placeholders,
parse_preserve_slides,
parse_template_slides,
@@ -818,24 +818,55 @@ def _create_custom_layout(
base_rels_path.read_text(encoding="utf-8"),
encoding="utf-8",
)
+ master_target = posixpath.relpath(
+ master_part,
+ posixpath.dirname(new_layout_part),
+ )
+ rels_content = new_rels_path.read_text(encoding="utf-8")
+ master_rel_ids = [
+ rel_id
+ for rel_id, attrs in _read_relationships(new_rels_path).items()
+ if attrs.get("Type") == SLIDE_MASTER_REL_TYPE
+ ]
+ if len(master_rel_ids) != 1:
+ raise RuntimeError(
+ f"Cloned slide layout must have one Master relationship: {new_layout_part}"
+ )
+ master_rel_id = master_rel_ids[0]
+ master_rel_pattern = re.compile(
+ rf'(<Relationship\b[^>]*\bId="{re.escape(master_rel_id)}"'
+ rf'[^>]*\bTarget=")[^"]*(")'
+ )
+ rels_content, replaced = master_rel_pattern.subn(
+ rf"\g<1>{master_target}\g<2>",
+ rels_content,
+ count=1,
+ )
+ if replaced != 1:
+ raise RuntimeError(
+ f"Could not retarget cloned Layout to Master {master_part}"
+ )
+ new_rels_path.write_text(rels_content, encoding="utf-8")
master_path = extract_dir / master_part
master_rels_path = _relationships_path_for_part(extract_dir, master_part)
layout_target = posixpath.relpath(new_layout_part, posixpath.dirname(master_part))
rel_id = _append_relationship(master_rels_path, SLIDE_LAYOUT_REL_TYPE, layout_target)
- master_xml = master_path.read_text(encoding="utf-8")
- layout_id = _next_slide_layout_id(extract_dir, master_xml)
- entry = f'<p:sldLayoutId id="{layout_id}" r:id="{rel_id}"/>'
- if "</p:sldLayoutIdLst>" not in master_xml:
+ master_tree = ET.parse(master_path)
+ master_root = master_tree.getroot()
+ layout_list = master_root.find(f"{{{PML_NS}}}sldLayoutIdLst")
+ if layout_list is None:
raise RuntimeError(f"Slide master has no sldLayoutIdLst: {master_part}")
- master_path.write_text(
- master_xml.replace(
- "</p:sldLayoutIdLst>",
- f"{entry}</p:sldLayoutIdLst>",
- 1,
- ),
- encoding="utf-8",
+ layout_id = _next_slide_layout_id(
+ extract_dir,
+ master_path.read_text(encoding="utf-8"),
)
+ ET.SubElement(
+ layout_list,
+ f"{{{PML_NS}}}sldLayoutId",
+ {"id": str(layout_id), f"{{{REL_NS}}}id": rel_id},
+ )
+ _write_xml_tree(master_path, master_tree)
content_types_path = extract_dir / "[Content_Types].xml"
content_types_path.write_text(
@@ -849,8 +880,132 @@ def _create_custom_layout(
return posixpath.relpath(new_layout_part, "ppt/slides"), new_layout_part
+def _set_master_picker_name(master_path: Path, master_name: str) -> None:
+ """Set the visible PowerPoint Master name on its common slide data."""
+ tree = ET.parse(master_path)
+ c_sld = tree.getroot().find(f"{{{PML_NS}}}cSld")
+ if c_sld is None:
+ raise RuntimeError(f"Slide master has no p:cSld: {master_path}")
+ c_sld.set("name", master_name)
+ _write_xml_tree(master_path, tree)
+
+
+def _next_master_part_number(extract_dir: Path) -> int:
+ numbers = [
+ int(match.group(1))
+ for path in (extract_dir / "ppt" / "slideMasters").glob("slideMaster*.xml")
+ if (match := re.fullmatch(r"slideMaster(\d+)\.xml", path.name))
+ ]
+ return max(numbers, default=0) + 1
+
+
+def _clone_structured_master(
+ extract_dir: Path,
+ source_master_part: str,
+ master_name: str,
+) -> str:
+ """Clone a clean Master part and register it with the Presentation."""
+ master_num = _next_master_part_number(extract_dir)
+ master_part = f"ppt/slideMasters/slideMaster{master_num}.xml"
+ master_path = extract_dir / master_part
+ source_master_path = extract_dir / source_master_part
+ shutil.copyfile(source_master_path, master_path)
+
+ tree = ET.parse(master_path)
+ root = tree.getroot()
+ c_sld = root.find(f"{{{PML_NS}}}cSld")
+ if c_sld is None:
+ raise RuntimeError(f"Slide master has no p:cSld: {source_master_part}")
+ c_sld.set("name", master_name)
+ layout_list = root.find(f"{{{PML_NS}}}sldLayoutIdLst")
+ if layout_list is None:
+ raise RuntimeError(
+ f"Slide master has no p:sldLayoutIdLst: {source_master_part}"
+ )
+ for entry in list(layout_list):
+ layout_list.remove(entry)
+ _write_xml_tree(master_path, tree)
+
+ source_rels = _relationships_path_for_part(extract_dir, source_master_part)
+ master_rels = _relationships_path_for_part(extract_dir, master_part)
+ master_rels.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(source_rels, master_rels)
+ for rel_id, attrs in tuple(_read_relationships(master_rels).items()):
+ if attrs.get("Type") == SLIDE_LAYOUT_REL_TYPE:
+ _remove_relationship(master_rels, rel_id)
+
+ presentation_rels = extract_dir / "ppt" / "_rels" / "presentation.xml.rels"
+ relationship_target = posixpath.relpath(master_part, "ppt")
+ relationship_id = _append_relationship(
+ presentation_rels,
+ SLIDE_MASTER_REL_TYPE,
+ relationship_target,
+ )
+ presentation_path = extract_dir / "ppt" / "presentation.xml"
+ presentation_xml = presentation_path.read_text(encoding="utf-8")
+ master_ids = [
+ int(value)
+ for value in re.findall(r'<p:sldMasterId\b[^>]*\bid="(\d+)"', presentation_xml)
+ ]
+ master_id = max(master_ids, default=(1 << 31) - 1) + 1
+ if master_id > OOXML_UINT32_MAX:
+ raise TemplateStructureError("Presentation Master id exceeds OOXML UInt32")
+ entry = f'<p:sldMasterId id="{master_id}" r:id="{relationship_id}"/>'
+ if "</p:sldMasterIdLst>" not in presentation_xml:
+ raise RuntimeError("presentation.xml has no p:sldMasterIdLst")
+ presentation_path.write_text(
+ presentation_xml.replace(
+ "</p:sldMasterIdLst>",
+ f"{entry}</p:sldMasterIdLst>",
+ 1,
+ ),
+ encoding="utf-8",
+ )
+
+ content_types_path = extract_dir / "[Content_Types].xml"
+ content_types_path.write_text(
+ _add_content_type_override(
+ content_types_path.read_text(encoding="utf-8"),
+ master_part,
+ "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml",
+ ),
+ encoding="utf-8",
+ )
+ return master_part
+
+
+def _assign_structured_masters(
+ extract_dir: Path,
+ structure: PptxStructureContext,
+ specs: list[TemplateSlideSpec],
+) -> dict[str, str]:
+ """Create one registered package Master for each explicit SVG Master key."""
+ if not specs:
+ raise TemplateStructureError("Structured export requires at least one slide")
+ source_master = structure.slide_master_part(specs[0].slide_num)
+ masters: dict[str, str] = {}
+ for spec in specs:
+ existing_part = masters.get(spec.master_key)
+ if existing_part is None:
+ if not masters:
+ existing_part = source_master
+ _set_master_picker_name(
+ extract_dir / existing_part,
+ spec.master_name,
+ )
+ else:
+ existing_part = _clone_structured_master(
+ extract_dir,
+ source_master,
+ spec.master_name,
+ )
+ masters[spec.master_key] = existing_part
+ structure.slide_master_parts[spec.slide_num] = existing_part
+ return masters
+
+
def _clear_master_placeholder_shapes(master_path: Path) -> None:
- """Remove base-template placeholders before installing an explicit template."""
+ """Remove base-package placeholders before installing structured content."""
tree = ET.parse(master_path)
root = tree.getroot()
sp_tree = root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
@@ -1305,6 +1460,133 @@ def _template_shape_for_item(
)
+def _shape_transform(shape: ET.Element) -> ET.Element | None:
+ """Return the direct DrawingML transform for one top-level shape."""
+ paths = {
+ f"{{{PML_NS}}}sp": f"{{{PML_NS}}}spPr/{{{DML_NS}}}xfrm",
+ f"{{{PML_NS}}}pic": f"{{{PML_NS}}}spPr/{{{DML_NS}}}xfrm",
+ f"{{{PML_NS}}}cxnSp": f"{{{PML_NS}}}spPr/{{{DML_NS}}}xfrm",
+ f"{{{PML_NS}}}graphicFrame": f"{{{PML_NS}}}xfrm",
+ f"{{{PML_NS}}}grpSp": f"{{{PML_NS}}}grpSpPr/{{{DML_NS}}}xfrm",
+ }
+ path = paths.get(shape.tag)
+ return shape.find(path) if path is not None else None
+
+
+def _int_attr(elem: ET.Element, name: str, context: str) -> int:
+ try:
+ return int(elem.attrib[name])
+ except (KeyError, ValueError) as exc:
+ raise TemplateStructureError(f"{context} has invalid {name!r}") from exc
+
+
+def _flatten_group_transform(
+ group: ET.Element,
+ carrier: ET.Element,
+ *,
+ context: str,
+) -> None:
+ """Map a single group's child transform into slide coordinates."""
+ group_xfrm = _shape_transform(group)
+ carrier_xfrm = _shape_transform(carrier)
+ if group_xfrm is None or carrier_xfrm is None:
+ raise TemplateStructureError(
+ f"{context} cannot be unwrapped because its DrawingML transform is missing"
+ )
+ if any(group_xfrm.get(name) is not None for name in ("rot", "flipH", "flipV")):
+ raise TemplateStructureError(
+ f"{context} wrapper carries an unsupported group rotation or flip"
+ )
+ group_off = group_xfrm.find(f"{{{DML_NS}}}off")
+ group_ext = group_xfrm.find(f"{{{DML_NS}}}ext")
+ child_off = group_xfrm.find(f"{{{DML_NS}}}chOff")
+ child_ext = group_xfrm.find(f"{{{DML_NS}}}chExt")
+ carrier_off = carrier_xfrm.find(f"{{{DML_NS}}}off")
+ carrier_ext = carrier_xfrm.find(f"{{{DML_NS}}}ext")
+ if any(value is None for value in (
+ group_off,
+ group_ext,
+ child_off,
+ child_ext,
+ carrier_off,
+ carrier_ext,
+ )):
+ raise TemplateStructureError(
+ f"{context} cannot be unwrapped because its group transform is incomplete"
+ )
+ child_width = _int_attr(child_ext, "cx", context)
+ child_height = _int_attr(child_ext, "cy", context)
+ if child_width <= 0 or child_height <= 0:
+ raise TemplateStructureError(f"{context} group child extent must be positive")
+ scale_x = _int_attr(group_ext, "cx", context) / child_width
+ scale_y = _int_attr(group_ext, "cy", context) / child_height
+ mapped_x = _int_attr(group_off, "x", context) + round(
+ (_int_attr(carrier_off, "x", context) - _int_attr(child_off, "x", context))
+ * scale_x
+ )
+ mapped_y = _int_attr(group_off, "y", context) + round(
+ (_int_attr(carrier_off, "y", context) - _int_attr(child_off, "y", context))
+ * scale_y
+ )
+ carrier_off.set("x", str(mapped_x))
+ carrier_off.set("y", str(mapped_y))
+ carrier_ext.set(
+ "cx",
+ str(round(_int_attr(carrier_ext, "cx", context) * scale_x)),
+ )
+ carrier_ext.set(
+ "cy",
+ str(round(_int_attr(carrier_ext, "cy", context) * scale_y)),
+ )
+
+
+def _unwrap_placeholder_carrier(
+ state: _TemplateRuntimeSlide,
+ item: TemplateElementSpec,
+) -> ET.Element:
+ """Remove one SVG-only slot wrapper and return its top-level carrier."""
+ wrapper = _template_shape_for_item(state, item)
+ if wrapper is None:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: placeholder {item.element_id!r} cannot "
+ "be a slide background"
+ )
+ if item.tag != "g" or wrapper.tag != f"{{{PML_NS}}}grpSp":
+ return wrapper
+ carriers = [
+ child for child in wrapper if child.tag in _TOP_LEVEL_SHAPE_TAGS
+ ]
+ if len(carriers) != 1:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: placeholder group {item.element_id!r} "
+ f"converted to {len(carriers)} native children; expected one carrier"
+ )
+ carrier = carriers[0]
+ _flatten_group_transform(
+ wrapper,
+ carrier,
+ context=f"{state.spec.svg_path.name} placeholder {item.element_id!r}",
+ )
+ sp_tree = _slide_sp_tree(state)
+ try:
+ wrapper_index = list(sp_tree).index(wrapper)
+ except ValueError as exc:
+ raise TemplateStructureError(
+ f"{state.spec.svg_path.name}: placeholder wrapper "
+ f"{item.element_id!r} is not top-level"
+ ) from exc
+ wrapper.remove(carrier)
+ sp_tree.remove(wrapper)
+ sp_tree.insert(wrapper_index, carrier)
+ wrapper_id = _shape_id(wrapper)
+ carrier_id = _shape_id(carrier)
+ if wrapper_id:
+ state.shapes.pop(wrapper_id, None)
+ if carrier_id:
+ state.shapes[carrier_id] = carrier
+ return carrier
+
+
def _slide_sp_tree(state: _TemplateRuntimeSlide) -> ET.Element:
sp_tree = state.root.find(f".//{{{PML_NS}}}cSld/{{{PML_NS}}}spTree")
if sp_tree is None:
@@ -1923,11 +2205,11 @@ def _layout_placeholder_shape(
return shape
-def _distilled_binding_proxy(
+def _placeholder_binding_proxy(
layout_placeholder: ET.Element,
item: TemplateElementSpec,
) -> ET.Element:
- """Bind a Layout slot invisibly while leaving its visible carrier ordinary.
+ """Bind a Layout slot invisibly while leaving its visible content ordinary.
An unbound object placeholder can leak its inherited empty frame into a
finished Slide in non-PowerPoint renderers. A hidden matching proxy suppresses
@@ -1938,25 +2220,25 @@ def _distilled_binding_proxy(
c_nv_pr = next(proxy.iter(f"{{{PML_NS}}}cNvPr"), None)
if c_nv_pr is None:
raise TemplateStructureError(
- f"Cannot create distilled binding for {item.element_id!r}: "
+ f"Cannot create placeholder binding for {item.element_id!r}: "
"p:cNvPr is missing"
)
placeholder = proxy.find(f".//{{{PML_NS}}}ph")
if placeholder is None:
raise TemplateStructureError(
- f"Cannot create distilled binding for {item.element_id!r}: "
+ f"Cannot create placeholder binding for {item.element_id!r}: "
"p:ph is missing"
)
c_nv_pr.set(
"name",
- "Distilled Binding "
+ "Placeholder Binding "
f"{placeholder.get('type', 'body')} {placeholder.get('idx', '0')}",
)
c_nv_pr.set("hidden", "1")
tx_body = proxy.find(f"{{{PML_NS}}}txBody")
if tx_body is None:
raise TemplateStructureError(
- f"Cannot create distilled binding for {item.element_id!r}: "
+ f"Cannot create placeholder binding for {item.element_id!r}: "
"p:txBody is missing"
)
for child in list(tx_body):
@@ -2077,17 +2359,22 @@ def _apply_explicit_layout_structure(
verbose: bool = False,
) -> tuple[dict[str, str | None], dict[str, tuple[str, ...]]]:
"""Materialize explicit SVG master/layout/placeholder metadata into OOXML."""
+ master_parts_by_key = _assign_structured_masters(
+ extract_dir,
+ structure,
+ specs,
+ )
states = _template_runtime_slides(extract_dir, specs, conversion_traces)
states_by_slide = {state.spec.slide_num: state for state in states}
slide_size_emu = _presentation_slide_size_emu(extract_dir)
- master_items = specs[0].master_elements
expected_backgrounds: dict[str, str | None] = {}
expected_shape_rosters: dict[str, tuple[str, ...]] = {}
states_by_master: dict[str, list[_TemplateRuntimeSlide]] = {}
for state in states:
- master_part = structure.slide_master_part(state.spec.slide_num)
+ master_part = master_parts_by_key[state.spec.master_key]
states_by_master.setdefault(master_part, []).append(state)
+ master_shape_count = 0
for master_part, master_states in states_by_master.items():
master_path = extract_dir / master_part
master_rels_path = _relationships_path_for_part(extract_dir, master_part)
@@ -2095,6 +2382,7 @@ def _apply_explicit_layout_structure(
master_path.read_text(encoding="utf-8")
)
_clear_master_placeholder_shapes(master_path)
+ master_items = master_states[0].spec.master_elements
for item in master_items:
background_xml = _move_template_static_shape(
master_states,
@@ -2105,6 +2393,7 @@ def _apply_explicit_layout_structure(
)
if background_xml is not None:
expected_backgrounds[master_part] = background_xml
+ master_shape_count += 1
specs_by_layout: dict[str, list[TemplateSlideSpec]] = {}
for spec in specs:
@@ -2158,11 +2447,25 @@ def _apply_explicit_layout_structure(
continue
if not item.placeholder:
continue
- prototype_shape = _template_shape_for_item(layout_states[0], item)
- if prototype_shape is None:
- raise TemplateStructureError(
- f"Placeholder {item.element_id!r} cannot be a slide background"
- )
+ proxy_binding = is_proxy_placeholder(item)
+ if proxy_binding:
+ placeholder_shapes = [
+ _template_shape_for_item(state, item)
+ for state in layout_states
+ ]
+ if any(shape is None for shape in placeholder_shapes):
+ raise TemplateStructureError(
+ f"Placeholder {item.element_id!r} cannot be a slide background"
+ )
+ resolved_shapes = [
+ shape for shape in placeholder_shapes if shape is not None
+ ]
+ else:
+ resolved_shapes = [
+ _unwrap_placeholder_carrier(state, item)
+ for state in layout_states
+ ]
+ prototype_shape = resolved_shapes[0]
binding = placeholder_bindings[item.element_id]
assigned_idx = binding.assigned_idx
layout_placeholder = _layout_placeholder_shape(
@@ -2172,37 +2475,26 @@ def _apply_explicit_layout_structure(
theme_font_spec,
)
_append_shape_to_part(layout_path, layout_placeholder)
- for state in layout_states:
- shape = _template_shape_for_item(state, item)
- if shape is None:
- raise TemplateStructureError(
- f"{state.spec.svg_path.name}: placeholder {item.element_id!r} "
- "did not produce a shape"
- )
- composite_distilled_carrier = is_composite_distilled_placeholder(
- item,
- prototype.layout_kind,
- )
- if not composite_distilled_carrier:
+ for state, shape in zip(layout_states, resolved_shapes):
+ if not proxy_binding:
_patch_slide_placeholder(
shape,
item,
assigned_idx,
theme_font_spec=theme_font_spec,
)
- if prototype.layout_kind == "distilled":
- _set_shape_name(
- shape,
- f"{item.element_id} Distilled Carrier",
- )
+ _set_shape_name(
+ shape,
+ f"{item.element_id} Placeholder Carrier",
+ )
else:
_set_shape_name(
shape,
- f"{item.element_id} Distilled Carrier",
+ f"{item.element_id} Proxy Content",
)
_append_shape_to_runtime_slide(
state,
- _distilled_binding_proxy(layout_placeholder, item),
+ _placeholder_binding_proxy(layout_placeholder, item),
)
placeholder_count += 1
@@ -2241,8 +2533,9 @@ def _apply_explicit_layout_structure(
if verbose:
print(
" Explicit Layout structure: "
+ f"{len(states_by_master)} master(s), "
f"{len(specs_by_layout)} layout(s), "
- f"{len(master_items)} master element(s), "
+ f"{master_shape_count} master element(s), "
f"{layout_shape_count} layout element(s), "
f"{len(slide_backgrounds)} slide background(s), "
f"{placeholder_count} placeholder definition(s)"
@@ -3545,7 +3838,7 @@ def create_pptx_with_native_svg(
native_objects: bool = False,
conversion_trace_path: Path | None = None,
doc_metadata: dict[str, Any] | None = None,
- pptx_structure: str = "baseline",
+ pptx_structure: str = "structured",
native_structure_contract: NativeStructureContract | None = None,
theme_font_spec: ThemeFontSpec | None = None,
master_text_style_spec: MasterTextStyleSpec | None = None,
@@ -3593,26 +3886,21 @@ def create_pptx_with_native_svg(
then extracts semantic page-role layout families and exact
family-wide structurally marked leading chrome; marker-free legacy
SVGs retain filename/id fallback;
- ``template`` consumes explicit SVG master/layout/placeholder
+ ``structured`` consumes explicit SVG master/layout/placeholder
metadata; ``preserve`` reuses an imported source PPTX package;
``flat`` keeps generated structure slide-local.
native_structure_contract: Validated source package contract for
``preserve`` mode.
- theme_font_spec: Locked project major/minor fonts for baseline/template
+ theme_font_spec: Locked project major/minor fonts for baseline/structured
theme inheritance. Preserve and flat modes ignore this value.
- master_text_style_spec: Required locked title/body sizes for template
- and structured-baseline slide-master text styles. Other structure
+ master_text_style_spec: Required locked title/body sizes for structured
+ slide-master text styles. Other structure
routes ignore this value.
theme_color_spec: Locked project color scheme for context-aware
- baseline/template theme inheritance. Preserve and flat modes
+ baseline/structured theme inheritance. Preserve and flat modes
ignore this value.
- structured_baseline: Explicitly route a baseline/free-design deck
- through the reusable Layout compiler. This is an all-or-none
- route selected by the project contract, never inferred here from
- visual similarity or root metadata.
- baseline_layout_specs: Fully parsed explicit Layout contracts for a
- structured baseline deck. Required exactly when
- ``structured_baseline`` is true.
+ structured_baseline: Obsolete compatibility argument; must remain false.
+ baseline_layout_specs: Obsolete compatibility argument; must remain None.
Returns:
Whether all slides were successfully created.
@@ -3627,46 +3915,23 @@ def create_pptx_with_native_svg(
return False
use_compat_mode = False
- if pptx_structure not in {"baseline", "template", "preserve", "flat"}:
+ if pptx_structure not in {"baseline", "structured", "preserve", "flat"}:
raise ValueError(f"Unsupported pptx_structure: {pptx_structure}")
- if structured_baseline and pptx_structure != "baseline":
+ if structured_baseline:
raise ValueError(
- "structured_baseline is available only with pptx_structure='baseline'"
+ "structured_baseline is obsolete; use pptx_structure='structured'"
)
- if structured_baseline:
- if not baseline_layout_specs:
- raise TemplateStructureError(
- "Structured baseline export requires explicit Layout specs for every slide"
- )
- expected_slide_nums = list(range(1, len(svg_files) + 1))
- actual_slide_nums = [spec.slide_num for spec in baseline_layout_specs]
- if actual_slide_nums != expected_slide_nums:
- raise TemplateStructureError(
- "Structured baseline Layout specs must cover every generated slide "
- "exactly once in slide order"
- )
- actual_paths = [spec.svg_path.resolve() for spec in baseline_layout_specs]
- expected_paths = [svg_path.resolve() for svg_path in svg_files]
- if actual_paths != expected_paths:
- raise TemplateStructureError(
- "Structured baseline Layout specs do not match the generated SVG files"
- )
- elif baseline_layout_specs is not None:
+ if baseline_layout_specs is not None:
raise ValueError(
- "baseline_layout_specs requires structured_baseline=True"
+ "baseline_layout_specs is obsolete; structured export parses SVG metadata"
)
- if (
- pptx_structure == "template" or structured_baseline
- ) and master_text_style_spec is None:
- context = "Structured baseline" if structured_baseline else "Template"
+ if pptx_structure == "structured" and master_text_style_spec is None:
raise ValueError(
- f"{context} export requires locked typography title/body sizes "
+ "Structured export requires locked typography title/body sizes "
"in master_text_style_spec"
)
- if use_native_shapes and pptx_structure == "template":
+ if use_native_shapes and pptx_structure == "structured":
template_specs = parse_template_slides(svg_files)
- elif use_native_shapes and structured_baseline:
- template_specs = baseline_layout_specs
elif use_native_shapes and pptx_structure == "preserve":
if native_structure_contract is None:
raise TemplateStructureError(
@@ -3691,9 +3956,7 @@ def create_pptx_with_native_svg(
if native_placeholders:
kinds = ", ".join(str(kind) for kind in native_placeholders)
context = (
- "Structured baseline"
- if structured_baseline
- else pptx_structure.capitalize()
+ pptx_structure.capitalize()
)
raise TemplateStructureError(
f"{context} {kinds} placeholder(s) require --native-objects so each "
@@ -3738,12 +4001,7 @@ def create_pptx_with_native_svg(
" Native table/chart objects: "
f"{'Enabled' if native_objects else 'Disabled'}"
)
- structure_label = (
- "baseline (explicit layouts)"
- if structured_baseline
- else pptx_structure
- )
- print(f" PPTX structure: {structure_label}")
+ print(f" PPTX structure: {pptx_structure}")
if image_optimize:
if image_sizing == 'display':
image_mode = (
@@ -3811,35 +4069,18 @@ def create_pptx_with_native_svg(
_clear_preserved_slide_collections(extract_dir)
active_theme_font_spec = (
theme_font_spec
- if use_native_shapes and pptx_structure in {"baseline", "template"}
+ if use_native_shapes and pptx_structure in {"baseline", "structured"}
else None
)
if active_theme_font_spec is not None:
apply_theme_font_spec(extract_dir, active_theme_font_spec)
active_theme_color_spec = (
theme_color_spec
- if use_native_shapes and pptx_structure in {"baseline", "template"}
+ if use_native_shapes and pptx_structure in {"baseline", "structured"}
else None
)
if active_theme_color_spec is not None:
apply_theme_color_spec(extract_dir, active_theme_color_spec)
- if pptx_structure == "template" or structured_baseline:
- master_count = apply_master_text_style_spec(
- extract_dir,
- master_text_style_spec,
- )
- if verbose:
- context = (
- "Structured baseline"
- if structured_baseline
- else "Template"
- )
- print(
- f" {context} master text styles: "
- f"{master_count} master(s), "
- f"title {master_text_style_spec.title_hpt / 100:g}pt, "
- f"body {master_text_style_spec.body_hpt / 100:g}pt"
- )
structure = _read_slide_layout_targets(extract_dir, len(svg_files))
media_dir = extract_dir / 'ppt' / 'media'
@@ -3890,7 +4131,7 @@ def create_pptx_with_native_svg(
)
structure_trace: list[dict[str, Any]] | None = (
runtime_trace
- if use_native_shapes and pptx_structure in {"baseline", "template", "preserve"}
+ if use_native_shapes and pptx_structure in {"baseline", "structured", "preserve"}
else None
)
@@ -4323,55 +4564,34 @@ def create_pptx_with_native_svg(
extract_dir,
len(svg_files),
conversion_trace if conversion_trace is not None else structure_trace,
- context=(
- "Structured baseline"
- if structured_baseline
- else "Baseline"
- ),
+ context="Baseline",
+ verbose=verbose,
+ )
+ _promote_common_slide_backgrounds_to_masters(
+ extract_dir,
+ structure,
+ len(svg_files),
+ verbose=verbose,
+ )
+ _promote_common_chrome_shapes_to_masters(
+ extract_dir,
+ structure,
+ len(svg_files),
+ conversion_trace if conversion_trace is not None else structure_trace,
+ verbose=verbose,
+ )
+ _extract_baseline_layout_families(
+ extract_dir,
+ structure,
+ svg_files,
+ verbose=verbose,
+ )
+ _promote_common_chrome_shapes_to_layouts(
+ extract_dir,
+ len(svg_files),
+ conversion_trace if conversion_trace is not None else structure_trace,
verbose=verbose,
)
- if structured_baseline:
- if template_specs is None:
- raise TemplateStructureError(
- "Structured baseline metadata was not parsed before export"
- )
- (
- template_background_expectations,
- template_shape_roster_expectations,
- ) = _apply_explicit_layout_structure(
- extract_dir,
- structure,
- template_specs,
- conversion_trace if conversion_trace is not None else structure_trace,
- active_theme_font_spec,
- verbose=verbose,
- )
- else:
- _promote_common_slide_backgrounds_to_masters(
- extract_dir,
- structure,
- len(svg_files),
- verbose=verbose,
- )
- _promote_common_chrome_shapes_to_masters(
- extract_dir,
- structure,
- len(svg_files),
- conversion_trace if conversion_trace is not None else structure_trace,
- verbose=verbose,
- )
- _extract_baseline_layout_families(
- extract_dir,
- structure,
- svg_files,
- verbose=verbose,
- )
- _promote_common_chrome_shapes_to_layouts(
- extract_dir,
- len(svg_files),
- conversion_trace if conversion_trace is not None else structure_trace,
- verbose=verbose,
- )
_prune_unused_slide_layouts(
extract_dir,
structure,
@@ -4381,19 +4601,19 @@ def create_pptx_with_native_svg(
if (
use_native_shapes
- and pptx_structure == "template"
+ and pptx_structure == "structured"
and success_count == len(svg_files)
):
_convert_page_number_texts_to_fields(
extract_dir,
len(svg_files),
conversion_trace if conversion_trace is not None else structure_trace,
- context="Template",
+ context="Structured",
verbose=verbose,
)
if template_specs is None:
raise TemplateStructureError(
- "Template structure metadata was not parsed before export"
+ "Structured metadata was not parsed before export"
)
(
template_background_expectations,
@@ -4406,6 +4626,17 @@ def create_pptx_with_native_svg(
active_theme_font_spec,
verbose=verbose,
)
+ master_count = apply_master_text_style_spec(
+ extract_dir,
+ master_text_style_spec,
+ )
+ if verbose:
+ print(
+ " Structured master text styles: "
+ f"{master_count} master(s), "
+ f"title {master_text_style_spec.title_hpt / 100:g}pt, "
+ f"body {master_text_style_spec.body_hpt / 100:g}pt"
+ )
_prune_unused_slide_layouts(
extract_dir,
structure,
@@ -4528,7 +4759,7 @@ def create_pptx_with_native_svg(
zf.write(file_path, arcname)
if (
use_native_shapes
- and (pptx_structure == "template" or structured_baseline)
+ and pptx_structure == "structured"
and success_count == len(svg_files)
):
if template_specs is None:
@@ -4543,13 +4774,8 @@ def create_pptx_with_native_svg(
expected_shape_rosters=template_shape_roster_expectations,
)
except ValueError as exc:
- context = (
- "Structured baseline"
- if structured_baseline
- else "Template"
- )
raise TemplateStructureError(
- f"PPTX {context.lower()} package validation failed: {exc}"
+ f"PPTX structured package validation failed: {exc}"
) from exc
try:
validate_pptx_transition_package(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
index 8b416b08..836261e7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import sys
import json
import math
+import re
import shutil
import argparse
from datetime import datetime
@@ -48,11 +49,7 @@ from .narration import NARRATION_EXTENSIONS, find_narration_files, probe_audio_d
from .slide_xml import TRANSITIONS
from .template_structure import (
TemplateStructureError,
- load_native_structure_contract,
load_pptx_structure_lock,
- native_structure_lock_errors,
- parse_optional_layout_slides,
- parse_preserve_slides,
parse_template_slides,
template_lock_errors,
template_prototype_errors,
@@ -69,6 +66,50 @@ def _as_dict(value: object) -> dict:
return value if isinstance(value, dict) else {}
+_PPTX_STRUCTURE_SECTION_RE = re.compile(
+ r"(?ms)^##[ \t]+pptx_structure[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
+)
+_PPTX_STRUCTURE_MODE_RE = re.compile(
+ r"(?m)^-[ \t]+mode[ \t]*:[ \t]*([^\s#]+)[ \t]*(?:#.*)?$"
+)
+_LEGACY_PPTX_STRUCTURE_MODES = frozenset({
+ 'baseline',
+ 'generated',
+ 'preserve',
+ 'template',
+})
+
+
+def _declared_pptx_structure_mode(project_path: Path) -> str | None:
+ """Return the explicitly locked SVG export mode, without legacy fallback."""
+ lock_path = project_path / 'spec_lock.md'
+ try:
+ content = lock_path.read_text(encoding='utf-8')
+ except OSError:
+ return None
+ section_match = _PPTX_STRUCTURE_SECTION_RE.search(content)
+ if section_match is None:
+ return None
+ mode_match = _PPTX_STRUCTURE_MODE_RE.search(section_match.group(1))
+ return mode_match.group(1).strip().lower() if mode_match else None
+
+
+def _print_structure_migration_error(mode: str | None) -> None:
+ """Explain how a legacy or absent SVG structure contract is restored."""
+ label = repr(mode) if mode else 'missing (legacy implicit baseline)'
+ print(
+ "Error: release SVG export requires spec_lock.md "
+ "pptx_structure.mode: structured; found " + label + ".",
+ file=sys.stderr,
+ )
+ print(
+ " Restore explicit Master/Layout metadata first by following "
+ "skills/ppt-master/workflows/restore-pptx-structure.md, then rerun "
+ "the quality gate and export.",
+ file=sys.stderr,
+ )
+
+
def _native_object_fallbacks(svg_files: list[Path]) -> list[tuple[str, str, str]]:
"""Return fallback-only native object statuses from SVG inputs."""
fallbacks: list[tuple[str, str, str]] = []
@@ -269,20 +310,22 @@ Recorded narration:
'to tell it apart from a plain shape export.')
parser.add_argument(
'--pptx-structure',
- choices=['baseline', 'template', 'preserve', 'flat'],
+ choices=[
+ 'structured',
+ 'flat',
+ 'baseline',
+ 'template',
+ 'preserve',
+ 'generated',
+ ],
default=None,
help=(
- 'PPTX structure strategy for native export. When omitted, read '
- 'spec_lock.md pptx_structure.mode, falling back to baseline. baseline '
- 'compiles an all-page explicit Layout contract when pptx_layouts and '
- 'matching SVG metadata are present; otherwise it promotes safe repeated '
- 'background/chrome and extracts conservative semantic page-role layout '
- 'families (legacy filenames/ids remain fallbacks); '
- 'template consumes finalized explicit '
- 'data-pptx-layout/layer/placeholder metadata to build reusable layouts '
- '(a deferred page_layouts prototype contract must be distilled first); '
- 'preserve is legacy compatibility for imported source packages; '
- 'flat leaves generated structure slide-local for debugging/comparison.'
+ 'PPTX structure strategy for native export. Release export requires '
+ 'spec_lock.md pptx_structure.mode: structured and complete explicit '
+ 'Master/Layout metadata in every SVG. flat is an explicit diagnostic '
+ 'override that leaves all generated objects slide-local. baseline, '
+ 'template, preserve, and generated are accepted only so legacy '
+ 'invocations can receive a targeted migration error.'
),
)
parser.add_argument('--no-image-optimize', action='store_true',
@@ -367,50 +410,44 @@ Recorded narration:
if not project_path.exists():
print(f"Error: Path does not exist: {project_path}")
return 1
+
structure_lock = None
native_structure_contract = None
pptx_structure = args.pptx_structure
- if pptx_structure is None or pptx_structure in {'template', 'preserve'}:
+ declared_structure_mode = _declared_pptx_structure_mode(project_path)
+ if pptx_structure in _LEGACY_PPTX_STRUCTURE_MODES:
+ _print_structure_migration_error(pptx_structure)
+ return 1
+ if pptx_structure is None:
+ if declared_structure_mode != 'structured':
+ _print_structure_migration_error(declared_structure_mode)
+ return 1
+ pptx_structure = 'structured'
+ elif pptx_structure == 'structured' and declared_structure_mode != 'structured':
+ _print_structure_migration_error(declared_structure_mode)
+ return 1
+
+ if pptx_structure == 'structured':
try:
structure_lock = load_pptx_structure_lock(project_path)
except TemplateStructureError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
- if pptx_structure is None:
- pptx_structure = structure_lock.mode if structure_lock else 'baseline'
- elif (
- pptx_structure == 'template'
- and structure_lock is not None
- and structure_lock.mode != 'template'
- ):
- # Keep the explicit diagnostic override for non-template projects, but
- # never detach a real template project from its pending/ready lock.
- structure_lock = None
- elif pptx_structure == 'preserve':
- if structure_lock is None or structure_lock.mode != 'preserve':
+ if structure_lock is None or structure_lock.mode != 'structured':
print(
- "Error: --pptx-structure preserve requires a preserve-mode "
- "spec_lock.md with source_template/native_structure rows",
+ "Error: spec_lock.md must contain one complete "
+ "pptx_structure.mode: structured contract",
file=sys.stderr,
)
return 1
- if pptx_structure == 'preserve':
- if structure_lock is None:
- print("Error: preserve mode requires spec_lock.md", file=sys.stderr)
- return 1
- try:
- native_structure_contract = load_native_structure_contract(structure_lock)
- except TemplateStructureError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
+
theme_font_spec = None
master_text_style_spec = None
theme_color_spec = None
- if pptx_structure in {'baseline', 'template'}:
+ if pptx_structure == 'structured':
try:
theme_font_spec = load_theme_font_spec(project_path)
- if pptx_structure == 'template':
- master_text_style_spec = load_master_text_style_spec(project_path)
+ master_text_style_spec = load_master_text_style_spec(project_path)
theme_color_spec = load_theme_color_spec(project_path)
except (ThemeFontError, ThemeColorError) as exc:
print(f"Error: {exc}", file=sys.stderr)
@@ -446,104 +483,13 @@ Recorded narration:
print("Error: No SVG files found")
return 1
+ # Compatibility kwargs remain until the builder's old baseline-specific
+ # parameters are removed. Structured export never activates either path.
structured_baseline = False
baseline_layout_specs = None
- if pptx_structure == 'baseline':
- try:
- baseline_layout_specs = parse_optional_layout_slides(native_files)
- except TemplateStructureError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
-
- if structure_lock is None:
- if baseline_layout_specs is not None:
- try:
- structure_lock = load_pptx_structure_lock(project_path)
- except TemplateStructureError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
- elif args.pptx_structure == 'baseline':
- # A diagnostic baseline override may bypass a stale or damaged
- # template/preserve lock. A valid baseline lock remains
- # authoritative, so its pptx_layouts mapping cannot be silently
- # downgraded to the unmapped page-role route.
- try:
- candidate_lock = load_pptx_structure_lock(project_path)
- except TemplateStructureError:
- candidate_lock = None
- if candidate_lock is not None and candidate_lock.mode == 'baseline':
- structure_lock = candidate_lock
-
- locked_layouts = structure_lock.layouts if structure_lock is not None else ()
- if (
- structure_lock is not None
- and structure_lock.layout_strategy == 'distill'
- and (baseline_layout_specs is None or not locked_layouts)
- ):
- print(
- "Error: post-design Layout distillation is incomplete; add a "
- "complete spec_lock.md pptx_layouts mapping and matching "
- "data-pptx-layout metadata before export",
- file=sys.stderr,
- )
- return 1
- if baseline_layout_specs is None:
- if locked_layouts:
- print(
- "Error: spec_lock.md pptx_layouts requires every baseline SVG "
- "root to declare data-pptx-layout and data-pptx-layout-name",
- file=sys.stderr,
- )
- return 1
- else:
- if not locked_layouts or structure_lock is None:
- print(
- "Error: explicit baseline Layout metadata requires a complete "
- "spec_lock.md pptx_layouts mapping",
- file=sys.stderr,
- )
- return 1
- lock_errors = template_lock_errors(
- baseline_layout_specs,
- structure_lock,
- )
- if lock_errors:
- print(
- "Error: PPTX structure does not match spec_lock.md:",
- file=sys.stderr,
- )
- for message in lock_errors:
- print(f" {message}", file=sys.stderr)
- return 1
- structured_baseline = True
- try:
- master_text_style_spec = load_master_text_style_spec(project_path)
- except ThemeFontError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
-
- if (
- pptx_structure in {'template', 'preserve'}
- and structure_lock is not None
- ):
- if (
- pptx_structure == 'template'
- and structure_lock.layout_strategy == 'distill'
- and not structure_lock.layouts
- ):
- print(
- "Error: template Layout distillation is still pending; run the "
- "distill-layouts workflow to write the complete pptx_layouts "
- "mapping and final SVG Layout metadata before export",
- file=sys.stderr,
- )
- return 1
+ if pptx_structure == 'structured' and structure_lock is not None:
try:
- template_specs = (
- parse_preserve_slides(native_files)
- if pptx_structure == 'preserve'
- else parse_template_slides(native_files)
- )
+ template_specs = parse_template_slides(native_files)
except TemplateStructureError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
@@ -559,30 +505,13 @@ Recorded narration:
)
if prototype_errors:
print(
- "Error: distilled template structure does not match page_layouts "
+ "Error: structured template output does not match page_layouts "
"prototypes:",
file=sys.stderr,
)
for message in prototype_errors:
print(f" {message}", file=sys.stderr)
return 1
- if pptx_structure == 'preserve':
- if native_structure_contract is None:
- print("Error: preserve mode contract is unavailable", file=sys.stderr)
- return 1
- preserve_errors = native_structure_lock_errors(
- template_specs,
- structure_lock,
- native_structure_contract,
- )
- if preserve_errors:
- print(
- "Error: PPTX structure does not match native_structure.json:",
- file=sys.stderr,
- )
- for message in preserve_errors:
- print(f" {message}", file=sys.stderr)
- return 1
release_blocked = _release_blocked_graphics(native_files)
if release_blocked:
@@ -992,26 +921,6 @@ Recorded narration:
print(f" [warn] svg_output backup skipped: {exc}")
elif verbose:
print(f" [info] svg_output/ not found, backup skipped")
- if pptx_structure == 'preserve' and structure_lock is not None:
- try:
- preserve_sources = [
- project_path / 'spec_lock.md',
- structure_lock.source_template,
- structure_lock.native_structure,
- ]
- for source in preserve_sources:
- if source is None or not source.is_file():
- continue
- source_path = source.resolve()
- relative = source_path.relative_to(project_path.resolve())
- destination = backup_dir / relative
- destination.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source_path, destination)
- if verbose:
- print(f" preserve contract backup: {backup_dir}")
- except (OSError, ValueError) as exc:
- if verbose:
- print(f" [warn] preserve contract backup skipped: {exc}")
return 0 if success else 1
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 0d66d953..a9b9295d 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
@@ -38,8 +38,12 @@ _STRUCTURE_ATTRS = frozenset({
"data-pptx-layout",
"data-pptx-layout-kind",
"data-pptx-layout-name",
+ "data-pptx-master",
+ "data-pptx-master-name",
"data-pptx-placeholder",
+ "data-pptx-placeholder-binding",
"data-pptx-placeholder-bounds",
+ "data-pptx-placeholder-carrier",
"data-pptx-placeholder-idx",
"data-pptx-editable",
})
@@ -88,14 +92,18 @@ _OBJECT_PLACEHOLDER_TAGS = frozenset({
"polyline",
"text",
"image",
+ "svg",
+ "use",
})
_LAYOUT_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
-_LOCK_ROW_RE = re.compile(r"^-\s+([A-Za-z0-9_]+)\s*:\s*(.+?)\s*$")
+_MASTER_KEY_RE = _LAYOUT_KEY_RE
+_LOCK_ROW_RE = re.compile(
+ r"^-\s+([A-Za-z0-9][A-Za-z0-9._-]*)\s*:\s*(.+?)\s*$"
+)
_LOCK_PAGE_RE = re.compile(r"^P(\d+)$")
-PPTX_STRUCTURE_MODES = frozenset({"baseline", "template", "preserve", "flat"})
+PPTX_STRUCTURE_MODES = frozenset({"structured", "preserve", "flat"})
TEMPLATE_ADHERENCE_MODES = frozenset({"strict", "adaptive"})
-LAYOUT_STRATEGIES = frozenset({"distill"})
-DISTILLED_LAYOUT_KINDS = frozenset({"distilled", "utility"})
+PLACEHOLDER_BINDING_MODES = frozenset({"carrier", "proxy"})
_TEMPLATE_SKIN_ATTRS = frozenset({
"color",
"fill",
@@ -147,7 +155,15 @@ class PptxLayoutReference:
slide_num: int
layout_key: str
layout_name: str | None = None
- layout_kind: str | None = None
+ master_key: str | None = None
+
+
+@dataclass(frozen=True)
+class PptxMasterReference:
+ """One named Master declared by the structured project lock."""
+
+ master_key: str
+ master_name: str
@dataclass(frozen=True)
@@ -166,11 +182,11 @@ class PptxStructureLock:
mode: str
template_adherence: str | None = None
+ masters: tuple[PptxMasterReference, ...] = ()
layouts: tuple[PptxLayoutReference, ...] = ()
prototypes: tuple[PptxPrototypeReference, ...] = ()
source_template: Path | None = None
native_structure: Path | None = None
- layout_strategy: str | None = None
@dataclass(frozen=True)
@@ -224,6 +240,8 @@ class TemplateElementSpec:
placeholder: str | None = None
placeholder_bounds: tuple[float, float, float, float] | None = None
placeholder_idx: int | None = None
+ placeholder_binding: str | None = None
+ placeholder_carrier_tag: str | None = None
is_background: bool = False
def contract_signature(self) -> tuple[object, ...]:
@@ -235,6 +253,8 @@ class TemplateElementSpec:
self.placeholder,
self.placeholder_bounds,
self.placeholder_idx,
+ self.placeholder_binding,
+ self.placeholder_carrier_tag,
self.is_background,
)
@@ -245,10 +265,11 @@ class TemplateSlideSpec:
slide_num: int
svg_path: Path
+ master_key: str
+ master_name: str
layout_key: str
layout_name: str
elements: tuple[TemplateElementSpec, ...]
- layout_kind: str | None = None
@property
def master_elements(self) -> tuple[TemplateElementSpec, ...]:
@@ -271,29 +292,9 @@ class TemplateSlideSpec:
)
-def _is_composite_distilled_placeholder_contract(
- tag: str,
- placeholder: str | None,
- layout_kind: str | None,
-) -> bool:
- """Return whether raw SVG metadata declares a composite region proxy."""
- return (
- layout_kind == "distilled"
- and tag == "g"
- and placeholder == "object"
- )
-
-
-def is_composite_distilled_placeholder(
- item: TemplateElementSpec,
- layout_kind: str | None,
-) -> bool:
- """Return the single parsed-contract predicate for a composite region proxy."""
- return _is_composite_distilled_placeholder_contract(
- item.tag,
- item.placeholder,
- layout_kind,
- )
+def is_proxy_placeholder(item: TemplateElementSpec) -> bool:
+ """Return whether a visible composite slot uses an invisible binding proxy."""
+ return item.placeholder_binding == "proxy"
@dataclass(frozen=True)
@@ -499,6 +500,7 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
continue
if current_section not in {
"pptx_structure",
+ "pptx_masters",
"pptx_layouts",
"page_layouts",
}:
@@ -508,16 +510,20 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
sections[current_section].append((match.group(1), match.group(2)))
structure_rows = sections.get("pptx_structure", [])
+ master_rows = sections.get("pptx_masters", [])
layout_rows = sections.get("pptx_layouts", [])
prototype_rows = sections.get("page_layouts", [])
structure_section_present = "pptx_structure" in sections
+ master_section_present = "pptx_masters" in sections
layout_section_present = "pptx_layouts" in sections
prototype_section_present = "page_layouts" in sections
if (
not structure_rows
+ and not master_rows
and not layout_rows
and not prototype_rows
and not structure_section_present
+ and not master_section_present
and not layout_section_present
and not prototype_section_present
):
@@ -554,30 +560,17 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
if mode == "preserve" and template_adherence == "adaptive":
raise TemplateStructureError(
"spec_lock.md preserve mode requires template_adherence: strict; "
- "adaptive template use must export through template mode"
+ "adaptive template use must export through structured mode"
)
-
- strategy_rows = [
- value.strip().lower()
- for key, value in structure_rows
- if key == "layout_strategy"
- ]
- if len(strategy_rows) > 1:
+ if template_adherence and mode not in {"structured", "preserve"}:
raise TemplateStructureError(
- "spec_lock.md pptx_structure allows at most one "
- "'- layout_strategy:' row"
- )
- layout_strategy = strategy_rows[0] if strategy_rows else None
- if layout_strategy and layout_strategy not in LAYOUT_STRATEGIES:
- allowed = ", ".join(sorted(LAYOUT_STRATEGIES))
- raise TemplateStructureError(
- "spec_lock.md pptx_structure.layout_strategy must be one of: "
- f"{allowed}"
+ "spec_lock.md template_adherence is allowed only in structured or "
+ "preserve mode"
)
- if layout_strategy and mode not in {"baseline", "template"}:
+ if any(key == "layout_strategy" for key, _value in structure_rows):
raise TemplateStructureError(
- "spec_lock.md pptx_structure.layout_strategy is allowed only when "
- "mode is baseline or template"
+ "spec_lock.md pptx_structure.layout_strategy is obsolete; SVG pages "
+ "must declare their final structured Master/Layout contract directly"
)
source_rows = [
@@ -612,21 +605,47 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
"when pptx_structure.mode is preserve"
)
+ masters: list[PptxMasterReference] = []
+ seen_master_keys: set[str] = set()
+ for master_key, raw_name in master_rows:
+ master_name = raw_name.strip()
+ if not _MASTER_KEY_RE.fullmatch(master_key):
+ raise TemplateStructureError(
+ f"spec_lock.md has invalid Master key {master_key!r}; use 1-64 "
+ "ASCII letters, digits, dots, underscores, or hyphens"
+ )
+ if master_key in seen_master_keys:
+ raise TemplateStructureError(
+ f"spec_lock.md pptx_masters repeats Master key {master_key!r}"
+ )
+ if not master_name:
+ raise TemplateStructureError(
+ f"spec_lock.md Master {master_key!r} has an empty name"
+ )
+ seen_master_keys.add(master_key)
+ masters.append(PptxMasterReference(master_key, master_name))
+
+ if mode == "structured":
+ if not master_rows:
+ raise TemplateStructureError(
+ "spec_lock.md structured mode requires a non-empty pptx_masters section"
+ )
+ elif master_section_present:
+ raise TemplateStructureError(
+ "spec_lock.md pptx_masters is allowed only when "
+ "pptx_structure.mode is structured"
+ )
+
prototypes: list[PptxPrototypeReference] = []
seen_prototype_slides: set[int] = set()
template_dir = (project_path / "templates").resolve()
template_replication_mode = _template_replication_mode(template_dir)
- if mode != "template" and prototype_rows:
+ if mode != "structured" and prototype_rows:
raise TemplateStructureError(
"spec_lock.md page_layouts is allowed only when pptx_structure.mode "
- "is template"
+ "is structured"
)
- parsed_prototype_rows = (
- prototype_rows
- if mode == "template" and layout_strategy == "distill"
- else []
- )
- for page_key, raw_value in parsed_prototype_rows:
+ for page_key, raw_value in prototype_rows:
page_match = _LOCK_PAGE_RE.fullmatch(page_key)
if not page_match or int(page_match.group(1)) <= 0:
raise TemplateStructureError(
@@ -668,9 +687,13 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
replication_mode=template_replication_mode,
))
- if mode == "template" and layout_strategy == "distill" and not prototypes:
+ if mode == "structured" and template_adherence and not prototypes:
+ raise TemplateStructureError(
+ "spec_lock.md structured template use requires one page_layouts row per page"
+ )
+ if prototypes and not template_adherence:
raise TemplateStructureError(
- "spec_lock.md template mode requires one page_layouts row per page"
+ "spec_lock.md page_layouts requires template_adherence: strict or adaptive"
)
references: list[PptxLayoutReference] = []
@@ -687,130 +710,75 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
f"spec_lock.md pptx_layouts repeats page P{slide_num:02d}"
)
seen_slides.add(slide_num)
- layout_key, separator, remainder = raw_value.partition("|")
- layout_key = layout_key.strip()
- layout_name = remainder.strip() if separator else None
- layout_kind = None
- if layout_strategy == "distill" and separator:
- name_part, kind_separator, kind_part = remainder.rpartition("|")
- if kind_separator:
- layout_name = name_part.strip()
- layout_kind = kind_part.strip().lower()
+ parts = [part.strip() for part in raw_value.split("|")]
+ master_key: str | None = None
+ if mode == "structured":
+ if len(parts) != 3 or not all(parts):
+ raise TemplateStructureError(
+ f"spec_lock.md P{slide_num:02d} structured mapping must be "
+ "'<master_key> | <layout_key> | <PowerPoint layout name>'"
+ )
+ master_key, layout_key, layout_name = parts
+ if not _MASTER_KEY_RE.fullmatch(master_key):
+ raise TemplateStructureError(
+ f"spec_lock.md P{slide_num:02d} has invalid Master key "
+ f"{master_key!r}"
+ )
+ if master_key not in seen_master_keys:
+ raise TemplateStructureError(
+ f"spec_lock.md P{slide_num:02d} references undeclared Master "
+ f"{master_key!r}"
+ )
+ else:
+ if len(parts) not in {1, 2} or not parts[0]:
+ raise TemplateStructureError(
+ f"spec_lock.md P{slide_num:02d} preserve mapping must be "
+ "'<layout_key>' or '<layout_key> | <PowerPoint layout name>'"
+ )
+ layout_key = parts[0]
+ layout_name = parts[1] if len(parts) == 2 else None
if not _LAYOUT_KEY_RE.fullmatch(layout_key):
raise TemplateStructureError(
f"spec_lock.md P{slide_num:02d} has invalid layout key "
f"{layout_key!r}"
)
- if separator and not layout_name:
- raise TemplateStructureError(
- f"spec_lock.md P{slide_num:02d} has an empty layout name"
- )
- if layout_strategy == "distill" and separator and not layout_kind:
- raise TemplateStructureError(
- f"spec_lock.md P{slide_num:02d} distilled mapping must end with "
- "'| distilled' or '| utility'"
- )
- if layout_kind and layout_kind not in DISTILLED_LAYOUT_KINDS:
- allowed = ", ".join(sorted(DISTILLED_LAYOUT_KINDS))
- raise TemplateStructureError(
- f"spec_lock.md P{slide_num:02d} layout kind must be one of: "
- f"{allowed}"
- )
references.append(PptxLayoutReference(
slide_num=slide_num,
layout_key=layout_key,
layout_name=layout_name,
- layout_kind=layout_kind,
+ master_key=master_key,
))
- deferred_template = mode == "template" and layout_strategy == "distill"
- if deferred_template and template_adherence not in TEMPLATE_ADHERENCE_MODES:
- raise TemplateStructureError(
- "spec_lock.md deferred template distillation requires exactly one "
- "template_adherence row: strict or adaptive"
- )
- if mode in {"template", "preserve"} and not references and not deferred_template:
+ if mode in {"structured", "preserve"} and not references:
raise TemplateStructureError(
f"spec_lock.md {mode} mode requires one pptx_layouts row per page"
)
- if deferred_template and layout_section_present and not references:
+ if mode == "structured" and layout_section_present and not layout_rows:
raise TemplateStructureError(
- "spec_lock.md deferred template distillation must omit the whole "
- "pptx_layouts section while pending; an empty section is invalid"
+ "spec_lock.md structured pptx_layouts section cannot be empty"
)
- if deferred_template and any(
- reference.layout_name is None for reference in references
- ):
- raise TemplateStructureError(
- "spec_lock.md deferred template pptx_layouts rows require "
- "'<layout_key> | <PowerPoint layout name> | distilled'"
- )
- if mode == "baseline" and layout_section_present and not references:
- raise TemplateStructureError(
- "spec_lock.md baseline pptx_layouts section must contain one row per "
- "page; omit the whole section for an undistilled or legacy baseline "
- "project"
- )
- if mode == "baseline" and any(
- reference.layout_name is None for reference in references
- ):
- raise TemplateStructureError(
- "spec_lock.md baseline pptx_layouts rows require "
- "'<layout_key> | <PowerPoint layout name>'"
- )
- if layout_strategy == "distill" and mode == "baseline":
- if not references:
- raise TemplateStructureError(
- "spec_lock.md layout_strategy: distill requires a complete "
- "pptx_layouts mapping"
- )
- if any(reference.layout_kind is None for reference in references):
- raise TemplateStructureError(
- "spec_lock.md layout_strategy: distill requires every pptx_layouts "
- "row to end with '| distilled' or '| utility'"
- )
- if not any(
- reference.layout_kind == "distilled" for reference in references
- ):
- raise TemplateStructureError(
- "spec_lock.md layout_strategy: distill requires at least one "
- "user-selected distilled Layout"
- )
- utility_keys = {
- reference.layout_key
- for reference in references
- if reference.layout_kind == "utility"
- }
- if len(utility_keys) > 1:
+ layout_contracts: dict[str, tuple[str | None, str | None]] = {}
+ for reference in references:
+ contract = (reference.master_key, reference.layout_name)
+ previous = layout_contracts.setdefault(reference.layout_key, contract)
+ if previous != contract:
raise TemplateStructureError(
- "spec_lock.md layout_strategy: distill allows at most one shared "
- "utility Layout key; found: " + ", ".join(sorted(utility_keys))
- )
- if layout_strategy == "distill" and mode == "template" and references:
- non_distilled = sorted({
- reference.layout_kind or "<missing>"
- for reference in references
- if reference.layout_kind != "distilled"
- })
- if non_distilled:
+ f"spec_lock.md layout key {reference.layout_key!r} must be globally "
+ "unique to one Master and one Layout name"
+ )
+ if mode == "structured":
+ unused_masters = sorted(
+ seen_master_keys - {
+ reference.master_key
+ for reference in references
+ if reference.master_key is not None
+ }
+ )
+ if unused_masters:
raise TemplateStructureError(
- "spec_lock.md deferred template distillation requires every "
- "pptx_layouts row to end with '| distilled'; found: "
- + ", ".join(non_distilled)
+ "spec_lock.md pptx_masters contains unreferenced Master key(s): "
+ + ", ".join(unused_masters)
)
- layout_kinds_by_key: dict[str, set[str | None]] = {}
- for reference in references:
- layout_kinds_by_key.setdefault(reference.layout_key, set()).add(
- reference.layout_kind
- )
- mixed_kind_keys = sorted(
- key for key, kinds in layout_kinds_by_key.items() if len(kinds) > 1
- )
- if mixed_kind_keys:
- raise TemplateStructureError(
- "spec_lock.md reuses layout key(s) with different layout kinds: "
- + ", ".join(mixed_kind_keys)
- )
if mode == "flat" and layout_section_present:
raise TemplateStructureError(
"spec_lock.md pptx_layouts section is not allowed when "
@@ -819,7 +787,7 @@ def load_pptx_structure_lock(project_path: Path) -> PptxStructureLock | None:
return PptxStructureLock(
mode=mode,
template_adherence=template_adherence,
- layout_strategy=layout_strategy,
+ masters=tuple(masters),
layouts=tuple(sorted(references, key=lambda item: item.slide_num)),
prototypes=tuple(sorted(prototypes, key=lambda item: item.slide_num)),
source_template=source_template,
@@ -1049,56 +1017,53 @@ def _parse_placeholder_idx(
return parsed
-def _validate_placeholder_element(
- elem: ET.Element,
+def _validate_placeholder_carrier(
+ carrier: ET.Element,
placeholder: str,
*,
svg_path: Path,
element_id: str,
- layout_kind: str | None,
) -> None:
- tag = _local_tag(elem)
+ tag = _local_tag(carrier)
if placeholder in _TEXT_PLACEHOLDERS and tag != "text":
raise TemplateStructureError(
f"{svg_path.name}: {element_id} placeholder '{placeholder}' must be "
- "declared on a direct <text> element"
+ "carried by one direct <text> child"
)
if placeholder == "picture" and tag not in {"image", "svg"}:
raise TemplateStructureError(
f"{svg_path.name}: {element_id} picture placeholder must be declared "
- "on a direct <image> or nested crop <svg> element"
+ "with one direct <image> or crop <svg> carrier"
)
if placeholder == "media" and tag not in {"image", "svg"}:
raise TemplateStructureError(
f"{svg_path.name}: {element_id} media placeholder must be declared "
- "on a direct <image> or nested crop <svg> element"
+ "with one direct <image> or crop <svg> carrier"
)
- composite_distilled_object = _is_composite_distilled_placeholder_contract(
- tag,
- placeholder,
- layout_kind,
- )
- if (
- placeholder == "object"
- and tag not in _OBJECT_PLACEHOLDER_TAGS
- and not composite_distilled_object
- ):
+ if placeholder == "object" and tag not in _OBJECT_PLACEHOLDER_TAGS:
raise TemplateStructureError(
- f"{svg_path.name}: {element_id} object placeholder must resolve to "
- "one direct text, image, or basic SVG shape; only a completed "
- "distilled Layout may use one direct group as a Layout-only region "
- "proxy"
+ f"{svg_path.name}: {element_id} object placeholder carrier must be "
+ "one direct text, image, or basic SVG shape"
)
if placeholder in {"chart", "table"}:
- native_kind = (elem.get("data-pptx-native") or "").strip().lower()
+ native_kind = (carrier.get("data-pptx-native") or "").strip().lower()
if tag != "g" or native_kind != placeholder:
raise TemplateStructureError(
f"{svg_path.name}: {element_id} placeholder '{placeholder}' must be "
- f"a direct <g data-pptx-native=\"{placeholder}\"> marker"
+ f"carried by one direct <g data-pptx-native=\"{placeholder}\"> marker"
)
-def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
+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_template_slide(
+ svg_path: Path,
+ slide_num: int,
+ *,
+ structured: bool = True,
+) -> TemplateSlideSpec:
"""Parse one SVG's explicit template layout and structure elements."""
try:
root = ET.parse(svg_path).getroot()
@@ -1117,6 +1082,26 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
if _local_tag(root) != "svg":
raise TemplateStructureError(f"{svg_path.name}: root element must be <svg>")
+ master_key = (root.get("data-pptx-master") or "").strip()
+ master_name = (root.get("data-pptx-master-name") or "").strip()
+ if structured and not master_key:
+ raise TemplateStructureError(
+ f"{svg_path.name}: structured export requires root data-pptx-master"
+ )
+ if structured and not master_name:
+ raise TemplateStructureError(
+ f"{svg_path.name}: structured export requires root data-pptx-master-name"
+ )
+ if not master_key:
+ master_key = "preserved-source"
+ if not master_name:
+ master_name = "Preserved Source Master"
+ if not _MASTER_KEY_RE.fullmatch(master_key):
+ raise TemplateStructureError(
+ f"{svg_path.name}: invalid data-pptx-master {master_key!r}; use 1-64 "
+ "ASCII letters, digits, dots, underscores, or hyphens"
+ )
+
layout_key = (root.get("data-pptx-layout") or "").strip()
if not layout_key:
raise TemplateStructureError(
@@ -1128,18 +1113,16 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
"ASCII letters, digits, dots, underscores, or hyphens"
)
layout_name = (root.get("data-pptx-layout-name") or "").strip()
- if not layout_name:
- layout_name = re.sub(r"[-_.]+", " ", layout_key).strip().title() or layout_key
- layout_kind_raw = root.get("data-pptx-layout-kind")
- layout_kind = (layout_kind_raw or "").strip().lower() or None
- if layout_kind_raw is not None and layout_kind is None:
+ if structured and not layout_name:
raise TemplateStructureError(
- f"{svg_path.name}: data-pptx-layout-kind cannot be empty"
+ f"{svg_path.name}: structured export requires root data-pptx-layout-name"
)
- if layout_kind and layout_kind not in DISTILLED_LAYOUT_KINDS:
- allowed = ", ".join(sorted(DISTILLED_LAYOUT_KINDS))
+ if not layout_name:
+ layout_name = re.sub(r"[-_.]+", " ", layout_key).strip().title() or layout_key
+ if structured and root.get("data-pptx-layout-kind") is not None:
raise TemplateStructureError(
- f"{svg_path.name}: data-pptx-layout-kind must be one of: {allowed}"
+ f"{svg_path.name}: data-pptx-layout-kind is obsolete; the root "
+ "Master/Layout identity is already final"
)
illegal_root_attrs = sorted(
@@ -1147,8 +1130,9 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
if (
attr not in {
"data-pptx-layout",
- "data-pptx-layout-kind",
"data-pptx-layout-name",
+ "data-pptx-master",
+ "data-pptx-master-name",
}
and root.get(attr) is not None
)
@@ -1170,18 +1154,6 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
+ ", ".join(duplicate_ids)
)
- direct_children = set(root)
- for elem in root.iter():
- if elem is root or elem in direct_children:
- continue
- nested_attrs = sorted(attr for attr in _STRUCTURE_ATTRS if elem.get(attr) is not None)
- if nested_attrs:
- element_id = elem.get("id") or _local_tag(elem) or "<unnamed>"
- raise TemplateStructureError(
- f"{svg_path.name}: {element_id} uses Layout metadata below the SVG "
- "root; structure metadata is allowed only on direct children"
- )
-
elements: list[TemplateElementSpec] = []
canvas = _svg_canvas(root)
last_order_rank = -1
@@ -1200,18 +1172,21 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
)
bounds_raw = elem.get("data-pptx-placeholder-bounds")
placeholder_idx_raw = elem.get("data-pptx-placeholder-idx")
+ binding_raw = elem.get("data-pptx-placeholder-binding")
+ carrier_raw = elem.get("data-pptx-placeholder-carrier")
editable_raw = elem.get("data-pptx-editable")
is_background = _is_full_canvas_solid_rect(elem, canvas)
effective_layer = layer or ("slide" if is_background else None)
if (
elem.get("data-pptx-layout") is not None
- or elem.get("data-pptx-layout-kind") is not None
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
):
raise TemplateStructureError(
- f"{svg_path.name}: data-pptx-layout, data-pptx-layout-name, and "
- "data-pptx-layout-kind belong on the root <svg> only"
+ f"{svg_path.name}: Master/Layout identity attributes belong on "
+ "the root <svg> only"
)
if layer and layer not in _LAYERS:
raise TemplateStructureError(
@@ -1242,6 +1217,11 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
f"{svg_path.name}: data-pptx-layer='slide' is allowed only on a "
"direct full-canvas solid background rect"
)
+ if structured and layer in {"master", "layout"} and tag == "g":
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} is a <g> on the {layer} "
+ "layer; Master/Layout fixed elements must be root-level atoms"
+ )
if bounds_raw is not None and not placeholder:
raise TemplateStructureError(
f"{svg_path.name}: {element_id or tag} has placeholder bounds without "
@@ -1252,6 +1232,17 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
f"{svg_path.name}: {element_id or tag} has placeholder idx without "
"data-pptx-placeholder"
)
+ if binding_raw is not None and not placeholder:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} has placeholder binding "
+ "without data-pptx-placeholder"
+ )
+ if carrier_raw is not None:
+ raise TemplateStructureError(
+ f"{svg_path.name}: {element_id or tag} declares "
+ "data-pptx-placeholder-carrier on a root child; the marker belongs "
+ "on the direct child inside a placeholder <g>"
+ )
if (effective_layer or placeholder) and not element_id:
raise TemplateStructureError(
f"{svg_path.name}: direct <{tag}> with Layout metadata requires an id"
@@ -1279,23 +1270,15 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
)
last_order_rank = order_rank
- if placeholder:
- _validate_placeholder_element(
- elem,
- placeholder,
- svg_path=svg_path,
- element_id=element_id,
- layout_kind=layout_kind,
- )
placeholder_bounds = _parse_placeholder_bounds(
bounds_raw,
svg_path=svg_path,
element_id=element_id or tag,
)
- if layout_kind == "distilled" and placeholder and placeholder_bounds is None:
+ if structured and placeholder and placeholder_bounds is None:
raise TemplateStructureError(
- f"{svg_path.name}: distilled Layout placeholder {element_id!r} "
- "requires explicit data-pptx-placeholder-bounds; derive the "
+ f"{svg_path.name}: Layout placeholder {element_id!r} requires "
+ "explicit data-pptx-placeholder-bounds; define the "
"reusable frame from the design zone, not the current text bounds"
)
placeholder_idx = _parse_placeholder_idx(
@@ -1304,6 +1287,127 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
element_id=element_id or tag,
)
+ placeholder_binding: str | None = None
+ placeholder_carrier_tag: str | None = None
+ if placeholder and structured:
+ if tag != "g":
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} must be declared "
+ "on a root-level <g> authoring boundary"
+ )
+ wrapper_visual_attrs = sorted(
+ name
+ for name in elem.attrib
+ if name != "id" and not name.startswith("data-pptx-")
+ )
+ if wrapper_visual_attrs:
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder group {element_id!r} must be a "
+ "render-neutral authoring boundary; move these attributes to "
+ "its content: " + ", ".join(wrapper_visual_attrs)
+ )
+ placeholder_binding = (binding_raw or "carrier").strip().lower()
+ if binding_raw is not None and not binding_raw.strip():
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} has an empty "
+ "data-pptx-placeholder-binding"
+ )
+ if placeholder_binding not in PLACEHOLDER_BINDING_MODES:
+ allowed = ", ".join(sorted(PLACEHOLDER_BINDING_MODES))
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} binding must be "
+ f"one of: {allowed}"
+ )
+ visual_children = [
+ child for child in elem if _local_tag(child) not in _NON_VISUAL_TAGS
+ ]
+ carrier_children = [
+ child
+ for child in visual_children
+ if (child.get("data-pptx-placeholder-carrier") or "")
+ .strip()
+ .lower()
+ == "true"
+ ]
+ for child in elem:
+ marker = child.get("data-pptx-placeholder-carrier")
+ if marker is not None and marker.strip().lower() != "true":
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} carrier marker "
+ "must be exactly 'true'"
+ )
+ illegal_child_attrs = [
+ attr
+ for attr in _structure_attrs(child)
+ if attr != "data-pptx-placeholder-carrier"
+ ]
+ if illegal_child_attrs:
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} child uses "
+ "nested structure metadata: " + ", ".join(illegal_child_attrs)
+ )
+ for descendant in child.iter():
+ if descendant is child:
+ continue
+ nested_attrs = _structure_attrs(descendant)
+ if nested_attrs:
+ nested_id = descendant.get("id") or _local_tag(descendant)
+ raise TemplateStructureError(
+ f"{svg_path.name}: {nested_id} uses nested structure "
+ "metadata: " + ", ".join(nested_attrs)
+ )
+ if placeholder_binding == "proxy":
+ if placeholder != "object":
+ raise TemplateStructureError(
+ f"{svg_path.name}: placeholder {element_id!r} may use proxy "
+ "binding only with data-pptx-placeholder='object'"
+ )
+ if carrier_children:
+ raise TemplateStructureError(
+ f"{svg_path.name}: proxy placeholder {element_id!r} must not "
+ "declare a carrier child"
+ )
+ if not visual_children:
+ raise TemplateStructureError(
+ f"{svg_path.name}: proxy placeholder {element_id!r} must "
+ "contain visible Slide-local content"
+ )
+ else:
+ if len(visual_children) != 1 or len(carrier_children) != 1:
+ raise TemplateStructureError(
+ f"{svg_path.name}: carrier placeholder {element_id!r} must "
+ "contain exactly one visual direct child and mark it "
+ "data-pptx-placeholder-carrier='true'"
+ )
+ carrier = carrier_children[0]
+ placeholder_carrier_tag = _local_tag(carrier)
+ _validate_placeholder_carrier(
+ carrier,
+ placeholder,
+ svg_path=svg_path,
+ element_id=element_id,
+ )
+ elif placeholder:
+ placeholder_binding = "carrier"
+ placeholder_carrier_tag = tag
+ _validate_placeholder_carrier(
+ elem,
+ placeholder,
+ svg_path=svg_path,
+ element_id=element_id,
+ )
+ else:
+ for descendant in elem.iter():
+ if descendant is elem:
+ continue
+ nested_attrs = _structure_attrs(descendant)
+ if nested_attrs:
+ nested_id = descendant.get("id") or _local_tag(descendant)
+ raise TemplateStructureError(
+ f"{svg_path.name}: {nested_id} uses structure metadata below "
+ "the SVG root: " + ", ".join(nested_attrs)
+ )
+
if effective_layer or placeholder:
elements.append(TemplateElementSpec(
element_id=element_id,
@@ -1313,6 +1417,8 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
placeholder=placeholder,
placeholder_bounds=placeholder_bounds,
placeholder_idx=placeholder_idx,
+ placeholder_binding=placeholder_binding,
+ placeholder_carrier_tag=placeholder_carrier_tag,
is_background=is_background,
))
visual_order += 1
@@ -1331,25 +1437,12 @@ def parse_template_slide(svg_path: Path, slide_num: int) -> TemplateSlideSpec:
spec = TemplateSlideSpec(
slide_num=slide_num,
svg_path=svg_path,
+ master_key=master_key,
+ master_name=master_name,
layout_key=layout_key,
layout_name=layout_name,
- layout_kind=layout_kind,
elements=tuple(elements),
)
- if layout_kind == "utility" and (spec.layout_elements or spec.placeholders):
- raise TemplateStructureError(
- f"{svg_path.name}: utility Layouts must contain zero Layout elements "
- "and placeholders"
- )
- if (
- layout_kind == "distilled"
- and not spec.layout_elements
- and not spec.placeholders
- ):
- raise TemplateStructureError(
- f"{svg_path.name}: distilled Layout must define at least one Layout "
- "element or placeholder"
- )
return spec
@@ -1364,19 +1457,29 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
"Explicit Layout export requires at least one SVG slide"
)
- expected_master = tuple(
- item.contract_signature() for item in specs[0].master_elements
- )
- for spec in specs[1:]:
- actual_master = tuple(
- item.contract_signature() for item in spec.master_elements
- )
- if actual_master != expected_master:
- raise TemplateStructureError(
- f"{spec.svg_path.name}: master layer contract differs from "
- f"{specs[0].svg_path.name}; every structured slide must repeat the same "
- "explicit master elements in the same order"
+ by_master: dict[str, list[TemplateSlideSpec]] = {}
+ for spec in specs:
+ by_master.setdefault(spec.master_key, []).append(spec)
+ for master_key, master_specs in by_master.items():
+ prototype = master_specs[0]
+ expected_master = tuple(
+ item.contract_signature() for item in prototype.master_elements
+ )
+ for spec in master_specs[1:]:
+ if spec.master_name != prototype.master_name:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: Master {master_key!r} uses name "
+ f"{spec.master_name!r}, expected {prototype.master_name!r}"
+ )
+ actual_master = tuple(
+ item.contract_signature() for item in spec.master_elements
)
+ if actual_master != expected_master:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name}: Master {master_key!r} contract differs "
+ f"from {prototype.svg_path.name}; slides sharing one Master must "
+ "repeat the same root-level atoms in the same order"
+ )
by_layout: dict[str, list[TemplateSlideSpec]] = {}
for spec in specs:
@@ -1390,10 +1493,11 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
f"{spec.svg_path.name}: layout {layout_key!r} uses name "
f"{spec.layout_name!r}, expected {prototype.layout_name!r}"
)
- if spec.layout_kind != prototype.layout_kind:
+ if spec.master_key != prototype.master_key:
raise TemplateStructureError(
- f"{spec.svg_path.name}: layout {layout_key!r} uses kind "
- f"{spec.layout_kind!r}, expected {prototype.layout_kind!r}"
+ f"{spec.svg_path.name}: globally unique layout {layout_key!r} "
+ f"belongs to Master {spec.master_key!r}, expected "
+ f"{prototype.master_key!r}"
)
if spec.layout_contract != prototype.layout_contract:
raise TemplateStructureError(
@@ -1407,7 +1511,7 @@ def parse_template_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
def parse_optional_layout_slides(
svg_files: list[Path],
) -> list[TemplateSlideSpec] | None:
- """Parse an all-or-none Layout contract, or return unmapped baseline absence."""
+ """Parse an all-or-none structured Layout contract, or return no metadata."""
roots: list[tuple[Path, ET.Element]] = []
has_structure_metadata = False
for svg_path in svg_files:
@@ -1427,6 +1531,16 @@ def parse_optional_layout_slides(
if not has_structure_metadata:
return None
+ missing_master_keys = [
+ svg_path.name
+ for svg_path, root in roots
+ if not (root.get("data-pptx-master") or "").strip()
+ ]
+ missing_master_names = [
+ svg_path.name
+ for svg_path, root in roots
+ if not (root.get("data-pptx-master-name") or "").strip()
+ ]
missing_keys = [
svg_path.name
for svg_path, root in roots
@@ -1437,8 +1551,16 @@ def parse_optional_layout_slides(
for svg_path, root in roots
if not (root.get("data-pptx-layout-name") or "").strip()
]
- if missing_keys or missing_names:
+ if missing_master_keys or missing_master_names or missing_keys or missing_names:
missing_fields: list[str] = []
+ if missing_master_keys:
+ missing_fields.append(
+ "data-pptx-master: " + ", ".join(missing_master_keys)
+ )
+ if missing_master_names:
+ missing_fields.append(
+ "data-pptx-master-name: " + ", ".join(missing_master_names)
+ )
if missing_keys:
missing_fields.append(
"data-pptx-layout: " + ", ".join(missing_keys)
@@ -1450,31 +1572,17 @@ def parse_optional_layout_slides(
raise TemplateStructureError(
"Explicit Layout metadata is all-or-none: once any SVG uses PPTX "
"structure metadata, every generated page root must declare "
- "data-pptx-layout and data-pptx-layout-name with non-empty values; "
+ "Master/Layout keys and names with non-empty values; "
"missing "
+ "; ".join(missing_fields)
)
- specs = parse_template_slides(svg_files)
- empty_layouts = sorted({
- spec.layout_key
- for spec in specs
- if spec.layout_kind != "utility"
- if not spec.layout_elements and not spec.placeholders
- })
- if empty_layouts:
- raise TemplateStructureError(
- "Explicit baseline Layout contracts must define at least one "
- "data-pptx-layer='layout' element or data-pptx-placeholder per "
- "layout key; empty: "
- + ", ".join(empty_layouts)
- )
- return specs
+ return parse_template_slides(svg_files)
def parse_preserve_slides(svg_files: list[Path]) -> list[TemplateSlideSpec]:
"""Parse preserve-mode slides before source master grouping is known."""
specs = [
- parse_template_slide(svg_path, slide_num)
+ parse_template_slide(svg_path, slide_num, structured=False)
for slide_num, svg_path in enumerate(svg_files, start=1)
]
if not specs:
@@ -1487,7 +1595,7 @@ def template_lock_errors(
structure_lock: PptxStructureLock,
) -> list[str]:
"""Return mismatches between parsed SVG layouts and the project lock."""
- if structure_lock.mode not in {"baseline", "template", "preserve"}:
+ if structure_lock.mode not in {"structured", "preserve"}:
return []
errors: list[str] = []
references = {
@@ -1524,12 +1632,24 @@ def template_lock_errors(
f"does not match spec_lock P{spec.slide_num:02d} layout name "
f"{reference.layout_name!r}"
)
- if spec.layout_kind != reference.layout_kind:
+ if reference.master_key and spec.master_key != reference.master_key:
errors.append(
- f"{spec.svg_path.name}: data-pptx-layout-kind="
- f"{spec.layout_kind!r} does not match spec_lock "
- f"P{spec.slide_num:02d} layout kind {reference.layout_kind!r}"
+ f"{spec.svg_path.name}: data-pptx-master={spec.master_key!r} "
+ f"does not match spec_lock P{spec.slide_num:02d} Master key "
+ f"{reference.master_key!r}"
)
+ if structure_lock.mode == "structured":
+ master_names = {
+ master.master_key: master.master_name for master in structure_lock.masters
+ }
+ for spec in specs:
+ expected_name = master_names.get(spec.master_key)
+ if expected_name is not None and spec.master_name != expected_name:
+ errors.append(
+ f"{spec.svg_path.name}: data-pptx-master-name="
+ f"{spec.master_name!r} does not match spec_lock Master "
+ f"{spec.master_key!r} name {expected_name!r}"
+ )
return errors
@@ -1970,8 +2090,8 @@ def _mirror_slide_local_signature(
Visible text values may change, but their element topology, attributes,
grouping, paint, geometry, and referenced asset bytes remain literal.
- Structure metadata may change when adaptive distillation promotes or
- demotes the same stable SVG id.
+ Structure metadata may change when adaptive template authoring assigns an
+ evolved Layout identity to the same stable SVG id.
"""
try:
root = ET.parse(spec.svg_path).getroot()
@@ -2021,11 +2141,8 @@ def template_prototype_errors(
*,
require_complete_roster: bool = True,
) -> list[str]:
- """Compare deferred-template pages with their selected SVG prototypes."""
- if (
- structure_lock.mode != "template"
- or structure_lock.layout_strategy != "distill"
- ):
+ """Compare structured template pages with their selected SVG prototypes."""
+ if structure_lock.mode != "structured" or not structure_lock.prototypes:
return []
errors: list[str] = []
prototypes = {
@@ -2079,14 +2196,16 @@ def template_prototype_errors(
errors.append(str(exc))
continue
if (
- tuple(item.contract_signature() for item in spec.master_elements)
+ spec.master_key != prototype.master_key
+ or spec.master_name != prototype.master_name
+ or tuple(item.contract_signature() for item in spec.master_elements)
!= tuple(
item.contract_signature() for item in prototype.master_elements
)
or actual_master_structure != expected_master_structure
):
errors.append(
- f"{spec.svg_path.name}: distilled template Master structure differs "
+ f"{spec.svg_path.name}: template Master structure differs "
f"from prototype {reference.svg_path.name}; strict and adaptive "
"routes must retain its ids, topology, geometry, and content"
+ (" including mirror visual styling" if literal_visual else "")
@@ -2176,14 +2295,14 @@ def template_prototype_errors(
if adherence == "adaptive" and not reuses_prototype_key:
if spec.layout_name == prototype.layout_name:
errors.append(
- f"{spec.svg_path.name}: adaptive template distillation created "
+ f"{spec.svg_path.name}: adaptive template authoring created "
f"new layout key {spec.layout_key!r} but reused prototype picker "
f"name {prototype.layout_name!r}; assign a new key and name to "
"the evolved Layout contract"
)
if reusable_contract_same:
errors.append(
- f"{spec.svg_path.name}: adaptive template distillation changed "
+ f"{spec.svg_path.name}: adaptive template authoring changed "
"only the Layout key/name while the reusable static, "
"placeholder, and default-bounds contract is unchanged; "
f"reuse prototype identity {prototype.layout_key!r} / "
@@ -2200,7 +2319,7 @@ def template_prototype_errors(
if adherence == "strict":
errors.append(
f"{reference.svg_path.name}: deferred strict template "
- "distillation requires explicit data-pptx-placeholder-bounds "
+ "authoring requires explicit data-pptx-placeholder-bounds "
"on every prototype placeholder; missing: "
+ ", ".join(missing_bounds)
)
@@ -2214,14 +2333,14 @@ def template_prototype_errors(
continue
if spec.layout_key != prototype.layout_key:
errors.append(
- f"{spec.svg_path.name}: strict template distillation must keep "
+ f"{spec.svg_path.name}: strict template use must keep "
f"prototype layout key {prototype.layout_key!r}, found "
f"{spec.layout_key!r}"
)
if spec.layout_name != prototype.layout_name:
if adherence == "strict":
errors.append(
- f"{spec.svg_path.name}: strict template distillation must keep "
+ f"{spec.svg_path.name}: strict template use must keep "
f"prototype layout name {prototype.layout_name!r}, found "
f"{spec.layout_name!r}"
)
@@ -2403,14 +2522,27 @@ def _placement_lint_errors(svg_path: Path) -> list[str]:
return []
errors: list[str] = []
direct_children = set(root)
+ allowed_carriers = {
+ carrier
+ for slot in root
+ if (slot.get("data-pptx-placeholder") or "").strip()
+ for carrier in slot
+ if carrier.get("data-pptx-placeholder-carrier") is not None
+ }
for elem in root.iter():
if elem is root or elem in direct_children:
continue
- if any(elem.get(attr) is not None for attr in _STRUCTURE_ATTRS):
+ attrs = _structure_attrs(elem)
+ if elem in allowed_carriers:
+ attrs = [
+ attr for attr in attrs
+ if attr != "data-pptx-placeholder-carrier"
+ ]
+ if attrs:
element_id = elem.get("id") or _local_tag(elem) or "<unnamed>"
errors.append(
f"{svg_path.name}: {element_id} uses template metadata below the SVG "
- "root; structure metadata is allowed only on direct children"
+ "root; only a direct slot child may declare its carrier marker"
)
canvas = _svg_canvas(root)
last_order_rank = -1
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 cfff1a0a..f7499ac3 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
@@ -2,7 +2,7 @@
"""
PPT Master - Template Package Validation
-Read a generated template-mode PPTX back and verify its reusable Layout graph.
+Read a generated structured PPTX back and verify its reusable Master/Layout graph.
Usage:
Imported by svg_to_pptx.pptx_package.builder.
@@ -30,7 +30,7 @@ if __name__ == "__main__":
print(__doc__)
raise SystemExit(0)
print(
- "Use this validator through the template-mode SVG-to-PPTX exporter.",
+ "Use this validator through the structured SVG-to-PPTX exporter.",
file=sys.stderr,
)
raise SystemExit(1)
@@ -41,7 +41,7 @@ from .template_structure import (
TemplatePlaceholderBinding,
TemplateSlideSpec,
TemplateStructureError,
- is_composite_distilled_placeholder,
+ is_proxy_placeholder,
template_placeholder_bindings,
)
@@ -898,6 +898,8 @@ def validate_pptx_template_package(
used_master_parts: set[str] = set()
layout_parts_by_master: dict[str, set[str]] = {}
master_specs_by_part: dict[str, TemplateSlideSpec] = {}
+ master_parts_by_key: dict[str, str] = {}
+ keys_by_master_part: dict[str, str] = {}
for layout_key, layout_specs in specs_by_layout.items():
prototype = layout_specs[0]
layout_part = layout_parts_by_key.get(layout_key)
@@ -927,20 +929,6 @@ def validate_pptx_template_package(
f"{expected_name!r}"
)
- if layout_specs[0].layout_kind == "utility" and c_sld is not None:
- if c_sld.find(f"{{{PML_NS}}}bg") is not None:
- errors.append(
- f"{layout_part} utility Layout must not define a background"
- )
- shape_tree = c_sld.find(f"{{{PML_NS}}}spTree")
- if shape_tree is not None and any(
- child.tag in _TOP_LEVEL_VISIBLE_TAGS
- for child in shape_tree
- ):
- errors.append(
- f"{layout_part} utility Layout must not contain shapes"
- )
-
override_values = overrides.get(f"/{layout_part}", [])
if override_values != [SLIDE_LAYOUT_CONTENT_TYPE]:
errors.append(
@@ -1004,10 +992,6 @@ def validate_pptx_template_package(
slide_root = slide_roots.get(spec.slide_num)
if slide_root is None:
continue
- # Atomic distilled carriers bind directly. A composite
- # object region remains ordinary and uses one hidden,
- # transparent matching proxy to suppress empty inherited
- # placeholder paint in non-PowerPoint renderers.
expected_slide_bindings = bindings
slide_placeholders[spec.slide_num] = _validate_placeholder_roster(
slide_root,
@@ -1037,96 +1021,106 @@ def validate_pptx_template_package(
f"Slide {spec.slide_num} has no pre-promotion p:bg "
"payload for exact read-back"
)
- if spec.layout_kind == "distilled":
- expected_distilled_names = [
- f"{item.element_id} Distilled Carrier"
- for item in spec.placeholders
- ]
- expected_distilled_names.extend(
- "Distilled Binding "
- f"{binding.placeholder_type} {binding.effective_idx}"
- for binding in bindings
- if is_composite_distilled_placeholder(
- binding.element,
- spec.layout_kind,
+ expected_carrier_names = [
+ (
+ f"{item.element_id} Proxy Content"
+ if is_proxy_placeholder(item)
+ else f"{item.element_id} Placeholder Carrier"
+ )
+ for item in spec.placeholders
+ ]
+ expected_carrier_names.extend(
+ "Placeholder Binding "
+ f"{binding.placeholder_type} {binding.effective_idx}"
+ for binding in bindings
+ if is_proxy_placeholder(binding.element)
+ )
+ _validate_named_shape_roster(
+ slide_root,
+ expected_carrier_names,
+ f"Slide {spec.slide_num}",
+ errors,
+ exact=False,
+ ordered=True,
+ )
+ bindings_by_element = {
+ binding.element.element_id: binding
+ for binding in bindings
+ }
+ for item in spec.placeholders:
+ proxy_binding = is_proxy_placeholder(item)
+ carrier_name = (
+ f"{item.element_id} Proxy Content"
+ if proxy_binding
+ else f"{item.element_id} Placeholder Carrier"
+ )
+ carrier = _top_level_shape_by_name(slide_root, carrier_name)
+ carrier_placeholder = (
+ carrier.find(f".//{{{PML_NS}}}ph")
+ if carrier is not None
+ else None
+ )
+ if proxy_binding:
+ if carrier_placeholder is not None:
+ errors.append(
+ f"Slide {spec.slide_num} proxy content "
+ f"{carrier_name!r} must remain ordinary"
+ )
+ elif carrier is not None and carrier_placeholder is None:
+ errors.append(
+ f"Slide {spec.slide_num} carrier "
+ f"{carrier_name!r} must own its p:ph binding"
)
+ if not proxy_binding:
+ continue
+ placeholder_binding = bindings_by_element[item.element_id]
+ binding_name = (
+ "Placeholder Binding "
+ f"{placeholder_binding.placeholder_type} "
+ f"{placeholder_binding.effective_idx}"
)
- _validate_named_shape_roster(
+ binding_shape = _top_level_shape_by_name(
slide_root,
- expected_distilled_names,
- f"Slide {spec.slide_num}",
- errors,
- exact=False,
- ordered=True,
+ binding_name,
)
- bindings_by_element = {
- binding.element.element_id: binding
- for binding in bindings
- }
- for item in spec.placeholders:
- carrier_name = (
- f"{item.element_id} Distilled Carrier"
- )
- carrier = _top_level_shape_by_name(
- slide_root,
- carrier_name,
- )
- carrier_placeholder = (
- carrier.find(f".//{{{PML_NS}}}ph")
- if carrier is not None
- else None
+ if binding_shape is None:
+ continue
+ c_nv_pr = next(
+ binding_shape.iter(f"{{{PML_NS}}}cNvPr"),
+ None,
+ )
+ if (
+ c_nv_pr is None
+ or c_nv_pr.get("hidden", "0").lower()
+ not in {"1", "true"}
+ ):
+ errors.append(
+ f"Slide {spec.slide_num} binding proxy "
+ f"{binding_name!r} must be hidden"
)
- composite_object = is_composite_distilled_placeholder(
- item,
- spec.layout_kind,
+ if binding_shape.find(f".//{{{PML_NS}}}ph") is None:
+ errors.append(
+ f"Slide {spec.slide_num} binding proxy "
+ f"{binding_name!r} has no p:ph"
)
- if composite_object:
- if carrier_placeholder is not None:
- errors.append(
- f"Slide {spec.slide_num} composite carrier "
- f"{carrier_name!r} must remain ordinary"
- )
- elif carrier is not None and carrier_placeholder is None:
- errors.append(
- f"Slide {spec.slide_num} atomic carrier "
- f"{carrier_name!r} must own its p:ph binding"
- )
- placeholder_binding = bindings_by_element[
- item.element_id
- ]
- if not composite_object:
- continue
- binding_name = (
- "Distilled Binding "
- f"{placeholder_binding.placeholder_type} "
- f"{placeholder_binding.effective_idx}"
+ alpha_values = {
+ alpha.get("val")
+ for alpha in binding_shape.findall(
+ f".//{{{DML_NS}}}srgbClr/{{{DML_NS}}}alpha"
)
- binding_shape = _top_level_shape_by_name(
- slide_root,
- binding_name,
+ }
+ proxy_text = "".join(
+ node.text or ""
+ for node in binding_shape.findall(
+ f".//{{{DML_NS}}}t"
)
- if binding_shape is None:
- continue
- c_nv_pr = next(
- binding_shape.iter(f"{{{PML_NS}}}cNvPr"),
- None,
+ )
+ if "0" not in alpha_values or proxy_text != "\u200b":
+ errors.append(
+ f"Slide {spec.slide_num} binding proxy "
+ f"{binding_name!r} must contain exactly one fully "
+ "transparent zero-width run"
)
- if (
- c_nv_pr is None
- or c_nv_pr.get("hidden", "0").lower()
- not in {"1", "true"}
- ):
- errors.append(
- f"Slide {spec.slide_num} binding proxy "
- f"{binding_name!r} must be hidden"
- )
- if binding_shape.find(
- f".//{{{PML_NS}}}ph"
- ) is None:
- errors.append(
- f"Slide {spec.slide_num} binding proxy "
- f"{binding_name!r} has no p:ph"
- )
prototype_placeholders = slide_placeholders.get(
prototype.slide_num,
@@ -1136,10 +1130,7 @@ def validate_pptx_template_package(
idx = binding.effective_idx
layout_placeholder = layout_placeholders.get(idx)
prototype_placeholder = prototype_placeholders.get(idx)
- if is_composite_distilled_placeholder(
- binding.element,
- prototype.layout_kind,
- ):
+ if is_proxy_placeholder(binding.element):
prototype_placeholder = None
if layout_placeholder is None:
continue
@@ -1225,7 +1216,32 @@ def validate_pptx_template_package(
continue
reader.xml(master_part)
used_master_parts.add(master_part)
- master_specs_by_part.setdefault(master_part, prototype)
+ previous_master_part = master_parts_by_key.setdefault(
+ prototype.master_key,
+ master_part,
+ )
+ if previous_master_part != master_part:
+ errors.append(
+ f"Master key {prototype.master_key!r} targets both "
+ f"{previous_master_part} and {master_part}"
+ )
+ previous_master_key = keys_by_master_part.setdefault(
+ master_part,
+ prototype.master_key,
+ )
+ if previous_master_key != prototype.master_key:
+ errors.append(
+ f"Master keys {previous_master_key!r} and "
+ f"{prototype.master_key!r} both target {master_part}"
+ )
+ previous_master_spec = master_specs_by_part.setdefault(
+ master_part,
+ prototype,
+ )
+ if previous_master_spec.master_key != prototype.master_key:
+ errors.append(
+ f"{master_part} is shared by conflicting SVG Master contracts"
+ )
layout_parts_by_master.setdefault(master_part, set()).add(
layout_part
)
@@ -1237,6 +1253,18 @@ def validate_pptx_template_package(
continue
master_spec = master_specs_by_part.get(master_part)
if master_spec is not None:
+ master_c_sld = master_root.find(f"{{{PML_NS}}}cSld")
+ actual_master_name = (
+ master_c_sld.get("name")
+ if master_c_sld is not None
+ else None
+ )
+ if actual_master_name != master_spec.master_name:
+ errors.append(
+ f"Master {master_part} has picker name "
+ f"{actual_master_name!r}, expected "
+ f"{master_spec.master_name!r}"
+ )
_validate_named_shape_roster(
master_root,
tuple(