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
refactor(template-workflow): unify PPTX import flow and fix SVG asset handling
hugohe3760e3c68a177
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.mdindex 2a495d7a..e0c4b6a6 100644--- a/skills/ppt-master/references/template-designer.md+++ b/skills/ppt-master/references/template-designer.md@@ -14,12 +14,14 @@ Generate reusable page templates for the **global template library** based on a- **Output location**: `templates/layouts/<template_name>/`- **Input**: finalized template brief (template ID, display name, category, applicable scenarios, tone, theme mode, canvas format, optional reference assets)-When the workflow provides PPTX import output, the effective input package becomes:+When the workflow provides a PPTX reference source, the effective input package comes from the unified `pptx_template_import.py` preparation workspace and becomes:- finalized template brief- `manifest.json`- `analysis.md`- exported `assets/`+- cleaned slide SVG references from `svg/`+- `reference_svg_selection.json`- optional screenshots for visual cross-checkingInput priority for PPTX-backed template creation:@@ -27,7 +29,9 @@ Input priority for PPTX-backed template creation:1. `manifest.json` for factual metadata2. exported `assets/` for reusable visual resources3. `analysis.md` for page-type guidance-4. screenshots / original PPTX only for style verification+4. `reference_svg_selection.json` for deciding which exported SVG pages to inspect first+5. cleaned slide SVG references for composition, spacing, and fixed decorative cues+6. screenshots / original PPTX only for style verification---@@ -96,6 +100,8 @@ Do:- rebuild the layout into a clean SVG structure aligned with PPT Master constraints- simplify repeated decorative fragments into a smaller number of maintainable SVG elements- use a background image asset when the original decorative layer is too complex to recreate cleanly+- use cleaned slide SVG references to inspect composition, spacing, text hierarchy, and fixed decorative structure only after factual metadata has been anchored+- do not read every exported SVG by default; always inspect slides 1, 2, and the last slide, then inspect at least 7 additional representative pages from the selection fileDo not:- attempt 1:1 translation of every PowerPoint shape, group, shadow, or decorative fragmentdiff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex ee4a241d..07f8f533 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -6,6 +6,7 @@ This directory contains user-facing scripts for conversion, project setup, SVG p- Top-level `scripts/`: runnable entry scripts- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`+- `scripts/template_import/`: internal PPTX reference-preparation helpers used by `pptx_template_import.py`- `scripts/svg_finalize/`: internal post-processing helpers used by `finalize_svg.py`- `scripts/docs/`: topic-focused script documentation- `scripts/assets/`: static assets consumed by scripts@@ -54,6 +55,7 @@ Template source import:```bashpython3 scripts/pptx_template_import.py <template.pptx>+python3 scripts/pptx_template_import.py <template.pptx> --manifest-only```Post-processing and export:@@ -81,7 +83,7 @@ python3 scripts/update_repo.py --skip-pip## Recommendations-- Keep new runnable scripts at the top level of `scripts/`+- Keep one user-facing entry point per workflow at the top level of `scripts/`- Move provider-specific or helper internals into subdirectories- Prefer the unified entry points `project_manager.py`, `finalize_svg.py`, and `image_gen.py`- Prefer `svg_final/` over `svg_output/` when exporting@@ -95,4 +97,4 @@ python3 scripts/update_repo.py --skip-pip- [Troubleshooting](./docs/troubleshooting.md)- [AGENTS Guide](../../../AGENTS.md)-_Last updated: 2026-03-26_+_Last updated: 2026-04-09_diff --git a/skills/ppt-master/scripts/docs/project.md b/skills/ppt-master/scripts/docs/project.mdindex ea96d743..cdc9ffa8 100644--- a/skills/ppt-master/scripts/docs/project.md+++ b/skills/ppt-master/scripts/docs/project.md@@ -75,19 +75,30 @@ python3 scripts/generate_examples_index.py examples## `pptx_template_import.py`-Lightweight importer for `.pptx` template sources.+Unified PPTX preparation entry point for `/create-template`.```bashpython3 scripts/pptx_template_import.py <template.pptx>python3 scripts/pptx_template_import.py <template.pptx> -o <output_dir>+python3 scripts/pptx_template_import.py <template.pptx> --manifest-only+python3 scripts/pptx_template_import.py <template.pptx> --keep-raw+python3 scripts/pptx_template_import.py <template.pptx> --skip-manifest```Notes:- Extracts reusable media assets from `ppt/media/`- Summarizes slide size, theme colors, and font metadata- Infers background image inheritance across slide, layout, and master-- Produces `manifest.json`, `analysis.md`, and `assets/`-- Intended as an internal helper for template reconstruction, not a direct PPTX-to-SVG converter+- Generates `manifest.json`, `analysis.md`, `assets/`, cleaned slide SVGs, and `reference_svg_selection.json`+- Windows-only when SVG export is needed because it uses installed Microsoft PowerPoint+- Writes cleaned SVG files to `svg/` after externalizing inline Base64 image payloads+- Required in `/create-template` whenever the reference source is `.pptx`+- Default output directory is `<pptx_stem>_template_import/`+- Use `--manifest-only` when you explicitly want only the lightweight import output without slide SVG export+- Intended for template reference preparation, not for final 1:1 template delivery++Implementation note:+- Internal helpers for this workflow live under `scripts/template_import/`## `error_helper.py`diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex cca86c65..0fdb867e 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -24,14 +24,6 @@ It aggregates:- `flatten_tspan.py`- `svg_rect_to_path.py`-Typical usage:--```bash-python3 scripts/finalize_svg.py <project_path>-```--Use standalone sub-tools only when you need advanced debugging or one-off fixes.-## `svg_to_pptx.py`Convert project SVGs into PPTX.diff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.pyindex aa0598c0..d75c00a6 100644--- a/skills/ppt-master/scripts/pptx_template_import.py+++ b/skills/ppt-master/scripts/pptx_template_import.py@@ -1,461 +1,194 @@#!/usr/bin/env python3-"""Extract lightweight template assets and style metadata from a PPTX file.+"""Unified PPTX preparation entry point for the /create-template workflow.-This helper is intentionally limited in scope:-- extract reusable media assets-- summarize slide size, theme colors, and fonts-- infer common background assets through slide/layout/master inheritance-- produce a compact manifest for downstream template reconstruction+This command prepares a reusable reference workspace from a PPTX source. It can:-It does NOT try to convert arbitrary PPTX shapes into SVG templates.+1. extract lightweight PPTX metadata and reusable assets+2. export every slide to SVG with PowerPoint on Windows+3. replace inline Base64 images inside exported SVG files with external assets+4. optimize cleaned reference SVG files for downstream inspection"""from __future__ import annotationsimport argparseimport json-import posixpath-import re-import shutil-import zipfile-from collections import Counter, defaultdict-from dataclasses import dataclass-from pathlib import Path, PurePosixPath-from typing import Any-from xml.etree import ElementTree as ET---NS = {- "a": "http://schemas.openxmlformats.org/drawingml/2006/main",- "p": "http://schemas.openxmlformats.org/presentationml/2006/main",- "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",- "rel": "http://schemas.openxmlformats.org/package/2006/relationships",+import platform+import subprocess+import tempfile+from pathlib import Path++from template_import.externalize_images import discover_svg_files, externalize_svg_batch+from template_import.manifest import build_manifest+from template_import.optimize_reference import optimize_reference_batch++PPT_PDF_TO_SVG_SCALE = 96.0 / 72.0+++POWERSHELL_EXPORT_SCRIPT = r"""+param(+ [Parameter(Mandatory = $true)][string]$PptxPath,+ [Parameter(Mandatory = $true)][string]$OutputDir+)++$ErrorActionPreference = 'Stop'+$powerpoint = $null+$presentation = $null++try {+ New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null+ $powerpoint = New-Object -ComObject PowerPoint.Application+ $powerpoint.Visible = -1+ $presentation = $powerpoint.Presentations.Open($PptxPath, $false, $false, $false)++ foreach ($slide in $presentation.Slides) {+ $fileName = ('slide_{0:D2}.svg' -f $slide.SlideIndex)+ $target = Join-Path $OutputDir $fileName+ $slide.Export($target, 'SVG')+ }}+finally {+ if ($presentation -ne $null) {+ $presentation.Close()+ }+ if ($powerpoint -ne $null) {+ $powerpoint.Quit()+ }+ [System.GC]::Collect()+ [System.GC]::WaitForPendingFinalizers()+}+"""-EMU_PER_INCH = 914400-SLIDE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"-LAYOUT_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"-MASTER_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"-THEME_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"-IMAGE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"+POWERSHELL_PDF_EXPORT_SCRIPT = r"""+param(+ [Parameter(Mandatory = $true)][string]$PptxPath,+ [Parameter(Mandatory = $true)][string]$PdfPath+)-THANKS_KEYWORDS = ("thank", "thanks", "q&a", "qa", "contact", "致谢", "谢谢", "感谢", "答疑", "联系方式")-TOC_KEYWORDS = ("agenda", "contents", "content", "outline", "目录", "议程", "目录页")-CHAPTER_KEYWORDS = ("chapter", "part", "section", "章节", "部分")+$ErrorActionPreference = 'Stop'+$powerpoint = $null+$presentation = $null+try {+ $pdfDir = Split-Path -Parent $PdfPath+ New-Item -ItemType Directory -Force -Path $pdfDir | Out-Null+ $powerpoint = New-Object -ComObject PowerPoint.Application+ $powerpoint.Visible = -1+ $presentation = $powerpoint.Presentations.Open($PptxPath, $false, $false, $false)+ $presentation.SaveAs($PdfPath, 32)+}+finally {+ if ($presentation -ne $null) {+ $presentation.Close()+ }+ if ($powerpoint -ne $null) {+ $powerpoint.Quit()+ }+ [System.GC]::Collect()+ [System.GC]::WaitForPendingFinalizers()+}+"""-@dataclass-class SlideRecord:- index: int- name: str- slide_path: str- layout_path: str | None- master_path: str | None- background_asset: str | None- background_source: str | None- image_assets: list[str]- text_samples: list[str]- text_count: int- shape_count: int- page_type: str+def run_powershell_script(script_body: str, *script_args: str) -> subprocess.CompletedProcess[bytes]:+ with tempfile.NamedTemporaryFile("w", suffix=".ps1", delete=False, encoding="utf-8") as handle:+ handle.write(script_body)+ script_path = Path(handle.name)-def normalize_part(path: str, base: str | None = None) -> str:- if base:- path = str(PurePosixPath(base).parent.joinpath(path))- path = path.replace("\\", "/")- normalized = posixpath.normpath(path)- if normalized.startswith("./"):- normalized = normalized[2:]- return normalized.lstrip("/")+ try:+ completed = subprocess.run(+ [+ "powershell",+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(script_path),+ *script_args,+ ],+ capture_output=True,+ text=False,+ check=False,+ )+ finally:+ script_path.unlink(missing_ok=True)+ return completed-def rels_path_for(part_path: str) -> str:- part = PurePosixPath(part_path)- return str(part.parent / "_rels" / f"{part.name}.rels")+def decode_process_output(completed: subprocess.CompletedProcess[bytes]) -> str:+ stderr = (completed.stderr or b"").decode("utf-8", errors="replace").strip()+ stdout = (completed.stdout or b"").decode("utf-8", errors="replace").strip()+ return stderr or stdout or "PowerPoint export failed"-def load_xml_from_zip(zf: zipfile.ZipFile, part_path: str) -> ET.Element | None:- try:- with zf.open(part_path) as fh:- return ET.parse(fh).getroot()- except KeyError:- return None- except ET.ParseError:- return None---def parse_relationships(zf: zipfile.ZipFile, part_path: str) -> dict[str, dict[str, str]]:- rels_root = load_xml_from_zip(zf, rels_path_for(part_path))- if rels_root is None:- return {}-- rels: dict[str, dict[str, str]] = {}- for rel in rels_root.findall("rel:Relationship", NS):- rel_id = rel.attrib.get("Id")- target = rel.attrib.get("Target")- rel_type = rel.attrib.get("Type")- if not rel_id or not target or not rel_type:- continue- rels[rel_id] = {- "type": rel_type,- "target": normalize_part(target, part_path),- }- return rels---def emu_to_pixels(value: int) -> int:- # PowerPoint uses 96 dpi; enough for summary output.- return int(round(value / EMU_PER_INCH * 96))---def sanitize_filename(value: str) -> str:- value = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())- return value.strip("._") or "asset"---def extract_text_samples(root: ET.Element | None, limit: int = 6) -> list[str]:- if root is None:- return []- samples: list[str] = []- for node in root.findall(".//a:t", NS):- text = (node.text or "").strip()- if not text:- continue- samples.append(text)- if len(samples) >= limit:- break- return samples---def extract_image_targets(root: ET.Element | None, rels: dict[str, dict[str, str]]) -> list[str]:- if root is None:- return []- targets: list[str] = []- seen: set[str] = set()- for blip in root.findall(".//a:blip", NS):- rel_id = blip.attrib.get(f"{{{NS['r']}}}embed")- if not rel_id:- continue- rel = rels.get(rel_id)- if not rel or rel["type"] != IMAGE_REL:- continue- target = rel["target"]- if target in seen:- continue- seen.add(target)- targets.append(target)- return targets---def detect_background_asset(root: ET.Element | None, rels: dict[str, dict[str, str]]) -> str | None:- if root is None:- return None-- bg = root.find("p:cSld/p:bg", NS)- if bg is None:- bg = root.find("p:bg", NS)- if bg is None:- return None-- blip = bg.find(".//a:blip", NS)- if blip is None:- return None-- rel_id = blip.attrib.get(f"{{{NS['r']}}}embed")- if not rel_id:- return None- rel = rels.get(rel_id)- if not rel or rel["type"] != IMAGE_REL:- return None- return rel["target"]---def count_slide_shapes(root: ET.Element | None) -> int:- if root is None:- return 0- sp_tree = root.find("p:cSld/p:spTree", NS)- if sp_tree is None:- return 0- return len(list(sp_tree))---def classify_slide(index: int, total: int, texts: list[str], image_count: int, shape_count: int) -> str:- joined = " ".join(texts).lower()- if any(keyword in joined for keyword in THANKS_KEYWORDS):- return "ending_candidate"- if any(keyword in joined for keyword in TOC_KEYWORDS):- return "toc_candidate"- if any(keyword in joined for keyword in CHAPTER_KEYWORDS):- return "chapter_candidate"- if index == 1 and image_count <= 3:- return "cover_candidate"- if index == total and len(texts) <= 6:- return "ending_candidate"- if len(texts) <= 3 and shape_count <= 12:- return "chapter_candidate"- return "content_candidate"---def parse_theme(root: ET.Element | None) -> dict[str, Any]:- if root is None:- return {"colors": {}, "fonts": {}}-- colors: dict[str, str] = {}- clr_scheme = root.find(".//a:clrScheme", NS)- if clr_scheme is not None:- for child in list(clr_scheme):- if not isinstance(child.tag, str):- continue- name = child.tag.split("}", 1)[-1]- srgb = child.find("a:srgbClr", NS)- sys_clr = child.find("a:sysClr", NS)- if srgb is not None and "val" in srgb.attrib:- colors[name] = f"#{srgb.attrib['val']}"- elif sys_clr is not None:- last = sys_clr.attrib.get("lastClr")- if last:- colors[name] = f"#{last}"-- fonts: dict[str, str] = {}- font_scheme = root.find(".//a:fontScheme", NS)- if font_scheme is not None:- major = font_scheme.find("a:majorFont", NS)- minor = font_scheme.find("a:minorFont", NS)- if major is not None:- latin = major.find("a:latin", NS)- if latin is not None and latin.attrib.get("typeface"):- fonts["majorLatin"] = latin.attrib["typeface"]- if minor is not None:- latin = minor.find("a:latin", NS)- if latin is not None and latin.attrib.get("typeface"):- fonts["minorLatin"] = latin.attrib["typeface"]- ea = minor.find("a:ea", NS)- if ea is not None and ea.attrib.get("typeface"):- fonts["minorEastAsia"] = ea.attrib["typeface"]-- return {"colors": colors, "fonts": fonts}---def choose_common_assets(asset_usage: Counter[str]) -> list[str]:- common = [asset for asset, count in asset_usage.items() if count > 1]- return sorted(common)---def write_analysis(- output_path: Path,- pptx_name: str,- slide_size: dict[str, int],- theme: dict[str, Any],- slides: list[SlideRecord],- common_assets: list[str],-) -> None:- lines = [- f"# Template Import Analysis - {pptx_name}",- "",- "## Summary",- f"- Slide size: {slide_size['width_px']} x {slide_size['height_px']} px",- f"- Theme colors: {', '.join(sorted(theme['colors'].keys())) or 'none detected'}",- f"- Theme fonts: {', '.join(f'{k}={v}' for k, v in theme['fonts'].items()) or 'none detected'}",- f"- Common assets: {len(common_assets)}",- "",- "## Slide Candidates",- ]+def export_pptx_slides_to_svg(pptx_path: Path, output_dir: Path) -> list[Path]:+ if platform.system() != "Windows":+ raise RuntimeError("pptx_template_import.py currently requires Windows PowerPoint")- for slide in slides:- sample = " | ".join(slide.text_samples[:3]) if slide.text_samples else "(no text sample)"- lines.extend(- [- f"- Slide {slide.index}: {slide.page_type}",- f" - Name: {slide.name}",- f" - Background: {slide.background_asset or 'none'} ({slide.background_source or 'n/a'})",- f" - Images: {len(slide.image_assets)}",- f" - Text sample: {sample}",- ]- )+ output_dir.mkdir(parents=True, exist_ok=True)+ completed = run_powershell_script(+ POWERSHELL_EXPORT_SCRIPT,+ "-PptxPath",+ str(pptx_path),+ "-OutputDir",+ str(output_dir),+ )- output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")---def build_manifest(pptx_path: Path, output_dir: Path) -> dict[str, Any]:- with zipfile.ZipFile(pptx_path, "r") as zf:- presentation_root = load_xml_from_zip(zf, "ppt/presentation.xml")- if presentation_root is None:- raise RuntimeError("Invalid PPTX: missing ppt/presentation.xml")-- slide_size = {"width_emu": 0, "height_emu": 0, "width_px": 0, "height_px": 0}- sld_sz = presentation_root.find("p:sldSz", NS)- if sld_sz is not None:- width_emu = int(sld_sz.attrib.get("cx", "0"))- height_emu = int(sld_sz.attrib.get("cy", "0"))- slide_size = {- "width_emu": width_emu,- "height_emu": height_emu,- "width_px": emu_to_pixels(width_emu),- "height_px": emu_to_pixels(height_emu),- }-- presentation_rels = parse_relationships(zf, "ppt/presentation.xml")- slide_parts: list[str] = []- for sld_id in presentation_root.findall("p:sldIdLst/p:sldId", NS):- rel_id = sld_id.attrib.get(f"{{{NS['r']}}}id")- rel = presentation_rels.get(rel_id or "")- if rel and rel["type"] == SLIDE_REL:- slide_parts.append(rel["target"])-- asset_dir = output_dir / "assets"- asset_dir.mkdir(parents=True, exist_ok=True)-- copied_assets: dict[str, str] = {}- for info in zf.infolist():- if not info.filename.startswith("ppt/media/") or info.is_dir():- continue- original_name = PurePosixPath(info.filename).name- safe_name = sanitize_filename(original_name)- destination = asset_dir / safe_name- stem = destination.stem- suffix = destination.suffix- counter = 2- while destination.exists():- destination = asset_dir / f"{stem}_{counter}{suffix}"- counter += 1- with zf.open(info.filename) as src, open(destination, "wb") as dst:- shutil.copyfileobj(src, dst)- copied_assets[info.filename] = destination.name-- slide_records: list[SlideRecord] = []- asset_usage: Counter[str] = Counter()-- theme_summary = {"colors": {}, "fonts": {}}-- for index, slide_path in enumerate(slide_parts, 1):- slide_root = load_xml_from_zip(zf, slide_path)- slide_rels = parse_relationships(zf, slide_path)-- layout_path = None- for rel in slide_rels.values():- if rel["type"] == LAYOUT_REL:- layout_path = rel["target"]- break-- layout_root = load_xml_from_zip(zf, layout_path) if layout_path else None- layout_rels = parse_relationships(zf, layout_path) if layout_path else {}-- master_path = None- for rel in layout_rels.values():- if rel["type"] == MASTER_REL:- master_path = rel["target"]- break-- master_root = load_xml_from_zip(zf, master_path) if master_path else None- master_rels = parse_relationships(zf, master_path) if master_path else {}-- theme_path = None- for rel in master_rels.values():- if rel["type"] == THEME_REL:- theme_path = rel["target"]- break- if theme_path and not theme_summary["colors"] and not theme_summary["fonts"]:- theme_summary = parse_theme(load_xml_from_zip(zf, theme_path))-- bg_asset = None- bg_source = None- for label, root, rels in (- ("slide", slide_root, slide_rels),- ("layout", layout_root, layout_rels),- ("master", master_root, master_rels),- ):- candidate = detect_background_asset(root, rels)- if candidate:- bg_asset = candidate- bg_source = label- break-- image_targets = extract_image_targets(slide_root, slide_rels)- texts = extract_text_samples(slide_root)- shape_count = count_slide_shapes(slide_root)- page_type = classify_slide(index, len(slide_parts), texts, len(image_targets), shape_count)-- resolved_bg = copied_assets.get(bg_asset, PurePosixPath(bg_asset).name if bg_asset else None)- resolved_images = [- copied_assets.get(target, PurePosixPath(target).name)- for target in image_targets- ]-- if resolved_bg:- asset_usage[resolved_bg] += 1- for asset_name in resolved_images:- asset_usage[asset_name] += 1-- slide_records.append(- SlideRecord(- index=index,- name=PurePosixPath(slide_path).name,- slide_path=slide_path,- layout_path=layout_path,- master_path=master_path,- background_asset=resolved_bg,- background_source=bg_source,- image_assets=resolved_images,- text_samples=texts,- text_count=len(texts),- shape_count=shape_count,- page_type=page_type,- )+ if completed.returncode != 0:+ raise RuntimeError(decode_process_output(completed))++ svg_files = discover_svg_files([str(output_dir)])+ if not svg_files:+ raise RuntimeError("PowerPoint export completed but no SVG files were found")+ return svg_files+++def export_pptx_to_pdf(pptx_path: Path, pdf_path: Path) -> Path:+ completed = run_powershell_script(+ POWERSHELL_PDF_EXPORT_SCRIPT,+ "-PptxPath",+ str(pptx_path),+ "-PdfPath",+ str(pdf_path),+ )+ if completed.returncode != 0:+ raise RuntimeError(decode_process_output(completed))+ if not pdf_path.exists():+ raise RuntimeError("PowerPoint PDF export completed but no PDF file was found")+ return pdf_path+++def export_pdf_pages_to_svg(pdf_path: Path, output_dir: Path) -> list[Path]:+ import fitz++ output_dir.mkdir(parents=True, exist_ok=True)+ svg_files: list[Path] = []+ matrix = fitz.Matrix(PPT_PDF_TO_SVG_SCALE, PPT_PDF_TO_SVG_SCALE)+ with fitz.open(pdf_path) as document:+ for index, page in enumerate(document, 1):+ target = output_dir / f"slide_{index:02d}.svg"+ target.write_text(+ page.get_svg_image(matrix=matrix, text_as_path=False),+ encoding="utf-8",)+ svg_files.append(target)+ return svg_files- common_assets = choose_common_assets(asset_usage)- page_type_map: dict[str, list[int]] = defaultdict(list)- for slide in slide_records:- page_type_map[slide.page_type].append(slide.index)-- manifest = {- "source": {- "pptx": str(pptx_path),- "name": pptx_path.name,- },- "slideSize": slide_size,- "theme": theme_summary,- "assets": {- "exportDir": "assets",- "commonAssets": common_assets,- "allAssets": sorted(copied_assets.values()),- },- "pageTypeCandidates": dict(sorted(page_type_map.items())),- "slides": [- {- "index": slide.index,- "name": slide.name,- "slidePath": slide.slide_path,- "layoutPath": slide.layout_path,- "masterPath": slide.master_path,- "backgroundAsset": slide.background_asset,- "backgroundSource": slide.background_source,- "imageAssets": slide.image_assets,- "textSamples": slide.text_samples,- "textCount": slide.text_count,- "shapeCount": slide.shape_count,- "pageType": slide.page_type,- }- for slide in slide_records- ],- }- write_analysis(- output_dir / "analysis.md",- pptx_path.name,- slide_size,- theme_summary,- slide_records,- common_assets,- )- return manifest+def export_pptx_slides_to_svg_with_fallback(pptx_path: Path, output_dir: Path) -> tuple[list[Path], str]:+ try:+ return export_pptx_slides_to_svg(pptx_path, output_dir), "powerpoint-svg"+ except Exception:+ pdf_path = output_dir.parent / f"{pptx_path.stem}_slides.pdf"+ export_pptx_to_pdf(pptx_path, pdf_path)+ svg_files = export_pdf_pages_to_svg(pdf_path, output_dir)+ return svg_files, "powerpoint-pdf-fallback"def parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser(- description="Extract reusable assets and style metadata from a PPTX template source."+ description="Prepare a PPTX reference workspace for /create-template.")parser.add_argument("pptx_file", help="Path to the source .pptx file")parser.add_argument(@@ -463,9 +196,120 @@ def parse_args() -> argparse.Namespace:"--output",help="Output directory (default: <pptx_stem>_template_import beside the source file)",)+ parser.add_argument(+ "--skip-manifest",+ action="store_true",+ help="Skip PPTX metadata extraction and asset inventory generation",+ )+ parser.add_argument(+ "--manifest-only",+ action="store_true",+ help="Only extract manifest.json, analysis.md, and reusable assets without exporting slides to SVG",+ )+ parser.add_argument(+ "--keep-raw",+ action="store_true",+ help="Keep raw PowerPoint-exported SVG files in svg_raw/",+ )+ parser.add_argument(+ "--no-externalize",+ action="store_true",+ help="Skip inline image externalization and keep raw SVG output only",+ )+ parser.add_argument(+ "--no-optimize",+ action="store_true",+ help="Skip the second-pass structural optimization for cleaned reference SVG files",+ )return parser.parse_args()+def build_reference_svg_selection(manifest: dict, svg_files: list[Path]) -> dict:+ slides = manifest.get("slides", [])+ total = len(slides) or len(svg_files)+ svg_by_index = {+ index: f"svg/slide_{index:02d}.svg"+ for index in range(1, len(svg_files) + 1)+ }++ mandatory: list[int] = []+ for index in (1, 2, total):+ if 1 <= index <= total and index not in mandatory:+ mandatory.append(index)++ selected = list(mandatory)+ selected_set = set(selected)++ # Prefer page-type diversity first.+ by_page_type: dict[str, list[int]] = {}+ for slide in slides:+ by_page_type.setdefault(slide.get("pageType", "unknown"), []).append(slide["index"])++ preferred_types = [+ "cover_candidate",+ "chapter_candidate",+ "toc_candidate",+ "content_candidate",+ "ending_candidate",+ ]+ for page_type in preferred_types:+ for index in by_page_type.get(page_type, []):+ if index not in selected_set and index not in mandatory:+ selected.append(index)+ selected_set.add(index)+ break++ # Then fill with evenly distributed content/reference pages until+ # there are at least 7 pages beyond 1/2/last when possible.+ target_total = min(total, len(mandatory) + 7)+ remaining = [index for index in range(1, total + 1) if index not in selected_set]+ while len(selected) < target_total and remaining:+ needed = target_total - len(selected)+ picks: list[int] = []+ for slot in range(needed):+ pos = round((slot + 1) * (len(remaining) + 1) / (needed + 1)) - 1+ pos = max(0, min(pos, len(remaining) - 1))+ candidate = remaining[pos]+ if candidate not in picks:+ picks.append(candidate)+ for candidate in picks:+ if candidate not in selected_set:+ selected.append(candidate)+ selected_set.add(candidate)+ remaining = [index for index in remaining if index not in selected_set]++ selected.sort()+ recommended = [+ {+ "index": index,+ "svg": svg_by_index.get(index, f"svg/slide_{index:02d}.svg"),+ "pageType": next(+ (slide.get("pageType", "unknown") for slide in slides if slide["index"] == index),+ "unknown",+ ),+ "reason": (+ "mandatory"+ if index in mandatory+ else "representative_reference"+ ),+ }+ for index in selected+ ]++ return {+ "totalSlides": total,+ "mandatoryIndexes": mandatory,+ "minimumAdditionalReferenceCount": 7,+ "recommendedIndexes": selected,+ "recommendedSvgRefs": recommended,+ "guidance": (+ "Always reference slides 1, 2, and the last slide. "+ "Beyond those mandatory pages, use at least 7 additional representative SVG pages "+ "instead of consuming every exported SVG by default."+ ),+ }++def main() -> int:args = parse_args()pptx_path = Path(args.pptx_file).expanduser().resolve()@@ -483,24 +327,85 @@ def main() -> int:)output_dir.mkdir(parents=True, exist_ok=True)+ if args.skip_manifest and args.manifest_only:+ print("Error: --skip-manifest and --manifest-only cannot be used together")+ return 1++ if not args.skip_manifest:+ try:+ manifest = build_manifest(pptx_path, output_dir)+ except Exception as exc:+ print(f"Error: failed to extract PPTX metadata: {exc}")+ return 1++ manifest_path = output_dir / "manifest.json"+ manifest_path.write_text(+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+ else:+ manifest = {"slides": []}++ if args.manifest_only:+ print(f"Imported PPTX template source: {pptx_path.name}")+ print(f"Output directory: {output_dir}")+ if not args.skip_manifest:+ print(f"Manifest: {manifest_path.name}")+ print(f"Assets exported: {len(manifest['assets']['allAssets'])}")+ print(f"Common assets: {len(manifest['assets']['commonAssets'])}")+ print(f"Slides analyzed: {len(manifest['slides'])}")+ return 0++ raw_dir = output_dir / "svg_raw"try:- manifest = build_manifest(pptx_path, output_dir)+ raw_svg_files, export_mode = export_pptx_slides_to_svg_with_fallback(pptx_path, raw_dir)except Exception as exc:- print(f"Error: failed to import template source: {exc}")+ print(f"Error: failed to export PPTX slides to SVG: {exc}")return 1- manifest_path = output_dir / "manifest.json"- manifest_path.write_text(- json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",+ if args.no_externalize:+ print(f"Export mode: {export_mode}")+ print(f"Exported raw SVG slides: {len(raw_svg_files)}")+ print(f"Output directory: {output_dir}")+ return 0++ cleaned_dir = output_dir / "svg"+ results = externalize_svg_batch(+ svg_files=raw_svg_files,+ output_dir=cleaned_dir,+ assets_dir=output_dir / "assets",+ )+ final_svg_bytes = sum(item.output_svg_bytes for item in results)++ if not args.no_optimize:+ optimize_results, optimize_output_dir = optimize_reference_batch([str(cleaned_dir)], precision=2)+ before_opt = sum(item.original_bytes for item in optimize_results)+ after_opt = sum(item.optimized_bytes for item in optimize_results)+ final_svg_bytes = after_opt+ print(f"Optimized SVG files: {len(optimize_results)}")+ print(f"SVG bytes after structural optimization: {before_opt} -> {after_opt}")+ print(f"Icon candidate report: {optimize_output_dir / 'icon_candidates.json'}")++ if not args.keep_raw:+ for svg_file in raw_dir.glob("*.svg"):+ svg_file.unlink(missing_ok=True)+ raw_dir.rmdir()++ reference_selection = build_reference_svg_selection(manifest, sorted(cleaned_dir.glob("*.svg")))+ (output_dir / "reference_svg_selection.json").write_text(+ json.dumps(reference_selection, ensure_ascii=False, indent=2) + "\n",encoding="utf-8",)- print(f"Imported PPTX template source: {pptx_path.name}")+ total_before = sum(item.original_svg_bytes for item in results)+ total_images = sum(item.images_externalized for item in results)++ print(f"Export mode: {export_mode}")+ print(f"Exported SVG slides: {len(results)}")+ print(f"Inline images externalized: {total_images}")+ print(f"SVG bytes: {total_before} -> {final_svg_bytes}")+ print(f"Reference SVG selection: {output_dir / 'reference_svg_selection.json'}")print(f"Output directory: {output_dir}")- print(f"Manifest: {manifest_path.name}")- print(f"Assets exported: {len(manifest['assets']['allAssets'])}")- print(f"Common assets: {len(manifest['assets']['commonAssets'])}")- print(f"Slides analyzed: {len(manifest['slides'])}")return 0diff --git a/skills/ppt-master/scripts/svg_finalize/crop_images.py b/skills/ppt-master/scripts/svg_finalize/crop_images.pyindex 358b8795..5b2e3103 100644--- a/skills/ppt-master/scripts/svg_finalize/crop_images.py+++ b/skills/ppt-master/scripts/svg_finalize/crop_images.py@@ -231,10 +231,24 @@ def process_svg_images(try:# Open and process imageimg = Image.open(img_path)-- # Convert mode- if img.mode in ('RGBA', 'P'):- img = img.convert('RGB')+ output_is_png = img_path.suffix.lower() == '.png'++ # Preserve alpha for PNG assets such as translucent overlays.+ if output_is_png:+ if img.mode == 'P':+ img = img.convert('RGBA')+ elif img.mode not in ('RGBA', 'LA', 'RGB', 'L'):+ img = img.convert('RGBA' if 'A' in img.getbands() else 'RGB')+ else:+ if img.mode in ('RGBA', 'LA'):+ background = Image.new('RGB', img.size, (255, 255, 255))+ alpha = img.getchannel('A')+ background.paste(img.convert('RGB'), mask=alpha)+ img = background+ elif img.mode == 'P':+ img = img.convert('RGB')+ elif img.mode not in ('RGB', 'L'):+ img = img.convert('RGB')# Cropcropped = crop_image_to_size(img, target_width, target_height, x_anchor, y_anchor)@@ -244,7 +258,7 @@ def process_svg_images(output_path = output_dir / output_filename# Save- if img_path.suffix.lower() == '.png':+ if output_is_png:cropped.save(output_path, 'PNG', optimize=True)else:cropped.save(output_path, 'JPEG', quality=90, optimize=True)diff --git a/skills/ppt-master/scripts/template_import/__init__.py b/skills/ppt-master/scripts/template_import/__init__.pynew file mode 100644index 00000000..ac7715c7--- /dev/null+++ b/skills/ppt-master/scripts/template_import/__init__.py@@ -0,0 +1 @@+"""Internal helpers for pptx_template_import.py."""diff --git a/skills/ppt-master/scripts/template_import/externalize_images.py b/skills/ppt-master/scripts/template_import/externalize_images.pynew file mode 100644index 00000000..3dc9510e--- /dev/null+++ b/skills/ppt-master/scripts/template_import/externalize_images.py@@ -0,0 +1,241 @@+#!/usr/bin/env python3+"""Internal helper: extract inline SVG images into external asset files.++This tool is the inverse of svg_finalize/embed_images.py. It is useful when+PowerPoint exports SVG files with large inline Base64 images and those SVGs need+to be reused as lightweight template references.+"""++from __future__ import annotations++import argparse+import base64+import hashlib+import html+import os+import re+from dataclasses import dataclass+from pathlib import Path+++DATA_URI_RE = re.compile(+ r'(?P<attr>(?:xlink:)?href)="data:(?P<mime>image/[^;"]+);base64,(?P<data>[^"]+)"',+ re.IGNORECASE,+)+++@dataclass+class ExternalizedImage:+ asset_path: Path+ original_bytes: int+ digest: str+++@dataclass+class SvgExternalizeResult:+ svg_path: Path+ output_svg_path: Path+ original_svg_bytes: int+ output_svg_bytes: int+ images_found: int+ images_externalized: int+ assets_written: list[Path]+++def detect_extension(mime_type: str, file_bytes: bytes) -> str:+ mime_type = mime_type.lower()+ if mime_type == "image/png" or file_bytes.startswith(b"\x89PNG\r\n\x1a\n"):+ return ".png"+ if mime_type in {"image/jpeg", "image/jpg"} or file_bytes.startswith(b"\xff\xd8\xff"):+ return ".jpg"+ if mime_type == "image/gif" or file_bytes.startswith((b"GIF87a", b"GIF89a")):+ return ".gif"+ if mime_type == "image/webp" or (+ file_bytes.startswith(b"RIFF") and file_bytes[8:12] == b"WEBP"+ ):+ return ".webp"+ if mime_type == "image/svg+xml" or file_bytes.lstrip().startswith(b"<svg"):+ return ".svg"+ return ".bin"+++def relpath_for_svg(target: Path, svg_path: Path) -> str:+ return os.path.relpath(target, start=svg_path.parent).replace("\\", "/")+++def discover_svg_files(inputs: list[str]) -> list[Path]:+ svg_files: list[Path] = []+ for raw in inputs:+ path = Path(raw).expanduser().resolve()+ if not path.exists():+ raise FileNotFoundError(f"Path does not exist: {path}")+ if path.is_dir():+ svg_files.extend(+ sorted(+ child+ for child in path.iterdir()+ if child.is_file() and child.suffix.lower() == ".svg"+ )+ )+ continue+ if path.suffix.lower() != ".svg":+ raise ValueError(f"Expected .svg input, got: {path}")+ svg_files.append(path)+ return svg_files+++def externalize_svg_file(+ svg_path: Path,+ output_svg_path: Path,+ assets_dir: Path,+ digest_index: dict[str, Path] | None = None,+) -> SvgExternalizeResult:+ digest_index = digest_index if digest_index is not None else {}+ assets_dir.mkdir(parents=True, exist_ok=True)+ output_svg_path.parent.mkdir(parents=True, exist_ok=True)++ content = svg_path.read_text(encoding="utf-8")+ original_svg_bytes = len(content.encode("utf-8"))+ assets_written: list[Path] = []+ images_found = 0+ images_externalized = 0++ def replace(match: re.Match[str]) -> str:+ nonlocal images_found, images_externalized++ images_found += 1+ attr_name = match.group("attr")+ mime_type = match.group("mime")+ data = html.unescape(match.group("data"))++ try:+ payload = base64.b64decode(data)+ except ValueError:+ return match.group(0)++ digest = hashlib.sha1(payload).hexdigest()+ asset_path = digest_index.get(digest)+ if asset_path is None:+ extension = detect_extension(mime_type, payload)+ asset_path = assets_dir / f"inline_{digest[:12]}{extension}"+ if not asset_path.exists():+ asset_path.write_bytes(payload)+ assets_written.append(asset_path)+ digest_index[digest] = asset_path++ images_externalized += 1+ relative_ref = relpath_for_svg(asset_path, output_svg_path)+ return f'{attr_name}="{relative_ref}"'++ updated = DATA_URI_RE.sub(replace, content)+ output_svg_path.write_text(updated, encoding="utf-8")++ return SvgExternalizeResult(+ svg_path=svg_path,+ output_svg_path=output_svg_path,+ original_svg_bytes=original_svg_bytes,+ output_svg_bytes=len(updated.encode("utf-8")),+ images_found=images_found,+ images_externalized=images_externalized,+ assets_written=assets_written,+ )+++def externalize_svg_batch(+ svg_files: list[Path],+ output_dir: Path | None,+ assets_dir: Path | None,+) -> list[SvgExternalizeResult]:+ digest_index: dict[str, Path] = {}+ results: list[SvgExternalizeResult] = []++ default_assets_dir = assets_dir+ if default_assets_dir is None:+ if output_dir is not None:+ default_assets_dir = output_dir / "assets"+ elif svg_files:+ default_assets_dir = svg_files[0].parent / "assets"+ else:+ default_assets_dir = Path.cwd() / "assets"++ for svg_path in svg_files:+ destination = output_dir / svg_path.name if output_dir else svg_path+ result = externalize_svg_file(+ svg_path=svg_path,+ output_svg_path=destination,+ assets_dir=default_assets_dir,+ digest_index=digest_index,+ )+ results.append(result)++ return results+++def print_summary(results: list[SvgExternalizeResult]) -> None:+ total_original = sum(item.original_svg_bytes for item in results)+ total_output = sum(item.output_svg_bytes for item in results)+ total_images = sum(item.images_externalized for item in results)+ written_assets = sorted({asset for item in results for asset in item.assets_written})++ for item in results:+ print(f"[FILE] {item.svg_path.name}")+ print(+ f" SVG size: {item.original_svg_bytes} -> {item.output_svg_bytes} bytes"+ )+ print(+ f" Images externalized: {item.images_externalized}/{item.images_found}"+ )+ if item.assets_written:+ for asset in item.assets_written:+ print(f" Asset written: {asset.name}")++ print("=" * 50)+ print(f"[DONE] Processed SVG files: {len(results)}")+ print(f"[DONE] Images externalized: {total_images}")+ print(f"[DONE] SVG bytes: {total_original} -> {total_output}")+ print(f"[DONE] Unique assets written: {len(written_assets)}")+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Extract inline Base64 SVG images into external asset files."+ )+ parser.add_argument(+ "inputs",+ nargs="+",+ help="SVG files or directories containing SVG files",+ )+ parser.add_argument(+ "-o",+ "--output-dir",+ help="Write cleaned SVG files to this directory instead of editing in place",+ )+ parser.add_argument(+ "--assets-dir",+ help="Directory for extracted image assets (default: <output>/assets or sibling assets/)",+ )+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ try:+ svg_files = discover_svg_files(args.inputs)+ except (FileNotFoundError, ValueError) as exc:+ print(f"Error: {exc}")+ return 1++ if not svg_files:+ print("Error: no SVG files found")+ return 1++ output_dir = Path(args.output_dir).expanduser().resolve() if args.output_dir else None+ assets_dir = Path(args.assets_dir).expanduser().resolve() if args.assets_dir else None++ results = externalize_svg_batch(svg_files, output_dir, assets_dir)+ print_summary(results)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/template_import/manifest.py b/skills/ppt-master/scripts/template_import/manifest.pynew file mode 100644index 00000000..76fe9348--- /dev/null+++ b/skills/ppt-master/scripts/template_import/manifest.py@@ -0,0 +1,508 @@+#!/usr/bin/env python3+"""Internal helper: extract lightweight template assets and style metadata from a PPTX file.++This helper is intentionally limited in scope:+- extract reusable media assets+- summarize slide size, theme colors, and fonts+- infer common background assets through slide/layout/master inheritance+- produce a compact manifest for downstream template reconstruction++It does NOT try to convert arbitrary PPTX shapes into SVG templates.+"""++from __future__ import annotations++import argparse+import json+import posixpath+import re+import shutil+import zipfile+from collections import Counter, defaultdict+from dataclasses import dataclass+from pathlib import Path, PurePosixPath+from typing import Any+from xml.etree import ElementTree as ET+++NS = {+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "rel": "http://schemas.openxmlformats.org/package/2006/relationships",+}++EMU_PER_INCH = 914400++SLIDE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"+LAYOUT_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"+MASTER_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"+THEME_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"+IMAGE_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"++THANKS_KEYWORDS = ("thank", "thanks", "q&a", "qa", "contact", "致谢", "谢谢", "感谢", "答疑", "联系方式")+TOC_KEYWORDS = ("agenda", "contents", "content", "outline", "目录", "议程", "目录页")+CHAPTER_KEYWORDS = ("chapter", "part", "section", "章节", "部分")+++@dataclass+class SlideRecord:+ index: int+ name: str+ slide_path: str+ layout_path: str | None+ master_path: str | None+ background_asset: str | None+ background_source: str | None+ image_assets: list[str]+ text_samples: list[str]+ text_count: int+ shape_count: int+ page_type: str+++def normalize_part(path: str, base: str | None = None) -> str:+ if base:+ path = str(PurePosixPath(base).parent.joinpath(path))+ path = path.replace("\\", "/")+ normalized = posixpath.normpath(path)+ if normalized.startswith("./"):+ normalized = normalized[2:]+ return normalized.lstrip("/")+++def rels_path_for(part_path: str) -> str:+ part = PurePosixPath(part_path)+ return str(part.parent / "_rels" / f"{part.name}.rels")+++def load_xml_from_zip(zf: zipfile.ZipFile, part_path: str) -> ET.Element | None:+ try:+ with zf.open(part_path) as fh:+ return ET.parse(fh).getroot()+ except KeyError:+ return None+ except ET.ParseError:+ return None+++def parse_relationships(zf: zipfile.ZipFile, part_path: str) -> dict[str, dict[str, str]]:+ rels_root = load_xml_from_zip(zf, rels_path_for(part_path))+ if rels_root is None:+ return {}++ rels: dict[str, dict[str, str]] = {}+ for rel in rels_root.findall("rel:Relationship", NS):+ rel_id = rel.attrib.get("Id")+ target = rel.attrib.get("Target")+ rel_type = rel.attrib.get("Type")+ if not rel_id or not target or not rel_type:+ continue+ rels[rel_id] = {+ "type": rel_type,+ "target": normalize_part(target, part_path),+ }+ return rels+++def emu_to_pixels(value: int) -> int:+ # PowerPoint uses 96 dpi; enough for summary output.+ return int(round(value / EMU_PER_INCH * 96))+++def sanitize_filename(value: str) -> str:+ value = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())+ return value.strip("._") or "asset"+++def extract_text_samples(root: ET.Element | None, limit: int = 6) -> list[str]:+ if root is None:+ return []+ samples: list[str] = []+ for node in root.findall(".//a:t", NS):+ text = (node.text or "").strip()+ if not text:+ continue+ samples.append(text)+ if len(samples) >= limit:+ break+ return samples+++def extract_image_targets(root: ET.Element | None, rels: dict[str, dict[str, str]]) -> list[str]:+ if root is None:+ return []+ targets: list[str] = []+ seen: set[str] = set()+ for blip in root.findall(".//a:blip", NS):+ rel_id = blip.attrib.get(f"{{{NS['r']}}}embed")+ if not rel_id:+ continue+ rel = rels.get(rel_id)+ if not rel or rel["type"] != IMAGE_REL:+ continue+ target = rel["target"]+ if target in seen:+ continue+ seen.add(target)+ targets.append(target)+ return targets+++def detect_background_asset(root: ET.Element | None, rels: dict[str, dict[str, str]]) -> str | None:+ if root is None:+ return None++ bg = root.find("p:cSld/p:bg", NS)+ if bg is None:+ bg = root.find("p:bg", NS)+ if bg is None:+ return None++ blip = bg.find(".//a:blip", NS)+ if blip is None:+ return None++ rel_id = blip.attrib.get(f"{{{NS['r']}}}embed")+ if not rel_id:+ return None+ rel = rels.get(rel_id)+ if not rel or rel["type"] != IMAGE_REL:+ return None+ return rel["target"]+++def count_slide_shapes(root: ET.Element | None) -> int:+ if root is None:+ return 0+ sp_tree = root.find("p:cSld/p:spTree", NS)+ if sp_tree is None:+ return 0+ return len(list(sp_tree))+++def classify_slide(index: int, total: int, texts: list[str], image_count: int, shape_count: int) -> str:+ joined = " ".join(texts).lower()+ if any(keyword in joined for keyword in THANKS_KEYWORDS):+ return "ending_candidate"+ if any(keyword in joined for keyword in TOC_KEYWORDS):+ return "toc_candidate"+ if any(keyword in joined for keyword in CHAPTER_KEYWORDS):+ return "chapter_candidate"+ if index == 1 and image_count <= 3:+ return "cover_candidate"+ if index == total and len(texts) <= 6:+ return "ending_candidate"+ if len(texts) <= 3 and shape_count <= 12:+ return "chapter_candidate"+ return "content_candidate"+++def parse_theme(root: ET.Element | None) -> dict[str, Any]:+ if root is None:+ return {"colors": {}, "fonts": {}}++ colors: dict[str, str] = {}+ clr_scheme = root.find(".//a:clrScheme", NS)+ if clr_scheme is not None:+ for child in list(clr_scheme):+ if not isinstance(child.tag, str):+ continue+ name = child.tag.split("}", 1)[-1]+ srgb = child.find("a:srgbClr", NS)+ sys_clr = child.find("a:sysClr", NS)+ if srgb is not None and "val" in srgb.attrib:+ colors[name] = f"#{srgb.attrib['val']}"+ elif sys_clr is not None:+ last = sys_clr.attrib.get("lastClr")+ if last:+ colors[name] = f"#{last}"++ fonts: dict[str, str] = {}+ font_scheme = root.find(".//a:fontScheme", NS)+ if font_scheme is not None:+ major = font_scheme.find("a:majorFont", NS)+ minor = font_scheme.find("a:minorFont", NS)+ if major is not None:+ latin = major.find("a:latin", NS)+ if latin is not None and latin.attrib.get("typeface"):+ fonts["majorLatin"] = latin.attrib["typeface"]+ if minor is not None:+ latin = minor.find("a:latin", NS)+ if latin is not None and latin.attrib.get("typeface"):+ fonts["minorLatin"] = latin.attrib["typeface"]+ ea = minor.find("a:ea", NS)+ if ea is not None and ea.attrib.get("typeface"):+ fonts["minorEastAsia"] = ea.attrib["typeface"]++ return {"colors": colors, "fonts": fonts}+++def choose_common_assets(asset_usage: Counter[str]) -> list[str]:+ common = [asset for asset, count in asset_usage.items() if count > 1]+ return sorted(common)+++def write_analysis(+ output_path: Path,+ pptx_name: str,+ slide_size: dict[str, int],+ theme: dict[str, Any],+ slides: list[SlideRecord],+ common_assets: list[str],+) -> None:+ lines = [+ f"# Template Import Analysis - {pptx_name}",+ "",+ "## Summary",+ f"- Slide size: {slide_size['width_px']} x {slide_size['height_px']} px",+ f"- Theme colors: {', '.join(sorted(theme['colors'].keys())) or 'none detected'}",+ f"- Theme fonts: {', '.join(f'{k}={v}' for k, v in theme['fonts'].items()) or 'none detected'}",+ f"- Common assets: {len(common_assets)}",+ "",+ "## Slide Candidates",+ ]++ for slide in slides:+ sample = " | ".join(slide.text_samples[:3]) if slide.text_samples else "(no text sample)"+ lines.extend(+ [+ f"- Slide {slide.index}: {slide.page_type}",+ f" - Name: {slide.name}",+ f" - Background: {slide.background_asset or 'none'} ({slide.background_source or 'n/a'})",+ f" - Images: {len(slide.image_assets)}",+ f" - Text sample: {sample}",+ ]+ )++ output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")+++def build_manifest(pptx_path: Path, output_dir: Path) -> dict[str, Any]:+ with zipfile.ZipFile(pptx_path, "r") as zf:+ presentation_root = load_xml_from_zip(zf, "ppt/presentation.xml")+ if presentation_root is None:+ raise RuntimeError("Invalid PPTX: missing ppt/presentation.xml")++ slide_size = {"width_emu": 0, "height_emu": 0, "width_px": 0, "height_px": 0}+ sld_sz = presentation_root.find("p:sldSz", NS)+ if sld_sz is not None:+ width_emu = int(sld_sz.attrib.get("cx", "0"))+ height_emu = int(sld_sz.attrib.get("cy", "0"))+ slide_size = {+ "width_emu": width_emu,+ "height_emu": height_emu,+ "width_px": emu_to_pixels(width_emu),+ "height_px": emu_to_pixels(height_emu),+ }++ presentation_rels = parse_relationships(zf, "ppt/presentation.xml")+ slide_parts: list[str] = []+ for sld_id in presentation_root.findall("p:sldIdLst/p:sldId", NS):+ rel_id = sld_id.attrib.get(f"{{{NS['r']}}}id")+ rel = presentation_rels.get(rel_id or "")+ if rel and rel["type"] == SLIDE_REL:+ slide_parts.append(rel["target"])++ asset_dir = output_dir / "assets"+ asset_dir.mkdir(parents=True, exist_ok=True)++ copied_assets: dict[str, str] = {}+ for info in zf.infolist():+ if not info.filename.startswith("ppt/media/") or info.is_dir():+ continue+ original_name = PurePosixPath(info.filename).name+ safe_name = sanitize_filename(original_name)+ destination = asset_dir / safe_name+ stem = destination.stem+ suffix = destination.suffix+ counter = 2+ while destination.exists():+ destination = asset_dir / f"{stem}_{counter}{suffix}"+ counter += 1+ with zf.open(info.filename) as src, open(destination, "wb") as dst:+ shutil.copyfileobj(src, dst)+ copied_assets[info.filename] = destination.name++ slide_records: list[SlideRecord] = []+ asset_usage: Counter[str] = Counter()++ theme_summary = {"colors": {}, "fonts": {}}++ for index, slide_path in enumerate(slide_parts, 1):+ slide_root = load_xml_from_zip(zf, slide_path)+ slide_rels = parse_relationships(zf, slide_path)++ layout_path = None+ for rel in slide_rels.values():+ if rel["type"] == LAYOUT_REL:+ layout_path = rel["target"]+ break++ layout_root = load_xml_from_zip(zf, layout_path) if layout_path else None+ layout_rels = parse_relationships(zf, layout_path) if layout_path else {}++ master_path = None+ for rel in layout_rels.values():+ if rel["type"] == MASTER_REL:+ master_path = rel["target"]+ break++ master_root = load_xml_from_zip(zf, master_path) if master_path else None+ master_rels = parse_relationships(zf, master_path) if master_path else {}++ theme_path = None+ for rel in master_rels.values():+ if rel["type"] == THEME_REL:+ theme_path = rel["target"]+ break+ if theme_path and not theme_summary["colors"] and not theme_summary["fonts"]:+ theme_summary = parse_theme(load_xml_from_zip(zf, theme_path))++ bg_asset = None+ bg_source = None+ for label, root, rels in (+ ("slide", slide_root, slide_rels),+ ("layout", layout_root, layout_rels),+ ("master", master_root, master_rels),+ ):+ candidate = detect_background_asset(root, rels)+ if candidate:+ bg_asset = candidate+ bg_source = label+ break++ image_targets = extract_image_targets(slide_root, slide_rels)+ texts = extract_text_samples(slide_root)+ shape_count = count_slide_shapes(slide_root)+ page_type = classify_slide(index, len(slide_parts), texts, len(image_targets), shape_count)++ resolved_bg = copied_assets.get(bg_asset, PurePosixPath(bg_asset).name if bg_asset else None)+ resolved_images = [+ copied_assets.get(target, PurePosixPath(target).name)+ for target in image_targets+ ]++ if resolved_bg:+ asset_usage[resolved_bg] += 1+ for asset_name in resolved_images:+ asset_usage[asset_name] += 1++ slide_records.append(+ SlideRecord(+ index=index,+ name=PurePosixPath(slide_path).name,+ slide_path=slide_path,+ layout_path=layout_path,+ master_path=master_path,+ background_asset=resolved_bg,+ background_source=bg_source,+ image_assets=resolved_images,+ text_samples=texts,+ text_count=len(texts),+ shape_count=shape_count,+ page_type=page_type,+ )+ )++ common_assets = choose_common_assets(asset_usage)+ page_type_map: dict[str, list[int]] = defaultdict(list)+ for slide in slide_records:+ page_type_map[slide.page_type].append(slide.index)++ manifest = {+ "source": {+ "pptx": str(pptx_path),+ "name": pptx_path.name,+ },+ "slideSize": slide_size,+ "theme": theme_summary,+ "assets": {+ "exportDir": "assets",+ "commonAssets": common_assets,+ "allAssets": sorted(copied_assets.values()),+ },+ "pageTypeCandidates": dict(sorted(page_type_map.items())),+ "slides": [+ {+ "index": slide.index,+ "name": slide.name,+ "slidePath": slide.slide_path,+ "layoutPath": slide.layout_path,+ "masterPath": slide.master_path,+ "backgroundAsset": slide.background_asset,+ "backgroundSource": slide.background_source,+ "imageAssets": slide.image_assets,+ "textSamples": slide.text_samples,+ "textCount": slide.text_count,+ "shapeCount": slide.shape_count,+ "pageType": slide.page_type,+ }+ for slide in slide_records+ ],+ }++ write_analysis(+ output_dir / "analysis.md",+ pptx_path.name,+ slide_size,+ theme_summary,+ slide_records,+ common_assets,+ )+ return manifest+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Extract reusable assets and style metadata from a PPTX template source."+ )+ parser.add_argument("pptx_file", help="Path to the source .pptx file")+ parser.add_argument(+ "-o",+ "--output",+ help="Output directory (default: <pptx_stem>_template_import beside the source file)",+ )+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ pptx_path = Path(args.pptx_file).expanduser().resolve()+ if not pptx_path.exists():+ print(f"Error: file does not exist: {pptx_path}")+ return 1+ if pptx_path.suffix.lower() != ".pptx":+ print(f"Error: expected a .pptx file, got: {pptx_path.name}")+ return 1++ output_dir = (+ Path(args.output).expanduser().resolve()+ if args.output+ else pptx_path.with_name(f"{pptx_path.stem}_template_import")+ )+ output_dir.mkdir(parents=True, exist_ok=True)++ try:+ manifest = build_manifest(pptx_path, output_dir)+ except Exception as exc:+ print(f"Error: failed to import template source: {exc}")+ return 1++ manifest_path = output_dir / "manifest.json"+ manifest_path.write_text(+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )++ print(f"Imported PPTX template source: {pptx_path.name}")+ print(f"Output directory: {output_dir}")+ print(f"Manifest: {manifest_path.name}")+ print(f"Assets exported: {len(manifest['assets']['allAssets'])}")+ print(f"Common assets: {len(manifest['assets']['commonAssets'])}")+ print(f"Slides analyzed: {len(manifest['slides'])}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/template_import/optimize_reference.py b/skills/ppt-master/scripts/template_import/optimize_reference.pynew file mode 100644index 00000000..ec9c4731--- /dev/null+++ b/skills/ppt-master/scripts/template_import/optimize_reference.py@@ -0,0 +1,326 @@+#!/usr/bin/env python3+"""Internal helper: optimize reference SVG files generated from PPTX/PDF exports.++This helper targets reference-quality SVGs used during template reconstruction.+It focuses on safe structural reductions:++- deduplicate identical clipPath definitions inside each SVG+- round excessive numeric precision in geometric attributes+- emit a small report with potential repeated icon/path candidates+"""++from __future__ import annotations++import argparse+import json+import math+import re+from collections import defaultdict+from dataclasses import dataclass+from pathlib import Path+from xml.etree import ElementTree as ET++from .externalize_images import discover_svg_files+++SVG_NS = "http://www.w3.org/2000/svg"+XLINK_NS = "http://www.w3.org/1999/xlink"+INKSCAPE_NS = "http://www.inkscape.org/namespaces/inkscape"++ET.register_namespace("", SVG_NS)+ET.register_namespace("xlink", XLINK_NS)+ET.register_namespace("inkscape", INKSCAPE_NS)++NS = {"svg": SVG_NS}+TAG_SUFFIX_RE = re.compile(r"\{[^}]+\}")+NUMBER_RE = re.compile(r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?")++SAFE_ROUND_ATTRS = {+ "d",+ "transform",+ "x",+ "y",+ "x1",+ "x2",+ "y1",+ "y2",+ "cx",+ "cy",+ "r",+ "rx",+ "ry",+ "width",+ "height",+ "font-size",+ "stroke-width",+ "viewBox",+ "dx",+ "dy",+ "letter-spacing",+}+++@dataclass+class OptimizeResult:+ svg_path: Path+ original_bytes: int+ optimized_bytes: int+ clip_paths_removed: int+ numeric_tokens_rounded: int+ flattened_tspans: int+++def local_name(tag: str) -> str:+ return TAG_SUFFIX_RE.sub("", tag)+++def format_number(value: float, precision: int) -> str:+ rounded = round(value, precision)+ if math.isclose(rounded, round(rounded), abs_tol=10 ** (-(precision + 1))):+ return str(int(round(rounded)))+ text = f"{rounded:.{precision}f}".rstrip("0").rstrip(".")+ return text if text != "-0" else "0"+++def round_numbers_in_text(text: str, precision: int) -> tuple[str, int]:+ count = 0++ def repl(match: re.Match[str]) -> str:+ nonlocal count+ raw = match.group(0)+ try:+ value = float(raw)+ except ValueError:+ return raw+ rounded = format_number(value, precision)+ if rounded != raw:+ count += 1+ return rounded++ return NUMBER_RE.sub(repl, text), count+++def round_element_attributes(root: ET.Element, precision: int) -> int:+ rounded = 0+ for element in root.iter():+ for attr_name, attr_value in list(element.attrib.items()):+ if local_name(attr_name) not in SAFE_ROUND_ATTRS:+ continue+ updated, count = round_numbers_in_text(attr_value, precision)+ if count:+ element.set(attr_name, updated)+ rounded += count+ return rounded+++def clip_signature(clip_element: ET.Element) -> str:+ payload = []+ for child in list(clip_element):+ payload.append(ET.tostring(child, encoding="unicode"))+ return "".join(payload)+++def apply_id_remap(root: ET.Element, remap: dict[str, str]) -> None:+ if not remap:+ return+ for element in root.iter():+ for attr_name, attr_value in list(element.attrib.items()):+ updated = attr_value+ for old_id, new_id in remap.items():+ updated = updated.replace(f"url(#{old_id})", f"url(#{new_id})")+ updated = updated.replace(f"#{old_id}", f"#{new_id}")+ if updated != attr_value:+ element.set(attr_name, updated)+++def deduplicate_clip_paths(root: ET.Element) -> int:+ removed = 0+ remap: dict[str, str] = {}++ for defs in root.findall(".//svg:defs", NS):+ seen: dict[str, str] = {}+ for clip in list(defs):+ if local_name(clip.tag) != "clipPath":+ continue+ clip_id = clip.attrib.get("id")+ if not clip_id:+ continue+ signature = clip_signature(clip)+ existing = seen.get(signature)+ if existing is None:+ seen[signature] = clip_id+ continue+ remap[clip_id] = existing+ defs.remove(clip)+ removed += 1++ apply_id_remap(root, remap)+ return removed+++def collect_icon_candidates(root: ET.Element, svg_name: str) -> list[dict[str, str | int]]:+ candidates: list[dict[str, str | int]] = []+ for path in root.iter():+ if local_name(path.tag) != "path":+ continue+ d = path.attrib.get("d", "")+ if not d or len(d) > 220:+ continue+ if any(ancestor in d for ancestor in ("960V540", "1280V720")):+ continue+ candidates.append(+ {+ "file": svg_name,+ "d": d,+ "fill": path.attrib.get("fill", ""),+ "stroke": path.attrib.get("stroke", ""),+ }+ )+ return candidates+++def flatten_single_tspan_text(root: ET.Element) -> int:+ flattened = 0+ for text_el in list(root.iter()):+ if local_name(text_el.tag) != "text":+ continue+ children = list(text_el)+ if len(children) != 1 or local_name(children[0].tag) != "tspan":+ continue+ tspan = children[0]+ if list(tspan):+ continue+ if (tspan.tail or "").strip():+ continue++ for attr_name, attr_value in list(tspan.attrib.items()):+ if attr_name not in text_el.attrib:+ text_el.set(attr_name, attr_value)+ text_el.text = tspan.text or ""+ text_el.remove(tspan)+ flattened += 1+ return flattened+++def optimize_svg_file(svg_path: Path, precision: int) -> tuple[OptimizeResult, list[dict[str, str | int]]]:+ original_bytes = svg_path.stat().st_size+ root = ET.parse(svg_path).getroot()++ rounded = round_element_attributes(root, precision)+ clip_paths_removed = deduplicate_clip_paths(root)+ flattened_tspans = flatten_single_tspan_text(root)+ icon_candidates = collect_icon_candidates(root, svg_path.name)++ xml = ET.tostring(root, encoding="unicode")+ svg_path.write_text(xml, encoding="utf-8")++ return (+ OptimizeResult(+ svg_path=svg_path,+ original_bytes=original_bytes,+ optimized_bytes=svg_path.stat().st_size,+ clip_paths_removed=clip_paths_removed,+ numeric_tokens_rounded=rounded,+ flattened_tspans=flattened_tspans,+ ),+ icon_candidates,+ )+++def write_component_reports(candidates: list[dict[str, str | int]], output_dir: Path) -> None:+ grouped: dict[tuple[str, str, str], list[str]] = defaultdict(list)+ for item in candidates:+ grouped[(str(item["d"]), str(item["fill"]), str(item["stroke"]))].append(str(item["file"]))++ icon_report = []+ component_report = []+ for (d, fill, stroke), files in grouped.items():+ unique_files = sorted(set(files))+ if len(unique_files) < 2:+ continue+ record = {+ "files": unique_files,+ "fileCount": len(unique_files),+ "occurrences": len(files),+ "fill": fill,+ "stroke": stroke,+ "path": d,+ }+ icon_report.append(record)++ is_boundary = d in {"M0 540H960V0L0 0", "M0 540H960V0H0", "M0 540H960V0L00"}+ if fill and not stroke and not is_boundary and len(d) <= 120:+ component_report.append({**record, "kind": "decorative_component"})++ icon_report.sort(key=lambda item: (-item["fileCount"], -item["occurrences"], len(item["path"])))+ component_report.sort(key=lambda item: (-item["fileCount"], -item["occurrences"], len(item["path"])))+ (output_dir / "icon_candidates.json").write_text(+ json.dumps(icon_report[:200], ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+ (output_dir / "template_component_candidates.json").write_text(+ json.dumps(component_report[:200], ensure_ascii=False, indent=2) + "\n",+ encoding="utf-8",+ )+++def optimize_reference_batch(+ inputs: list[str],+ precision: int = 2,+) -> tuple[list[OptimizeResult], Path]:+ svg_files = discover_svg_files(inputs)+ if not svg_files:+ raise ValueError("no SVG files found")++ results: list[OptimizeResult] = []+ icon_candidates: list[dict[str, str | int]] = []+ for svg_file in svg_files:+ result, icons = optimize_svg_file(svg_file, precision=precision)+ results.append(result)+ icon_candidates.extend(icons)++ output_dir = svg_files[0].parent.parent if svg_files[0].parent.name == "svg" else svg_files[0].parent+ write_component_reports(icon_candidates, output_dir)+ return results, output_dir+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Optimize reference SVG files by deduplicating clip paths and reducing numeric precision."+ )+ parser.add_argument("inputs", nargs="+", help="SVG files or directories")+ parser.add_argument(+ "--precision",+ type=int,+ default=2,+ help="Decimal precision for geometric attributes (default: 2)",+ )+ return parser.parse_args()+++def main() -> int:+ args = parse_args()+ try:+ results, output_dir = optimize_reference_batch(args.inputs, precision=args.precision)+ except ValueError as exc:+ print(f"Error: {exc}")+ return 1++ before = sum(item.original_bytes for item in results)+ after = sum(item.optimized_bytes for item in results)+ removed = sum(item.clip_paths_removed for item in results)+ rounded = sum(item.numeric_tokens_rounded for item in results)+ flattened = sum(item.flattened_tspans for item in results)++ print(f"Optimized SVG files: {len(results)}")+ print(f"SVG bytes: {before} -> {after}")+ print(f"Duplicate clipPaths removed: {removed}")+ print(f"Rounded numeric tokens: {rounded}")+ print(f"Flattened single-tspan texts: {flattened}")+ print(f"Icon candidate report: {output_dir / 'icon_candidates.json'}")+ print(f"Template component report: {output_dir / 'template_component_candidates.json'}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/templates/layouts/layouts_index.json b/skills/ppt-master/templates/layouts/layouts_index.jsonindex 5053a8cc..dcd6a867 100644--- a/skills/ppt-master/templates/layouts/layouts_index.json+++ b/skills/ppt-master/templates/layouts/layouts_index.json@@ -5,7 +5,7 @@"formats": ["ppt169"],"standardFiles": ["design_spec.md", "01_cover.svg", "02_toc.svg", "02_chapter.svg", "03_content.svg", "04_ending.svg"],"standardPageTypes": ["cover", "toc", "chapter", "content", "ending"],- "updated": "2026-03-22"+ "updated": "2026-04-09"},"categories": {"brand": {diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.mdindex 354a507d..b0b9f61e 100644--- a/skills/ppt-master/workflows/create-template.md+++ b/skills/ppt-master/workflows/create-template.md@@ -49,29 +49,43 @@ Confirm the following with the user:ls -la "<reference_source_path>"```-If the reference source is a `.pptx` template file, first run the lightweight import helper to extract reusable assets and style metadata:+If the reference source is a `.pptx` template file, use the unified preparation helper:```bashpython3 skills/ppt-master/scripts/pptx_template_import.py "<reference_template.pptx>"```-Use the generated `manifest.json`, `analysis.md`, and exported `assets/` as internal reference material for template reconstruction. This helper is intentionally limited to asset/style extraction; it does **not** directly convert the PPTX into final template SVG files.+This helper performs the full PPTX reference preparation in one workspace:-When `.pptx` import output exists, use the following internal priority order during template creation:+- extracts reusable assets and style metadata+- generates `manifest.json`+- generates `analysis.md`+- exports each slide to `svg/`+- externalizes large inline bitmap payloads into `assets/`+- generates `reference_svg_selection.json`++It is still a reconstruction aid, not a final direct template conversion.++Use the generated `manifest.json`, `analysis.md`, exported `assets/`, and `svg/` slide references as internal reference material for template reconstruction.++When the reference source is `.pptx`, use the following internal priority order during template creation:1. `manifest.json`2. `analysis.md`3. exported `assets/`-4. user-provided screenshots or the original PPTX only for visual cross-checking+4. cleaned slide SVG references from `svg/`+5. user-provided screenshots or the original PPTX only for visual cross-checkingInterpretation rule:- `manifest.json` is the source of truth for slide size, theme colors, fonts, background inheritance, and reusable asset inventory- `analysis.md` is the compact human-readable summary used to guide page-type selection- exported `assets/` are the preferred source for backgrounds, logos, and decorative images+- cleaned `svg/` slides are mandatory reference material for layout rhythm, page composition, and fixed decorative structure+- do not consume every exported SVG by default: always reference slides `1`, `2`, and the last slide, then add at least `7` representative SVG pages from the remaining slides- screenshots remain useful for judging composition and style, but should not override extracted factual metadata unless the import result is clearly incomplete-Do **not** treat the imported PPTX as a direct SVG conversion target. The goal is to reconstruct a clean, maintainable PPT Master template package, not to perform 1:1 shape translation.+Do **not** treat the imported PPTX or exported slide SVGs as direct final template assets. The goal is to reconstruct a clean, maintainable PPT Master template package, not to perform 1:1 shape translation.---@@ -91,12 +105,14 @@ mkdir -p "skills/ppt-master/templates/layouts/<template_id>"**Switch to the Template_Designer role** and generate per role definition. The role input is the finalized template brief from Step 1, not a project design spec.-If `.pptx` import output exists, pass the following internal package to the role:+If the reference source is `.pptx`, pass the following internal package to the role:- finalized template brief from Step 1- `manifest.json`- `analysis.md`- exported `assets/`+- cleaned slide SVG references from `svg/`+- `reference_svg_selection.json`- optional screenshots, if availableThe role should use the import output to anchor objective facts such as theme colors, fonts, reusable backgrounds, and common branding assets, then rebuild the final SVG templates in a simplified, maintainable form.