AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
feat(template-fill): add direct PPTX template-fill route (issue #53)
hugohe3e64a5f979b92
diff --git a/AGENTS.md b/AGENTS.mdindex ca9e1dbb..c7bdff9b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -12,6 +12,8 @@ PPT Master is an AI-driven presentation generation system. Multi-role collaborat> Topic-only requests with no source material: run the standalone [`topic-research`](skills/ppt-master/workflows/topic-research.md) workflow before SKILL.md Step 1 to gather web materials.>+> Template fill: when the user provides an existing `.pptx` template plus text materials or a topic and asks to reuse the original PPT design or fill content back into it (trigger phrases the user types include "套模板", "套一下", "填回去"), run the standalone [`template-fill-pptx`](skills/ppt-master/workflows/template-fill-pptx.md) workflow. This route edits PPTX directly and must not enter the SVG generation pipeline.+>> Phase B resumption (split-mode execution): when the user opens a fresh chat and says "继续生成 projects/<x>" or similar, run the standalone [`resume-execute`](skills/ppt-master/workflows/resume-execute.md) workflow to enter Phase B (SVG generation + export) without re-running Phase A.>> Decks containing data charts: run the standalone [`verify-charts`](skills/ppt-master/workflows/verify-charts.md) workflow between the executor and post-processing steps to calibrate chart coordinates.diff --git a/CLAUDE.md b/CLAUDE.mdindex dc055e34..cd9d25fe 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -12,6 +12,8 @@ PPT Master is an AI-driven presentation generation system. Multi-role collaborat> Topic-only requests with no source material: run the standalone [`topic-research`](skills/ppt-master/workflows/topic-research.md) workflow before SKILL.md Step 1 to gather web materials.>+> Template fill: when the user provides an existing `.pptx` template plus text materials or a topic and asks to reuse the original PPT design or fill content back into it (trigger phrases the user types include "套模板", "套一下", "填回去"), run the standalone [`template-fill-pptx`](skills/ppt-master/workflows/template-fill-pptx.md) workflow. This route edits PPTX directly and must not enter the SVG generation pipeline.+>> Phase B resumption (split-mode execution): when the user opens a fresh chat and says "继续生成 projects/<x>" or similar, run the standalone [`resume-execute`](skills/ppt-master/workflows/resume-execute.md) workflow to enter Phase B (SVG generation + export) without re-running Phase A.>> Decks containing data charts: run the standalone [`verify-charts`](skills/ppt-master/workflows/verify-charts.md) workflow between the executor and post-processing steps to calibrate chart coordinates.diff --git a/README.md b/README.mdindex 43dfa154..cb6fb015 100644--- a/README.md+++ b/README.md@@ -247,6 +247,8 @@ The AI handles everything — content analysis, visual design, SVG generation, a> **Output:** Native-shapes `.pptx` (directly editable) saved to `exports/<name>_<timestamp>.pptx`. A copy of `svg_output/` is always snapshotted to `backup/<timestamp>/svg_output/` for re-export / archival. Pass `--svg-snapshot` to additionally emit an SVG-image preview pptx alongside the native pptx in `exports/` (see [FAQ](./docs/faq.md)). Requires Office 2016+.+> **Already have a `.pptx` you want to reuse?** Hand the AI that deck plus your material and say "套模板" — it fills new content (text, table, and chart data) into your existing design and exports only the pages you pick, staying natively editable. See the [FAQ](./docs/faq.md) and [template-fill workflow](./skills/ppt-master/workflows/template-fill-pptx.md).+> **AI lost context?** Ask it to read `skills/ppt-master/SKILL.md`.> **Something went wrong?** Check the **[FAQ](./docs/faq.md)** — it covers model selection, layout issues, export problems, and more. Continuously updated from real user reports.diff --git a/README_CN.md b/README_CN.mdindex a8d52d8c..51fab884 100644--- a/README_CN.md+++ b/README_CN.md@@ -255,6 +255,8 @@ AI 全程处理——内容分析、视觉设计、SVG 生成、PPTX 导出。> **输出说明:** 原生形状版 `.pptx`(可直接编辑)保存至 `exports/<name>_<timestamp>.pptx`;`svg_output/` 始终镜像到 `backup/<timestamp>/svg_output/`,便于归档或后续重跑。加 `--svg-snapshot` 时,额外在 `exports/` 内并排生成 SVG 快照版 pptx(详见[常见问题](./docs/zh/faq.md))。需要 Office 2016+。+> **已有一份想复用的 `.pptx`?** 把那份 deck 连同素材给 AI,说「套模板」即可——它会把新内容(文字、表格、图表数据)填进你现有的设计,只导出你挑选的页面,且保持原生可编辑。详见 [常见问题](./docs/zh/faq.md) 与 [套模板工作流](./skills/ppt-master/workflows/template-fill-pptx.md)。+> **AI 迷失上下文?** 让它先读 `skills/ppt-master/SKILL.md`。> **遇到问题?** 查看 **[常见问题](./docs/zh/faq.md)** — 涵盖模型选择、排版问题、导出异常等,基于真实用户反馈持续更新。diff --git a/docs/faq.md b/docs/faq.mdindex e46bef73..8f36859e 100644--- a/docs/faq.md+++ b/docs/faq.md@@ -151,6 +151,14 @@ Yes. You can **interrupt the workflow at any time** — after the first few pageFor post-generation fixes, simply tell the AI: "Page 3 has a layout issue — the title overlaps the chart" and it will fix that specific SVG.+## Q: I already have a finished `.pptx` — can I reuse its design and just fill in new content?++Yes — this is the **template fill** route, separate from the SVG generation pipeline. Give the AI your existing `.pptx` plus your material (or a topic) and say "套模板" / "fill this back into the template". It treats your deck as a native slide library, lets you pick only the pages that fit the new story (reorder freely, and reuse one page for several output slides), and writes the new text — plus native table cells and chart data — straight into the original OOXML.++The output stays 100% native-editable PowerPoint: the original design, layouts, images, and animations are preserved, and only the selected pages are exported. It deliberately does **not** change layouts, add pages, or swap images — a deck's page structure encodes its logic (lead-then-detail, comparison, progression), so pick pages whose structure already fits your content rather than forcing it in. For a fresh structure or a different page count, use create-template (next question) instead. Full steps: [template-fill workflow](../skills/ppt-master/workflows/template-fill-pptx.md).++---+## Q: How do I create a custom template?Want to turn a PPT you love into a reusable template for PPT Master? Here's how:diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 47b6f341..e56f0a9e 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -16,7 +16,16 @@ The short path to your first deck, how to use everything around it — templates**Optional.** By default PPT Master uses **free design** — you don't need a template, and you can skip to the next section. Reach for one only when a deck must reuse a fixed layout set or brand identity.-**To reuse an existing PowerPoint, you must explicitly run the create-template flow — don't just hand over a `.pptx` and expect the AI to handle it.** The AI defaults to free design and won't switch into the template flow on its own; without an explicit trigger, generation easily goes off the rails. First turn that `.pptx` into a PPT Master template via create-template:+**Two ways to reuse an existing `.pptx`, depending on what you want back:**++| You want… | Route | What happens |+|---|---|---|+| **This exact deck, with new content** | Template fill | Picks the pages that fit (a page can be reused for several output slides), swaps text / table / chart data straight in the original file. Design, layouts, images, animations preserved; output is the same deck, natively editable. Fastest; bound to the existing layouts. |+| **A new deck in this deck's style** | create-template | Parses the `.pptx` into a reusable style bundle, then generates a fresh deck through the SVG pipeline — new structure, any page count. More flexible; full regeneration. |++For the first, give the AI your `.pptx` plus your material (or a topic) and say "套模板" — see the [template-fill workflow](../skills/ppt-master/workflows/template-fill-pptx.md). The rest of this section covers create-template.++**To generate a new deck in an existing PowerPoint's style, you must explicitly run the create-template flow — don't just hand over a `.pptx` and expect the AI to handle it.** The AI defaults to free design and won't switch into the template flow on its own; without an explicit trigger, generation easily goes off the rails. First turn that `.pptx` into a PPT Master template via create-template:```You: Replicate this as a template via /create-template: projects/brand/our_deck.pptxdiff --git a/docs/zh/faq.md b/docs/zh/faq.mdindex 3c0268ea..d4fca82d 100644--- a/docs/zh/faq.md+++ b/docs/zh/faq.md@@ -153,6 +153,14 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project> --animation-trigger o生成后的修正也一样简单,直接告诉 AI:"第 3 页布局有问题——标题和图表重叠了",它会修正那个特定的 SVG。+## Q: 我已经有一份做好的 `.pptx`,能不能复用它的设计、只填新内容?++可以——这就是 **套模板(template fill)** 路径,独立于 SVG 生成管线。把你现成的 `.pptx` 连同素材(或一个主题)给 AI,说「套模板 / 把这些填回去」。它会把你的 deck 当作原生页面库,只挑适合新内容的页面(可乱序、可重复),把新文字——以及原生表格单元格、图表数据——直接写回原始 OOXML。++输出仍是 100% 原生可编辑的 PowerPoint:原设计、母版、图片、动画都保留,且只导出选中的页面。它刻意**不**改版式、不加页、不换图——一份 deck 的页面结构本身承载着逻辑(总分、对比、递进),所以应挑选结构本就契合内容的页面,而不是硬塞进去。若需要全新结构或不同页数,请改用 create-template(见下一问)。完整步骤:[套模板工作流](../../skills/ppt-master/workflows/template-fill-pptx.md)。++---+## Q: 如何制作自定义模板?想把自己喜欢的 PPT 模板制作成 PPT Master 可调用的模板?按以下步骤操作:diff --git a/docs/zh/getting-started.md b/docs/zh/getting-started.mdindex fd6a4a94..451c08d6 100644--- a/docs/zh/getting-started.md+++ b/docs/zh/getting-started.md@@ -16,7 +16,16 @@**可选。** 默认走**自由设计**——不需要模板,可以直接跳到下一节。只有当 deck 必须复用一套固定版式或品牌时,才需要模板。-**想让 deck 复用某份现成 PPT,必须显式走 create-template 流程——别直接丢个 `.pptx` 指望 AI 自动处理。** AI 默认走自由设计,不会主动切进创建模板的流程;不显式启动它,生成过程就容易错乱。先用 create-template 把那份 `.pptx` 复刻成 PPT Master 模板:+**复用现成 `.pptx` 有两条路,取决于你想要什么结果:**++| 你想要… | 路径 | 会发生什么 |+|---|---|---|+| **就要这份 deck,换成新内容** | 套模板(template fill) | 挑出合适的页面,把文字 / 表格 / 图表数据直接写回原文件。设计、版式、图片、动画都保留;输出就是同一份 deck,原生可编辑。最快;但受限于现有页面。 |+| **基于这份 deck 的风格生成新 deck** | create-template | 把 `.pptx` 解析成可复用的风格资产包,再走 SVG 管线**重新生成**——结构自由、页数任意。更灵活;完整重建。 |++前者:把 `.pptx` 连同素材(或一个主题)给 AI,说「套模板」——见 [套模板工作流](../../skills/ppt-master/workflows/template-fill-pptx.md)。本节其余部分讲 create-template。++**想基于某份现成 PPT 的风格重新生成 deck,必须显式走 create-template 流程——别直接丢个 `.pptx` 指望 AI 自动处理。** AI 默认走自由设计,不会主动切进创建模板的流程;不显式启动它,生成过程就容易错乱。先用 create-template 把那份 `.pptx` 复刻成 PPT Master 模板:```你:用 /create-template 把这个复刻成模板:projects/brand/our_deck.pptxdiff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.mdindex 8aa020bf..aab4ada1 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -78,6 +78,7 @@ For complete tool documentation, see `${SKILL_DIR}/scripts/README.md`.| Workflow | Path | Purpose ||----------|------|---------|| `topic-research` | `workflows/topic-research.md` | Pre-pipeline — gather web sources when the user supplies only a topic with no source files |+| `template-fill` | `workflows/template-fill-pptx.md` | Give a native PPTX template deck plus source material; select fitting pages (a page may be reused for several output slides) and fill text back without SVG conversion || `create-template` | `workflows/create-template.md` | Standalone layout template creation workflow || `create-brand` | `workflows/create-brand.md` | Standalone brand-only template creation (identity preset; no SVG page roster) || `resume-execute` | `workflows/resume-execute.md` | Phase B entry — resume execution in a fresh chat after Phase A (Step 1–5) completed in another session (split mode) |diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex d20b9890..3f72e27b 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -1,6 +1,6 @@# PPT Master Toolset-This directory contains user-facing scripts for conversion, project setup, SVG processing, export, recorded narration, and image generation.+This directory contains user-facing scripts for conversion, project setup, direct PPTX template filling, SVG processing, export, recorded narration, and image generation.## Directory Layout@@ -41,7 +41,7 @@ python3 scripts/update_repo.py| Area | Primary scripts | Documentation ||------|-----------------|---------------|| Conversion | `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py` | [docs/conversion.md](./docs/conversion.md) |-| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py` | [docs/project.md](./docs/project.md) |+| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py` | [docs/project.md](./docs/project.md) || SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) || Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) || Image tools | `image_gen.py`, `latex_render.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |@@ -76,6 +76,18 @@ python3 scripts/pptx_template_import.py <template.pptx> --manifest-onlypython3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode both```+Template fill (direct PPTX, no SVG conversion):++```bash+mkdir -p <project_path>/sources <project_path>/analysis <project_path>/exports <project_path>/validation+python3 scripts/template_fill_pptx.py analyze <project_path>/sources/<source.pptx> -o <project_path>/analysis/slide_library.json+python3 scripts/template_fill_pptx.py scaffold <project_path>/analysis/slide_library.json -o <project_path>/analysis/fill_plan.json --slides "1,3,4"+python3 scripts/template_fill_pptx.py check-plan <project_path>/analysis/slide_library.json <project_path>/analysis/fill_plan.json -o <project_path>/analysis/check_report.json+python3 scripts/template_fill_pptx.py apply <project_path>/sources/<source.pptx> <project_path>/analysis/fill_plan.json -o <project_path>/exports/filled.pptx+```++`apply` automatically writes `filled_YYYYMMDD_HHMMSS.pptx` unless the output stem already ends with a timestamp. It applies a `fade` page transition by default; `--transition <effect>` (fade/push/wipe/split/strips/cover/random, `--transition-duration` in seconds) changes it, `--transition none` removes it, `--transition keep` preserves the source transitions, and a per-slide `transition` field in the plan overrides whatever the CLI selects.+Post-processing and export:```bashdiff --git a/skills/ppt-master/scripts/template_fill_pptx.py b/skills/ppt-master/scripts/template_fill_pptx.pynew file mode 100644index 00000000..df569060--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx.py@@ -0,0 +1,26 @@+#!/usr/bin/env python3+"""PPT Master - PPTX Template Fill (thin wrapper).++Delegates to the template_fill_pptx package. Kept as the CLI entry point so the+documented command paths keep working:++ python3 scripts/template_fill_pptx.py analyze <deck.pptx> -o slide_library.json+ python3 scripts/template_fill_pptx.py scaffold slide_library.json -o fill_plan.json+ python3 scripts/template_fill_pptx.py check-plan slide_library.json fill_plan.json+ python3 scripts/template_fill_pptx.py apply <deck.pptx> fill_plan.json -o output.pptx++Implementation lives in the template_fill_pptx/ package (ooxml, analyzer,+scaffolder, checker, text_fill, table_fill, chart_fill, transitions, notes,+package, applier, cli).+"""++import sys+from pathlib import Path++# Ensure the scripts directory is on sys.path so the package can be found.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from template_fill_pptx import main++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/ppt-master/scripts/template_fill_pptx/__init__.py b/skills/ppt-master/scripts/template_fill_pptx/__init__.pynew file mode 100644index 00000000..1fc98d45--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/__init__.py@@ -0,0 +1,26 @@+"""PPTX template fill — analyze a deck as a reusable slide library and fill text.++Direct OOXML editing (no SVG round-trip): select source slides, replace+text / table / chart content from a fill plan, and write a new .pptx that keeps+the original PowerPoint design. Four stages mirror the CLI subcommands:+analyze -> scaffold -> check-plan -> apply.++Public entry: analyze_pptx(), scaffold_plan(), check_plan(), apply_plan(), main().+"""++from __future__ import annotations++from .analyzer import analyze_pptx+from .applier import apply_plan+from .checker import check_plan, print_check_report+from .cli import main+from .scaffolder import scaffold_plan++__all__ = [+ "analyze_pptx",+ "scaffold_plan",+ "check_plan",+ "print_check_report",+ "apply_plan",+ "main",+]diff --git a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py b/skills/ppt-master/scripts/template_fill_pptx/analyzer.pynew file mode 100644index 00000000..d08f3417--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/analyzer.py@@ -0,0 +1,185 @@+"""analyze: read a PPTX as a reusable slide library of text / table / chart slots."""++from __future__ import annotations++import zipfile+from pathlib import Path+from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import (+ NS,+ _chart_containers,+ _container_geometry,+ _emu_to_px,+ _paragraph_texts,+ _parse_slide_refs,+ _read_xml,+ _shape_identity,+ _table_containers,+ _text_containers,+)++THANKS_KEYWORDS = ("thank", "thanks", "q&a", "qa", "contact", "致谢", "谢谢", "感谢", "答疑", "联系方式")+TOC_KEYWORDS = ("agenda", "contents", "content", "outline", "目录", "议程")+CHAPTER_KEYWORDS = ("chapter", "part", "section", "章节", "部分")+++def _analyze_tables(slide_root: ET.Element, source_slide: int) -> list[dict[str, Any]]:+ tables: list[dict[str, Any]] = []+ for order, container in enumerate(_table_containers(slide_root), start=1):+ shape_id, _shape_name = _shape_identity(container, order)+ rows: list[dict[str, Any]] = []+ max_columns = 0+ for row_index, row in enumerate(container.findall(".//a:tbl/a:tr", NS)):+ cells: list[dict[str, Any]] = []+ for col_index, cell in enumerate(row.findall("a:tc", NS)):+ cells.append(+ {+ "row": row_index,+ "col": col_index,+ "text": "\n".join(_paragraph_texts(cell)),+ }+ )+ max_columns = max(max_columns, len(cells))+ rows.append({"row": row_index, "cells": cells})+ tables.append(+ {+ "table_id": f"s{source_slide:02d}_tbl{shape_id}",+ "row_count": len(rows),+ "column_count": max_columns,+ "rows": rows,+ }+ )+ return tables+++def _analyze_charts(slide_root: ET.Element, source_slide: int) -> list[dict[str, Any]]:+ charts: list[dict[str, Any]] = []+ for order, container in enumerate(_chart_containers(slide_root), start=1):+ shape_id, _shape_name = _shape_identity(container, order)+ charts.append({"chart_id": f"s{source_slide:02d}_ch{shape_id}"})+ return charts+++def _slot_role(slot: dict[str, Any], order: int) -> str:+ text = str(slot.get("text") or "")+ name = str(slot.get("shape_name") or "").lower()+ geometry = slot.get("geometry") or {}+ y = geometry.get("y")+ if order == 1 or "title" in name or "标题" in name:+ return "title_candidate"+ if isinstance(y, int) and y < 160 and len(text) <= 80:+ return "title_candidate"+ if slot.get("text_node_count", 0) >= 4 or len(text) >= 120:+ return "body_candidate"+ return "label_candidate"+++def _classify_page_type(index: int, total: int, text: str, slots: list[dict[str, Any]]) -> str:+ normalized = text.lower()+ if index == 1:+ return "cover_candidate"+ if index == total or any(keyword in normalized for keyword in THANKS_KEYWORDS):+ return "ending_candidate"+ if any(keyword in normalized for keyword in TOC_KEYWORDS):+ return "toc_candidate"+ if any(keyword in normalized for keyword in CHAPTER_KEYWORDS):+ return "chapter_candidate"+ if len(slots) <= 2 and len(text) <= 80:+ return "chapter_candidate"+ return "content_candidate"+++def _canvas_px(pres_root: ET.Element) -> dict[str, int | None]:+ size = pres_root.find("p:sldSz", NS)+ if size is None:+ return {"width": None, "height": None}+ return {+ "width": _emu_to_px(size.attrib.get("cx")),+ "height": _emu_to_px(size.attrib.get("cy")),+ }+++def analyze_pptx(pptx_path: Path) -> dict[str, Any]:+ """Extract a slide library with text replacement slots."""+ with zipfile.ZipFile(pptx_path) as zf:+ pres_root = _read_xml(zf, "ppt/presentation.xml")+ slide_refs = _parse_slide_refs(zf)+ slides: list[dict[str, Any]] = []+ for slide_ref in slide_refs:+ slide_root = _read_xml(zf, slide_ref.part_name)+ slots: list[dict[str, Any]] = []+ for order, container in enumerate(_text_containers(slide_root), start=1):+ shape_id, shape_name = _shape_identity(container, order)+ paragraphs = _paragraph_texts(container)+ text = "\n".join(paragraphs)+ geometry = _container_geometry(container)+ role = _slot_role(+ {+ "text": text,+ "shape_name": shape_name,+ "geometry": geometry,+ "text_node_count": len(container.findall(".//a:t", NS)),+ },+ order,+ )+ slots.append(+ {+ "slot_id": f"s{slide_ref.index:02d}_sh{shape_id}",+ "role": role,+ "text": text,+ "paragraph_count": len(paragraphs),+ "geometry": geometry,+ }+ )++ tables = _analyze_tables(slide_root, slide_ref.index)+ charts = _analyze_charts(slide_root, slide_ref.index)+ slide_text = "\n".join(slot["text"] for slot in slots if slot["text"])+ slides.append(+ {+ "slide_index": slide_ref.index,+ "page_type": _classify_page_type(slide_ref.index, len(slide_refs), slide_text, slots),+ "text_summary": slide_text[:500],+ "slots": slots,+ "tables": tables,+ "charts": charts,+ }+ )++ return {+ "schema": "template_fill_pptx_library.v1",+ "source_pptx": str(pptx_path),+ "slide_count": len(slides),+ "canvas_px": _canvas_px(pres_root),+ "slides": slides,+ "plan_contract": {+ "schema": "template_fill_pptx_plan.v1",+ "slides": [+ {+ "source_slide": 1,+ "purpose": "封面 / 章节 / 内容 / 结尾",+ "replacements": [+ {+ "slot_id": "s01_sh2",+ "text": "替换后的文字",+ }+ ],+ "table_edits": [+ {+ "table_id": "s01_tbl3",+ "cells": [{"row": 0, "col": 0, "text": "替换后的单元格"}],+ }+ ],+ "chart_edits": [+ {+ "chart_id": "s01_ch4",+ "categories": ["A", "B"],+ "series": [{"name": "系列1", "values": [1, 2]}],+ }+ ],+ }+ ],+ },+ }diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.pynew file mode 100644index 00000000..db9af1a4--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py@@ -0,0 +1,169 @@+"""apply: clone selected source slides into a new PPTX and write replacements.++Orchestrates the per-stage helpers (text / table / chart / transition / notes)+and rebuilds the presentation slide list, relationships, and content types.+"""++from __future__ import annotations++import zipfile+from pathlib import Path+from typing import Any+from xml.etree import ElementTree as ET++from .chart_fill import (+ _apply_chart_edits_to_slide_package,+ _max_chart_part_number,+ _max_embedding_part_number,+)+from .notes import _find_notes_master_target, _slide_rels_with_notes+from .ooxml import NS, REL_NS, SLIDE_REL_TYPE, _parse_slide_refs, _qn, _xml_bytes+from .package import (+ _add_notes_override,+ _add_slide_override,+ _content_type_root,+ _empty_relationships_root,+ _max_numeric_rid,+ _max_slide_id,+ _max_slide_part_number,+ _prune_unreferenced_parts,+)+from .table_fill import _apply_table_edits_to_slide+from .text_fill import _apply_replacements_to_slide+from .transitions import (+ DEFAULT_TRANSITION,+ DEFAULT_TRANSITION_DURATION,+ _resolve_slide_transition,+ _set_slide_transition,+)+++def apply_plan(+ pptx_path: Path,+ plan: dict[str, Any],+ output_path: Path,+ *,+ transition: str | None = DEFAULT_TRANSITION,+ transition_duration: float = DEFAULT_TRANSITION_DURATION,+) -> None:+ """Create a filled PPTX by cloning selected source slides and replacing text."""+ plan_slides = plan.get("slides")+ if not isinstance(plan_slides, list) or not plan_slides:+ raise RuntimeError("Plan must contain a non-empty 'slides' list")++ with zipfile.ZipFile(pptx_path) as zf:+ entries = {info.filename: zf.read(info.filename) for info in zf.infolist() if not info.is_dir()}+ slide_refs = {slide.index: slide for slide in _parse_slide_refs(zf)}+ notes_master_target = _find_notes_master_target(entries)++ pres_root = ET.fromstring(entries["ppt/presentation.xml"])+ pres_rels_root = ET.fromstring(entries["ppt/_rels/presentation.xml.rels"])+ content_root = _content_type_root(ET.fromstring(entries["[Content_Types].xml"]))+ sld_id_lst = pres_root.find("p:sldIdLst", NS)+ if sld_id_lst is None:+ sld_id_lst = ET.SubElement(pres_root, _qn(NS["p"], "sldIdLst"))++ for child in list(sld_id_lst):+ sld_id_lst.remove(child)+ for rel in list(pres_rels_root.findall(_qn(REL_NS, "Relationship"))):+ if rel.attrib.get("Type") == SLIDE_REL_TYPE:+ pres_rels_root.remove(rel)++ next_slide_number = _max_slide_part_number(entries) + 1+ next_slide_id = _max_slide_id(sld_id_lst) + 1+ next_rel_number = _max_numeric_rid(pres_rels_root) + 1+ next_chart_number = _max_chart_part_number(entries)+ next_embedding_number = _max_embedding_part_number(entries)++ for offset, item in enumerate(plan_slides):+ source_slide = int(item.get("source_slide", 0))+ if source_slide not in slide_refs:+ raise RuntimeError(f"Plan references a missing source slide: {source_slide}")+ source_ref = slide_refs[source_slide]+ new_slide_number = next_slide_number + offset+ new_part = f"ppt/slides/slide{new_slide_number}.xml"+ new_rels = f"ppt/slides/_rels/slide{new_slide_number}.xml.rels"+ new_rid = f"rId{next_rel_number + offset}"++ slide_root = ET.fromstring(entries[source_ref.part_name])+ replacements = item.get("replacements", [])+ if not isinstance(replacements, list):+ raise RuntimeError(f"Slide {source_slide} replacements must be a list")+ _apply_replacements_to_slide(+ slide_root,+ source_slide=source_slide,+ replacements=replacements,+ )+ table_edits = item.get("table_edits", [])+ if not isinstance(table_edits, list):+ raise RuntimeError(f"Slide {source_slide} table_edits must be a list")+ _apply_table_edits_to_slide(+ slide_root,+ source_slide=source_slide,+ table_edits=table_edits,+ )+ slide_effect, slide_duration, slide_advance = _resolve_slide_transition(+ item,+ default_effect=transition,+ default_duration=transition_duration,+ )+ _set_slide_transition(+ slide_root,+ effect=slide_effect,+ duration=slide_duration,+ advance_after=slide_advance,+ )++ source_rels = entries.get(source_ref.rels_name)+ slide_rels_root = ET.fromstring(source_rels) if source_rels else _empty_relationships_root()+ chart_edits = item.get("chart_edits", [])+ if not isinstance(chart_edits, list):+ raise RuntimeError(f"Slide {source_slide} chart_edits must be a list")+ next_chart_number, next_embedding_number = _apply_chart_edits_to_slide_package(+ slide_root,+ slide_rels_root,+ entries,+ content_root,+ source_slide=source_slide,+ new_slide_part=new_part,+ chart_edits=chart_edits,+ next_chart_number=next_chart_number,+ next_embedding_number=next_embedding_number,+ )+ entries[new_part] = _xml_bytes(slide_root)+ notes_text = str(item.get("notes") or item.get("speaker_notes") or "")+ entries[new_rels], note_entries = _slide_rels_with_notes(+ _xml_bytes(slide_rels_root),+ slide_number=new_slide_number,+ notes_text=notes_text,+ notes_master_target=notes_master_target,+ )+ entries.update(note_entries)+ _add_slide_override(content_root, new_part)+ if note_entries:+ _add_notes_override(content_root, f"ppt/notesSlides/notesSlide{new_slide_number}.xml")++ ET.SubElement(+ pres_rels_root,+ _qn(REL_NS, "Relationship"),+ {+ "Id": new_rid,+ "Type": SLIDE_REL_TYPE,+ "Target": f"slides/slide{new_slide_number}.xml",+ },+ )+ ET.SubElement(+ sld_id_lst,+ _qn(NS["p"], "sldId"),+ {"id": str(next_slide_id + offset), _qn(NS["r"], "id"): new_rid},+ )++ entries["ppt/presentation.xml"] = _xml_bytes(pres_root)+ entries["ppt/_rels/presentation.xml.rels"] = _xml_bytes(pres_rels_root)+ _prune_unreferenced_parts(entries, content_root)+ entries["[Content_Types].xml"] = _xml_bytes(content_root)++ output_path.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(output_path, "w", compression=zipfile.ZIP_DEFLATED) as out:+ for name, data in entries.items():+ out.writestr(name, data)diff --git a/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py b/skills/ppt-master/scripts/template_fill_pptx/chart_fill.pynew file mode 100644index 00000000..34467445--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py@@ -0,0 +1,366 @@+"""apply: edit native PowerPoint chart data on cloned slides.++Each referenced chart part is cloned, its ``<c:ser>`` caches are rewritten from+the plan's categories / series, and the embedded ``.xlsx`` workbook is rebuilt so+PowerPoint's "Edit Data" view stays consistent. Chart styling / axes / legend+layout are left untouched.+"""++from __future__ import annotations++import io+import re+import zipfile+from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import (+ CHART_CONTENT_TYPE,+ CHART_REL_TYPE,+ NS,+ PACKAGE_REL_TYPE,+ REL_NS,+ XLSX_CONTENT_TYPE,+ _chart_containers,+ _normalize_part,+ _qn,+ _rels_name_for_part,+ _shape_identity,+ _xml_bytes,+)+from .package import _add_content_type_override, _find_relationship, _relative_target+from .selectors import _chart_selectors+++def _chart_key_maps(slide_root: ET.Element, source_slide: int) -> dict[str, dict[str, str]]:+ maps: dict[str, dict[str, str]] = {}+ for order, container in enumerate(_chart_containers(slide_root), start=1):+ shape_id, shape_name = _shape_identity(container, order)+ chart = container.find(".//c:chart", NS)+ rel_id = chart.attrib.get(_qn(NS["r"], "id")) if chart is not None else ""+ info = {"shape_id": shape_id, "shape_name": shape_name, "rel_id": rel_id or ""}+ maps[f"chart_id:s{source_slide:02d}_ch{shape_id}"] = info+ maps[f"shape_id:{shape_id}"] = info+ if shape_name:+ maps[f"shape_name:{shape_name}"] = info+ return maps+++def _max_chart_part_number(entries: dict[str, bytes]) -> int:+ max_number = 0+ pattern = re.compile(r"^ppt/charts/chart(\d+)\.xml$")+ for name in entries:+ match = pattern.match(name)+ if match:+ max_number = max(max_number, int(match.group(1)))+ return max_number+++def _max_embedding_part_number(entries: dict[str, bytes]) -> int:+ max_number = 0+ pattern = re.compile(r"^ppt/embeddings/templateFillChart(\d+)\.xlsx$")+ for name in entries:+ match = pattern.match(name)+ if match:+ max_number = max(max_number, int(match.group(1)))+ return max_number+++def _chart_part_from_relationship(slide_part: str, rel: ET.Element) -> str:+ target = rel.attrib.get("Target", "")+ if rel.attrib.get("Type") != CHART_REL_TYPE or not target:+ raise RuntimeError("Matched chart shape does not point to a chart relationship")+ return _normalize_part(target, slide_part)+++def _chart_type_with_series(chart_root: ET.Element) -> ET.Element:+ plot_area = chart_root.find(".//c:plotArea", NS)+ if plot_area is None:+ raise RuntimeError("Chart XML has no plotArea")+ for child in list(plot_area):+ if child.tag.endswith("Chart") and child.findall("c:ser", NS):+ return child+ raise RuntimeError("Chart XML has no editable series")+++def _ensure_child(parent: ET.Element, tag: str) -> ET.Element:+ child = parent.find(tag, NS)+ if child is not None:+ return child+ return ET.SubElement(parent, _qn(NS["c"], tag.split(":", 1)[1]))+++def _set_val_attr(element: ET.Element, value: str | int | float) -> None:+ element.set("val", str(value))+++def _excel_col(index: int) -> str:+ result = ""+ while index:+ index, remainder = divmod(index - 1, 26)+ result = chr(65 + remainder) + result+ return result or "A"+++def _write_string_cache(cache: ET.Element, values: list[str]) -> None:+ for child in list(cache):+ cache.remove(child)+ pt_count = ET.SubElement(cache, _qn(NS["c"], "ptCount"))+ _set_val_attr(pt_count, len(values))+ for index, value in enumerate(values):+ pt = ET.SubElement(cache, _qn(NS["c"], "pt"), {"idx": str(index)})+ v = ET.SubElement(pt, _qn(NS["c"], "v"))+ v.text = str(value)+++def _write_number_cache(cache: ET.Element, values: list[Any]) -> None:+ for child in list(cache):+ cache.remove(child)+ fmt = ET.SubElement(cache, _qn(NS["c"], "formatCode"))+ fmt.text = "General"+ pt_count = ET.SubElement(cache, _qn(NS["c"], "ptCount"))+ _set_val_attr(pt_count, len(values))+ for index, value in enumerate(values):+ pt = ET.SubElement(cache, _qn(NS["c"], "pt"), {"idx": str(index)})+ v = ET.SubElement(pt, _qn(NS["c"], "v"))+ v.text = str(value)+++def _set_series_name(series: ET.Element, name: str, column_index: int) -> None:+ tx = _ensure_child(series, "c:tx")+ for child in list(tx):+ tx.remove(child)+ str_ref = ET.SubElement(tx, _qn(NS["c"], "strRef"))+ formula = ET.SubElement(str_ref, _qn(NS["c"], "f"))+ formula.text = f"Sheet1!${_excel_col(column_index)}$1"+ cache = ET.SubElement(str_ref, _qn(NS["c"], "strCache"))+ _write_string_cache(cache, [name])+++def _set_category_cache(series: ET.Element, categories: list[str]) -> None:+ cat = _ensure_child(series, "c:cat")+ for child in list(cat):+ cat.remove(child)+ str_ref = ET.SubElement(cat, _qn(NS["c"], "strRef"))+ formula = ET.SubElement(str_ref, _qn(NS["c"], "f"))+ formula.text = f"Sheet1!$A$2:$A${len(categories) + 1}"+ cache = ET.SubElement(str_ref, _qn(NS["c"], "strCache"))+ _write_string_cache(cache, [str(item) for item in categories])+++def _set_value_cache(series: ET.Element, values: list[Any], column_index: int) -> None:+ val = _ensure_child(series, "c:val")+ for child in list(val):+ val.remove(child)+ num_ref = ET.SubElement(val, _qn(NS["c"], "numRef"))+ formula = ET.SubElement(num_ref, _qn(NS["c"], "f"))+ formula.text = f"Sheet1!${_excel_col(column_index)}$2:${_excel_col(column_index)}${len(values) + 1}"+ cache = ET.SubElement(num_ref, _qn(NS["c"], "numCache"))+ _write_number_cache(cache, values)+++def _apply_chart_edit_to_chart_xml(chart_root: ET.Element, chart_edit: dict[str, Any]) -> None:+ categories = [str(item) for item in chart_edit.get("categories", [])]+ series_payload = chart_edit.get("series", [])+ if not categories or not isinstance(series_payload, list) or not series_payload:+ raise RuntimeError("Chart edit requires non-empty categories and series")+ chart_type = _chart_type_with_series(chart_root)+ series_nodes = chart_type.findall("c:ser", NS)+ if not series_nodes:+ raise RuntimeError("Chart XML has no editable series")+ template_series = series_nodes[-1]+ while len(series_nodes) < len(series_payload):+ clone = ET.fromstring(ET.tostring(template_series, encoding="utf-8"))+ chart_type.append(clone)+ series_nodes.append(clone)+ for extra in series_nodes[len(series_payload) :]:+ chart_type.remove(extra)+ series_nodes = chart_type.findall("c:ser", NS)+ for index, (series, payload) in enumerate(zip(series_nodes, series_payload), start=0):+ values = payload.get("values", [])+ if len(values) != len(categories):+ raise RuntimeError("Chart series values must match categories length")+ idx = _ensure_child(series, "c:idx")+ order = _ensure_child(series, "c:order")+ _set_val_attr(idx, index)+ _set_val_attr(order, index)+ _set_series_name(series, str(payload.get("name", f"系列{index + 1}")), index + 2)+ _set_category_cache(series, categories)+ _set_value_cache(series, values, index + 2)+++def _spreadsheet_relationships(xlsx_entries: dict[str, bytes], part_name: str) -> dict[str, str]:+ rels_name = _rels_name_for_part(part_name)+ if rels_name not in xlsx_entries:+ return {}+ root = ET.fromstring(xlsx_entries[rels_name])+ rels: dict[str, str] = {}+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ rel_id = rel.attrib.get("Id")+ target = rel.attrib.get("Target")+ if rel_id and target:+ rels[rel_id] = _normalize_part(target, part_name)+ return rels+++def _first_workbook_sheet(xlsx_entries: dict[str, bytes]) -> str | None:+ workbook_part = "xl/workbook.xml"+ if workbook_part not in xlsx_entries:+ return None+ root = ET.fromstring(xlsx_entries[workbook_part])+ sheets = root.find("{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheets")+ if sheets is None:+ return None+ first = next(iter(list(sheets)), None)+ if first is None:+ return None+ rel_id = first.attrib.get(_qn(NS["r"], "id"))+ if not rel_id:+ return None+ return _spreadsheet_relationships(xlsx_entries, workbook_part).get(rel_id)+++def _spreadsheet_cell_ref(row: int, col: int) -> str:+ return f"{_excel_col(col)}{row}"+++def _spreadsheet_cell(value: Any, row: int, col: int) -> ET.Element:+ cell = ET.Element(+ "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}c",+ {"r": _spreadsheet_cell_ref(row, col)},+ )+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ v = ET.SubElement(cell, "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}v")+ v.text = str(value)+ return cell+ cell.set("t", "inlineStr")+ inline = ET.SubElement(cell, "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}is")+ text = ET.SubElement(inline, "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t")+ text.text = str(value)+ return cell+++def _rewrite_chart_workbook(xlsx_bytes: bytes, chart_edit: dict[str, Any]) -> bytes:+ categories = chart_edit.get("categories", [])+ series_payload = chart_edit.get("series", [])+ with zipfile.ZipFile(io.BytesIO(xlsx_bytes)) as zin:+ xlsx_entries = {info.filename: zin.read(info.filename) for info in zin.infolist() if not info.is_dir()}+ sheet_part = _first_workbook_sheet(xlsx_entries) or "xl/worksheets/sheet1.xml"+ if sheet_part not in xlsx_entries:+ return xlsx_bytes+ sheet_root = ET.fromstring(xlsx_entries[sheet_part])+ sheet_ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"+ sheet_data = sheet_root.find(_qn(sheet_ns, "sheetData"))+ if sheet_data is None:+ sheet_data = ET.SubElement(sheet_root, _qn(sheet_ns, "sheetData"))+ for child in list(sheet_data):+ sheet_data.remove(child)++ rows = [["Category"] + [str(item.get("name", f"系列{idx + 1}")) for idx, item in enumerate(series_payload)]]+ for row_index, category in enumerate(categories):+ rows.append([category] + [item.get("values", [])[row_index] for item in series_payload])+ for row_index, values in enumerate(rows, start=1):+ row = ET.SubElement(sheet_data, _qn(sheet_ns, "row"), {"r": str(row_index)})+ for col_index, value in enumerate(values, start=1):+ row.append(_spreadsheet_cell(value, row_index, col_index))+ xlsx_entries[sheet_part] = _xml_bytes(sheet_root)++ out_buffer = io.BytesIO()+ with zipfile.ZipFile(out_buffer, "w", compression=zipfile.ZIP_DEFLATED) as zout:+ for name, data in xlsx_entries.items():+ zout.writestr(name, data)+ return out_buffer.getvalue()+++def _find_chart_workbook_rel(chart_rels_root: ET.Element) -> ET.Element | None:+ for rel in chart_rels_root.findall(_qn(REL_NS, "Relationship")):+ target = rel.attrib.get("Target", "")+ if rel.attrib.get("Type") == PACKAGE_REL_TYPE or target.lower().endswith(".xlsx"):+ return rel+ return None+++def _clone_and_update_chart_part(+ entries: dict[str, bytes],+ content_root: ET.Element,+ *,+ source_chart_part: str,+ new_chart_part: str,+ chart_edit: dict[str, Any],+ next_embedding_number: int,+) -> int:+ if source_chart_part not in entries:+ raise RuntimeError(f"Missing chart part: {source_chart_part}")+ chart_root = ET.fromstring(entries[source_chart_part])+ _apply_chart_edit_to_chart_xml(chart_root, chart_edit)+ entries[new_chart_part] = _xml_bytes(chart_root)+ _add_content_type_override(content_root, new_chart_part, CHART_CONTENT_TYPE)++ source_chart_rels = _rels_name_for_part(source_chart_part)+ if source_chart_rels not in entries:+ return next_embedding_number+ new_chart_rels = _rels_name_for_part(new_chart_part)+ chart_rels_root = ET.fromstring(entries[source_chart_rels])+ workbook_rel = _find_chart_workbook_rel(chart_rels_root)+ if workbook_rel is not None:+ workbook_target = workbook_rel.attrib.get("Target", "")+ workbook_part = _normalize_part(workbook_target, source_chart_part)+ if workbook_part in entries:+ next_embedding_number += 1+ new_workbook_part = f"ppt/embeddings/templateFillChart{next_embedding_number}.xlsx"+ entries[new_workbook_part] = _rewrite_chart_workbook(entries[workbook_part], chart_edit)+ workbook_rel.set("Target", _relative_target(new_chart_part, new_workbook_part))+ _add_content_type_override(content_root, new_workbook_part, XLSX_CONTENT_TYPE)+ entries[new_chart_rels] = _xml_bytes(chart_rels_root)+ return next_embedding_number+++def _apply_chart_edits_to_slide_package(+ slide_root: ET.Element,+ rels_root: ET.Element,+ entries: dict[str, bytes],+ content_root: ET.Element,+ *,+ source_slide: int,+ new_slide_part: str,+ chart_edits: list[dict[str, Any]],+ next_chart_number: int,+ next_embedding_number: int,+) -> tuple[int, int]:+ maps = _chart_key_maps(slide_root, source_slide)+ cloned_by_rel_id: dict[str, str] = {}+ errors: list[str] = []+ for chart_edit in chart_edits:+ selectors = _chart_selectors(chart_edit)+ chart_info = next((maps[key] for key in selectors if key in maps), None)+ if chart_info is None:+ if chart_edit.get("optional"):+ continue+ errors.append(", ".join(selectors) or "<missing selector>")+ continue+ rel_id = chart_info.get("rel_id", "")+ rel = _find_relationship(rels_root, rel_id)+ if rel is None:+ errors.append(f"{selectors[0] if selectors else '<chart>'} relationship={rel_id}")+ continue+ if rel_id not in cloned_by_rel_id:+ next_chart_number += 1+ source_chart_part = _chart_part_from_relationship(new_slide_part, rel)+ new_chart_part = f"ppt/charts/chart{next_chart_number}.xml"+ next_embedding_number = _clone_and_update_chart_part(+ entries,+ content_root,+ source_chart_part=source_chart_part,+ new_chart_part=new_chart_part,+ chart_edit=chart_edit,+ next_embedding_number=next_embedding_number,+ )+ rel.set("Target", _relative_target(new_slide_part, new_chart_part))+ cloned_by_rel_id[rel_id] = new_chart_part+ continue+ chart_root = ET.fromstring(entries[cloned_by_rel_id[rel_id]])+ _apply_chart_edit_to_chart_xml(chart_root, chart_edit)+ entries[cloned_by_rel_id[rel_id]] = _xml_bytes(chart_root)+ if errors:+ raise RuntimeError(f"Missing chart edit target(s) on slide {source_slide}: {'; '.join(errors)}")+ return next_chart_number, next_embedding_numberdiff --git a/skills/ppt-master/scripts/template_fill_pptx/checker.py b/skills/ppt-master/scripts/template_fill_pptx/checker.pynew file mode 100644index 00000000..84519349--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/checker.py@@ -0,0 +1,330 @@+"""check-plan: compare planned text / table / chart edits against source capacity."""++from __future__ import annotations++from typing import Any++from .selectors import (+ _chart_selectors,+ _plain_len,+ _replacement_selectors,+ _replacement_text,+ _table_selectors,+)+++def _slot_lookup(library: dict[str, Any]) -> dict[tuple[int, str], dict[str, Any]]:+ lookup: dict[tuple[int, str], dict[str, Any]] = {}+ for slide in library.get("slides", []):+ slide_index = int(slide.get("slide_index", 0))+ for slot in slide.get("slots", []):+ if slot.get("slot_id"):+ lookup[(slide_index, f"slot_id:{slot['slot_id']}")] = slot+ if slot.get("shape_id"):+ lookup[(slide_index, f"shape_id:{slot['shape_id']}")] = slot+ if slot.get("shape_name"):+ lookup[(slide_index, f"shape_name:{slot['shape_name']}")] = slot+ return lookup+++def _table_lookup(library: dict[str, Any]) -> dict[tuple[int, str], dict[str, Any]]:+ lookup: dict[tuple[int, str], dict[str, Any]] = {}+ for slide in library.get("slides", []):+ slide_index = int(slide.get("slide_index", 0))+ for table in slide.get("tables", []):+ if table.get("table_id"):+ lookup[(slide_index, f"table_id:{table['table_id']}")] = table+ if table.get("shape_id"):+ lookup[(slide_index, f"shape_id:{table['shape_id']}")] = table+ if table.get("shape_name"):+ lookup[(slide_index, f"shape_name:{table['shape_name']}")] = table+ return lookup+++def _chart_lookup(library: dict[str, Any]) -> dict[tuple[int, str], dict[str, Any]]:+ lookup: dict[tuple[int, str], dict[str, Any]] = {}+ for slide in library.get("slides", []):+ slide_index = int(slide.get("slide_index", 0))+ for chart in slide.get("charts", []):+ if chart.get("chart_id"):+ lookup[(slide_index, f"chart_id:{chart['chart_id']}")] = chart+ if chart.get("shape_id"):+ lookup[(slide_index, f"shape_id:{chart['shape_id']}")] = chart+ if chart.get("shape_name"):+ lookup[(slide_index, f"shape_name:{chart['shape_name']}")] = chart+ return lookup+++def _fit_status(+ *,+ role: str,+ old_len: int,+ new_len: int,+ old_paragraphs: int,+ new_paragraphs: int,+ geometry: dict[str, Any],+) -> tuple[str, str]:+ old_len = max(old_len, 1)+ ratio = new_len / old_len+ width = geometry.get("width")+ height = geometry.get("height")++ if role == "label_candidate" or (old_len <= 6 and old_paragraphs <= 1):+ if new_len > old_len:+ return "WARN", "short label exceeds original length; rewrite shorter"+ return "OK", "short label fits original length"++ if role == "title_candidate" and old_paragraphs <= 1:+ limit = 1.15 if old_len <= 8 else 1.35+ if ratio > limit:+ return "WARN", "title is too long for the original slot; rewrite first"+ return "OK", "title stays near original capacity"++ paragraph_limit = max(old_paragraphs + 2, old_paragraphs * 2, 2)+ if new_paragraphs > paragraph_limit:+ return "WARN", "body paragraph count changed too much; compress or split pages"++ if isinstance(width, int) and isinstance(height, int) and width * height < 30000 and ratio > 2.0:+ return "WARN", "small text box with much longer text; rewrite shorter"++ # Body text reflows, so a moderate amount of extra length is fine; only flag+ # gross overflow. Labels / titles keep their tighter guards above.+ body_limit = 3.0 if role == "body_candidate" else 2.2+ if ratio > body_limit:+ return "WARN", "text is much longer than source slot; rewrite or choose another page"+ return "OK", "within estimated slot capacity"+++def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:+ """Compare fill replacements against source slot capacity."""+ lookup = _slot_lookup(library)+ table_lookup = _table_lookup(library)+ chart_lookup = _chart_lookup(library)+ results: list[dict[str, Any]] = []+ summary = {"ok": 0, "warn": 0, "error": 0}++ for slide_index, slide in enumerate(plan.get("slides", []), start=1):+ source_slide = int(slide.get("source_slide", 0))+ replacements = slide.get("replacements", [])+ if not isinstance(replacements, list):+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "message": "replacements must be a list",+ }+ )+ summary["error"] += 1+ continue++ for replacement in replacements:+ selectors = _replacement_selectors(replacement)+ slot = next((lookup.get((source_slide, selector)) for selector in selectors), None)+ text = _replacement_text(replacement)+ if slot is None:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "replacement target not found in slide library",+ }+ )+ summary["error"] += 1+ continue++ old_text = str(slot.get("text") or "")+ old_len = _plain_len(old_text)+ new_len = _plain_len(text)+ old_paragraphs = int(slot.get("paragraph_count") or 1)+ new_paragraphs = max(len([line for line in text.splitlines() if line.strip()]), 1)+ status, message = _fit_status(+ role=str(slot.get("role") or ""),+ old_len=old_len,+ new_len=new_len,+ old_paragraphs=old_paragraphs,+ new_paragraphs=new_paragraphs,+ geometry=slot.get("geometry") or {},+ )+ summary["warn" if status == "WARN" else "ok"] += 1+ results.append(+ {+ "status": status,+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "slot_id": slot.get("slot_id"),+ "role": slot.get("role"),+ "old_len": old_len,+ "new_len": new_len,+ "ratio": round(new_len / max(old_len, 1), 2),+ "old_paragraphs": old_paragraphs,+ "new_paragraphs": new_paragraphs,+ "message": message,+ "old_text": old_text,+ "new_text": text,+ }+ )+ table_edits = slide.get("table_edits", [])+ if not isinstance(table_edits, list):+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "message": "table_edits must be a list",+ }+ )+ summary["error"] += 1+ continue+ for table_edit in table_edits:+ selectors = _table_selectors(table_edit)+ table = next((table_lookup.get((source_slide, selector)) for selector in selectors), None)+ if table is None:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "table target not found in slide library",+ }+ )+ summary["error"] += 1+ continue+ cells = table_edit.get("cells", [])+ if not isinstance(cells, list):+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "table edit cells must be a list",+ }+ )+ summary["error"] += 1+ continue+ row_count = int(table.get("row_count") or 0)+ column_count = int(table.get("column_count") or 0)+ for cell in cells:+ row = int(cell.get("row", -1))+ col = int(cell.get("col", -1))+ if row < 0 or col < 0 or row >= row_count or col >= column_count:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": f"table cell out of bounds: row={row} col={col}",+ }+ )+ summary["error"] += 1+ continue+ summary["ok"] += 1+ results.append(+ {+ "status": "OK",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "table_id": table.get("table_id"),+ "row": row,+ "col": col,+ "message": "table cell target exists",+ }+ )+ chart_edits = slide.get("chart_edits", [])+ if not isinstance(chart_edits, list):+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "message": "chart_edits must be a list",+ }+ )+ summary["error"] += 1+ continue+ for chart_edit in chart_edits:+ selectors = _chart_selectors(chart_edit)+ chart = next((chart_lookup.get((source_slide, selector)) for selector in selectors), None)+ if chart is None:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "chart target not found in slide library",+ }+ )+ summary["error"] += 1+ continue+ categories = chart_edit.get("categories", [])+ series = chart_edit.get("series", [])+ if not isinstance(categories, list) or not isinstance(series, list) or not series:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "chart edit requires categories list and non-empty series list",+ }+ )+ summary["error"] += 1+ continue+ bad_series = [+ item+ for item in series+ if not isinstance(item, dict)+ or not isinstance(item.get("values", []), list)+ or len(item.get("values", [])) != len(categories)+ ]+ if bad_series:+ results.append(+ {+ "status": "ERROR",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "message": "each chart series needs values matching categories length",+ }+ )+ summary["error"] += 1+ continue+ summary["ok"] += 1+ results.append(+ {+ "status": "OK",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "chart_id": chart.get("chart_id"),+ "category_count": len(categories),+ "series_count": len(series),+ "message": "chart edit target and data shape are valid",+ }+ )+ return {"schema": "template_fill_pptx_check.v1", "summary": summary, "results": results}+++def print_check_report(report: dict[str, Any]) -> None:+ summary = report["summary"]+ print(f"check-plan: ok={summary['ok']} warn={summary['warn']} error={summary['error']}")+ for item in report["results"]:+ if item["status"] == "OK":+ continue+ if "ratio" in item:+ line = (+ "{status} P{plan_slide:02d} source={source_slide} {slot_id} "+ "{role} old={old_len} new={new_len} ratio={ratio}: {message}".format(**item)+ )+ else:+ target = item.get("slot_id") or item.get("selector") or ""+ line = (+ f"{item['status']} P{item['plan_slide']:02d} "+ f"source={item['source_slide']} {target}: {item['message']}".strip()+ )+ print(line)diff --git a/skills/ppt-master/scripts/template_fill_pptx/cli.py b/skills/ppt-master/scripts/template_fill_pptx/cli.pynew file mode 100644index 00000000..7b143ccf--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/cli.py@@ -0,0 +1,164 @@+"""Command-line interface: analyze / scaffold / check-plan / apply subcommands."""++from __future__ import annotations++import argparse+import re+import sys+from datetime import datetime+from pathlib import Path++from .analyzer import analyze_pptx+from .applier import apply_plan+from .checker import check_plan, print_check_report+from .ooxml import _load_json, _write_json+from .scaffolder import scaffold_plan+from .transitions import (+ DEFAULT_TRANSITION,+ DEFAULT_TRANSITION_DURATION,+ KEEP_TRANSITION,+ TRANSITIONS,+)+++def _parse_slide_list(value: str | None) -> list[int] | None:+ if not value:+ return None+ slides: list[int] = []+ for part in value.split(","):+ part = part.strip()+ if not part:+ continue+ if "-" in part:+ start, end = part.split("-", 1)+ slides.extend(range(int(start), int(end) + 1))+ else:+ slides.append(int(part))+ return slides+++def _timestamped_pptx_path(path: Path) -> Path:+ if path.suffix.lower() != ".pptx":+ return path+ if re.search(r"_\d{8}_\d{6}$", path.stem):+ return path+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ return path.with_name(f"{path.stem}_{timestamp}{path.suffix}")+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Analyze and fill native PPTX templates without converting slides to SVG.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ subparsers = parser.add_subparsers(dest="command", required=True)++ analyze = subparsers.add_parser("analyze", help="Extract slide library JSON from a PPTX")+ analyze.add_argument("pptx_file", help="Source PPTX file")+ analyze.add_argument("-o", "--output", required=True, help="Output slide_library.json path")++ scaffold = subparsers.add_parser("scaffold", help="Create an editable fill plan skeleton")+ scaffold.add_argument("library_json", help="slide_library.json from analyze")+ scaffold.add_argument("-o", "--output", required=True, help="Output fill_plan.json path")+ scaffold.add_argument(+ "--slides",+ help="Comma/range source slide list, e.g. 1,3,5-7. Defaults to first six slides.",+ )+ scaffold.add_argument(+ "--include-empty",+ action="store_true",+ help="Include empty text slots in the scaffold. Defaults to text-bearing slots only.",+ )++ check = subparsers.add_parser("check-plan", help="Check a fill plan against source slot capacity")+ check.add_argument("library_json", help="slide_library.json from analyze")+ check.add_argument("plan_json", help="Fill plan JSON")+ check.add_argument("-o", "--output", help="Optional JSON report output path")++ apply = subparsers.add_parser("apply", help="Apply fill plan and write a new PPTX")+ apply.add_argument("pptx_file", help="Source PPTX file")+ apply.add_argument("plan_json", help="Fill plan JSON")+ apply.add_argument(+ "-o",+ "--output",+ required=True,+ help=(+ "Output PPTX path. A _YYYYMMDD_HHMMSS timestamp is appended "+ "automatically unless the stem already ends with one."+ ),+ )+ apply.add_argument(+ "--transition",+ choices=sorted(TRANSITIONS) + ["none", KEEP_TRANSITION],+ default=DEFAULT_TRANSITION,+ help=(+ "Page-to-page transition applied to every cloned slide "+ "(per-slide 'transition' in the plan overrides this). "+ f"Default: {DEFAULT_TRANSITION}. Use 'none' for no motion, "+ "or 'keep' to preserve each source slide's existing transition."+ ),+ )+ apply.add_argument(+ "--transition-duration",+ type=float,+ default=DEFAULT_TRANSITION_DURATION,+ help="Transition duration in seconds (default: 0.5).",+ )++ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ if args.command == "analyze":+ pptx_path = Path(args.pptx_file).expanduser().resolve()+ if not pptx_path.exists():+ print(f"Error: file does not exist: {pptx_path}", file=sys.stderr)+ return 1+ library = analyze_pptx(pptx_path)+ _write_json(Path(args.output).expanduser().resolve(), library)+ print(f"Analyzed {library['slide_count']} slides -> {args.output}", file=sys.stderr)+ return 0++ if args.command == "scaffold":+ library = _load_json(Path(args.library_json).expanduser().resolve())+ plan = scaffold_plan(+ library,+ _parse_slide_list(args.slides),+ include_empty=args.include_empty,+ )+ _write_json(Path(args.output).expanduser().resolve(), plan)+ print(f"Plan scaffold -> {args.output}", file=sys.stderr)+ return 0++ if args.command == "check-plan":+ library = _load_json(Path(args.library_json).expanduser().resolve())+ plan = _load_json(Path(args.plan_json).expanduser().resolve())+ report = check_plan(library, plan)+ print_check_report(report)+ if args.output:+ _write_json(Path(args.output).expanduser().resolve(), report)+ print(f"Check report -> {args.output}", file=sys.stderr)+ return 0 if report["summary"]["error"] == 0 else 1++ if args.command == "apply":+ pptx_path = Path(args.pptx_file).expanduser().resolve()+ plan = _load_json(Path(args.plan_json).expanduser().resolve())+ output_path = _timestamped_pptx_path(Path(args.output).expanduser().resolve())+ apply_plan(+ pptx_path,+ plan,+ output_path,+ transition=args.transition,+ transition_duration=args.transition_duration,+ )+ print(f"Template-filled PPTX -> {output_path}", file=sys.stderr)+ return 0+ except RuntimeError as exc:+ print(f"Error: {exc}", file=sys.stderr)+ return 1++ parser.print_help()+ return 1diff --git a/skills/ppt-master/scripts/template_fill_pptx/notes.py b/skills/ppt-master/scripts/template_fill_pptx/notes.pynew file mode 100644index 00000000..d34cadba--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/notes.py@@ -0,0 +1,114 @@+"""Speaker-notes parts for cloned slides.++Builds native PowerPoint notes-slide XML and the slide<->notesSlide<->notesMaster+relationships from a plan's ``notes`` field, reusing the SVG pipeline's notes+renderer so embedded notes also feed ``notes_to_audio.py``.+"""++from __future__ import annotations++import posixpath+from xml.etree import ElementTree as ET++from svg_to_pptx.pptx_notes import create_notes_slide_xml, markdown_to_plain_text++from .ooxml import NOTES_SLIDE_REL_TYPE, REL_NS, SLIDE_REL_TYPE, _qn, _xml_bytes+from .package import _empty_relationships_root, _max_numeric_rid+++def _find_notes_master_target(entries: dict[str, bytes]) -> str | None:+ notes_master_rel_type = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster"+ )++ for name, data in entries.items():+ if not name.startswith("ppt/notesSlides/_rels/notesSlide") or not name.endswith(".xml.rels"):+ continue+ try:+ root = ET.fromstring(data)+ except ET.ParseError:+ continue+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("Type") == notes_master_rel_type:+ return rel.attrib.get("Target")++ presentation_rels = entries.get("ppt/_rels/presentation.xml.rels")+ if not presentation_rels:+ return None+ try:+ root = ET.fromstring(presentation_rels)+ except ET.ParseError:+ return None+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("Type") != notes_master_rel_type:+ continue+ target = rel.attrib.get("Target")+ if not target:+ return None+ if target.startswith("/"):+ target = target.lstrip("/")+ else:+ target = posixpath.normpath(posixpath.join("ppt", target))+ return posixpath.relpath(target, "ppt/notesSlides")+ return None+++def _create_notes_rels_xml(slide_number: int, notes_master_target: str | None) -> bytes:+ root = _empty_relationships_root()+ if notes_master_target:+ ET.SubElement(+ root,+ _qn(REL_NS, "Relationship"),+ {+ "Id": "rId1",+ "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster",+ "Target": notes_master_target,+ },+ )+ slide_rel_id = "rId2"+ else:+ slide_rel_id = "rId1"+ ET.SubElement(+ root,+ _qn(REL_NS, "Relationship"),+ {+ "Id": slide_rel_id,+ "Type": SLIDE_REL_TYPE,+ "Target": f"../slides/slide{slide_number}.xml",+ },+ )+ return _xml_bytes(root)+++def _slide_rels_with_notes(+ rels_bytes: bytes | None,+ *,+ slide_number: int,+ notes_text: str,+ notes_master_target: str | None,+) -> tuple[bytes, dict[str, bytes]]:+ root = ET.fromstring(rels_bytes) if rels_bytes else _empty_relationships_root()+ for rel in list(root.findall(_qn(REL_NS, "Relationship"))):+ if rel.attrib.get("Type") == NOTES_SLIDE_REL_TYPE:+ root.remove(rel)++ note_entries: dict[str, bytes] = {}+ notes_text = notes_text.strip()+ if notes_text:+ rel_id = f"rId{_max_numeric_rid(root) + 1}"+ notes_part = f"ppt/notesSlides/notesSlide{slide_number}.xml"+ notes_rels_part = f"ppt/notesSlides/_rels/notesSlide{slide_number}.xml.rels"+ ET.SubElement(+ root,+ _qn(REL_NS, "Relationship"),+ {+ "Id": rel_id,+ "Type": NOTES_SLIDE_REL_TYPE,+ "Target": f"../notesSlides/notesSlide{slide_number}.xml",+ },+ )+ plain_notes = markdown_to_plain_text(notes_text)+ note_entries[notes_part] = create_notes_slide_xml(slide_number, plain_notes).encode("utf-8")+ note_entries[notes_rels_part] = _create_notes_rels_xml(slide_number, notes_master_target)++ return _xml_bytes(root), note_entriesdiff --git a/skills/ppt-master/scripts/template_fill_pptx/ooxml.py b/skills/ppt-master/scripts/template_fill_pptx/ooxml.pynew file mode 100644index 00000000..fd73b321--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/ooxml.py@@ -0,0 +1,221 @@+"""Shared OOXML primitives for the template-fill pipeline.++Read-side helpers only: namespaces and content-type constants, part /+relationship resolution, EMU unit conversion, slide-shape discovery, and small+JSON readers / writers. Write-side package plumbing lives in ``package.py``.+"""++from __future__ import annotations++import json+import posixpath+import zipfile+from dataclasses import dataclass+from pathlib import Path+from typing import Any+from xml.etree import ElementTree as ET+++NS = {+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+}+REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"+CT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"+P14_NS = "http://schemas.microsoft.com/office/powerpoint/2010/main"++SLIDE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"+NOTES_SLIDE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"+CHART_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart"+PACKAGE_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package"+SLIDE_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.slide+xml"+NOTES_SLIDE_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"+CHART_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"+XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+EMU_PER_INCH = 914400+PX_PER_INCH = 96+++for prefix, uri in NS.items():+ ET.register_namespace(prefix, uri)+ET.register_namespace("", REL_NS)+ET.register_namespace("p14", P14_NS)+++@dataclass(frozen=True)+class SlideRef:+ """Presentation slide reference resolved from presentation.xml.rels."""++ index: int+ rel_id: str+ target: str+ part_name: str+ rels_name: str+++def _qn(namespace: str, tag: str) -> str:+ return f"{{{namespace}}}{tag}"+++def _read_xml(zf: zipfile.ZipFile, name: str) -> ET.Element:+ try:+ return ET.fromstring(zf.read(name))+ except KeyError as exc:+ raise RuntimeError(f"Missing required PPTX part: {name}") from exc+++def _xml_bytes(root: ET.Element) -> bytes:+ return ET.tostring(root, encoding="utf-8", xml_declaration=True)+++def _normalize_part(target: str, base: str = "ppt/presentation.xml") -> str:+ if target.startswith("/"):+ return target.lstrip("/")+ normalized = posixpath.normpath(posixpath.join(posixpath.dirname(base), target))+ return normalized.lstrip("/")+++def _rels_name_for_part(part_name: str) -> str:+ parent = posixpath.dirname(part_name)+ basename = posixpath.basename(part_name)+ return posixpath.join(parent, "_rels", f"{basename}.rels")+++def _emu_to_px(value: str | None) -> int | None:+ if not value:+ return None+ try:+ return round(int(value) / EMU_PER_INCH * PX_PER_INCH)+ except ValueError:+ return None+++def _parse_relationships(zf: zipfile.ZipFile) -> dict[str, dict[str, str]]:+ rels_root = _read_xml(zf, "ppt/_rels/presentation.xml.rels")+ relationships: dict[str, dict[str, str]] = {}+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):+ rel_id = rel.attrib.get("Id")+ target = rel.attrib.get("Target")+ rel_type = rel.attrib.get("Type")+ if rel_id and target and rel_type:+ relationships[rel_id] = {"target": target, "type": rel_type}+ return relationships+++def _parse_slide_refs(zf: zipfile.ZipFile) -> list[SlideRef]:+ pres_root = _read_xml(zf, "ppt/presentation.xml")+ relationships = _parse_relationships(zf)+ sld_id_lst = pres_root.find("p:sldIdLst", NS)+ if sld_id_lst is None:+ return []++ slides: list[SlideRef] = []+ for index, sld_id in enumerate(sld_id_lst.findall("p:sldId", NS), start=1):+ rel_id = sld_id.attrib.get(_qn(NS["r"], "id"))+ if not rel_id or rel_id not in relationships:+ continue+ rel = relationships[rel_id]+ if rel["type"] != SLIDE_REL_TYPE:+ continue+ part_name = _normalize_part(rel["target"])+ slides.append(+ SlideRef(+ index=index,+ rel_id=rel_id,+ target=rel["target"],+ part_name=part_name,+ rels_name=_rels_name_for_part(part_name),+ )+ )+ return slides+++def _slide_relationships(zf: zipfile.ZipFile, rels_name: str) -> dict[str, dict[str, str]]:+ try:+ rels_root = _read_xml(zf, rels_name)+ except RuntimeError:+ return {}+ relationships: dict[str, dict[str, str]] = {}+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):+ rel_id = rel.attrib.get("Id")+ target = rel.attrib.get("Target")+ rel_type = rel.attrib.get("Type")+ if rel_id and target and rel_type:+ relationships[rel_id] = {"target": target, "type": rel_type}+ return relationships+++def _paragraph_texts(container: ET.Element) -> list[str]:+ paragraphs: list[str] = []+ for paragraph in container.findall(".//a:p", NS):+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", NS)).strip()+ if text:+ paragraphs.append(text)+ if paragraphs:+ return paragraphs+ text = "".join(node.text or "" for node in container.findall(".//a:t", NS)).strip()+ return [text] if text else []+++def _container_geometry(container: ET.Element) -> dict[str, int | None]:+ xfrm = container.find("p:spPr/a:xfrm", NS)+ if xfrm is None:+ xfrm = container.find("p:xfrm", NS)+ if xfrm is None:+ xfrm = container.find(".//a:xfrm", NS)+ if xfrm is None:+ return {"x": None, "y": None, "width": None, "height": None}+ off = xfrm.find("a:off", NS)+ ext = xfrm.find("a:ext", NS)+ return {+ "x": _emu_to_px(off.attrib.get("x")) if off is not None else None,+ "y": _emu_to_px(off.attrib.get("y")) if off is not None else None,+ "width": _emu_to_px(ext.attrib.get("cx")) if ext is not None else None,+ "height": _emu_to_px(ext.attrib.get("cy")) if ext is not None else None,+ }+++def _text_containers(slide_root: ET.Element) -> list[ET.Element]:+ containers: list[ET.Element] = []+ for tag in ("p:sp", "p:graphicFrame"):+ for element in slide_root.findall(f".//{tag}", NS):+ if element.find(".//p:txBody", NS) is not None or element.findall(".//a:t", NS):+ containers.append(element)+ return containers+++def _table_containers(slide_root: ET.Element) -> list[ET.Element]:+ return [+ frame+ for frame in slide_root.findall(".//p:graphicFrame", NS)+ if frame.find(".//a:tbl", NS) is not None+ ]+++def _chart_containers(slide_root: ET.Element) -> list[ET.Element]:+ return [+ frame+ for frame in slide_root.findall(".//p:graphicFrame", NS)+ if frame.find(".//c:chart", NS) is not None+ ]+++def _shape_identity(container: ET.Element, order: int) -> tuple[str, str]:+ c_nv_pr = container.find(".//p:cNvPr", NS)+ shape_id = c_nv_pr.attrib.get("id") if c_nv_pr is not None else str(order)+ shape_name = c_nv_pr.attrib.get("name") if c_nv_pr is not None else ""+ return shape_id, shape_name+++def _load_json(path: Path) -> dict[str, Any]:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except json.JSONDecodeError as exc:+ raise RuntimeError(f"Invalid JSON: {path}: {exc}") from exc+++def _write_json(path: Path, payload: dict[str, Any]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")diff --git a/skills/ppt-master/scripts/template_fill_pptx/package.py b/skills/ppt-master/scripts/template_fill_pptx/package.pynew file mode 100644index 00000000..8f728c9c--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/package.py@@ -0,0 +1,155 @@+"""Write-side OOXML package plumbing for the apply stage.++Content-type override insertion, relationship-element construction / lookup, and+part-number allocation used when cloning slides into a new package.+"""++from __future__ import annotations++import posixpath+import re+from xml.etree import ElementTree as ET++from .ooxml import (+ CT_NS,+ NOTES_SLIDE_CONTENT_TYPE,+ NS,+ REL_NS,+ SLIDE_CONTENT_TYPE,+ _normalize_part,+ _qn,+ _rels_name_for_part,+)+++def _content_type_root(root: ET.Element) -> ET.Element:+ if root.tag != _qn(CT_NS, "Types"):+ raise RuntimeError("[Content_Types].xml has an unexpected root element")+ return root+++def _add_content_type_override(content_root: ET.Element, part_name: str, content_type: str) -> None:+ part_name = "/" + part_name.lstrip("/")+ for override in content_root.findall(_qn(CT_NS, "Override")):+ if override.attrib.get("PartName") == part_name:+ return+ ET.SubElement(+ content_root,+ _qn(CT_NS, "Override"),+ {"PartName": part_name, "ContentType": content_type},+ )+++def _add_slide_override(content_root: ET.Element, part_name: str) -> None:+ _add_content_type_override(content_root, part_name, SLIDE_CONTENT_TYPE)+++def _add_notes_override(content_root: ET.Element, part_name: str) -> None:+ _add_content_type_override(content_root, part_name, NOTES_SLIDE_CONTENT_TYPE)+++def _empty_relationships_root() -> ET.Element:+ return ET.Element(_qn(REL_NS, "Relationships"))+++def _find_relationship(root: ET.Element, rel_id: str) -> ET.Element | None:+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("Id") == rel_id:+ return rel+ return None+++def _relative_target(from_part: str, to_part: str) -> str:+ return posixpath.relpath(to_part, posixpath.dirname(from_part))+++def _max_slide_part_number(entries: dict[str, bytes]) -> int:+ max_number = 0+ pattern = re.compile(r"^ppt/slides/slide(\d+)\.xml$")+ for name in entries:+ match = pattern.match(name)+ if match:+ max_number = max(max_number, int(match.group(1)))+ return max_number+++def _max_numeric_rid(root: ET.Element) -> int:+ max_id = 0+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ rel_id = rel.attrib.get("Id", "")+ match = re.fullmatch(r"rId(\d+)", rel_id)+ if match:+ max_id = max(max_id, int(match.group(1)))+ return max_id+++def _max_slide_id(sld_id_lst: ET.Element) -> int:+ max_id = 255+ for sld_id in sld_id_lst.findall("p:sldId", NS):+ try:+ max_id = max(max_id, int(sld_id.attrib.get("id", "0")))+ except ValueError:+ continue+ return max_id+++def _enqueue_rel_targets(+ entries: dict[str, bytes],+ rels_part: str,+ base_part: str,+ queue: list[str],+) -> None:+ data = entries.get(rels_part)+ if not data:+ return+ try:+ root = ET.fromstring(data)+ except ET.ParseError:+ return+ for rel in root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("TargetMode") == "External":+ continue+ target = rel.attrib.get("Target")+ if target:+ queue.append(_normalize_part(target, base_part or "x"))+++def _reachable_parts(entries: dict[str, bytes]) -> set[str]:+ """Parts reachable from the package root by following relationships."""+ keep: set[str] = set()+ queue: list[str] = []+ _enqueue_rel_targets(entries, "_rels/.rels", "", queue)+ while queue:+ part = queue.pop()+ if part in keep:+ continue+ keep.add(part)+ _enqueue_rel_targets(entries, _rels_name_for_part(part), part, queue)+ return keep+++def _prune_unreferenced_parts(entries: dict[str, bytes], content_root: ET.Element) -> None:+ """Drop parts not reachable from the package root through relationships.++ After cloning only the planned slides, the original slide / notesSlide /+ chart / embedding parts left in ``entries`` are orphaned — nothing in the+ rebuilt presentation references them. Reachability GC removes that dead+ weight so the output deck carries only the selected pages and their assets,+ and prunes the matching ``[Content_Types].xml`` overrides.+ """+ reachable = _reachable_parts(entries)+ keep = set(reachable)+ keep.update({"[Content_Types].xml", "_rels/.rels"})+ for part in reachable:+ rels = _rels_name_for_part(part)+ if rels in entries:+ keep.add(rels)++ for name in list(entries):+ if name not in keep:+ del entries[name]++ for override in list(content_root.findall(_qn(CT_NS, "Override"))):+ part_name = (override.attrib.get("PartName") or "").lstrip("/")+ if part_name and part_name not in reachable:+ content_root.remove(override)diff --git a/skills/ppt-master/scripts/template_fill_pptx/scaffolder.py b/skills/ppt-master/scripts/template_fill_pptx/scaffolder.pynew file mode 100644index 00000000..32ef3dab--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/scaffolder.py@@ -0,0 +1,75 @@+"""scaffold: turn a slide library into an editable fill-plan skeleton."""++from __future__ import annotations++from typing import Any+++def scaffold_plan(+ library: dict[str, Any],+ selected_slides: list[int] | None = None,+ *,+ include_empty: bool = False,+) -> dict[str, Any]:+ """Build an editable fill plan skeleton from a slide library."""+ selected = set(selected_slides or [])+ source_slides = library.get("slides", [])+ if not selected:+ source_slides = source_slides[: min(6, len(source_slides))]+ else:+ source_slides = [slide for slide in source_slides if int(slide["slide_index"]) in selected]++ slides: list[dict[str, Any]] = []+ for slide in source_slides:+ replacements = []+ for slot in slide.get("slots", []):+ if not include_empty and not str(slot.get("text") or "").strip():+ continue+ replacements.append(+ {+ "slot_id": slot["slot_id"],+ "old_text": slot["text"],+ "text": slot["text"],+ }+ )+ table_edits = []+ for table in slide.get("tables", []):+ table_edits.append(+ {+ "table_id": table["table_id"],+ "cells": [+ {+ "row": cell["row"],+ "col": cell["col"],+ "old_text": cell["text"],+ "text": cell["text"],+ }+ for row in table.get("rows", [])+ for cell in row.get("cells", [])+ ],+ }+ )+ chart_edits = []+ for chart in slide.get("charts", []):+ chart_edits.append(+ {+ "chart_id": chart["chart_id"],+ "categories": [],+ "series": [{"name": "系列1", "values": []}],+ }+ )+ slides.append(+ {+ "source_slide": slide["slide_index"],+ "purpose": slide.get("page_type", "content_candidate"),+ "replacements": replacements,+ "table_edits": table_edits,+ "chart_edits": chart_edits,+ }+ )++ return {+ "schema": "template_fill_pptx_plan.v1",+ "source_pptx": library.get("source_pptx"),+ "slides": slides,+ }diff --git a/skills/ppt-master/scripts/template_fill_pptx/selectors.py b/skills/ppt-master/scripts/template_fill_pptx/selectors.pynew file mode 100644index 00000000..2934006c--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/selectors.py@@ -0,0 +1,65 @@+"""Plan selector builders and text extraction shared by check-plan and apply.++A replacement / table / chart edit can target a slot by ``slot_id`` (or+``table_id`` / ``chart_id``), ``shape_id``, or ``shape_name``; these helpers turn+a plan entry into an ordered list of lookup keys and pull the new text out.+"""++from __future__ import annotations++from typing import Any+++def _plain_len(value: str) -> int:+ return len("".join(value.split()))+++def _replacement_selectors(replacement: dict[str, Any]) -> list[str]:+ selectors = []+ if replacement.get("slot_id"):+ selectors.append(f"slot_id:{replacement['slot_id']}")+ if replacement.get("shape_id"):+ selectors.append(f"shape_id:{replacement['shape_id']}")+ if replacement.get("shape_name"):+ selectors.append(f"shape_name:{replacement['shape_name']}")+ return selectors+++def _table_selectors(table_edit: dict[str, Any]) -> list[str]:+ selectors = []+ if table_edit.get("table_id"):+ selectors.append(f"table_id:{table_edit['table_id']}")+ if table_edit.get("shape_id"):+ selectors.append(f"shape_id:{table_edit['shape_id']}")+ if table_edit.get("shape_name"):+ selectors.append(f"shape_name:{table_edit['shape_name']}")+ return selectors+++def _chart_selectors(chart_edit: dict[str, Any]) -> list[str]:+ selectors = []+ if chart_edit.get("chart_id"):+ selectors.append(f"chart_id:{chart_edit['chart_id']}")+ if chart_edit.get("shape_id"):+ selectors.append(f"shape_id:{chart_edit['shape_id']}")+ if chart_edit.get("shape_name"):+ selectors.append(f"shape_name:{chart_edit['shape_name']}")+ return selectors+++def _replacement_text(replacement: dict[str, Any]) -> str:+ if "paragraphs" in replacement:+ paragraphs = replacement["paragraphs"]+ if not isinstance(paragraphs, list):+ raise RuntimeError("Replacement field 'paragraphs' must be a list")+ return "\n".join(str(item) for item in paragraphs)+ return str(replacement.get("text", ""))+++def _table_cell_text(cell_edit: dict[str, Any]) -> str:+ if "paragraphs" in cell_edit:+ paragraphs = cell_edit["paragraphs"]+ if not isinstance(paragraphs, list):+ raise RuntimeError("Table cell field 'paragraphs' must be a list")+ return "\n".join(str(item) for item in paragraphs)+ return str(cell_edit.get("text", ""))diff --git a/skills/ppt-master/scripts/template_fill_pptx/table_fill.py b/skills/ppt-master/scripts/template_fill_pptx/table_fill.pynew file mode 100644index 00000000..5b51110e--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/table_fill.py@@ -0,0 +1,59 @@+"""apply: edit native PowerPoint table cell text on cloned slides.++Edits existing cells only — row / column structure is left untouched.+"""++from __future__ import annotations++from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import NS, _shape_identity, _table_containers+from .selectors import _table_cell_text, _table_selectors+from .text_fill import _set_container_text+++def _table_key_maps(slide_root: ET.Element, source_slide: int) -> dict[str, ET.Element]:+ maps: dict[str, ET.Element] = {}+ for order, container in enumerate(_table_containers(slide_root), start=1):+ shape_id, shape_name = _shape_identity(container, order)+ maps[f"table_id:s{source_slide:02d}_tbl{shape_id}"] = container+ maps[f"shape_id:{shape_id}"] = container+ if shape_name:+ maps[f"shape_name:{shape_name}"] = container+ return maps+++def _apply_table_edits_to_slide(+ slide_root: ET.Element,+ *,+ source_slide: int,+ table_edits: list[dict[str, Any]],+) -> None:+ maps = _table_key_maps(slide_root, source_slide)+ errors: list[str] = []+ for table_edit in table_edits:+ selectors = _table_selectors(table_edit)+ table_frame = next((maps[key] for key in selectors if key in maps), None)+ if table_frame is None:+ if table_edit.get("optional"):+ continue+ errors.append(", ".join(selectors) or "<missing selector>")+ continue+ rows = table_frame.findall(".//a:tbl/a:tr", NS)+ cells = table_edit.get("cells", [])+ if not isinstance(cells, list):+ raise RuntimeError(f"Slide {source_slide} table edit cells must be a list")+ for cell_edit in cells:+ row_index = int(cell_edit.get("row", -1))+ col_index = int(cell_edit.get("col", -1))+ if row_index < 0 or row_index >= len(rows):+ errors.append(f"{selectors[0] if selectors else '<table>'} row={row_index}")+ continue+ row_cells = rows[row_index].findall("a:tc", NS)+ if col_index < 0 or col_index >= len(row_cells):+ errors.append(f"{selectors[0] if selectors else '<table>'} row={row_index} col={col_index}")+ continue+ _set_container_text(row_cells[col_index], _table_cell_text(cell_edit))+ if errors:+ raise RuntimeError(f"Invalid table edit target(s) on slide {source_slide}: {'; '.join(errors)}")diff --git a/skills/ppt-master/scripts/template_fill_pptx/text_fill.py b/skills/ppt-master/scripts/template_fill_pptx/text_fill.pynew file mode 100644index 00000000..d441325a--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/text_fill.py@@ -0,0 +1,117 @@+"""apply: replace text inside cloned slide shapes while keeping frames editable.++``_set_container_text`` is the shared text-writing primitive and is also reused+by ``table_fill`` for table-cell edits.+"""++from __future__ import annotations++from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import NS, _qn, _shape_identity, _text_containers+from .selectors import _replacement_text+++def _shape_key_maps(slide_root: ET.Element, source_slide: int) -> dict[str, ET.Element]:+ maps: dict[str, ET.Element] = {}+ for order, container in enumerate(_text_containers(slide_root), start=1):+ shape_id, shape_name = _shape_identity(container, order)+ maps[f"slot_id:s{source_slide:02d}_sh{shape_id}"] = container+ maps[f"shape_id:{shape_id}"] = container+ if shape_name:+ maps[f"shape_name:{shape_name}"] = container+ return maps+++def _ensure_text_nodes(container: ET.Element) -> list[ET.Element]:+ text_nodes = container.findall(".//a:t", NS)+ if text_nodes:+ return text_nodes+ tx_body = container.find(".//p:txBody", NS)+ if tx_body is None:+ tx_body = container.find(".//a:txBody", NS)+ if tx_body is None:+ return []+ paragraph = tx_body.find("a:p", NS)+ if paragraph is None:+ paragraph = ET.SubElement(tx_body, _qn(NS["a"], "p"))+ run = paragraph.find("a:r", NS)+ if run is None:+ run = ET.SubElement(paragraph, _qn(NS["a"], "r"))+ text_node = run.find("a:t", NS)+ if text_node is None:+ text_node = ET.SubElement(run, _qn(NS["a"], "t"))+ return [text_node]+++def _ensure_paragraph_text_node(paragraph: ET.Element) -> list[ET.Element]:+ text_nodes = paragraph.findall(".//a:t", NS)+ if text_nodes:+ return text_nodes+ run = paragraph.find("a:r", NS)+ if run is None:+ run = ET.SubElement(paragraph, _qn(NS["a"], "r"))+ text_node = run.find("a:t", NS)+ if text_node is None:+ text_node = ET.SubElement(run, _qn(NS["a"], "t"))+ return [text_node]+++def _set_paragraph_text(paragraph: ET.Element, text: str) -> None:+ text_nodes = _ensure_paragraph_text_node(paragraph)+ text_nodes[0].text = text+ for node in text_nodes[1:]:+ node.text = ""+++def _set_container_text(container: ET.Element, text: str) -> None:+ lines = text.splitlines() or [""]+ paragraphs = container.findall(".//a:p", NS)+ if len(lines) > 1 and paragraphs:+ for index, paragraph in enumerate(paragraphs):+ if index < len(lines):+ _set_paragraph_text(paragraph, lines[index])+ else:+ _set_paragraph_text(paragraph, "")+ if len(lines) > len(paragraphs):+ _set_paragraph_text(paragraphs[-1], "\n".join(lines[len(paragraphs) - 1 :]))+ return++ text_nodes = _ensure_text_nodes(container)+ if not text_nodes:+ raise RuntimeError("Matched shape does not contain a text body")+ if len(lines) <= len(text_nodes):+ for index, node in enumerate(text_nodes):+ node.text = lines[index] if index < len(lines) else ""+ return+ text_nodes[0].text = text+ for node in text_nodes[1:]:+ node.text = ""+++def _apply_replacements_to_slide(+ slide_root: ET.Element,+ *,+ source_slide: int,+ replacements: list[dict[str, Any]],+) -> None:+ maps = _shape_key_maps(slide_root, source_slide)+ errors: list[str] = []+ for replacement in replacements:+ selectors = []+ if replacement.get("slot_id"):+ selectors.append(f"slot_id:{replacement['slot_id']}")+ if replacement.get("shape_id"):+ selectors.append(f"shape_id:{replacement['shape_id']}")+ if replacement.get("shape_name"):+ selectors.append(f"shape_name:{replacement['shape_name']}")+ container = next((maps[key] for key in selectors if key in maps), None)+ if container is None:+ if replacement.get("optional"):+ continue+ errors.append(", ".join(selectors) or "<missing selector>")+ continue+ _set_container_text(container, _replacement_text(replacement))+ if errors:+ raise RuntimeError(f"Missing replacement target(s) on slide {source_slide}: {'; '.join(errors)}")diff --git a/skills/ppt-master/scripts/template_fill_pptx/transitions.py b/skills/ppt-master/scripts/template_fill_pptx/transitions.pynew file mode 100644index 00000000..445494b6--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/transitions.py@@ -0,0 +1,108 @@+"""apply: page-to-page transitions for cloned slides.++Native templates usually ship an empty ``<p:transition/>`` that renders as no+motion, so ``apply`` injects a default transition unless told to ``keep`` the+source or set ``none``. Effects come from the shared ``pptx_animations``+vocabulary so they match the SVG export path.+"""++from __future__ import annotations++from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import NS, P14_NS, _qn++try:+ from pptx_animations import TRANSITIONS+except ImportError:+ TRANSITIONS = {}++# Default page transition injected by `apply` when neither the CLI flag nor a+# per-slide plan field asks for something else. Use `keep` to preserve the+# source transitions instead.+DEFAULT_TRANSITION = "fade"+DEFAULT_TRANSITION_DURATION = 0.5+KEEP_TRANSITION = "keep"++_UNSET = object()+++def _build_transition_element(+ effect: str,+ duration: float,+ advance_after: float | None = None,+) -> ET.Element:+ """Build a populated <p:transition> element from the shared TRANSITIONS vocabulary."""+ info = TRANSITIONS[effect]+ transition = ET.Element(_qn(NS["p"], "transition"))+ transition.set(_qn(P14_NS, "dur"), str(int(float(duration) * 1000)))+ if advance_after is not None:+ transition.set("advTm", str(int(float(advance_after) * 1000)))+ child = ET.SubElement(transition, _qn(NS["p"], info["element"]))+ for key, value in info.get("attrs", {}).items():+ child.set(key, str(value))+ return transition+++def _set_slide_transition(+ slide_root: ET.Element,+ *,+ effect: str | None,+ duration: float,+ advance_after: float | None = None,+) -> None:+ """Replace the cloned slide's transition element (empty in most templates).++ ``effect`` of ``None`` or ``"keep"`` leaves the source transition untouched;+ ``"none"`` strips it so the slide advances with no animation. OOXML requires+ the transition to sit after ``p:clrMapOvr`` and before ``p:timing``.+ """+ if effect is None or effect == KEEP_TRANSITION:+ return++ new_element = None if effect == "none" else _build_transition_element(effect, duration, advance_after)+ existing = slide_root.find("p:transition", NS)+ if existing is not None:+ index = list(slide_root).index(existing)+ slide_root.remove(existing)+ if new_element is not None:+ slide_root.insert(index, new_element)+ return+ if new_element is None:+ return++ timing = slide_root.find("p:timing", NS)+ if timing is not None:+ slide_root.insert(list(slide_root).index(timing), new_element)+ return+ clr_map_ovr = slide_root.find("p:clrMapOvr", NS)+ if clr_map_ovr is not None:+ slide_root.insert(list(slide_root).index(clr_map_ovr) + 1, new_element)+ return+ slide_root.append(new_element)+++def _resolve_slide_transition(+ item: dict[str, Any],+ *,+ default_effect: str | None,+ default_duration: float,+) -> tuple[str | None, float, float | None]:+ """Pick a slide's transition from its plan entry, falling back to CLI defaults."""+ raw = item.get("transition", _UNSET)+ if raw is _UNSET:+ return default_effect, default_duration, None+ if isinstance(raw, dict):+ effect = raw.get("effect", default_effect)+ duration = raw.get("duration", default_duration)+ advance_after = raw.get("advance_after")+ else:+ effect = str(raw)+ duration = default_duration+ advance_after = None+ if effect is not None and effect not in ("none", KEEP_TRANSITION) and effect not in TRANSITIONS:+ raise RuntimeError(+ f"Unknown transition effect '{effect}'. Valid: {', '.join(sorted(TRANSITIONS))}, none, {KEEP_TRANSITION}"+ )+ return effect, float(duration), advance_afterdiff --git a/skills/ppt-master/workflows/template-fill-pptx.md b/skills/ppt-master/workflows/template-fill-pptx.mdnew file mode 100644index 00000000..03c44bac--- /dev/null+++ b/skills/ppt-master/workflows/template-fill-pptx.md@@ -0,0 +1,285 @@+---+description: PPTX template fill workflow — use a native PowerPoint template deck, select fitting pages, and fill new material back without SVG conversion+---++# Template Fill (PPTX) Workflow++> Run when the user wants to fill new content into an existing deck — trigger phrases the user types include **"套模板"** / **"套一下"** / **"填回去"**. They provide an existing `.pptx` as a native template deck plus topic / text materials and want the content filled back into that deck's design while selecting only the pages that fit the new story (a source page may be reused for several output slides).++This workflow is **independent** from the SVG generation pipeline. It treats the source PPTX as a native template / slide library, keeps the original PowerPoint design intact, and writes a new `.pptx` by cloning selected source slides and replacing text directly in OOXML.++## When to Run++Recognize any request that combines an existing PowerPoint with new content or a topic, for example:++| Pattern | Example |+|---|---|+| Existing `.pptx` + "fill back" intent | "给你一份 PPT 和资料,帮我填回去" |+| Existing `.pptx` + topic reuse | "根据这个主题重组这份 PPTX" |+| Existing `.pptx` + selective reuse | "不要还原全部页面,只挑适合的页来套内容" |+| Existing `.pptx` + copywriting replacement | "沿用原设计,把这些文字塞进去" |+| Native PPT template fill | "用这份PPT模板套一下这篇内容" |+| Direct wording | "套模板" / "帮我用这个PPT套一下" |++**Hard rule**: Do not run `pptx_to_svg.py`, `pptx_template_import.py`, `finalize_svg.py`, or `svg_to_pptx.py` for this workflow. SVG conversion is for presentation generation / template creation; this workflow is direct PowerPoint editing.++---++## Step 1: Inputs++🚧 **GATE**: The user has provided:++| Input | Required | Notes |+|---|---:|---|+| Source PPTX | Yes | Original design deck to reuse as a slide library |+| Content material | Yes | User text, Markdown, document, URL-derived source, or a clear topic brief |+| Target output intent | Optional | Audience, page count, tone, must-keep pages, must-drop pages |++If the content material is only a topic with no supporting facts, gather or ask for source material first. Do not invent detailed factual content.++---++## Step 2: Create the Project Workspace++Create a dedicated project directory under `projects/`. Do not write outputs directly into `projects/` root.++```bash+mkdir -p "<project_dir>/sources" "<project_dir>/analysis" "<project_dir>/exports" "<project_dir>/validation"+```++Use this fixed layout:++| Path | Required content |+|---|---|+| `<project_dir>/sources/` | Source PPTX and user-provided text / Markdown / converted materials |+| `<project_dir>/analysis/` | Slide library JSON, page-selection reasoning, and final fill plan |+| `<project_dir>/exports/` | Final generated PPTX only |+| `<project_dir>/validation/` | Read-back Markdown, extracted validation assets, and validation notes |++**Hard rule**: A template-fill project is a project, not a loose output file. The final answer must point to `<project_dir>/exports/<name>.pptx`, and all intermediate artifacts must remain inside `<project_dir>`.++---++## Step 3: Extract the Slide Library++Run:++```bash+python3 skills/ppt-master/scripts/template_fill_pptx.py analyze "<project_dir>/sources/<source.pptx>" -o "<project_dir>/analysis/slide_library.json"+```++Read `<project_dir>/analysis/slide_library.json` and identify:++| Field | Use |+|---|---|+| `slides[].page_type` | Cover / chapter / content / ending candidate |+| `slides[].text_summary` | Current semantic purpose of the source page |+| `slides[].slots[]` | Replaceable text slots with `slot_id`, `role`, `geometry`, paragraph count, and old text |+| `slides[].slots[].role` | Title / body / label candidate hint |+| `slides[].tables[]` | Native PowerPoint tables with `table_id`, row / column counts, and per-cell coordinates + text |+| `slides[].charts[]` | Native PowerPoint charts with `chart_id` |++**Selection rule**: Pick pages by content fitness, not by source order alone. A source page is useful only if its visible structure can carry the target message without heavy redesign.++A page's layout already encodes a rhetorical shape — a single hero statement, a lead-then-detail split, a 2×2 comparison, a stepwise progression, a metric row. Match the source material's own logic to a page whose structure expresses that same logic; do not pour unrelated content into a slot just because it is empty. When no selected page fits a piece of content well, drop that page or that content rather than forcing it — a forced fill reads as stiff. It is fine to use fewer pages than the source deck has.++---++## Step 4: Build the Fill Plan++Create a scaffold:++```bash+python3 skills/ppt-master/scripts/template_fill_pptx.py scaffold "<project_dir>/analysis/slide_library.json" -o "<project_dir>/analysis/fill_plan.json" --slides "1,3,4"+```++Then edit `<project_dir>/analysis/fill_plan.json` by hand from the source material. The plan is the single execution contract.++**Pages are reusable**: the output is the ordered `slides` list, not a one-to-one copy of the source deck. A source page is not single-use — list the same `source_slide` as many times as you need, each entry with its own `replacements`, to drive several output slides from one good layout (e.g., reuse a single content layout for five content pages). Likewise you may omit source pages entirely and put the selected ones in any order. The plan structure:++```json+{+ "schema": "template_fill_pptx_plan.v1",+ "source_pptx": "projects/source.pptx",+ "slides": [+ {+ "source_slide": 1,+ "purpose": "cover",+ "notes": "Speaker notes for this filled slide.",+ "transition": "fade",+ "replacements": [+ {+ "slot_id": "s01_sh4",+ "text": "New title"+ }+ ],+ "table_edits": [+ {+ "table_id": "s01_tbl3",+ "cells": [+ {"row": 0, "col": 0, "text": "Metric"},+ {"row": 0, "col": 1, "text": "Value"}+ ]+ }+ ],+ "chart_edits": [+ {+ "chart_id": "s01_ch4",+ "categories": ["A", "B"],+ "series": [+ {"name": "Series 1", "values": [10, 20]}+ ]+ }+ ]+ }+ ]+}+```++**Per-slide plan discipline**:++| Decision | Rule |+|---|---|+| `source_slide` | Repeat the same value across multiple entries to reuse one source layout for several output slides; order is free |+| `notes` | Optional spoken speaker notes for the filled slide — see **Speaker notes** below; write prose, not a copy of the on-slide text |+| `transition` | Optional per-slide page transition; overrides the `apply --transition` default. Accepts an effect name (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`), `none` to strip it, or `{ "effect": "push", "duration": 0.6 }` |+| `replacements` | Target by `slot_id` whenever possible; `shape_id` and `shape_name` are fallback selectors |+| `table_edits` | Optional native table cell edits; target by `table_id` whenever possible and use zero-based `row` / `col` |+| `chart_edits` | Optional native chart data edits; target by `chart_id`, set `categories`, and provide one or more `series` |+| Short text | For labels / chapter names / directory items, new text should be no longer than the original slot text |+| Body text | May be moderately freer than the original, but keep paragraph count and information density near the original slot |+| Empty slots | Use `scaffold --include-empty` only when a real placeholder is empty in the source deck |+| Native tables | Keep the original table row and column count; this workflow edits existing cells, not table structure |+| Native charts | Each series `values` list must match the category count; this workflow edits chart data, not chart styling |+| Facts | Every substantive claim must come from the user material |++**Fit check before apply**:++- Cover pages: replace title / subtitle / author only.+- Chapter pages: use short section labels.+- Dense content pages: compress material to bullets matching the existing slot capacity.+- Decorative or image-heavy pages: avoid forcing long prose into label-sized slots.++**Speaker notes (the `notes` field)** — distilled from the main pipeline's Logic Construction Phase, scaled to one note per planned slide:++Each `notes` value is **pure spoken narration**: write only what a presenter would say aloud, so the same text also works if the deck is later sent through `notes_to_audio.py`. The note explains and connects; it must not just restate the words already on the slide.++| Rule | Detail |+|---|---|+| Length | 2–5 natural sentences carrying the page's core message; cover / chapter / ending pages can be one or two sentences |+| Transitions | Carry page-to-page flow in the opening sentence as natural prose ("在明确了背景之后……" / "Having framed X, let's turn to Y") — never bracketed `[过渡]` / `[Transition]` tags |+| Plain prose only | No `#` heading line, no `- ` bullet lists, no `要点:① …` / `Key points:` lines, no `时长:2分钟` / `Duration:` annotations — embedded notes keep them verbatim and TTS would read them aloud |+| Number readability | Spell out figures when literal TTS pronunciation is awkward (Chinese "百分之六十八" over "68%"; plain English integers and percentages are fine) |+| One language | Match the deck's language; do not mix languages inside one note |+| Source-bound | Every substantive claim comes from the user material, same as `replacements` |++Example `notes` value for a Chinese content slide:++```json+"notes": "在看清整体市场格局之后,我们把镜头拉近到成都二手房的头部板块。当前挂牌均价同比上涨约百分之十二,但成交周期反而拉长到九十天以上,说明买方观望情绪在加重。这组数据是后面定价策略的基础,请重点留意。"+```++---++## Step 5: Check Text Capacity++Run the data-based capacity check before applying the plan:++```bash+python3 skills/ppt-master/scripts/template_fill_pptx.py check-plan "<project_dir>/analysis/slide_library.json" "<project_dir>/analysis/fill_plan.json" -o "<project_dir>/analysis/check_report.json"+```++Interpret the report:++| Warning type | Action |+|---|---|+| Short label exceeds original length | Rewrite shorter; do not shrink font by default |+| Title too long | Rewrite first; only use font-size changes as a last resort |+| Body much longer than source slot | Compress, split across another selected page, or choose a larger source page |+| Missing target | Fix `slot_id` / `shape_id`; do not apply the plan |++**Default fitting policy**: short text can be shorter but should not be longer; body text may be somewhat freer. Do not use per-item font shrinking as a default strategy because it breaks template consistency.++---++## Step 6: Apply the Plan++Run:++```bash+python3 skills/ppt-master/scripts/template_fill_pptx.py apply "<project_dir>/sources/<source.pptx>" "<project_dir>/analysis/fill_plan.json" -o "<project_dir>/exports/<output.pptx>"+```++By default `apply` gives every cloned slide a `fade` transition (`0.5s`), because most native templates ship an empty `<p:transition/>` that renders as *no* motion. Override the default with `--transition <effect>` (`fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random`) and `--transition-duration <seconds>`; pass `--transition none` for no motion, or `--transition keep` to preserve each source slide's existing transition unchanged. A per-slide `transition` field in the plan overrides whatever the CLI selects for that slide.++`apply` appends a timestamp automatically. For example, `-o "<project_dir>/exports/demo.pptx"` writes `demo_YYYYMMDD_HHMMSS.pptx`. If the filename already ends with `_YYYYMMDD_HHMMSS`, it is left unchanged.++The script:++| Behavior | Result |+|---|---|+| Clones selected source slides | Original slide design, relationships, images, layouts, and animations are preserved where PowerPoint supports them |+| Replaces text nodes | Text frames remain editable in PowerPoint |+| Writes `notes` fields | Speaker notes are embedded as native PowerPoint notes slides |+| Applies `--transition` / per-slide `transition` | Populates each slide's `<p:transition>` with a native PowerPoint page transition |+| Rebuilds presentation slide list | Output deck contains only the planned slide sequence |+| Adds timestamp to PPTX filename | Matches the main SVG-to-PPTX export convention |+| Drops orphaned source parts | Output carries only the selected pages and the layouts / media / charts they still reference (reachability prune) |++**Animation policy**: Template-fill preserves each cloned slide's existing object animation XML (the SVG pipeline's generated object animation defaults are not applied here). Page transitions are the one motion layer this workflow writes directly, and `apply` adds a `fade` transition by default so a filled deck is never left with the template's empty no-motion transitions; change it with `apply --transition` / a per-slide `transition` field, or opt out with `--transition keep` (preserve source) or `--transition none`. If the user asks to change object-level animation order / timing / effects, treat that as a separate direct-PPTX animation customization task.++---++## Step 7: Validate Output++Run a lightweight readability check:++```bash+python3 skills/ppt-master/scripts/source_to_md/ppt_to_md.py "<project_dir>/exports/<output.pptx>"+```++Move or copy the read-back Markdown and extracted files into `<project_dir>/validation/` so `exports/` contains only final deliverables.++Verify:++| Check | Expected |+|---|---|+| Output filename | Ends with `_YYYYMMDD_HHMMSS.pptx` |+| Slide count | Matches `len(fill_plan.slides)` |+| Key title text | Appears in the extracted Markdown |+| Native table cells | Updated values appear in the extracted Markdown table |+| Native chart data | Updated labels / values are present in the cloned chart XML |+| Multi-line body text | Preserves intended line / paragraph breaks |+| Speaker notes | `ppt_to_md.py` can read the generated PPTX without notes-related errors |+| Missing target errors | None from `template_fill_pptx.py apply` |++If the extracted text is correct but visual overflow is likely, reduce the text in `fill_plan.json` and re-run Step 4.++```markdown+## ✅ Template Fill Complete++- [x] `slide_library.json` extracted from the source PPTX+- [x] `fill_plan.json` selects only pages that fit the target story+- [x] `check-plan` run and capacity warnings resolved or explicitly accepted+- [x] Output PPTX generated through direct OOXML text replacement+- [x] Speaker notes embedded when `notes` fields are present+- [x] `ppt_to_md.py` readability check passed+```++---++## Current Boundary++| Capability | Status |+|---|---|+| Select / reorder / repeat source slides | Supported |+| Replace text in existing text frames | Supported |+| Edit native PowerPoint table cell text | Supported |+| Edit native PowerPoint chart categories / series data | Supported |+| Preserve original visual design | Supported by cloning slide parts directly |+| Page-to-page transitions | Supported via `apply --transition` or per-slide `transition` |+| Replace images | Not in v1 |+| Object-level entrance animations | Not in v1; preserved from source only, set as a separate task |+| Edit chart formatting / axes / legend layout | Not in v1 |+| Edit SmartArt deeply | Not in v1 |+| Automatic visual overflow detection | Not in v1; use text-capacity judgment from the library slots |