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): isolate private parts on slide reuse and improve capacity checks
hugohe39cd470e4952e
diff --git a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py b/skills/ppt-master/scripts/template_fill_pptx/analyzer.pyindex fe0108f2..03e32632 100644--- a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py+++ b/skills/ppt-master/scripts/template_fill_pptx/analyzer.py@@ -94,6 +94,30 @@ def _slot_role(slot: dict[str, Any], order: int) -> str:return "label_candidate"+def _font_size_px(container: ET.Element) -> float | None:+ sizes: list[float] = []+ for node in container.findall(".//a:rPr", NS) + container.findall(".//a:defRPr", NS):+ raw_size = node.attrib.get("sz")+ if not raw_size:+ continue+ try:+ sizes.append(int(raw_size) / 100 * 96 / 72)+ except ValueError:+ continue+ if not sizes:+ return None+ # Use the largest explicit run size as the conservative capacity baseline.+ return round(max(sizes), 2)+++def _text_metrics(container: ET.Element, paragraph_count: int) -> dict[str, Any]:+ font_size_px = _font_size_px(container)+ return {+ "font_size_px": font_size_px,+ "paragraph_count": paragraph_count,+ }++def _classify_page_type(index: int, total: int, text: str, slots: list[dict[str, Any]]) -> str:normalized = text.lower()if index == 1:@@ -149,6 +173,7 @@ def analyze_pptx(pptx_path: Path) -> dict[str, Any]:"text": text,"paragraph_count": len(paragraphs),"geometry": geometry,+ "text_metrics": _text_metrics(container, len(paragraphs)),})diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.pyindex db9af1a4..4704c1a7 100644--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py@@ -16,6 +16,7 @@ from .chart_fill import (_max_chart_part_number,_max_embedding_part_number,)+from .clone import _make_part_allocator, deep_clone_slide_private_partsfrom .notes import _find_notes_master_target, _slide_rels_with_notesfrom .ooxml import NS, REL_NS, SLIDE_REL_TYPE, _parse_slide_refs, _qn, _xml_bytesfrom .package import (@@ -74,6 +75,7 @@ def apply_plan(next_rel_number = _max_numeric_rid(pres_rels_root) + 1next_chart_number = _max_chart_part_number(entries)next_embedding_number = _max_embedding_part_number(entries)+ allocate_part = _make_part_allocator(entries)for offset, item in enumerate(plan_slides):source_slide = int(item.get("source_slide", 0))@@ -116,6 +118,13 @@ def apply_plan(source_rels = entries.get(source_ref.rels_name)slide_rels_root = ET.fromstring(source_rels) if source_rels else _empty_relationships_root()+ deep_clone_slide_private_parts(+ slide_rels_root,+ new_slide_part=new_part,+ entries=entries,+ content_root=content_root,+ allocate=allocate_part,+ )chart_edits = item.get("chart_edits", [])if not isinstance(chart_edits, list):raise RuntimeError(f"Slide {source_slide} chart_edits must be a list")diff --git a/skills/ppt-master/scripts/template_fill_pptx/checker.py b/skills/ppt-master/scripts/template_fill_pptx/checker.pyindex 84519349..901846be 100644--- a/skills/ppt-master/scripts/template_fill_pptx/checker.py+++ b/skills/ppt-master/scripts/template_fill_pptx/checker.py@@ -2,11 +2,11 @@from __future__ import annotations+import unicodedatafrom typing import Anyfrom .selectors import (_chart_selectors,- _plain_len,_replacement_selectors,_replacement_text,_table_selectors,@@ -55,27 +55,111 @@ def _chart_lookup(library: dict[str, Any]) -> dict[tuple[int, str], dict[str, Anreturn lookup+def _visual_width(text: str) -> float:+ """Estimate rendered text width in Latin-character units.++ ``len(text)`` is too crude for mixed CJK / Latin decks: Chinese characters+ generally consume about twice the horizontal space of ASCII letters, while+ punctuation and digits are narrower. The checker only needs a conservative+ fit signal, so use Unicode East Asian Width instead of a font-specific+ renderer.+ """+ width = 0.0+ for char in "".join(text.split()):+ east_asian_width = unicodedata.east_asian_width(char)+ if east_asian_width in {"F", "W"}:+ width += 2.0+ elif east_asian_width == "A":+ width += 1.5+ else:+ width += 1.0+ return width+++def _display_width(value: float) -> int | float:+ return int(value) if value.is_integer() else round(value, 1)+++def _fallback_font_size_px(role: str, geometry: dict[str, Any], old_paragraphs: int) -> float:+ height = geometry.get("height")+ if isinstance(height, int) and old_paragraphs > 0:+ inferred = height / max(old_paragraphs, 1) / 1.25+ if 8 <= inferred <= 56:+ return inferred+ if role == "title_candidate":+ return 28.0+ if role == "body_candidate":+ return 16.0+ return 14.0+++def _geometry_capacity_width(+ *,+ role: str,+ old_paragraphs: int,+ new_paragraphs: int,+ geometry: dict[str, Any],+ text_metrics: dict[str, Any],+) -> float | None:+ width = geometry.get("width")+ height = geometry.get("height")+ if not isinstance(width, int) or not isinstance(height, int) or width <= 0 or height <= 0:+ return None++ font_size_px = text_metrics.get("font_size_px")+ if not isinstance(font_size_px, (int, float)) or font_size_px <= 0:+ font_size_px = _fallback_font_size_px(role, geometry, old_paragraphs)++ line_height = max(font_size_px * 1.25, 1.0)+ max_lines = max(int(height / line_height), old_paragraphs, new_paragraphs, 1)+ horizontal_padding = 24 if width >= 180 else 12+ usable_width = max(width - horizontal_padding, width * 0.72, 1)+ latin_units_per_line = usable_width / max(font_size_px * 0.52, 1)+ capacity = latin_units_per_line * max_lines++ if role == "label_candidate":+ return capacity * 0.7+ if role == "title_candidate":+ return capacity * 0.85+ return capacity++def _fit_status(*,role: str,- old_len: int,- new_len: int,+ old_width: float,+ new_width: float,old_paragraphs: int,new_paragraphs: int,geometry: dict[str, Any],+ text_metrics: dict[str, Any],) -> tuple[str, str]:- old_len = max(old_len, 1)- ratio = new_len / old_len+ old_width = max(old_width, 1.0)+ ratio = new_width / old_widthwidth = geometry.get("width")height = geometry.get("height")+ capacity_width = _geometry_capacity_width(+ role=role,+ old_paragraphs=old_paragraphs,+ new_paragraphs=new_paragraphs,+ geometry=geometry,+ text_metrics=text_metrics,+ )- 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 == "label_candidate" or (old_width <= 8 and old_paragraphs <= 1):+ if capacity_width is not None and new_width <= capacity_width and not (old_width <= 8):+ return "OK", "short label fits estimated text-box capacity"+ label_limit = old_width+ if isinstance(width, int) and width >= 220:+ label_limit = max(label_limit, old_width * 1.25)+ if new_width > label_limit:+ return "WARN", "short label exceeds original visual width; rewrite shorter"+ return "OK", "short label fits original visual width"if role == "title_candidate" and old_paragraphs <= 1:- limit = 1.15 if old_len <= 8 else 1.35+ if capacity_width is not None and new_width <= capacity_width:+ return "OK", "title fits estimated text-box capacity"+ limit = 1.15 if old_width <= 12 else 1.35if ratio > limit:return "WARN", "title is too long for the original slot; rewrite first"return "OK", "title stays near original capacity"@@ -87,6 +171,9 @@ def _fit_status(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"+ if capacity_width is not None and new_width > capacity_width:+ return "WARN", "text exceeds estimated text-box capacity; rewrite or split"+# 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@@ -95,6 +182,27 @@ def _fit_status(return "OK", "within estimated slot capacity"+def _capacity_for_report(+ *,+ role: str,+ old_width: float,+ old_paragraphs: int,+ new_paragraphs: int,+ geometry: dict[str, Any],+ text_metrics: dict[str, Any],+) -> float | None:+ capacity = _geometry_capacity_width(+ role=role,+ old_paragraphs=old_paragraphs,+ new_paragraphs=new_paragraphs,+ geometry=geometry,+ text_metrics=text_metrics,+ )+ if capacity is None:+ return None+ return _display_width(max(capacity, old_width))++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)@@ -136,17 +244,26 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:continueold_text = str(slot.get("text") or "")- old_len = _plain_len(old_text)- new_len = _plain_len(text)+ old_width = _visual_width(old_text)+ new_width = _visual_width(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_width=old_width,+ new_width=new_width,+ old_paragraphs=old_paragraphs,+ new_paragraphs=new_paragraphs,+ geometry=slot.get("geometry") or {},+ text_metrics=slot.get("text_metrics") or {},+ )+ capacity_width = _capacity_for_report(+ role=str(slot.get("role") or ""),+ old_width=old_width,old_paragraphs=old_paragraphs,new_paragraphs=new_paragraphs,geometry=slot.get("geometry") or {},+ text_metrics=slot.get("text_metrics") or {},)summary["warn" if status == "WARN" else "ok"] += 1results.append(@@ -156,9 +273,12 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:"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_len": _display_width(old_width),+ "new_len": _display_width(new_width),+ "old_visual_width": _display_width(old_width),+ "new_visual_width": _display_width(new_width),+ "capacity_visual_width": capacity_width,+ "ratio": round(new_width / max(old_width, 1.0), 2),"old_paragraphs": old_paragraphs,"new_paragraphs": new_paragraphs,"message": message,diff --git a/skills/ppt-master/scripts/template_fill_pptx/clone.py b/skills/ppt-master/scripts/template_fill_pptx/clone.pynew file mode 100644index 00000000..2790007f--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/clone.py@@ -0,0 +1,176 @@+"""apply: deep-clone a cloned slide's structured private dependency parts.++When the same source slide is reused for several output slides (the workflow+lets a fill plan list one ``source_slide`` many times), copying its+relationships verbatim leaves every clone pointing at one shared set of private+parts — custom-data tags, per-slide theme overrides, SmartArt diagrams. The+pages are not really independent: editing one output slide's structure would+bleed into its siblings.++This helper gives each cloned slide its own copy of every *structured* private+dependency (parts that carry an explicit content-type ``Override``) and rewrites+the relationship targets. Cloning is recursive, so a private part's own private+sub-parts (e.g. a diagram data part's drawing) are cloned too.++Two classes of target are deliberately left shared:++* **Shared structure** — slide layout / master / theme / notes master.+* **Binary blobs typed by a ``Default`` extension rule** — media (png / jpeg /+ emf ...) and OLE embeddings. Picture/object edits happen in PowerPoint, which+ mints a new part and repoints only the edited shape's relationship, so sharing+ never bleeds — and it avoids duplicating large media when one source page+ drives many output slides.++Charts stay owned by ``chart_fill`` (which clones the chart part together with+its embedded workbook when an edit is applied) and notes slides by ``notes``;+both relationship types are skipped here.+"""++from __future__ import annotations++import posixpath+from typing import Callable+from xml.etree import ElementTree as ET++from .ooxml import (+ CHART_REL_TYPE,+ CT_NS,+ NOTES_SLIDE_REL_TYPE,+ REL_NS,+ SLIDE_REL_TYPE,+ _normalize_part,+ _qn,+ _rels_name_for_part,+ _xml_bytes,+)+from .package import _add_content_type_override, _relative_target++_REL_TYPE_BASE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"++# Structure shared across every slide: never cloned, target kept as-is. Note that+# ``themeOverride`` is a distinct, per-slide private type and is NOT listed here.+SHARED_REL_TYPES = frozenset(+ _REL_TYPE_BASE + name+ for name in ("slideLayout", "slideMaster", "notesMaster", "theme", "presProps", "viewProps", "tableStyles")+)++# Owned by other apply stages (chart_fill / notes) or a back-reference: skipped here.+SKIPPED_REL_TYPES = frozenset({CHART_REL_TYPE, NOTES_SLIDE_REL_TYPE, SLIDE_REL_TYPE})+++def _make_part_allocator(entries: dict[str, bytes]) -> Callable[[str], str]:+ """Return a function that mints a fresh part name beside a source part.++ Names keep the source extension (so a content-type ``Default`` still covers+ media) and are unique against both existing entries and earlier allocations.+ """+ used = set(entries)++ def allocate(source_part: str) -> str:+ directory = posixpath.dirname(source_part)+ stem, ext = posixpath.splitext(posixpath.basename(source_part))+ index = 1+ while True:+ candidate = posixpath.join(directory, f"{stem}_tf{index}{ext}")+ if candidate not in used:+ used.add(candidate)+ return candidate+ index += 1++ return allocate+++def _override_content_type(content_root: ET.Element, part: str) -> str | None:+ """Return the part's explicit content-type ``Override``, or ``None``.++ ``None`` means the part is typed by a ``Default`` extension rule — i.e. a+ binary blob (media / OLE) we deliberately keep shared rather than clone.+ """+ part_pn = "/" + part.lstrip("/")+ for override in content_root.findall(_qn(CT_NS, "Override")):+ if override.attrib.get("PartName") == part_pn:+ return override.attrib.get("ContentType")+ return None+++def _is_shared(rel_type: str | None) -> bool:+ return bool(rel_type) and rel_type in SHARED_REL_TYPES+++def _clone_part_private_deps(+ rels_root: ET.Element,+ *,+ owner_part: str,+ entries: dict[str, bytes],+ content_root: ET.Element,+ allocate: Callable[[str], str],+ cloned: dict[str, str],+) -> None:+ """Rewrite ``rels_root`` in place, cloning each private target it references.++ ``cloned`` maps an already-handled source part to its clone so a single slide+ that references the same asset twice reuses one copy.+ """+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("TargetMode") == "External":+ continue+ rel_type = rel.attrib.get("Type")+ if _is_shared(rel_type) or rel_type in SKIPPED_REL_TYPES:+ continue+ target = rel.attrib.get("Target")+ if not target:+ continue+ source_part = _normalize_part(target, owner_part)+ if source_part not in entries:+ continue+ content_type = _override_content_type(content_root, source_part)+ if content_type is None:+ # Binary blob typed by a Default extension rule (media / OLE): keep+ # it shared. See the module docstring for why this never bleeds.+ continue++ new_part = cloned.get(source_part)+ if new_part is None:+ new_part = allocate(source_part)+ entries[new_part] = entries[source_part]+ cloned[source_part] = new_part+ _add_content_type_override(content_root, new_part, content_type)++ sub_rels_data = entries.get(_rels_name_for_part(source_part))+ if sub_rels_data:+ sub_rels_root = ET.fromstring(sub_rels_data)+ _clone_part_private_deps(+ sub_rels_root,+ owner_part=new_part,+ entries=entries,+ content_root=content_root,+ allocate=allocate,+ cloned=cloned,+ )+ entries[_rels_name_for_part(new_part)] = _xml_bytes(sub_rels_root)++ rel.set("Target", _relative_target(owner_part, new_part))+++def deep_clone_slide_private_parts(+ slide_rels_root: ET.Element,+ *,+ new_slide_part: str,+ entries: dict[str, bytes],+ content_root: ET.Element,+ allocate: Callable[[str], str],+) -> None:+ """Give one cloned slide private copies of its private dependency parts.++ Mutates ``slide_rels_root`` (rewriting targets) and ``entries`` (adding the+ cloned parts and their content-type overrides). ``allocate`` is shared across+ every slide in the run so minted names never collide.+ """+ _clone_part_private_deps(+ slide_rels_root,+ owner_part=new_slide_part,+ entries=entries,+ content_root=content_root,+ allocate=allocate,+ cloned={},+ )diff --git a/skills/ppt-master/workflows/template-fill-pptx.md b/skills/ppt-master/workflows/template-fill-pptx.mdindex 88b336d0..f425b5d5 100644--- a/skills/ppt-master/workflows/template-fill-pptx.md+++ b/skills/ppt-master/workflows/template-fill-pptx.md@@ -83,6 +83,20 @@ Read `<project_dir>/analysis/slide_library.json` and identify: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.+**Layout-first planning**: Treat `slide_library.json` as a layout inventory, not as an ordered deck outline. Before writing `fill_plan.json`, infer each reusable source page's affordance from JSON fields:++| JSON signal | Layout planning use |+|---|---|+| `slides[].page_type` | Identify cover / TOC / chapter / ending candidates, but do not preserve their original order by default |+| `slots[].role` counts | Infer whether the page is a hero statement, comparison, multi-card list, timeline, metric row, or dense explanation |+| `slots[].geometry` | Estimate whether each text slot is a short label, medium title, body block, caption, or decorative number |+| `slots[].text_metrics.font_size_px` | Estimate text capacity together with geometry; larger type means fewer safe characters |+| `slots[].text_summary` | Read the source page's original rhetorical pattern, not its literal placeholder wording |++**Hard rule**: The target story controls output order. Source slides may move forward, move backward, be omitted, or be reused several times when their layout matches multiple target messages. Never treat source slide order as a default outline unless the user explicitly asks to preserve it.++**Required mapping pass**: Create a concise page-to-layout rationale in `<project_dir>/analysis/` before finalizing the plan. It can be JSON or Markdown, but it must record the intended target slide, chosen `source_slide`, and the layout reason (for example: `three-column strategy`, `two-problem contrast`, `timeline`, `metric focus`, `chapter divider`). This is evidence that selection came from template structure rather than sequential replacement.+---## Step 4: Build the Fill Plan@@ -95,7 +109,11 @@ python3 skills/ppt-master/scripts/template_fill_pptx.py scaffold "<project_dir>/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:+**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.++**Scaffold boundary**: `scaffold --slides` is only a convenience starter. If the final plan needs repeated source pages or a story order that differs from the template order, duplicate / reorder entries in `fill_plan.json` manually or generate the plan from `slide_library.json`; do not let scaffold output constrain the deck structure.++The plan structure:```json{@@ -140,14 +158,14 @@ Then edit `<project_dir>/analysis/fill_plan.json` by hand from the source materi| Decision | Rule ||---|---|-| `source_slide` | Repeat the same value across multiple entries to reuse one source layout for several output slides; order is free |+| `source_slide` | Repeat the same value across multiple entries to reuse one source layout for several output slides; order is free and must follow the target story rather than source deck order || `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 |+| Short text | For labels / chapter names / directory items, fit the slot's visual capacity from geometry and font size; do not rely on old placeholder length alone |+| Body text | May be moderately freer than the original, but keep paragraph count, visual width, and information density near the slot's geometry capacity || 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 |@@ -159,6 +177,8 @@ Then edit `<project_dir>/analysis/fill_plan.json` by hand from the source materi- 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.+- Repeated source pages: every repeated entry must carry a distinct purpose and replacement set; avoid visual repetition unless the repeated layout expresses the same rhetorical pattern.+- Reordered source pages: verify the new sequence reads as a coherent story; template page numbers, decorative section markers, and notes must be updated to match the output order.**Speaker notes (the `notes` field)** — distilled from the main pipeline's Logic Construction Phase, scaled to one note per planned slide:@@ -193,12 +213,12 @@ Interpret the report:| Warning type | Action ||---|---|-| Short label exceeds original length | Rewrite shorter; do not shrink font by default |+| Short label exceeds visual width | Rewrite shorter or choose a layout with a larger label slot; 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.+**Default fitting policy**: Check fit against visual capacity, not raw character count. CJK characters, Latin letters, numbers, and punctuation occupy different visual widths; old placeholder text is only a weak signal. Use `capacity_visual_width` when present, together with `slots[].geometry` and `slots[].text_metrics.font_size_px`, to decide whether to rewrite, split, or choose a different source layout. Do not use per-item font shrinking as a default strategy because it breaks template consistency.---