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(create-template): validate project brands and improve review prompts
hugohe308010e31c549
diff --git a/skills/ppt-master/scripts/register_template.py b/skills/ppt-master/scripts/register_template.pyindex 103657cc..5f9c6b77 100644--- a/skills/ppt-master/scripts/register_template.py+++ b/skills/ppt-master/scripts/register_template.py@@ -33,6 +33,10 @@ Usage::``--rebuild-all`` rebuilds every entry from scratch within the chosen kind;recommended for repairing index drift across many templates at once.++Project-scoped Brand workspaces are validated, not registered, through+``svg_quality_checker.py <workspace>/templates --template-mode``. That entry+reuses :func:`validate_brand_workspace`, so the Brand schema has one authority."""from __future__ import annotations@@ -83,17 +87,23 @@ KIND_CONFIG = {}_BRAND_REQUIRED_SECTIONS = (- "Brand Overview",- "Color Scheme",- "Typography",- "Logo",- "Voice & Tone",- "Icon Style",+ ("I", "Brand Overview"),+ ("II", "Color Scheme"),+ ("III", "Typography"),+ ("IV", "Logo"),+ ("V", "Voice & Tone"),+ ("VI", "Icon Style"),)_BRAND_FORBIDDEN_SECTIONS = ("Page Roster","Signature Design Elements",)+_BRAND_ALLOWED_FRONTMATTER_FIELDS = frozenset({+ "brand_id",+ "kind",+ "summary",+ "primary_color",+})_BRAND_PROVENANCE_VALUES = {"fact", "approx", "user"}_BRAND_ASSET_REF_RE = re.compile(r"`((?:\.\./)+(?:images|icons)/[^`]+)`"@@ -230,7 +240,7 @@ def _numbered_section(body: str, title: str) -> str | None:def _validate_brand_spec(- template_id: str,+ expected_template_id: str | None,template_root: Path,template_dir: Path,frontmatter: dict,@@ -240,7 +250,9 @@ def _validate_brand_spec("""Reject brand workspaces that cannot be locked as portable identity truth.Args:- template_id: Directory name used as the registry key.+ expected_template_id: Registry key to match in library scope. Project+ workspaces pass ``None`` because their root name is the project id,+ not the portable brand id.template_root: Brand workspace root containing assets and templates.template_dir: Directory containing ``design_spec.md`` and any page SVGs.frontmatter: Parsed design-spec frontmatter.@@ -250,9 +262,12 @@ def _validate_brand_spec(errors: list[str] = []declared_id = str(frontmatter.get("brand_id") or "").strip()- if declared_id != template_id:+ if not declared_id:+ errors.append("frontmatter brand_id must be non-empty")+ elif expected_template_id is not None and declared_id != expected_template_id:errors.append(- f"frontmatter brand_id must match directory {template_id!r}, "+ "frontmatter brand_id must match directory "+ f"{expected_template_id!r}, "f"got {declared_id!r}")@@ -263,15 +278,31 @@ def _validate_brand_spec(f"got {declared_kind!r}")+ if not str(frontmatter.get("summary") or "").strip():+ errors.append("frontmatter summary must be non-empty")++ unexpected_fields = sorted(+ set(frontmatter) - _BRAND_ALLOWED_FRONTMATTER_FIELDS+ )+ if unexpected_fields:+ errors.append(+ "brand frontmatter contains non-identity field(s): "+ + ", ".join(unexpected_fields)+ )+if pages:errors.append("brand workspaces must not contain page SVGs under templates/: "+ ", ".join(f"{page}.svg" for page in pages))- for title in _BRAND_REQUIRED_SECTIONS:- if _numbered_section(body, title) is None:- errors.append(f"missing required section: {title}")+ for numeral, title in _BRAND_REQUIRED_SECTIONS:+ if re.search(+ rf"^##\s+{numeral}\.\s+{re.escape(title)}\s*$",+ body,+ re.MULTILINE,+ ) is None:+ errors.append(f"missing required section: {numeral}. {title}")for title in _BRAND_FORBIDDEN_SECTIONS:if re.search(@@ -482,7 +513,11 @@ def _validate_svg_template_spec(# Per-kind extraction# ----------------------------------------------------------------------------def _extract_entry(kind: str, template_id: str, template_dir: Path) -> dict:+def _extract_entry(+ kind: str,+ template_id: str | None,+ template_dir: Path,+) -> dict:"""Build the index entry + extras for a single template."""template_root = template_dirtemplate_dir = _template_content_dir(template_root)@@ -509,6 +544,11 @@ def _extract_entry(kind: str, template_id: str, template_dir: Path) -> dict:pages = _list_pages(template_dir)primary_color = fm.get("primary_color") or _extract_primary_color(body) or ""+ resolved_template_id = (+ template_id+ or str(fm.get(KIND_CONFIG[kind]["id_key"]) or "").strip()+ or template_root.name+ )if kind == "brand":_validate_brand_spec(@@ -524,6 +564,8 @@ def _extract_entry(kind: str, template_id: str, template_dir: Path) -> dict:primary_color=str(primary_color),)elif kind == "layout":+ if template_id is None:+ raise SpecParseError("layout validation requires an expected layout_id")_validate_svg_template_spec(kind,template_id,@@ -539,6 +581,8 @@ def _extract_entry(kind: str, template_id: str, template_dir: Path) -> dict:page_types=list(page_types),)elif kind == "deck":+ if template_id is None:+ raise SpecParseError("deck validation requires an expected deck_id")_validate_svg_template_spec(kind,template_id,@@ -560,14 +604,28 @@ def _extract_entry(kind: str, template_id: str, template_dir: Path) -> dict:primary_color=str(primary_color),page_prefix="templates/" if template_dir != template_root else "",preview=(- f"exports/{template_id}_template_preview.pptx"- if (template_root / "exports" / f"{template_id}_template_preview.pptx").is_file()+ f"exports/{resolved_template_id}_template_preview.pptx"+ if (+ template_root+ / "exports"+ / f"{resolved_template_id}_template_preview.pptx"+ ).is_file()else ""),)return {"entry": entry, "extras": extras}+def validate_brand_workspace(template_root: str | Path) -> dict:+ """Validate a portable Brand workspace without registering it.++ This is the project-scope entry used by ``svg_quality_checker.py+ --template-mode``. Library registration calls the same extraction path with+ an expected directory id, so both scopes share one Brand schema authority.+ """+ return _extract_entry("brand", None, Path(template_root))++# ---------------------------------------------------------------------------# Index / README writers# ---------------------------------------------------------------------------diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 2edbd182..ec06dd27 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -887,8 +887,8 @@ def _design_spec_is_brand(spec_path: Path) -> bool:Lightweight detector that does not require PyYAML — scans only thefrontmatter block (``---`` delimited) for a ``kind:`` line whose value- contains ``brand``. Used by ``check_directory`` to skip SVG validation- on brand-only template directories.+ contains ``brand``. Used by ``check_directory`` to select Brand schema+ validation instead of SVG-roster validation."""try:text = spec_path.read_text(encoding='utf-8')@@ -1152,6 +1152,7 @@ class SVGQualityChecker:# template_mode=True). Each entry is (severity, kind, message) where# severity is 'error' or 'warning'. Printed in print_summary.self._template_issues: List[Tuple[str, str, str]] = []+ self._brand_template_checked = Falseself._animation_issues: List[Tuple[str, str]] = []self._illustration_issues: List[Tuple[str, str, str]] = []self._pptx_structure_issues: List[Tuple[str, str]] = []@@ -4368,21 +4369,48 @@ class SVGQualityChecker:self.issue_types['Input issues'] += 1return []- # Brand-only template workspaces have no SVG roster. Resolve the current- # nested spec first and keep legacy-flat roots readable.+ # Brand-only workspaces have no SVG roster. Validate their portable+ # identity schema through the same authority used by library+ # registration, while keeping project scope independent of global+ # indexes and directory names.if self.template_mode and dir_path.is_dir():nested_spec = dir_path / 'templates' / 'design_spec.md'spec = nested_spec if nested_spec.is_file() else dir_path / 'design_spec.md'if spec.exists() and _design_spec_is_brand(spec):+ self._brand_template_checked = True+ self.summary['total'] += 1+ brand_valid = Trueprint(f"[INFO] Brand directory detected (kind: brand) — "- f"SVG checks skipped."+ f"validating design_spec.md and referenced assets.")- print(- f"[INFO] Validate brand specs via: "- f"python3 scripts/register_template.py "- f"--kind brand <brand_id> --dry-run"+ workspace_root = (+ spec.parent.parent+ if spec.parent.name == 'templates'+ else spec.parent)+ try:+ from register_template import (+ SpecParseError,+ validate_brand_workspace,+ )+ validate_brand_workspace(workspace_root)+ except ImportError as exc:+ brand_valid = False+ self._template_issues.append((+ 'error',+ 'brand_contract',+ f"Brand schema validator could not be imported: {exc}",+ ))+ except (OSError, SpecParseError) as exc:+ brand_valid = False+ self._template_issues.append((+ 'error',+ 'brand_contract',+ str(exc),+ ))+ if brand_valid:+ self.summary['passed'] += 1return self.results# Find all SVG files@@ -5774,7 +5802,7 @@ class SVGQualityChecker:from ``main`` agrees), warnings under ``warnings``. Both are listedper file so the user can act on them directly."""- if not self._template_issues:+ if not self._template_issues and not self._brand_template_checked:returnerrors = [item for item in self._template_issues if item[0] == 'error']@@ -5789,11 +5817,14 @@ class SVGQualityChecker:print(f" Warnings ({len(warnings)}):")for _sev, kind, msg in warnings:print(f" [{kind}] {msg}")+ if self._brand_template_checked and not errors:+ print(" Brand design_spec.md schema and asset references passed.")if not errors:- print(" No structural roster issues.")- print(" Conventional placeholder-name hints may be declared through "- "'placeholders:' frontmatter. Placeholder bounds are mandatory "- "design-zone metadata.")+ if not self._brand_template_checked:+ print(" No structural roster issues.")+ print(" Conventional placeholder-name hints may be declared through "+ "'placeholders:' frontmatter. Placeholder bounds are mandatory "+ "design-zone metadata.")def _apply_aggregated_issue_counts(self):"""Mirror project-level aggregate issues into summary counters once."""@@ -5925,8 +5956,9 @@ def print_usage() -> None:print("\nOptions:")print(" --format <ppt169|ppt43|...> Expected canvas format")print(" --template-mode Validate a template workspace's templates/ directory:")- print(" glob *.svg directly and skip spec_lock checks;")- print(" always enforce roster consistency and emit placeholder hints.")+ print(" Brand validates design_spec.md and referenced assets;")+ print(" Layout/Deck glob *.svg directly, skip spec_lock checks,")+ print(" enforce roster consistency, and emit placeholder hints.")print(" native_structure_mode: structured also enables complete")print(" per-file and cross-page structure validation. Legacy")print(" native_structure_mode: template fails and must be")diff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.pyindex 04cec500..28620735 100644--- a/skills/ppt-master/scripts/template_preview_pptx.py+++ b/skills/ppt-master/scripts/template_preview_pptx.py@@ -20,10 +20,14 @@ Dependencies:from __future__ import annotationsimport argparse+import contextlibimport mathimport re+import shutilimport statisticsimport sys+import tempfile+from collections.abc import Iteratorfrom pathlib import Pathfrom xml.etree import ElementTree as ET@@ -57,6 +61,7 @@ _CANVAS_VIEWBOX_RE = re.compile()_FONT_SIZE_RE = re.compile(r"^([0-9]+(?:\.[0-9]+)?)(?:px)?$")_FILENAME_UNSAFE_RE = re.compile(r"[\\/:*?\"<>|\x00-\x1f]+")+_PLACEHOLDER_MARKER_RE = re.compile(r"\{\{([A-Z][A-Z0-9_]*)\}\}")_TITLE_PLACEHOLDERS = frozenset({"title", "subtitle"})_BODY_PLACEHOLDERS = frozenset({"body",@@ -68,6 +73,76 @@ _DEFAULT_TITLE_PX = 40.0_DEFAULT_BODY_PX = 24.0+def _review_marker_text(match: re.Match[str]) -> str:+ """Return concise preview-only text for one canonical marker."""+ token = match.group(1)+ if token in {"PAGE_NUM", "SLIDE_NUM"}:+ return "1"+ if token.endswith("_NUM"):+ return "01"+ if token == "DATE":+ return "YYYY-MM-DD"+ return token.replace("_", " ").title()+++def _write_review_svg(source: Path, target: Path) -> bool:+ """Copy one SVG, shortening only visible placeholder-carrier prompts."""+ tree = ET.parse(source)+ changed = False+ for slot in tree.getroot().iter():+ if not (slot.get("data-pptx-placeholder") or "").strip():+ continue+ for carrier in slot.iter():+ if (+ carrier.get("data-pptx-placeholder-carrier") or ""+ ).strip().lower() != "true":+ continue+ for element in carrier.iter():+ if element.text:+ updated = _PLACEHOLDER_MARKER_RE.sub(+ _review_marker_text,+ element.text,+ )+ if updated != element.text:+ element.text = updated+ changed = True+ if changed:+ tree.write(target, encoding="utf-8", xml_declaration=True)+ else:+ shutil.copy2(source, target)+ return changed+++def _review_svg_sources(+ workspace: Path,+ svg_files: list[Path],+ *,+ shorten_placeholder_markers: bool,+) -> Iterator[list[Path]]:+ """Yield ephemeral review SVGs without modifying canonical template files."""+ if not shorten_placeholder_markers:+ yield svg_files+ return++ with tempfile.TemporaryDirectory(+ prefix=".template-preview-",+ dir=workspace,+ ) as temporary:+ review_dir = Path(temporary)+ review_files: list[Path] = []+ shortened = 0+ for source in svg_files:+ target = review_dir / source.name+ shortened += int(_write_review_svg(source, target))+ review_files.append(target)+ print(+ " Review prompt text: preview-only samples in "+ f"{shortened} SVG(s); canonical {{{{...}}}} markers unchanged"+ )+ yield review_files++def _partition_svg_prototypes(svg_files: list[Path],*,@@ -350,23 +425,34 @@ def main(argv: list[str] | None = None) -> int:print(" Review placeholder frames: full Layout bounds")print(f" Output: {output_path}")- success = create_pptx_with_native_svg(- svg_files=svg_files,- output_path=output_path,- canvas_format=None,- expected_viewbox=locked_canvas,- verbose=True,- transition=None,- enable_notes=False,- animation=None,- image_optimize=False,- native_objects=True,- pptx_structure="flat" if args.visual_only else "structured",- use_layout_placeholder_frames=use_full_placeholder_frames,- master_text_style_spec=text_style,- structure_name=template_id,- layout_definition_files=layout_definition_files,- )+ with _review_svg_sources(+ workspace,+ all_svg_files,+ shorten_placeholder_markers=use_full_placeholder_frames,+ ) as review_all_svg_files:+ review_svg_files, review_layout_definition_files = (+ _partition_svg_prototypes(+ review_all_svg_files,+ visual_only=args.visual_only,+ )+ )+ success = create_pptx_with_native_svg(+ svg_files=review_svg_files,+ output_path=output_path,+ canvas_format=None,+ expected_viewbox=locked_canvas,+ verbose=True,+ transition=None,+ enable_notes=False,+ animation=None,+ image_optimize=False,+ native_objects=True,+ pptx_structure="flat" if args.visual_only else "structured",+ use_layout_placeholder_frames=use_full_placeholder_frames,+ master_text_style_spec=text_style,+ structure_name=template_id,+ layout_definition_files=review_layout_definition_files,+ )if not success or not output_path.is_file():print("Error: template preview export did not produce a PPTX", file=sys.stderr)return 1