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(create-template): native-only PPTX import + replication mode
hugohe3a95fd6a31735
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.mdindex ad26691b..95310e24 100644--- a/skills/ppt-master/references/template-designer.md+++ b/skills/ppt-master/references/template-designer.md@@ -21,10 +21,8 @@ When the workflow provides a PPTX reference source, the effective input package- `master_layout_refs.json`- `master_layout_analysis.md`- `analysis.md`-- `normalized_assets.json`- exported `assets/`- cleaned slide SVG references from `svg/`-- `reference_svg_selection.json`- optional screenshots for visual cross-checkingInput priority for PPTX-backed template creation:@@ -32,16 +30,23 @@ Input priority for PPTX-backed template creation:1. `manifest.json` for factual metadata2. `master_layout_refs.json` for unique layout/master structure and inheritance3. `master_layout_analysis.md` for fast structural review-4. `normalized_assets.json` for canonical asset decisions+4. `analysis.md` for page-type guidance5. exported `assets/` for reusable visual resources-6. `analysis.md` for page-type guidance-7. `reference_svg_selection.json` for deciding which exported SVG pages to inspect first-8. cleaned slide SVG references for composition, spacing, and fixed decorative cues-9. screenshots / original PPTX only for style verification+6. cleaned slide SVG references for composition, spacing, and fixed decorative cues+7. screenshots / original PPTX only for style verification----## Core Template Inventory+## Page Roster++The output page set is determined by **replication mode**, declared in the Step 1 brief:++| Mode | When to use | Roster |+|------|-------------|--------|+| `standard` (default) | Most templates — clean, reusable, balanced coverage | `01_cover`, `02_chapter`, `03_content`, `04_ending`, optional `02_toc` |+| `fidelity` | User explicitly wants strict replication of a source PPTX | Standard roster + one variant per distinct layout cluster found in `manifest.json` |++### Standard mode| # | Filename | Purpose | Description ||---|----------|---------|-------------|@@ -55,11 +60,28 @@ Input priority for PPTX-backed template creation:**Naming note**: TOC page keeps `02_toc.svg` naming for template library compatibility and sort order.-### Optional Extension Pages (As Needed)+### Fidelity mode++When the brief sets `Replication mode: fidelity`, derive the page roster from `manifest.json` page-type clusters and emit one SVG per distinct visual cluster.++**Variant naming**: append a lowercase letter suffix to the parent type's index, preserving sort order:-- Transition / sub-section page (e.g., `05_section_break.svg`)-- Appendix page (e.g., `06_appendix.svg`)-- Disclaimer / confidentiality page (e.g., `07_disclaimer.svg`)+| Parent type | Example variants |+|-------------|------------------|+| Chapter | `02a_chapter_full.svg`, `02b_chapter_minimal.svg` |+| Content | `03a_content_two_col.svg`, `03b_content_data_card.svg`, `03c_content_quote.svg` |+| Ending | `04a_ending_thanks.svg`, `04b_ending_contact.svg` |++Extension page types beyond the canonical four (transition / appendix / disclaimer / divider) take the next free index: `05_section_break.svg`, `06_appendix.svg`, `07_disclaimer.svg`.++**Roster decision**:++- Cluster slides from `manifest.json` by `pageType` + visual structure (column count, hero-image vs. icon-grid vs. quote, etc.)+- One SVG per cluster — do **not** emit a variant for a cluster represented by a single source slide unless that slide is structurally distinct from existing variants+- Cap at 8 content variants per template; collapse near-duplicates into the closest existing variant+- Record every emitted page in `design_spec.md §VI` and in the `pages` field of the `layouts_index.json` entry++**Placeholder contract for variants**: variants reuse the parent type's placeholder set (every `03*_content*.svg` shares the content placeholder set). Do **not** introduce variant-specific placeholder families.---@@ -77,7 +99,7 @@ When creating a global template, a `design_spec.md` must be generated, containin## III. Color Scheme (primary, secondary, accent HEX values)## IV. Typography System (font stack, font size hierarchy)## V. Page Structure (common layout, decorative design)-## VI. Page Types (4 core page types)+## VI. Page Roster (one row per emitted SVG, with replication mode and cluster source)## VII. Layout Modes (recommended)## VIII. Spacing Specification## IX. SVG Technical Constraints@@ -94,12 +116,12 @@ Templates must strictly follow the finalized template brief and the generated `dIf PPTX import output exists:- Prefer imported theme colors and fonts over visually guessed values-- Reuse canonical backgrounds and logos from `normalized_assets.json` where they are globally meaningful to the template+- Reuse exported `assets/` images directly — `<image>` references in `svg/` already point at canonical files- Treat page-type candidates from `analysis.md` as hints, not guarantees**Precondition**:-- If `reference_svg_selection.json` is provided, do not generate any template SVG or `design_spec.md` until all selected reference SVG files have been read+- When PPTX import output is provided, do not generate any template SVG or `design_spec.md` until every file under `<import_workspace>/svg/` has been read- Before template generation begins, explicitly report the read slide indexes### 2.1 PPTX Import Simplification Rule@@ -111,25 +133,14 @@ 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-- prefer original exported assets such as `image1.png` over matched `inline_*` assets whenever AI normalization determines they represent the same visible image-- treat `inline_*` assets primarily as export-reference layers rather than final template asset names- use cleaned slide SVG references to inspect composition, spacing, text hierarchy, and fixed decorative structure only after factual metadata has been anchored-- if there are `<= 10` cleaned SVG reference pages to inspect, read all of them; if there are more than `10`, read only `10` representative pages+- read every cleaned SVG reference page under `svg/`, regardless of slide count — partial coverage drops template fidelity+- rename adopted assets to semantic names (`cover_bg.png`, `brand_emblem.png`) rather than carrying raw `image3.png` into the final templateDo not:- attempt 1:1 translation of every PowerPoint shape, group, shadow, or decorative fragment- mirror PPT-specific complexity when it makes the resulting SVG brittle or hard to edit- introduce dense low-value vector detail that does not materially improve template reuse-- promote mask-only / alpha-helper `inline_*` assets into the final template package unless they are the only viable reusable representation--### 2.2 Original-vs-Inline Asset Normalization--When `normalized_assets.json` exists, follow these rules:--1. If an original exported asset and an `inline_*` asset clearly correspond to the same visible image, use the **original exported asset** as the canonical template source.-2. If an `inline_*` asset has no reliable original exported counterpart, it may be kept as a derived template asset.-3. If an `inline_*` asset appears only as a mask, alpha helper, or other non-semantic support layer inside SVG export output, do not include it in the final template asset set by default.-4. Final template asset names should be semantic, such as `cover_bg.png` or `brand_emblem.png`, rather than `image3.png` or `inline_abcd1234.png`.### 3. Placeholder Markers@@ -187,6 +198,8 @@ When rebuilding from imported PPTX references, placeholder insertion takes prior### File Save Location+Standard mode (default):+```templates/layouts/<template_name>/├── design_spec.md # Design specification (required)@@ -198,6 +211,23 @@ templates/layouts/<template_name>/└── *.png / *.jpg # Image assets (if any)```+Fidelity mode adds variants and extension pages, e.g.:++```+templates/layouts/<template_name>/+├── design_spec.md+├── 01_cover.svg+├── 02a_chapter_full.svg+├── 02b_chapter_minimal.svg+├── 02_toc.svg+├── 03a_content_two_col.svg+├── 03b_content_data_card.svg+├── 03c_content_quote.svg+├── 04_ending.svg+├── 05_section_break.svg+└── *.png / *.jpg+```+### Template PreviewAfter each template is generated, provide a brief summary table listing each template's status.@@ -236,11 +266,10 @@ templates/layouts/## Template_Designer Phase Complete- [x] Read `references/template-designer.md`-- [x] Generated 4 core page templates-- [ ] TOC page template (optional)-- [ ] Optional extension pages (if needed)-- [x] All templates saved to `templates/layouts/<template_name>/`+- [x] Replication mode confirmed: `standard` | `fidelity`+- [x] Every page listed in `design_spec.md §VI` saved to `templates/layouts/<template_name>/`+- [x] Variant naming follows the letter-suffix convention; variants reuse parent placeholder contract- [x] Templates follow design spec (colors, fonts, layout)- [x] Placeholder markers are clear and standardized-- [ ] **Next step**: Validate assets and register the template in `layouts_index.json`+- [ ] **Next step**: Validate assets and register the template in `layouts_index.json` (include `pages` field)```diff --git a/skills/ppt-master/scripts/docs/project.md b/skills/ppt-master/scripts/docs/project.mdindex dacdd3e6..a1450b2c 100644--- a/skills/ppt-master/scripts/docs/project.md+++ b/skills/ppt-master/scripts/docs/project.md@@ -86,18 +86,17 @@ Unified PPTX preparation entry point for `/create-template`.python3 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-rawpython3 scripts/pptx_template_import.py <template.pptx> --skip-manifest+python3 scripts/pptx_template_import.py <template.pptx> --embed-images```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-- Generates `manifest.json`, `analysis.md`, `master_layout_refs.json`, `master_layout_analysis.md`, `assets/`, cleaned slide SVGs, and `reference_svg_selection.json`-- Native SVG export is Windows-only because it uses installed Microsoft PowerPoint-- On macOS, the script falls back to exporting PDF via Keynote and then converts PDF pages to SVG-- Writes cleaned SVG files to `svg/` after externalizing inline Base64 image payloads+- Generates `manifest.json`, `analysis.md`, `master_layout_refs.json`, `master_layout_analysis.md`, `assets/`, and shape-level slide SVGs under `svg/`+- SVG export reads OOXML directly via `pptx_to_svg` — no PowerPoint or Keynote dependency, runs on any platform+- `<image>` elements in `svg/` reference files in `assets/` directly; pass `--embed-images` to inline as data URIs instead- 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 exportdiff --git a/skills/ppt-master/scripts/pptx_template_import.py b/skills/ppt-master/scripts/pptx_template_import.pyindex e6ec9df2..0718de79 100644--- a/skills/ppt-master/scripts/pptx_template_import.py+++ b/skills/ppt-master/scripts/pptx_template_import.py@@ -1,223 +1,22 @@#!/usr/bin/env python3"""Unified PPTX preparation entry point for the /create-template workflow.-This command prepares a reusable reference workspace from a PPTX source. It can:+Reads OOXML directly via `pptx_to_svg` and writes a reusable reference workspace:-1. extract lightweight PPTX metadata and reusable assets-2. export every slide to SVG with PowerPoint on Windows-3. export PPTX to PDF on macOS with Keynote as a fallback bridge-4. replace inline Base64 images inside exported SVG files with external assets-5. optimize cleaned reference SVG files for downstream inspection+- `manifest.json` — slide size, theme colors, fonts, asset inventory+- `master_layout_refs.json` / `master_layout_analysis.md` — master/layout structure+- `analysis.md` — page-type guidance+- `assets/` — extracted reusable image assets+- `svg/` — shape-level SVG per slide (real <text>, <image>, geometry)"""from __future__ import annotationsimport argparseimport json-import platform-import subprocess-import tempfilefrom pathlib import Path-from template_import.externalize_images import discover_svg_files, externalize_svg_batchfrom 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()-}-"""---POWERSHELL_PDF_EXPORT_SCRIPT = r"""-param(- [Parameter(Mandatory = $true)][string]$PptxPath,- [Parameter(Mandatory = $true)][string]$PdfPath-)--$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()-}-"""---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)-- 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 run_osascript_lines(*script_lines: str) -> subprocess.CompletedProcess[bytes]:- command = ["osascript"]- for line in script_lines:- command.extend(["-e", line])- return subprocess.run(- command,- capture_output=True,- text=False,- check=False,- )--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 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")-- output_dir.mkdir(parents=True, exist_ok=True)- completed = run_powershell_script(- POWERSHELL_EXPORT_SCRIPT,- "-PptxPath",- str(pptx_path),- "-OutputDir",- str(output_dir),- )-- 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:- system = platform.system()-- if system == "Windows":- completed = run_powershell_script(- POWERSHELL_PDF_EXPORT_SCRIPT,- "-PptxPath",- str(pptx_path),- "-PdfPath",- str(pdf_path),- )- elif system == "Darwin":- pdf_path.parent.mkdir(parents=True, exist_ok=True)- completed = run_osascript_lines(- 'tell application "Keynote"',- "activate",- f'set pptxFile to POSIX file "{pptx_path}"',- f'set pdfFile to POSIX file "{pdf_path}"',- "with timeout of 600 seconds",- "set docRef to open pptxFile",- "export docRef to pdfFile as PDF",- "close docRef saving no",- "end timeout",- "end tell",- )- else:- raise RuntimeError(- "PPTX to PDF export is supported on Windows (PowerPoint) and macOS (Keynote)"- )-- if completed.returncode != 0:- raise RuntimeError(decode_process_output(completed))- if not pdf_path.exists():- raise RuntimeError("PPTX 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---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:@@ -240,125 +39,14 @@ def parse_args() -> argparse.Namespace:action="store_true",help="Only extract manifest.json, analysis.md, and reusable assets without exporting slides to SVG",)- parser.add_argument(- "--legacy-render",- action="store_true",- help=(- "Use the legacy renderer (PowerPoint COM on Windows, Keynote -> PDF "- "on macOS). Lossy: text becomes <path>, every cropped picture spawns "- "a new inline_*.png slice. The default semantic converter "- "(pptx_to_svg) reads OOXML directly and preserves shape primitives."- ),- )- parser.add_argument(- "--keep-raw",- action="store_true",- help="(--legacy-render only) Keep raw PowerPoint-exported SVG files in svg_raw/",- )- parser.add_argument(- "--no-externalize",- action="store_true",- help="(--legacy-render only) Skip inline image externalization",- )- parser.add_argument(- "--no-optimize",- action="store_true",- help="(--legacy-render only) Skip structural optimization of the cleaned reference SVGs",- )parser.add_argument("--embed-images",action="store_true",- help="(default renderer only) Inline images as data: URIs instead of writing files to assets/",+ help="Inline images as data: URIs instead of writing files to assets/",)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()@@ -392,8 +80,6 @@ def main() -> int: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}")@@ -405,49 +91,6 @@ def main() -> int:print(f"Slides analyzed: {len(manifest['slides'])}")return 0- # ---------- Slide rendering ----------- if args.legacy_render:- export_mode, slide_count, total_in, total_out = _render_slides_legacy(- pptx_path, output_dir, args,- )- else:- export_mode, slide_count, total_in, total_out = _render_slides_native(- pptx_path, output_dir, args,- )-- # reference_svg_selection.json (shared between both paths)- cleaned_dir = output_dir / "svg"- 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"Export mode: {export_mode}")- print(f"Exported SVG slides: {slide_count}")- if total_in is not None and total_out is not None:- print(f"SVG bytes: {total_in} -> {total_out}")- print(f"Reference SVG selection: {output_dir / 'reference_svg_selection.json'}")- print(f"Output directory: {output_dir}")- return 0---# ----------------------------------------------------------------------------# Slide rendering — default (native, semantic) path-# -----------------------------------------------------------------------------def _render_slides_native(- pptx_path: Path,- output_dir: Path,- args: argparse.Namespace,-) -> tuple[str, int, int | None, int | None]:- """Read OOXML directly via pptx_to_svg and emit shape-level SVGs.-- This path preserves text as <text>, picture primitives as <image>, and- doesn't spawn inline_*.png crop slices. Default since stage G integration.- """from pptx_to_svg import convert_pptx_to_svgfrom pptx_to_svg.converter import ConvertOptions@@ -458,59 +101,11 @@ def _render_slides_native()result = convert_pptx_to_svg(pptx_path, output_dir, options)total_bytes = sum(len(art.svg.encode("utf-8")) for art in result.slides)- return "pptx_to_svg-native", len(result.slides), total_bytes, total_bytes---# ----------------------------------------------------------------------------# Slide rendering — legacy (PowerPoint COM / Keynote PDF) path-# ----------------------------------------------------------------------------def _render_slides_legacy(- pptx_path: Path,- output_dir: Path,- args: argparse.Namespace,-) -> tuple[str, int, int | None, int | None]:- """Original lossy renderer: rasterize via PowerPoint or Keynote->PDF, then- externalize/optimize. Preserved for cases where the new semantic converter- misbehaves; intentionally opt-in (--legacy-render).- """- raw_dir = output_dir / "svg_raw"- raw_svg_files, export_mode = export_pptx_slides_to_svg_with_fallback(- pptx_path, raw_dir,- )-- if args.no_externalize:- return export_mode, len(raw_svg_files), None, None-- 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)- if raw_dir.exists():- raw_dir.rmdir()-- total_before = sum(item.original_svg_bytes for item in results)- total_images = sum(item.images_externalized for item in results)- print(f"Inline images externalized: {total_images}")- return export_mode, len(results), total_before, final_svg_bytes+ print(f"Exported SVG slides: {len(result.slides)}")+ print(f"SVG bytes: {total_bytes}")+ print(f"Output directory: {output_dir}")+ return 0if __name__ == "__main__":diff --git a/skills/ppt-master/scripts/template_import/externalize_images.py b/skills/ppt-master/scripts/template_import/externalize_images.pydeleted file mode 100644index 3dc9510e..00000000--- a/skills/ppt-master/scripts/template_import/externalize_images.py+++ /dev/null@@ -1,241 +0,0 @@-#!/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/optimize_reference.py b/skills/ppt-master/scripts/template_import/optimize_reference.pydeleted file mode 100644index cc1c5c9a..00000000--- a/skills/ppt-master/scripts/template_import/optimize_reference.py+++ /dev/null@@ -1,331 +0,0 @@-#!/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-import sys-from collections import defaultdict-from dataclasses import dataclass-from pathlib import Path-from xml.etree import ElementTree as ET--try:- from .externalize_images import discover_svg_files-except ImportError:- sys.path.insert(0, str(Path(__file__).resolve().parent))- from externalize_images import discover_svg_files # type: ignore---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/README.md b/skills/ppt-master/templates/layouts/README.mdindex d7b4b7ea..f86ba7c2 100644--- a/skills/ppt-master/templates/layouts/README.md+++ b/skills/ppt-master/templates/layouts/README.md@@ -3,7 +3,7 @@Pre-built PPT page layout templates supporting multiple styles and use cases.- **Full Index**: [README.md](./README.md) (human browsing — includes categories, primary colors, detailed tone)-- **Slim Index**: [layouts_index.json](./layouts_index.json) (lightweight lookup — `label` / `summary` / `keywords` only)+- **Slim Index**: [layouts_index.json](./layouts_index.json) (lightweight lookup — `label` / `summary` / `keywords` / `pages`)> **Template selection is opt-in.** The main workflow defaults to free design and does NOT read `layouts_index.json` unless the user explicitly requests a template. See `SKILL.md` Step 3.@@ -227,7 +227,7 @@ cp templates/layouts/government_red/* projects/<project>/templates/4. All SVGs use `viewBox="0 0 1280 720"`5. Follow SVG technical constraints (see below)6. Validate the template directory with `python3 scripts/svg_quality_checker.py templates/layouts/<template_name> --format ppt169`-7. Register the new template in `templates/layouts/layouts_index.json` with three fields: `label`, `summary`, `keywords`+7. Register the new template in `templates/layouts/layouts_index.json` with four fields: `label`, `summary`, `keywords`, `pages` (the SVG file stems shipped by the template)`layouts_index.json` is the lightweight lookup used when a user explicitly opts into the template flow. A template folder without an index entry will not be discoverable by that flow.diff --git a/skills/ppt-master/templates/layouts/layouts_index.json b/skills/ppt-master/templates/layouts/layouts_index.jsonindex 9d7fb297..19d65fd1 100644--- a/skills/ppt-master/templates/layouts/layouts_index.json+++ b/skills/ppt-master/templates/layouts/layouts_index.json@@ -2,106 +2,362 @@"academic_defense": {"label": "Academic Defense Template","summary": "A standard template for academic defenses, research presentations, and project proposals",- "keywords": ["Academic", "Defense", "Research", "Standard"]+ "keywords": [+ "Academic",+ "Defense",+ "Research",+ "Standard"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"ai_ops": {"label": "Enterprise Digital Intelligence Template","summary": "For high-density scenarios such as telecom AI operations architecture, IT system overview, and digital transformation plans",- "keywords": ["Telecom", "AI operations", "Digital intelligence", "High density", "Architecture view"]+ "keywords": [+ "Telecom",+ "AI operations",+ "Digital intelligence",+ "High density",+ "Architecture view"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"anthropic": {"label": "Anthropic Style Template","summary": "A tech-oriented template for AI/LLM knowledge sharing and product launches",- "keywords": ["AI", "LLM", "Developer", "Technology"]+ "keywords": [+ "AI",+ "LLM",+ "Developer",+ "Technology"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"china_telecom_template": {"label": "中国电信模板","summary": "A China Telecom style template for telecom solution proposals, digital transformation plans, and government-enterprise briefings",- "keywords": ["China Telecom", "Telecom", "Digital transformation", "Government-enterprise", "Briefing"]+ "keywords": [+ "China Telecom",+ "Telecom",+ "Digital transformation",+ "Government-enterprise",+ "Briefing"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"exhibit": {"label": "Exhibit Style Template","summary": "Conclusion-first layout with Exhibit takeaway bars for data-driven strategic reports and executive presentations",- "keywords": ["Exhibit", "Board", "Executive", "Strategy", "Conclusion-first"]+ "keywords": [+ "Exhibit",+ "Board",+ "Executive",+ "Strategy",+ "Conclusion-first"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"google_style": {"label": "Google Style Template","summary": "A Google-branded template for annual reports and technical sharing",- "keywords": ["Google", "Brand style", "Technical sharing", "Annual report"]+ "keywords": [+ "Google",+ "Brand style",+ "Technical sharing",+ "Annual report"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"government_blue": {"label": "Government Blue Template","summary": "A blue government-themed template for smart governance and digital transformation reports",- "keywords": ["Government affairs", "Government blue", "Smart city", "Digitalization"]+ "keywords": [+ "Government affairs",+ "Government blue",+ "Smart city",+ "Digitalization"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"government_red": {"label": "Government Red Template","summary": "A red government-themed template for government reports and party-building scenarios",- "keywords": ["Government affairs", "Party building", "Government red", "Authoritative"]+ "keywords": [+ "Government affairs",+ "Party building",+ "Government red",+ "Authoritative"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"mckinsey": {"label": "McKinsey Style Template","summary": "A McKinsey-style template for strategic consulting and investment analysis",- "keywords": ["McKinsey", "Consulting", "Structured", "Executive presentation"]+ "keywords": [+ "McKinsey",+ "Consulting",+ "Structured",+ "Executive presentation"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"medical_university": {"label": "Hospital/Medical University Template","summary": "A professional template for medical reports, case discussions, and research presentations",- "keywords": ["Medical", "Hospital", "Case study", "Research"]+ "keywords": [+ "Medical",+ "Hospital",+ "Case study",+ "Research"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"pixel_retro": {"label": "Pixel Retro Template","summary": "A pixel-art template for tech sharing and gaming-themed content",- "keywords": ["Pixel art", "Retro gaming", "Cyberpunk", "Technology"]+ "keywords": [+ "Pixel art",+ "Retro gaming",+ "Cyberpunk",+ "Technology"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"psychology_attachment": {"label": "Psychology Healing Template","summary": "A warm and professional template for psychotherapy training and counseling lectures",- "keywords": ["Psychology", "Healing", "Counseling", "Warm"]+ "keywords": [+ "Psychology",+ "Healing",+ "Counseling",+ "Warm"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"smart_red": {"label": "Smart Red-Orange Business Template","summary": "A vibrant business template for tech company introductions and education solutions",- "keywords": ["Red-orange business", "Tech enterprise", "Education", "Vibrant"]+ "keywords": [+ "Red-orange business",+ "Tech enterprise",+ "Education",+ "Vibrant"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"中国电建_常规": {"label": "PowerChina Standard Template","summary": "A solid brand template for engineering construction and state-owned enterprise reports",- "keywords": ["PowerChina", "State-owned enterprise", "Engineering", "Energy"]+ "keywords": [+ "PowerChina",+ "State-owned enterprise",+ "Engineering",+ "Energy"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"中国电建_现代": {"label": "PowerChina Modern Template","summary": "A modern engineering template for major projects and international business presentations",- "keywords": ["PowerChina", "International engineering", "Modern engineering", "Technology"]+ "keywords": [+ "PowerChina",+ "International engineering",+ "Modern engineering",+ "Technology"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"中汽研_商务": {"label": "CATARC Business Template","summary": "A CATARC brand template for certification showcase and high-end business presentations",- "keywords": ["CATARC", "Certification", "Business", "Technology"]+ "keywords": [+ "CATARC",+ "Certification",+ "Business",+ "Technology"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"中汽研_常规": {"label": "CATARC Standard Template","summary": "A standard CATARC template for certification and testing scenarios",- "keywords": ["CATARC", "Certification", "Testing", "Authoritative"]+ "keywords": [+ "CATARC",+ "Certification",+ "Testing",+ "Authoritative"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"中汽研_现代": {"label": "CATARC Modern Template","summary": "A futuristic tech template for cutting-edge technology showcase and premium launches",- "keywords": ["CATARC", "Future tech", "Cutting-edge technology", "Launch event"]+ "keywords": [+ "CATARC",+ "Future tech",+ "Cutting-edge technology",+ "Launch event"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"招商银行": {"label": "China Merchants Bank Transaction Banking Template","summary": "A transaction-banking template for sales collection solutions, product pitches, and branch training",- "keywords": ["China Merchants Bank", "Transaction banking", "Sales collection", "Finance", "Training"]+ "keywords": [+ "China Merchants Bank",+ "Transaction banking",+ "Sales collection",+ "Finance",+ "Training"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"科技蓝商务": {"label": "Tech Blue Business Template","summary": "A tech-business template for corporate reports and solution proposals",- "keywords": ["Tech blue", "Business", "Solution proposal", "Corporate report"]+ "keywords": [+ "Tech blue",+ "Business",+ "Solution proposal",+ "Corporate report"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]},"重庆大学": {"label": "Chongqing University Template","summary": "A university-exclusive template for academic defenses and research presentations",- "keywords": ["Chongqing University", "Academic", "Defense", "University"]+ "keywords": [+ "Chongqing University",+ "Academic",+ "Defense",+ "University"+ ],+ "pages": [+ "01_cover",+ "02_chapter",+ "02_toc",+ "03_content",+ "04_ending"+ ]}}diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.mdindex 8dfb7a27..28ddff5d 100644--- a/skills/ppt-master/workflows/create-template.md+++ b/skills/ppt-master/workflows/create-template.md@@ -13,7 +13,7 @@ Generate a complete set of reusable PPT layout templates for the **global templa## Process Overview```-Gather Brief -> Import PPTX References -> Normalize Assets -> Create Directory -> Invoke Template_Designer -> Validate Assets -> Register Index -> Output+Gather Brief -> Import PPTX References -> Create Directory -> Invoke Template_Designer -> Validate Assets -> Register Index -> Output```---@@ -31,6 +31,7 @@ Confirm the following with the user:| Tone summary | Yes | Short tone description for recommendation, such as `Modern, restrained, data-driven` || Theme mode | Yes | Theme description for recommendation, such as `Light theme (white background + blue accent)` || Canvas format | Yes | Default `ppt169`; if another format is needed, specify it explicitly before generation |+| Replication mode | Yes | `standard` (default, 5-page roster) or `fidelity` (preserve every distinct layout from a `.pptx` source); `fidelity` requires a `.pptx` reference source || Reference source | Optional | Existing project, screenshot folder, or `.pptx` template file path || Theme color | Optional | Primary color HEX value (can be auto-extracted from reference) || Design style | Optional | Additional style notes, decorative language, brand cues |@@ -55,35 +56,15 @@ If the reference source is a `.pptx` template file, use the unified preparationpython3 skills/ppt-master/scripts/pptx_template_import.py "<reference_template.pptx>"```-This helper performs the full PPTX reference preparation in one workspace:+This helper reads OOXML directly via `pptx_to_svg` and produces, in one workspace:-- extracts reusable assets and style metadata-- generates `manifest.json`-- generates `analysis.md`-- generates `master_layout_refs.json`-- generates `master_layout_analysis.md`-- exports each slide to `svg/`-- externalizes large inline bitmap payloads into `assets/`-- generates `reference_svg_selection.json`+- `manifest.json` — slide size, theme colors, fonts, asset inventory+- `analysis.md` — page-type guidance summary+- `master_layout_refs.json` / `master_layout_analysis.md` — master/layout structure and inheritance+- `assets/` — extracted reusable image assets+- `svg/` — shape-level SVG per slide (real `<text>`, `<image>`, geometry)-It is still a reconstruction aid, not a final direct template conversion.--Use the generated `manifest.json`, `analysis.md`, `master_layout_refs.json`, `master_layout_analysis.md`, exported `assets/`, and `svg/` slide references as internal reference material for template reconstruction.--Then perform an **AI-only asset normalization step** before template generation:--- compare exported original assets such as `image1.png` with `inline_*` assets used by the cleaned slide SVGs-- if an `inline_*` visible image corresponds to an original exported asset, treat the **original asset** as the canonical source-- if an `inline_*` asset has no matching original exported asset, keep it as a derived candidate asset-- if an `inline_*` asset is only used as a mask / alpha helper / auxiliary layer, do **not** promote it to the final template asset set by default-- write the normalization result to `<import_workspace>/normalized_assets.json`--Recommended fields in `normalized_assets.json`:--- canonical asset path-- matched `inline_*` references-- role guess such as `cover_background`, `content_background`, `brand_overlay`, `mask_only`-- whether the asset should enter the final template package+It is a reconstruction aid, not a final direct template conversion.When the reference source is `.pptx`, use the following internal priority order during template creation:@@ -91,10 +72,9 @@ When the reference source is `.pptx`, use the following internal priority order2. `master_layout_refs.json`3. `master_layout_analysis.md`4. `analysis.md`-5. `normalized_assets.json`-6. exported `assets/`-7. cleaned slide SVG references from `svg/`-8. user-provided screenshots or the original PPTX only for visual cross-checking+5. exported `assets/`+6. cleaned slide SVG references from `svg/`+7. user-provided screenshots or the original PPTX only for visual cross-checkingInterpretation rule:@@ -102,37 +82,20 @@ Interpretation rule:- `master_layout_refs.json` is the source of truth for unique layout/master structure, inherited backgrounds, and slide reuse relationships- `master_layout_analysis.md` is the compact human-readable summary for quickly understanding reusable master/layout motifs- `analysis.md` is the compact human-readable summary used to guide page-type selection-- `normalized_assets.json` is the source of truth for which imported assets are canonical and which `inline_*` assets are only derived helpers-- exported `assets/` remain the raw import pool and should not be consumed blindly once normalization exists-- cleaned `svg/` slides are mandatory reference material for layout rhythm, page composition, and fixed decorative structure-- if the remaining cleaned SVG reference pages are `<= 10`, read all of them; if they are `> 10`, read only `10` representative pages+- exported `assets/` are the canonical reusable image pool — `<image>` references in `svg/` already point at these files directly+- cleaned `svg/` slides are mandatory reference material for layout rhythm, page composition, and fixed decorative structure; read **every** exported page regardless of slide count- screenshots remain useful for judging composition and style, but should not override extracted factual metadata unless the import result is clearly incomplete**Hard gate**:-- Before creating any template file, the agent MUST finish reading all SVG files listed in `reference_svg_selection.json`+- Before creating any template file, the agent MUST finish reading every SVG file under `<import_workspace>/svg/`- The agent MUST explicitly report the read slide indexes before starting template generationDo **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.----## Step 2: Normalize Imported Assets--When the reference source is `.pptx`, create the normalization artifact before generating the template.--**Required outcome of Step 2**:--- original exported assets and `inline_*` assets have been compared-- canonical assets prefer original exported files when a reliable match exists-- mask-only / helper-only `inline_*` assets are excluded from the final template asset shortlist by default-- `normalized_assets.json` is available for downstream template generation--If no `.pptx` source is involved, this step can be skipped.-------## Step 3: Create Template Directory+## Step 2: Create Template Directory```bashmkdir -p "skills/ppt-master/templates/layouts/<template_id>"@@ -144,7 +107,7 @@ mkdir -p "skills/ppt-master/templates/layouts/<template_id>"----## Step 4: Invoke Template_Designer Role+## Step 3: Invoke Template_Designer Role**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.@@ -155,16 +118,14 @@ If the reference source is `.pptx`, pass the following internal package to the r- `master_layout_refs.json`- `master_layout_analysis.md`- `analysis.md`-- `normalized_assets.json`- 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.-1. **design_spec.md** — Design specification document-2. **4 core templates** — Cover, chapter, content, ending pages+1. **design_spec.md** — Design specification document, with §VI listing the page roster+2. **Page roster** — `standard` mode: `01_cover`, `02_chapter`, `03_content`, `04_ending`; `fidelity` mode: standard set + variant pages (`02a_chapter_*`, `03a_content_*`, ...) and extension pages (`05_section_break`, `06_appendix`, ...) per `manifest.json` clusters3. **TOC page (optional)** — `02_toc.svg`4. **Template assets (optional)** — Logos / PNG / JPG / reference SVG needed by the template package@@ -182,7 +143,7 @@ The role should use the import output to anchor objective facts such as theme co----## Step 5: Validate Template Assets+## Step 4: Validate Template Assets```bashls -la "skills/ppt-master/templates/layouts/<template_id>"@@ -196,8 +157,9 @@ python3 skills/ppt-master/scripts/svg_quality_checker.py "skills/ppt-master/temp**Checklist**:-- [ ] `design_spec.md` contains complete design specification-- [ ] All 4 core templates present+- [ ] `design_spec.md` contains complete design specification, with §VI listing every emitted page+- [ ] Every page declared in `design_spec.md §VI` exists as an SVG file in the template directory (and vice versa — no orphan files)+- [ ] Variant filenames follow the letter-suffix convention (e.g. `03a_content_two_col.svg`); variants reuse the parent type's placeholder set- [ ] If TOC exists, placeholder pattern uses the canonical indexed form- [ ] SVG viewBox matches the chosen canvas format (for `ppt169`: `0 0 1280 720`)- [ ] Placeholder names are consistent with the new-template contract and `design_spec.md`@@ -207,25 +169,28 @@ This step is a **hard gate**. Do not register the template into the library inde----## Step 6: Register Template in Library Index+## Step 5: Register Template in Library Index-Add a top-level entry to `skills/ppt-master/templates/layouts/layouts_index.json`. The file is a flat map of `template_id → { label, summary, keywords }`:+Add a top-level entry to `skills/ppt-master/templates/layouts/layouts_index.json`. The file is a flat map of `template_id → { label, summary, keywords, pages }`:```json"<template_id>": {"label": "<Human-readable Name>","summary": "<One-sentence description of what this template is for>",- "keywords": ["<Tag1>", "<Tag2>", "<Tag3>"]+ "keywords": ["<Tag1>", "<Tag2>", "<Tag3>"],+ "pages": ["01_cover", "02_chapter", "02_toc", "03_content", "04_ending"]}```+`pages` lists every layout SVG (without the `.svg` suffix) the template ships, so downstream consumers can see the full roster — especially for `fidelity`-mode templates that include variant pages such as `03a_content_two_col`.+`layouts_index.json` is the lightweight lookup used when a user explicitly opts into the template flow. The main workflow defaults to free design and does not read this file unless a template trigger fires (see `SKILL.md` Step 3). A template directory that is not registered here will not be discoverable by that flow.Also sync the summary table in `templates/layouts/README.md` (the human-facing index with categories, primary colors, and detailed tone).----## Step 7: Output Confirmation+## Step 6: Output Confirmation```markdown## Template Creation Complete