Skip to content

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(pptx-intake): read SmartArt semantic structure

hugohe3b94f93d61ba5
diff --git a/docs/technical-design.md b/docs/technical-design.md
index 09f419fb..11f8fe14 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -191,8 +191,8 @@ Source documents (PDF / DOCX / EPUB / XLSX / PPTX / web pages) are normalized be
| Channel | Artifact | Owner | Used for |
|---|---|---|---|
-| Content contract | `sources/` content-type files (primarily `<stem>.md`) | `source_to_md/*` converters + `import-sources` | text, tables, chart values, citations, and source narrative |
-| Structured analysis | `analysis/*.json` / `analysis/*.csv` | intake and analysis tools | PPTX identity, slide geometry, native tables/charts, image dimensions/colors/subjects |
+| Content contract | `sources/` content-type files (primarily `<stem>.md`) | `source_to_md/*` converters + `import-sources` | text, tables, chart values, SmartArt node wording, citations, and source narrative |
+| Structured analysis | `analysis/*.json` / `analysis/*.csv` | intake and analysis tools | PPTX identity, slide geometry, native tables/charts, SmartArt relationships, image dimensions/colors/subjects |
For PPTX sources, `project_manager.py import-sources` runs both `ppt_to_md.py` and `pptx_intake.py`. The Markdown remains the content source for the main generation pipeline. The intake bundle writes `<stem>.identity.json`, `<stem>.slide_library.json`, and merges a compact multi-deck index into `analysis/source_profile.json`. Strategist reads the compact index for source facts and opens raw per-deck artifacts only when a workflow needs them. That distinction matters: the main pipeline may rethink page count and story, while `template-fill` and `beautify` promote parts of the same intake facts into stronger constraints.
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 9886222c..d571a025 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -190,8 +190,8 @@ SVG 也是唯一同时满足流程中所有角色需要的格式:**AI 能可
| 通道 | 产物 | 所有者 | 用途 |
|---|---|---|---|
-| 内容契约 | `sources/` 内容型文件(以 `<stem>.md` 为主) | `source_to_md/*` 转换器 + `import-sources` | 文本、表格、图表数值、引用和源材料叙事 |
-| 结构化分析 | `analysis/*.json` / `analysis/*.csv` | intake 与分析工具 | PPTX 身份信息、页面几何、原生表格/图表、图片尺寸/色彩/主体 |
+| 内容契约 | `sources/` 内容型文件(以 `<stem>.md` 为主) | `source_to_md/*` 转换器 + `import-sources` | 文本、表格、图表数值、SmartArt 节点文字、引用和源材料叙事 |
+| 结构化分析 | `analysis/*.json` / `analysis/*.csv` | intake 与分析工具 | PPTX 身份信息、页面几何、原生表格/图表、SmartArt 关系、图片尺寸/色彩/主体 |
对 PPTX 源文件,`project_manager.py import-sources` 会同时运行 `ppt_to_md.py` 和 `pptx_intake.py`。Markdown 仍然是主生成流水线的内容源;intake bundle 会写出 `<stem>.identity.json`、`<stem>.slide_library.json`,并把紧凑的多 deck 索引合并到 `analysis/source_profile.json`。Strategist 默认读取这个紧凑索引来获取源事实;只有特定工作流需要原始细节时,才打开单个 deck 的原始 artifact。这个边界很重要:主流水线可以重构页数和叙事,而 `template-fill` 与 `beautify` 会把同一批 intake 事实中的一部分提升为更强约束。
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index b21cf8e6..d827df18 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -83,7 +83,7 @@ description: >
| Script | Purpose |
|--------|---------|
| `${SKILL_DIR}/scripts/source_to_md.py` | Unified source-to-Markdown dispatcher — default Step 1 entry for explicit file(s) or URL(s) |
-| `${SKILL_DIR}/scripts/pptx_intake.py` | Standard PPTX intake enrichment — canvas / identity / slide geometry / tables / native chart data |
+| `${SKILL_DIR}/scripts/pptx_intake.py` | Standard PPTX intake enrichment — canvas / identity / slide geometry / tables / native chart data / SmartArt structure |
| `${SKILL_DIR}/scripts/project_manager.py` | Project init / validate / manage |
| `${SKILL_DIR}/scripts/icon_sync.py` | Copy chosen library icons into `<project>/icons/` at selection time; missing names reported + non-zero (re-pick gate) |
| `${SKILL_DIR}/scripts/analyze_images.py` | Image analysis |
@@ -202,7 +202,7 @@ For PPTX sources, `import-sources` automatically runs the standard intake enrich
python3 ${SKILL_DIR}/scripts/pptx_intake.py <project_path>/sources/<source.pptx> -o <project_path>/analysis
```
-For each PPTX it writes `<stem>.identity.json` (canvas, theme palette/fonts, observed usage) and `<stem>.slide_library.json` (text slots, geometry, native tables, native chart caches), and merges that deck's Strategist-facing digest into the single multi-deck index `analysis/source_profile.json` (`decks[]`, one self-contained entry per source deck, with prefixed artifact pointers). In the main generation path these are source facts and recommendation candidates, not replica constraints; beautify and template-fill workflows decide separately which fields become locked constraints.
+For each PPTX it writes `<stem>.identity.json` (canvas, theme palette/fonts, observed usage) and `<stem>.slide_library.json` (text slots, geometry, native tables, native chart caches, SmartArt nodes/connections), and merges that deck's Strategist-facing digest into the single multi-deck index `analysis/source_profile.json` (`decks[]`, one self-contained entry per source deck, with prefixed artifact pointers). In the main generation path these are source facts and recommendation candidates, not replica constraints; beautify and template-fill workflows decide separately which fields become locked constraints.
Multi-deck: several PPTX files may be imported into one main-pipeline project — each gets its own `<stem>.*` artifacts and a deck entry in `source_profile.json`. `source_profile.json` stays the single must-read index (one entry for a one-deck project, several for a combined-source project). Stems must be distinct; re-importing the same stem replaces that deck's entry. The beautify / template-fill workflows remain single-deck (1:1 to one chosen source deck) and read that deck's `<stem>.*` artifacts.
@@ -377,9 +377,9 @@ Read references/strategist.md
**Artifact ownership**: fact-channel and source/derived artifact boundaries are defined in [`references/artifact-ownership.md`](references/artifact-ownership.md). This Step uses those ownership rules; it does not redefine them.
-**`<project_path>/analysis/` is the project's intermediate-analysis folder: the canonical home for machine-extracted source/asset facts — the PPTX intake bundle (`source_profile.json` index + per-deck `<stem>.identity.json` / `<stem>.slide_library.json`) and `image_analysis.csv`. It holds facts, not design contracts — `design_spec.md` / `spec_lock.md` stay at the project root.** The MUST-read contract covers only the **compact structured data files (`.json` / `.csv`)**; other artifacts that may live under `analysis/` (e.g. a beautify `source_svg_import/` vector reference package) are NOT bulk-read — they are read selectively only when a specific workflow step calls for them. Before the Strategist confirmation stage, Strategist MUST read the auto-extracted fact files already in `analysis/` — currently `source_profile.json` (PPTX intake), when present. This file is the multi-deck index: read it once for the `decks[]` digests (canvas / chart / table entries per source deck), then open a specific deck's `<stem>.identity.json` / `<stem>.slide_library.json` only if you need its full raw facts. Use these entries as **factual source context** (format default + content facts); when several decks are present, synthesize across all of them. The source's **palette / typography / visual identity are a reference, not a constraint**: the main pipeline may inherit them where they fit the content and the confirmed style, or design fresh where they don't — the Strategist's judgment, never an obligation to either keep or discard. (Template-fill preserves the native source design by editing cloned slides directly; beautify defaults to the source identity but still follows the confirmed values; the main pipeline treats source identity as reference only and defaults to fresh design.) (`image_analysis.csv` lands later, at the image-analysis step below, and is the authoritative regenerated image-fact view there — re-derived from the live `images/` folder, not a durable store.)
+**`<project_path>/analysis/` is the project's intermediate-analysis folder: the canonical home for machine-extracted source/asset facts — the PPTX intake bundle (`source_profile.json` index + per-deck `<stem>.identity.json` / `<stem>.slide_library.json`) and `image_analysis.csv`. It holds facts, not design contracts — `design_spec.md` / `spec_lock.md` stay at the project root.** The MUST-read contract covers only the **compact structured data files (`.json` / `.csv`)**; other artifacts that may live under `analysis/` (e.g. a beautify `source_svg_import/` vector reference package) are NOT bulk-read — they are read selectively only when a specific workflow step calls for them. Before the Strategist confirmation stage, Strategist MUST read the auto-extracted fact files already in `analysis/` — currently `source_profile.json` (PPTX intake), when present. This file is the multi-deck index: read it once for the `decks[]` digests (canvas / chart / table / SmartArt entries per source deck), then open a specific deck's `<stem>.identity.json` / `<stem>.slide_library.json` only if you need its full raw facts. Use these entries as **factual source context** (format default + content facts); when several decks are present, synthesize across all of them. The source's **palette / typography / visual identity are a reference, not a constraint**: the main pipeline may inherit them where they fit the content and the confirmed style, or design fresh where they don't — the Strategist's judgment, never an obligation to either keep or discard. (Template-fill preserves the native source design by editing cloned slides directly; beautify defaults to the source identity but still follows the confirmed values; the main pipeline treats source identity as reference only and defaults to fresh design.) (`image_analysis.csv` lands later, at the image-analysis step below, and is the authoritative regenerated image-fact view there — re-derived from the live `images/` folder, not a durable store.)
-**Channel ownership — read each fact once from its owning channel.** In the main pipeline the **content contract is the content-type files in `sources/`** — primarily `<stem>.md`, but also any user-supplied content the import archived there: `.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml` (a `metrics.json` or `data.csv` may carry core content — judge by what the file holds). Text, tables, and chart data values come from these (`ppt_to_md` now transcribes native chart data into Markdown tables). **Do NOT read pipeline sidecars in `sources/` as content**: `*.conversion_profile.json` (conversion audit) and `*_files/image_manifest.json` (asset index) are process metadata — open them only to audit a conversion or resolve assets, never as slide content. Converted-source originals archived in `sources/` (`.pdf` / `.pptx` / `.docx` / `.xlsx` / `.html` / `.epub` / `.tex` / `.rst` / `.ipynb` / `.typ`, etc.) are read via their converted `<stem>.md`, not scanned directly in the main pipeline. The `analysis/` chart / table entries are a **structural digest** for outline decisions (which slides carried charts, type, series names) — not a second copy of the values; do NOT also pull chart values from `<stem>.slide_library.json` in the main pipeline. The `<stem>.slide_library.json` full structured data is owned by the direct-PPTX workflows: template-fill uses it as the native fill contract; beautify uses it for native chart / table data while keeping slide text from the Markdown.
+**Channel ownership — read each fact once from its owning channel.** In the main pipeline the **content contract is the content-type files in `sources/`** — primarily `<stem>.md`, but also any user-supplied content the import archived there: `.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml` (a `metrics.json` or `data.csv` may carry core content — judge by what the file holds). Text, tables, chart data values, and SmartArt node wording come from these (`ppt_to_md` transcribes native charts as Markdown tables and SmartArt nodes as hierarchical bullets). **Do NOT read pipeline sidecars in `sources/` as content**: `*.conversion_profile.json` (conversion audit) and `*_files/image_manifest.json` (asset index) are process metadata — open them only to audit a conversion or resolve assets, never as slide content. Converted-source originals archived in `sources/` (`.pdf` / `.pptx` / `.docx` / `.xlsx` / `.html` / `.epub` / `.tex` / `.rst` / `.ipynb` / `.typ`, etc.) are read via their converted `<stem>.md`, not scanned directly in the main pipeline. The `analysis/` chart / table / diagram entries are a **structural digest** for outline decisions (which slides carried charts, tables, or SmartArt; chart types / series names; SmartArt layout and hierarchy) — not a second copy of the content values; do NOT also pull chart values or SmartArt wording from `<stem>.slide_library.json` in the main pipeline. The `<stem>.slide_library.json` full structured data is owned by the direct-PPTX workflows: template-fill uses it as the native fill contract while preserving SmartArt unchanged; beautify uses it for native chart / table data and SmartArt relationships while keeping all wording from the Markdown.
**Strategist confirmation stage** (full template: `templates/design_spec_reference.md`):
diff --git a/skills/ppt-master/references/artifact-ownership.md b/skills/ppt-master/references/artifact-ownership.md
index e23214a8..51b03d96 100644
--- a/skills/ppt-master/references/artifact-ownership.md
+++ b/skills/ppt-master/references/artifact-ownership.md
@@ -10,12 +10,12 @@ Global artifact ownership rules for PPT Master projects.
| Artifact | Owner | Role | Read/write contract |
|---|---|---|---|
-| `sources/` content-type files | Content contract | Main pipeline source for text, tables, and chart data values | Strategist reads content-type files (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`) and judges by content; do not replace values with PPTX geometry JSON in the main pipeline |
+| `sources/` content-type files | Content contract | Main pipeline source for text, tables, chart data values, and SmartArt node wording | Strategist reads content-type files (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`) and judges by content; do not replace values with PPTX geometry JSON in the main pipeline |
| `sources/` converted-source originals | Source archive | Imported source files that have a converted content contract (`.pdf` / `.pptx` / `.docx` / `.xlsx` / `.html` / `.epub` / `.tex` / `.rst` / `.ipynb` / `.typ`, etc.) and source-adjacent extracted assets | Read via the converted `<stem>.md` in the main pipeline; direct-PPTX workflows read the `.pptx` by route |
| `sources/*.conversion_profile.json`, `sources/*_files/image_manifest.json` | Pipeline sidecar | Conversion audit record / asset index | NOT read as slide content; open only to audit a conversion or resolve assets |
| `analysis/source_profile.json` | Machine fact index | Compact Strategist-facing PPTX intake digest | Main pipeline reads as factual context and recommendation candidates |
| `analysis/<stem>.identity.json` | Native deck identity facts | Canvas, theme palette/fonts, observed usage | Read selectively when detailed identity facts are needed |
-| `analysis/<stem>.slide_library.json` | Native PPTX structure facts | Text slots, geometry, native tables, native chart caches | Direct PPTX workflows use as native fill/structure contract |
+| `analysis/<stem>.slide_library.json` | Native PPTX structure facts | Text slots, geometry, native tables, native chart caches, SmartArt nodes/connections | Direct PPTX workflows use as native fill/structure contract |
| `analysis/image_analysis.csv` | Regenerated image fact view | Measured facts about the current `images/` folder | Re-run `analyze_images.py` before reading image facts after changes |
| `design_spec.md` | Human design narrative | Explains design intent, outline, rationale, and resource plan | Strategist writes; humans and later roles read for intent |
| `spec_lock.md` | Execution contract | Literal colors, typography, icons, images, page rhythm, templates, and charts | Executor re-reads before every page; values must be used verbatim |
@@ -38,9 +38,9 @@ Global artifact ownership rules for PPT Master projects.
| Invariant | Rule |
|---|---|
-| Content values | Main pipeline text, tables, and chart values come from content-type files in `sources/` (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`), not from `slide_library.json`. |
+| Content values | Main pipeline text, tables, chart values, and SmartArt node wording come from content-type files in `sources/` (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`), not from `slide_library.json`. |
| Sources read policy | In `sources/`, read content-type files (`.md` / `.markdown` / `.txt` / `.csv` / `.tsv` / `.json` / `.jsonl` / `.yaml` / `.yml`) and judge by content — a `.json` / `.csv` may be core content or just data. Exclude known sidecars: `*.conversion_profile.json` and `*_files/image_manifest.json`. `analysis/` facts (`source_profile.json`, `<stem>.slide_library.json`) are read per Step 4 / direct-PPTX workflow, not in the `sources/` content scan. |
-| PPTX structure | `slide_library.json` owns native geometry and slot facts for direct PPTX workflows. |
+| PPTX structure | `slide_library.json` owns native geometry, slot facts, and SmartArt layout/relationships for direct PPTX workflows. |
| Design contract | `design_spec.md` explains; `spec_lock.md` executes. Executor must not infer execution values from prose. |
| Image facts | `images/` is live state; `analysis/image_analysis.csv` is a regenerated view, not a durable cache. |
| SVG source | `svg_output/` is the only author source for generated pages. |
diff --git a/skills/ppt-master/scripts/beautify_inventory.py b/skills/ppt-master/scripts/beautify_inventory.py
index 025b0d3a..52013477 100644
--- a/skills/ppt-master/scripts/beautify_inventory.py
+++ b/skills/ppt-master/scripts/beautify_inventory.py
@@ -3,7 +3,7 @@
PPT Master - Beautify Inventory Builder
Mechanically merge a source deck's extracts into one per-slide ledger for the
-beautify-pptx workflow: text blocks + tables + charts (from a
+beautify-pptx workflow: text blocks + tables + charts + SmartArt structure (from a
`template_fill_pptx.py analyze` slide_library.json) joined with the images
bound to each slide (from a `ppt_to_md.py` image_manifest.json). The deterministic
join only — `ignored` and `needs_confirmation` are emitted empty for the agent
@@ -103,12 +103,27 @@ def build_inventory(slide_library: dict, images_by_slide: dict[int, list[dict]])
}
for c in slide.get("charts", [])
]
+ diagrams = [
+ {
+ "diagram_id": diagram.get("diagram_id"),
+ "shape_name": diagram.get("shape_name"),
+ "geometry": diagram.get("geometry"),
+ "layout": diagram.get("layout", {}),
+ "root_ids": diagram.get("root_ids", []),
+ "nodes": diagram.get("nodes", []),
+ "connections": diagram.get("connections", []),
+ "status": diagram.get("status"),
+ "warnings": diagram.get("warnings", []),
+ }
+ for diagram in slide.get("diagrams", [])
+ ]
slides_out.append({
"slide_index": idx,
"page_type": slide.get("page_type"),
"text_blocks": text_blocks,
"tables": tables,
"charts": charts,
+ "diagrams": diagrams,
"images": images_by_slide.get(idx, []),
"ignored": [], # agent fills: hidden shapes, master-only text, image crop/rotation
"needs_confirmation": [], # agent fills: combo/dual-axis charts, merged-cell tables, overcrowded pages
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index f32f1e32..c0c70a90 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -194,6 +194,7 @@ Behavior:
- extracts slide text in reading order
- converts PowerPoint tables to Markdown tables
- transcribes native chart data (type + categories × series values) into a Markdown table, so chart numbers are not lost in conversion
+- transcribes SmartArt semantic nodes as hierarchical Markdown; unreadable diagram data emits an explicit placeholder and conversion warning
- exports embedded pictures to a sibling `_files/` directory
- appends speaker notes when present
- writes `<input>.conversion_profile.json` after successful conversion
@@ -218,15 +219,15 @@ python3 scripts/pptx_intake.py deck.pptx -o projects/demo/analysis
Outputs (per source deck, prefixed by file stem):
- `<stem>.identity.json` — canvas size/aspect, theme palette/fonts, observed colors/fonts
-- `<stem>.slide_library.json` — text slots, geometry, native tables, native chart display caches
-- `source_profile.json` — the single multi-deck index: a compact Strategist-facing digest per deck (over identity, tables, charts, and page types) under `decks[]`, with prefixed artifact pointers
+- `<stem>.slide_library.json` — text slots, geometry, native tables, native chart display caches, and SmartArt nodes/connections
+- `source_profile.json` — the single multi-deck index: a compact Strategist-facing digest per deck (over identity, tables, charts, SmartArt, and page types) under `decks[]`, with prefixed artifact pointers
`project_manager.py import-sources` runs this automatically for PPTX/PPTM/PPSX/PPSM/POTX/POTM inputs and stores the bundle directly under `analysis/`. Multi-deck per project: importing several PPTX files gives each its own `<stem>.*` artifacts and a `decks[]` entry in the shared `source_profile.json` index (re-importing the same stem replaces its entry). The beautify / template-fill workflows stay single-deck and read one chosen deck's `<stem>.*` artifacts.
Usage boundary:
- Standard generation uses these fields as facts and recommendation candidates; it does not inherit source slide coordinates or page order by default.
-- Beautify promotes selected identity/content fields into locked constraints after confirmation.
-- Template-fill uses the slide library as the native PPTX fill contract.
+- Beautify promotes selected identity/content fields into locked constraints after confirmation and redraws SmartArt meaning with ordinary editable shapes.
+- Template-fill uses the slide library as the native PPTX fill contract; SmartArt is inventory-only and remains unchanged.
## `pptx_to_svg.py`
diff --git a/skills/ppt-master/scripts/pptx_intake.py b/skills/ppt-master/scripts/pptx_intake.py
index 6217a8dd..34e50b46 100644
--- a/skills/ppt-master/scripts/pptx_intake.py
+++ b/skills/ppt-master/scripts/pptx_intake.py
@@ -4,8 +4,8 @@ PPT Master - PPTX Intake Enrichment
Extract reusable PPTX intake facts into a standard analysis bundle. This is a
read-only companion to `ppt_to_md.py`: Markdown remains the content source,
-while this bundle provides canvas, visual identity, slide geometry, tables, and
-native chart data for downstream workflows.
+while this bundle provides canvas, visual identity, slide geometry, tables,
+native chart data, and SmartArt structure for downstream workflows.
Usage:
python3 scripts/pptx_intake.py <source.pptx> -o <output_dir>
@@ -90,6 +90,49 @@ def _table_summary(slide_library: dict[str, Any]) -> dict[str, Any]:
return {"table_count": len(tables), "tables": tables}
+def _diagram_summary(slide_library: dict[str, Any]) -> dict[str, Any]:
+ diagrams: list[dict[str, Any]] = []
+ text_item_count = 0
+ unreadable_count = 0
+ warning_count = 0
+ slides_with_diagrams: set[int] = set()
+ for slide in slide_library.get("slides", []):
+ slide_index = slide.get("slide_index")
+ for diagram in slide.get("diagrams", []):
+ node_count = int(diagram.get("node_count") or 0)
+ text_count = int(diagram.get("text_count") or 0)
+ text_item_count += text_count
+ if not diagram.get("text_extracted"):
+ unreadable_count += 1
+ if diagram.get("status") != "ok" or diagram.get("warnings"):
+ warning_count += 1
+ if isinstance(slide_index, int):
+ slides_with_diagrams.add(slide_index)
+ diagrams.append(
+ {
+ "slide_index": slide_index,
+ "diagram_id": diagram.get("diagram_id"),
+ "layout": diagram.get("layout", {}),
+ "node_count": node_count,
+ "text_count": text_count,
+ "connection_count": int(diagram.get("connection_count") or 0),
+ "max_depth": int(diagram.get("max_depth") or 0),
+ "text_extracted": bool(diagram.get("text_extracted")),
+ "has_persisted_drawing": bool(diagram.get("has_persisted_drawing")),
+ "status": diagram.get("status"),
+ "warnings": diagram.get("warnings", []),
+ }
+ )
+ return {
+ "diagram_count": len(diagrams),
+ "text_item_count": text_item_count,
+ "unreadable_count": unreadable_count,
+ "warning_count": warning_count,
+ "slides_with_diagrams": sorted(slides_with_diagrams),
+ "diagrams": diagrams,
+ }
+
+
def build_source_profile(
pptx_path: Path,
identity: dict[str, Any],
@@ -118,7 +161,8 @@ def build_source_profile(
"into locked constraints after user confirmation."
),
"template_fill": (
- "Use slide slots, tables, charts, and geometry as the native PPTX fill contract."
+ "Use slide slots, tables, charts, diagrams, and geometry as the native PPTX "
+ "fill contract; diagrams are inventory-only and remain unchanged."
),
},
"artifacts": {
@@ -142,12 +186,14 @@ def build_source_profile(
"slide_index": slide.get("slide_index"),
"page_type": slide.get("page_type"),
"slot_count": len(slide.get("slots", [])),
+ "diagram_count": len(slide.get("diagrams", [])),
}
for slide in slide_library.get("slides", [])
],
},
"tables": _table_summary(slide_library),
"charts": _chart_summary(slide_library),
+ "diagrams": _diagram_summary(slide_library),
}
diff --git a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
index c6774d6a..50b174fd 100644
--- a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py
@@ -2,8 +2,8 @@
"""
PowerPoint to Markdown Converter
-Extracts slide text, tables, speaker notes, and embedded pictures from
-Open XML PowerPoint files into Markdown.
+Extracts slide text, tables, SmartArt node structure, speaker notes, and
+embedded pictures from Open XML PowerPoint files into Markdown.
Primary use case: PPTX source decks -> Markdown for PPT generation input.
@@ -29,10 +29,12 @@ import json
import re
import shutil
import sys
+import zipfile
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
from urllib.parse import quote
+from xml.etree import ElementTree as ET
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
if str(_SCRIPTS_DIR) not in sys.path:
@@ -41,6 +43,10 @@ if str(_SCRIPTS_DIR) not in sys.path:
from console_encoding import configure_utf8_stdio # noqa: E402
from _batch import run_path_batch # noqa: E402
from _conversion_profile import write_conversion_profile_best_effort # noqa: E402
+from template_fill_pptx.diagram_read import ( # noqa: E402
+ read_smartart_diagrams,
+ smartart_to_markdown,
+)
from pptx import Presentation
from pptx.enum.action import PP_ACTION
@@ -721,6 +727,39 @@ def convert_presentation_to_markdown(
_reset_generated_asset_dir(asset_dir)
presentation = Presentation(str(input_file))
+ conversion_warnings: list[str] = []
+ diagrams_by_slide: dict[int, list[dict[str, object]]] = {}
+ diagram_scan_failures: dict[int, str] = {}
+ try:
+ with zipfile.ZipFile(input_file) as package:
+ for slide_index, slide in enumerate(presentation.slides, 1):
+ slide_part = str(slide.part.partname).lstrip("/")
+ try:
+ diagrams = read_smartart_diagrams(package, slide_part, slide_index)
+ except (OSError, RuntimeError, zipfile.BadZipFile, ET.ParseError) as exc:
+ diagrams_by_slide[slide_index] = []
+ diagram_scan_failures[slide_index] = str(exc)
+ conversion_warnings.append(
+ f"Slide {slide_index}: SmartArt scan failed: {exc}"
+ )
+ continue
+ diagrams_by_slide[slide_index] = diagrams
+ for diagram in diagrams:
+ issues = [str(item) for item in diagram.get("warnings", []) if item]
+ if diagram.get("status") != "ok":
+ issues.insert(0, f"status={diagram.get('status')}")
+ if not issues:
+ continue
+ conversion_warnings.append(
+ f"Slide {slide_index}, {diagram.get('shape_name') or diagram.get('diagram_id')}: "
+ f"SmartArt content {'; '.join(issues)}"
+ )
+ except (OSError, RuntimeError, zipfile.BadZipFile, ET.ParseError) as exc:
+ conversion_warnings.append(f"SmartArt package scan failed: {exc}")
+ for slide_index in range(1, len(presentation.slides) + 1):
+ diagrams_by_slide.setdefault(slide_index, [])
+ diagram_scan_failures.setdefault(slide_index, str(exc))
+
lines = [
f"# {input_file.stem}",
"",
@@ -741,6 +780,13 @@ def convert_presentation_to_markdown(
lines.append("")
blocks = []
+ slide_diagrams = diagrams_by_slide.get(slide_index, [])
+ diagrams_by_shape_id = {
+ str(diagram.get("shape_id")): diagram
+ for diagram in slide_diagrams
+ if diagram.get("shape_id") is not None
+ }
+ emitted_diagram_ids: set[str] = set()
for item in iter_leaf_shapes(slide.shapes):
shape = item.shape
@@ -750,6 +796,13 @@ def convert_presentation_to_markdown(
blocks.append(table_md)
continue
+ shape_id = str(getattr(shape, "shape_id", ""))
+ diagram = diagrams_by_shape_id.get(shape_id)
+ if diagram is not None:
+ blocks.append(smartart_to_markdown(diagram))
+ emitted_diagram_ids.add(str(diagram.get("diagram_id")))
+ continue
+
is_picture_shape = shape.shape_type in {
MSO_SHAPE_TYPE.PICTURE,
MSO_SHAPE_TYPE.LINKED_PICTURE,
@@ -795,6 +848,15 @@ def convert_presentation_to_markdown(
except (ValueError, AttributeError, KeyError):
blocks.append(f"> [Chart] {getattr(shape, 'name', 'Chart')}")
+ for diagram in slide_diagrams:
+ if str(diagram.get("diagram_id")) in emitted_diagram_ids:
+ continue
+ blocks.append(smartart_to_markdown(diagram))
+ if slide_index in diagram_scan_failures:
+ blocks.append(
+ f"> [SmartArt scan unavailable: {diagram_scan_failures[slide_index]}]"
+ )
+
if blocks:
lines.append("\n\n".join(blocks))
lines.append("")
@@ -822,6 +884,7 @@ def convert_presentation_to_markdown(
converter="ppt_to_md.py",
conversion_type=suffix.lstrip("."),
asset_dir=asset_dir,
+ warnings=conversion_warnings,
)
print(f"[OK] Saved Markdown to: {out_file}")
diff --git a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py b/skills/ppt-master/scripts/template_fill_pptx/analyzer.py
index d4296099..14165185 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/analyzer.py
@@ -1,4 +1,4 @@
-"""analyze: read a PPTX as a reusable slide library of text / table / chart slots."""
+"""Analyze a PPTX as reusable text, table, chart, and SmartArt source facts."""
from __future__ import annotations
@@ -8,6 +8,7 @@ from typing import Any
from xml.etree import ElementTree as ET
from .chart_read import empty_chart_data, read_chart_data
+from .diagram_read import read_smartart_diagrams
from .ooxml import (
CHART_REL_TYPE,
NS,
@@ -143,26 +144,36 @@ def _canvas_px(pres_root: ET.Element) -> dict[str, int | None]:
}
-def _fill_risk(tables: list[dict[str, Any]], charts: list[dict[str, Any]]) -> dict[str, Any] | None:
+def _fill_risk(
+ tables: list[dict[str, Any]],
+ charts: list[dict[str, Any]],
+ diagrams: list[dict[str, Any]],
+) -> dict[str, Any] | None:
"""Return a fill_risk descriptor when the slide has non-text content that text-fill cannot replace.
- Only tables and charts are checked; no new dependencies are introduced.
- Returns None when the slide has no such content.
+ Tables and charts may be covered by explicit edits. SmartArt is inventory-only:
+ template-fill preserves it unchanged, so its source text may show through.
"""
kinds: list[str] = []
if tables:
kinds.append("table")
if charts:
kinds.append("chart")
+ if diagrams:
+ kinds.append("smartart")
if not kinds:
return None
kind_str = "/".join(kinds)
+ guidance: list[str] = []
+ if tables or charts:
+ guidance.append("cover tables/charts with explicit edits")
+ if diagrams:
+ guidance.append("review preserved SmartArt source text")
+ guidance_text = "; ".join(guidance)
return {
"has_non_text_content": True,
- "reason": (
- f"has non-text content ({kind_str}) that text-fill cannot replace; "
- "provide table_edits/chart_edits or pick another source slide"
- ),
+ "kinds": kinds,
+ "reason": f"has non-text content ({kind_str}) that text-fill does not replace automatically; {guidance_text}",
}
@@ -202,7 +213,16 @@ def analyze_pptx(pptx_path: Path) -> dict[str, Any]:
tables = _analyze_tables(slide_root, slide_ref.index)
charts = _analyze_charts(zf, slide_root, slide_ref)
- slide_text = "\n".join(slot["text"] for slot in slots if slot["text"])
+ diagrams = read_smartart_diagrams(zf, slide_ref.part_name, slide_ref.index)
+ slide_text = "\n".join(
+ [slot["text"] for slot in slots if slot["text"]]
+ + [
+ str(text)
+ for diagram in diagrams
+ for text in diagram.get("text_items", [])
+ if text
+ ]
+ )
slide: dict[str, Any] = {
"slide_index": slide_ref.index,
"page_type": _classify_page_type(slide_ref.index, len(slide_refs), slide_text, slots),
@@ -210,8 +230,9 @@ def analyze_pptx(pptx_path: Path) -> dict[str, Any]:
"slots": slots,
"tables": tables,
"charts": charts,
+ "diagrams": diagrams,
}
- risk = _fill_risk(tables, charts)
+ risk = _fill_risk(tables, charts, diagrams)
if risk is not None:
slide["fill_risk"] = risk
slides.append(slide)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/checker.py b/skills/ppt-master/scripts/template_fill_pptx/checker.py
index db400db6..5488485f 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/checker.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/checker.py
@@ -1,4 +1,4 @@
-"""check-plan: compare planned text / table / chart edits against source capacity."""
+"""Check planned text/table/chart edits and preserved SmartArt source risks."""
from __future__ import annotations
@@ -463,9 +463,8 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:
}
)
# --- Guardrail 2: source slides with non-text content not covered by edits ---
- # For each plan slide, if the source slide has tables/charts in the library
- # but the plan slide provides no matching table_edits/chart_edits, warn that
- # text-fill will silently leave the original template content in place.
+ # Tables/charts may be covered by explicit edits. SmartArt is preserve-only,
+ # so selecting a source slide that contains it always needs a content review.
lib_slides = _library_slide_index(library)
for plan_slide_index, slide in enumerate(plan.get("slides", []), start=1):
source_slide = int(slide.get("source_slide", 0))
@@ -474,7 +473,8 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:
continue
lib_tables = lib_slide.get("tables", [])
lib_charts = lib_slide.get("charts", [])
- if not lib_tables and not lib_charts:
+ lib_diagrams = lib_slide.get("diagrams", [])
+ if not lib_tables and not lib_charts and not lib_diagrams:
continue
# Check whether the plan slide provides edits covering the non-text content.
has_table_edits = bool(slide.get("table_edits"))
@@ -484,9 +484,16 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:
uncovered_kinds.append("table")
if lib_charts and not has_chart_edits:
uncovered_kinds.append("chart")
+ if lib_diagrams:
+ uncovered_kinds.append("smartart")
if not uncovered_kinds:
continue
kind_str = "/".join(uncovered_kinds)
+ guidance = "add table_edits/chart_edits, or pick another source slide"
+ if lib_diagrams:
+ guidance = "SmartArt remains unchanged, so pick another source slide or accept this warning"
+ if any(kind in uncovered_kinds for kind in ("table", "chart")):
+ guidance = f"add table/chart edits where supported; {guidance}"
summary["warn"] += 1
results.append(
{
@@ -494,11 +501,16 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:
"code": "non_text_content_unedited",
"plan_slide": plan_slide_index,
"source_slide": source_slide,
+ "uncovered_kinds": uncovered_kinds,
+ "diagram_ids": [
+ diagram.get("diagram_id")
+ for diagram in lib_diagrams
+ if diagram.get("diagram_id")
+ ],
"message": (
f"source slide {source_slide} has non-text content ({kind_str}) "
- "with no matching edits in the plan; text-fill leaves it untouched "
- "and original template content may show through "
- "(add table_edits/chart_edits, or pick another source slide)"
+ "outside the plan's supported edits; template-fill leaves it untouched "
+ f"and original template content may show through ({guidance})"
),
}
)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/diagram_read.py b/skills/ppt-master/scripts/template_fill_pptx/diagram_read.py
new file mode 100644
index 00000000..878763f0
--- /dev/null
+++ b/skills/ppt-master/scripts/template_fill_pptx/diagram_read.py
@@ -0,0 +1,569 @@
+"""Read SmartArt content and structure from DrawingML diagram parts.
+
+The reader exposes source facts only. It does not edit DiagramML or promise
+native SmartArt regeneration; generated decks continue to redraw the extracted
+content through the SVG-to-DrawingML shape pipeline.
+"""
+
+from __future__ import annotations
+
+import zipfile
+from typing import Any
+from xml.etree import ElementTree as ET
+
+from .ooxml import (
+ MC_NS,
+ NS,
+ _container_geometry,
+ _normalize_part,
+ _paragraph_texts,
+ _qn,
+ _read_xml,
+ _rels_name_for_part,
+ _shape_identity,
+ _slide_relationships,
+)
+
+
+DIAGRAM_NS = "http://schemas.openxmlformats.org/drawingml/2006/diagram"
+DIAGRAM_DRAWING_NS = "http://schemas.microsoft.com/office/drawing/2008/diagram"
+DIAGRAM_URI = "http://schemas.openxmlformats.org/drawingml/2006/diagram"
+
+_DIAGRAM_REL_SUFFIXES = {
+ "colors": "diagramColors",
+ "data": "diagramData",
+ "layout": "diagramLayout",
+ "quick_style": "diagramQuickStyle",
+}
+_REL_ATTRS = {
+ "colors": "cs",
+ "data": "dm",
+ "layout": "lo",
+ "quick_style": "qs",
+}
+_CONTENT_POINT_TYPES = {"asst", "node"}
+
+DIAGRAM_NS_MAP = {
+ **NS,
+ "dgm": DIAGRAM_NS,
+ "dsp": DIAGRAM_DRAWING_NS,
+ "mc": MC_NS,
+}
+
+
+def _relationship_matches(rel_type: str, suffix: str) -> bool:
+ return rel_type.rsplit("/", 1)[-1] == suffix
+
+
+def _read_optional_xml(
+ zf: zipfile.ZipFile,
+ part_name: str | None,
+) -> tuple[ET.Element | None, str | None]:
+ if not part_name:
+ return None, "missing-part-reference"
+ try:
+ return _read_xml(zf, part_name), None
+ except RuntimeError:
+ return None, "missing-part"
+ except ET.ParseError:
+ return None, "invalid-xml"
+
+
+def _diagram_containers(slide_root: ET.Element) -> list[ET.Element]:
+ containers: list[ET.Element] = []
+ for frame in slide_root.findall(".//p:graphicFrame", DIAGRAM_NS_MAP):
+ graphic_data = frame.find("a:graphic/a:graphicData", DIAGRAM_NS_MAP)
+ if graphic_data is not None and graphic_data.attrib.get("uri") == DIAGRAM_URI:
+ containers.append(frame)
+ return containers
+
+
+def _fallback_preview_shape_ids(slide_root: ET.Element) -> set[str]:
+ shape_ids: set[str] = set()
+ for alternate in slide_root.findall(".//mc:AlternateContent", DIAGRAM_NS_MAP):
+ frame = alternate.find("mc:Choice//p:graphicFrame", DIAGRAM_NS_MAP)
+ if frame is None:
+ continue
+ graphic_data = frame.find("a:graphic/a:graphicData", DIAGRAM_NS_MAP)
+ if graphic_data is None or graphic_data.attrib.get("uri") != DIAGRAM_URI:
+ continue
+ if alternate.find("mc:Fallback//p:pic", DIAGRAM_NS_MAP) is None:
+ continue
+ shape_id, _shape_name = _shape_identity(frame, len(shape_ids) + 1)
+ shape_ids.add(shape_id)
+ return shape_ids
+
+
+def _diagram_parts(
+ rel_ids: ET.Element | None,
+ relationships: dict[str, dict[str, str]],
+ slide_part: str,
+) -> tuple[dict[str, str], str | None]:
+ if rel_ids is None:
+ return {}, "missing-rel-ids"
+
+ parts: dict[str, str] = {}
+ data_error: str | None = None
+ for key, attr_name in _REL_ATTRS.items():
+ rel_id = rel_ids.attrib.get(_qn(NS["r"], attr_name), "")
+ if not rel_id:
+ if key == "data":
+ data_error = "missing-data-relationship"
+ continue
+ relationship = relationships.get(rel_id)
+ if relationship is None:
+ if key == "data":
+ data_error = "missing-data-relationship"
+ continue
+ if not _relationship_matches(
+ relationship.get("type", ""),
+ _DIAGRAM_REL_SUFFIXES[key],
+ ):
+ if key == "data":
+ data_error = "invalid-data-relationship"
+ continue
+ parts[key] = _normalize_part(relationship["target"], slide_part)
+ return parts, data_error
+
+
+def _persisted_drawing_part(
+ zf: zipfile.ZipFile,
+ data_part: str | None,
+ data_root: ET.Element | None,
+ slide_part: str,
+ slide_relationships: dict[str, dict[str, str]],
+) -> tuple[str | None, list[str]]:
+ if not data_part or data_root is None:
+ return None, []
+ data_model_ext = data_root.find(".//dsp:dataModelExt", DIAGRAM_NS_MAP)
+ rel_id = data_model_ext.attrib.get("relId", "") if data_model_ext is not None else ""
+ if not rel_id:
+ return None, []
+
+ warnings: list[str] = []
+ relationship = slide_relationships.get(rel_id)
+ relationship_owner = slide_part
+ if relationship is not None and not _relationship_matches(
+ relationship.get("type", ""),
+ "diagramDrawing",
+ ):
+ relationship = None
+ if relationship is None:
+ try:
+ data_relationships = _slide_relationships(zf, _rels_name_for_part(data_part))
+ except ET.ParseError:
+ data_relationships = {}
+ warnings.append("invalid-persisted-drawing-relationships")
+ relationship = data_relationships.get(rel_id)
+ relationship_owner = data_part
+ if relationship is not None and not _relationship_matches(
+ relationship.get("type", ""),
+ "diagramDrawing",
+ ):
+ relationship = None
+ if relationship is None:
+ warnings.append("unresolved-persisted-drawing-relationship")
+ return None, warnings
+
+ part_name = _normalize_part(relationship["target"], relationship_owner)
+ if part_name not in zf.namelist():
+ warnings.append("missing-persisted-drawing-part")
+ return None, warnings
+ return part_name, warnings
+
+
+def _layout_info(
+ layout_root: ET.Element | None,
+ data_root: ET.Element | None,
+) -> dict[str, Any]:
+ unique_id = layout_root.attrib.get("uniqueId") if layout_root is not None else None
+ if not unique_id and data_root is not None:
+ document_properties = data_root.find(
+ ".//dgm:pt[@type='doc']/dgm:prSet",
+ DIAGRAM_NS_MAP,
+ )
+ if document_properties is not None:
+ unique_id = document_properties.attrib.get("loTypeId")
+ title = layout_root.find("dgm:title", DIAGRAM_NS_MAP) if layout_root is not None else None
+ name = title.attrib.get("val") if title is not None else None
+ if not name and unique_id:
+ name = unique_id.rstrip("/").rsplit("/", 1)[-1]
+ categories = (
+ [
+ category.attrib["type"]
+ for category in layout_root.findall("dgm:catLst/dgm:cat", DIAGRAM_NS_MAP)
+ if category.attrib.get("type")
+ ]
+ if layout_root is not None
+ else []
+ )
+ return {
+ "name": name,
+ "unique_id": unique_id,
+ "categories": categories,
+ }
+
+
+def _integer_or_none(value: str | None) -> int | None:
+ if value is None:
+ return None
+ try:
+ return int(value)
+ except ValueError:
+ return None
+
+
+def _point_text(point: ET.Element) -> str:
+ text_body = point.find("dgm:t", DIAGRAM_NS_MAP)
+ if text_body is None:
+ return ""
+ return "\n".join(_paragraph_texts(text_body)).strip()
+
+
+def _connections(data_root: ET.Element) -> list[dict[str, Any]]:
+ connections: list[dict[str, Any]] = []
+ for connection in data_root.findall(
+ ".//dgm:cxnLst/dgm:cxn",
+ DIAGRAM_NS_MAP,
+ ):
+ source_id = connection.attrib.get("srcId", "")
+ destination_id = connection.attrib.get("destId", "")
+ if not source_id or not destination_id:
+ continue
+ connections.append(
+ {
+ "type": connection.attrib.get("type") or "parOf",
+ "source_id": source_id,
+ "destination_id": destination_id,
+ "source_order": _integer_or_none(connection.attrib.get("srcOrd")),
+ "destination_order": _integer_or_none(connection.attrib.get("destOrd")),
+ }
+ )
+ return connections
+
+
+def _nearest_content_parent(
+ node_id: str,
+ parent_by_id: dict[str, str],
+ content_ids: set[str],
+) -> str | None:
+ current = parent_by_id.get(node_id)
+ visited = {node_id}
+ while current:
+ if current in content_ids:
+ return current
+ if current in visited:
+ return None
+ visited.add(current)
+ current = parent_by_id.get(current)
+ return None
+
+
+def _break_parent_cycles(
+ parent_by_node: dict[str, str | None],
+ source_order: dict[str, int],
+) -> list[str]:
+ """Break cycles in the Markdown tree projection while retaining raw connections."""
+ warnings: list[str] = []
+ for start_id in sorted(parent_by_node, key=lambda node_id: source_order[node_id]):
+ path: list[str] = []
+ path_index: dict[str, int] = {}
+ current_id: str | None = start_id
+ while current_id is not None and current_id in parent_by_node:
+ if current_id in path_index:
+ cycle = path[path_index[current_id] :]
+ root_id = min(cycle, key=lambda node_id: source_order[node_id])
+ parent_by_node[root_id] = None
+ warnings.append(f"parent-cycle-broken-at:{root_id}")
+ break
+ path_index[current_id] = len(path)
+ path.append(current_id)
+ current_id = parent_by_node.get(current_id)
+ return warnings
+
+
+def _ordered_nodes(
+ data_root: ET.Element,
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str]]:
+ raw_points: list[dict[str, Any]] = []
+ for source_index, point in enumerate(
+ data_root.findall(".//dgm:ptLst/dgm:pt", DIAGRAM_NS_MAP),
+ ):
+ model_id = point.attrib.get("modelId", "")
+ point_type = point.attrib.get("type") or "node"
+ text = _point_text(point)
+ if not model_id or point_type not in _CONTENT_POINT_TYPES:
+ continue
+ raw_points.append(
+ {
+ "id": model_id,
+ "type": point_type,
+ "text": text,
+ "source_index": source_index,
+ }
+ )
+
+ all_connections = _connections(data_root)
+ parent_by_id: dict[str, str] = {}
+ order_by_id: dict[str, int | None] = {}
+ for connection in all_connections:
+ if connection["type"] != "parOf":
+ continue
+ destination_id = connection["destination_id"]
+ parent_by_id.setdefault(destination_id, connection["source_id"])
+ order_by_id.setdefault(destination_id, connection["source_order"])
+
+ content_ids = {point["id"] for point in raw_points}
+ source_order = {point["id"]: int(point["source_index"]) for point in raw_points}
+ parent_by_node = {
+ point["id"]: _nearest_content_parent(
+ point["id"],
+ parent_by_id,
+ content_ids,
+ )
+ for point in raw_points
+ }
+ structure_warnings = _break_parent_cycles(parent_by_node, source_order)
+ nodes_by_id: dict[str, dict[str, Any]] = {}
+ for point in raw_points:
+ node = {
+ "id": point["id"],
+ "type": point["type"],
+ "text": point["text"],
+ "parent_id": parent_by_node[point["id"]],
+ "order": order_by_id.get(point["id"]),
+ "depth": 0,
+ "_source_index": point["source_index"],
+ }
+ nodes_by_id[point["id"]] = node
+
+ children: dict[str | None, list[dict[str, Any]]] = {}
+ for node in nodes_by_id.values():
+ children.setdefault(node["parent_id"], []).append(node)
+
+ def sort_key(node: dict[str, Any]) -> tuple[int, int]:
+ order = node["order"]
+ return (
+ order if isinstance(order, int) else 1_000_000,
+ int(node["_source_index"]),
+ )
+
+ for siblings in children.values():
+ siblings.sort(key=sort_key)
+
+ ordered: list[dict[str, Any]] = []
+ visited: set[str] = set()
+
+ def visit(node: dict[str, Any], depth: int) -> None:
+ node_id = str(node["id"])
+ if node_id in visited:
+ return
+ visited.add(node_id)
+ node["depth"] = depth
+ ordered.append(node)
+ for child in children.get(node_id, []):
+ visit(child, depth + 1)
+
+ for root in children.get(None, []):
+ visit(root, 0)
+ for node in sorted(nodes_by_id.values(), key=sort_key):
+ if node["id"] not in visited:
+ visit(node, 0)
+
+ for node in ordered:
+ node.pop("_source_index", None)
+
+ visible_connections = [
+ connection
+ for connection in all_connections
+ if connection["type"] == "parOf"
+ and connection["source_id"] in content_ids
+ and connection["destination_id"] in content_ids
+ ]
+ return ordered, visible_connections, structure_warnings
+
+
+def _read_diagram_container(
+ zf: zipfile.ZipFile,
+ container: ET.Element,
+ *,
+ slide_part: str,
+ slide_index: int,
+ order: int,
+ relationships: dict[str, dict[str, str]],
+ relationship_error: str | None,
+ fallback_shape_ids: set[str],
+) -> dict[str, Any]:
+ shape_id, shape_name = _shape_identity(container, order)
+ graphic_data = container.find("a:graphic/a:graphicData", DIAGRAM_NS_MAP)
+ rel_ids = (
+ graphic_data.find("dgm:relIds", DIAGRAM_NS_MAP)
+ if graphic_data is not None
+ else None
+ )
+ parts, diagram_relation_error = _diagram_parts(
+ rel_ids,
+ relationships,
+ slide_part,
+ )
+ data_root, data_error = _read_optional_xml(zf, parts.get("data"))
+ layout_root, layout_error = _read_optional_xml(zf, parts.get("layout"))
+ metadata_warnings = [f"layout:{layout_error}"] if layout_error else []
+ nodes: list[dict[str, Any]] = []
+ connections: list[dict[str, Any]] = []
+ structure_warnings: list[str] = []
+ if data_root is not None:
+ nodes, connections, structure_warnings = _ordered_nodes(data_root)
+
+ status = relationship_error or diagram_relation_error or data_error
+ if status is None and structure_warnings:
+ status = "structure-cycle"
+ persisted_drawing, drawing_warnings = _persisted_drawing_part(
+ zf,
+ parts.get("data"),
+ data_root,
+ slide_part,
+ relationships,
+ )
+ text_items = [node["text"] for node in nodes if node["text"]]
+ return {
+ "diagram_id": f"s{slide_index:02d}_dgm{shape_id}",
+ "kind": "smartart",
+ "shape_id": shape_id,
+ "shape_name": shape_name,
+ "geometry": _container_geometry(container),
+ "layout": _layout_info(layout_root, data_root),
+ "root_ids": [node["id"] for node in nodes if node["parent_id"] is None],
+ "nodes": nodes,
+ "connections": connections,
+ "text_items": text_items,
+ "node_count": len(nodes),
+ "text_count": len(text_items),
+ "connection_count": len(connections),
+ "max_depth": max((int(node["depth"]) for node in nodes), default=0),
+ "text_extracted": data_root is not None,
+ "has_persisted_drawing": persisted_drawing is not None,
+ "has_fallback_preview": shape_id in fallback_shape_ids,
+ "status": status or "ok",
+ "warnings": metadata_warnings + structure_warnings + drawing_warnings,
+ }
+
+
+def _failed_diagram(
+ container: ET.Element,
+ *,
+ slide_index: int,
+ order: int,
+ error: Exception,
+ fallback_shape_ids: set[str],
+) -> dict[str, Any]:
+ shape_id, shape_name = _shape_identity(container, order)
+ return {
+ "diagram_id": f"s{slide_index:02d}_dgm{shape_id}",
+ "kind": "smartart",
+ "shape_id": shape_id,
+ "shape_name": shape_name,
+ "geometry": _container_geometry(container),
+ "layout": {"name": None, "unique_id": None, "categories": []},
+ "root_ids": [],
+ "nodes": [],
+ "connections": [],
+ "text_items": [],
+ "node_count": 0,
+ "text_count": 0,
+ "connection_count": 0,
+ "max_depth": 0,
+ "text_extracted": False,
+ "has_persisted_drawing": False,
+ "has_fallback_preview": shape_id in fallback_shape_ids,
+ "status": "diagram-read-error",
+ "warnings": [f"{type(error).__name__}:{error}"],
+ }
+
+
+def read_smartart_diagrams(
+ zf: zipfile.ZipFile,
+ slide_part: str,
+ slide_index: int,
+) -> list[dict[str, Any]]:
+ """Return SmartArt source facts for one slide part."""
+ slide_root = _read_xml(zf, slide_part)
+ relationship_error: str | None = None
+ try:
+ relationships = _slide_relationships(zf, _rels_name_for_part(slide_part))
+ except ET.ParseError:
+ relationships = {}
+ relationship_error = "invalid-slide-relationships"
+ fallback_shape_ids = _fallback_preview_shape_ids(slide_root)
+ diagrams: list[dict[str, Any]] = []
+
+ for order, container in enumerate(_diagram_containers(slide_root), start=1):
+ try:
+ diagram = _read_diagram_container(
+ zf,
+ container,
+ slide_part=slide_part,
+ slide_index=slide_index,
+ order=order,
+ relationships=relationships,
+ relationship_error=relationship_error,
+ fallback_shape_ids=fallback_shape_ids,
+ )
+ except (OSError, RuntimeError, zipfile.BadZipFile, ET.ParseError, KeyError, ValueError) as exc:
+ diagram = _failed_diagram(
+ container,
+ slide_index=slide_index,
+ order=order,
+ error=exc,
+ fallback_shape_ids=fallback_shape_ids,
+ )
+ diagrams.append(diagram)
+ return diagrams
+
+
+def smartart_to_markdown(diagram: dict[str, Any]) -> str:
+ """Render one extracted SmartArt diagram as hierarchical Markdown."""
+ name = str(diagram.get("shape_name") or diagram.get("diagram_id") or "SmartArt")
+ layout = diagram.get("layout") or {}
+ layout_name = str(layout.get("name") or "") if isinstance(layout, dict) else ""
+ heading = f"### SmartArt: {name}"
+ if layout_name and layout_name.lower() not in name.lower():
+ heading += f" — {layout_name}"
+ lines = [heading, ""]
+ nodes = diagram.get("nodes") or []
+ text_nodes = [node for node in nodes if str(node.get("text") or "").strip()]
+ if text_nodes:
+ nodes_by_id = {
+ str(node.get("id")): node
+ for node in nodes
+ if node.get("id") is not None
+ }
+ rendered_depths: dict[str, int] = {}
+
+ def rendered_depth(node: dict[str, Any]) -> int:
+ node_id = str(node.get("id") or "")
+ if node_id in rendered_depths:
+ return rendered_depths[node_id]
+ parent = nodes_by_id.get(str(node.get("parent_id") or ""))
+ if parent is None:
+ depth = 0
+ else:
+ depth = rendered_depth(parent)
+ if str(parent.get("text") or "").strip():
+ depth += 1
+ rendered_depths[node_id] = depth
+ return depth
+
+ for node in text_nodes:
+ text = " / ".join(str(node.get("text") or "").splitlines()).strip()
+ indent = " " * rendered_depth(node)
+ lines.append(f"{indent}- {text}")
+ elif nodes:
+ lines.append(f"> [SmartArt structure has {len(nodes)} node(s), but no text]")
+ else:
+ status = str(diagram.get("status") or "content-unavailable")
+ if diagram.get("text_extracted") and status == "ok":
+ lines.append("> [SmartArt data is readable but has no semantic nodes]")
+ else:
+ lines.append(f"> [SmartArt content unavailable: {status}]")
+ return "\n".join(lines).rstrip()
diff --git a/skills/ppt-master/workflows/beautify-pptx.md b/skills/ppt-master/workflows/beautify-pptx.md
index 9e8227fa..e5abb8f8 100644
--- a/skills/ppt-master/workflows/beautify-pptx.md
+++ b/skills/ppt-master/workflows/beautify-pptx.md
@@ -114,19 +114,21 @@ python3 ${SKILL_DIR}/scripts/beautify_inventory.py <project_path>/analysis/<stem
--images <project_path>/images/image_manifest.json -o <project_path>/analysis/beautify_inventory.json
```
-If `images/image_manifest.json` does not exist because the source deck has no extracted pictures, omit `--images`. The script joins per slide: `text_blocks` (slot text + geometry), `tables` (cell grid) / `charts` (categories + series values) — the **frozen data values inlined**, so the inventory is a self-contained contract, not a pointer back to `slide_library.json` — and `images` (bound via `image_manifest` `occurrences[].slide_index`, with geometry / `usage_count`). It emits `ignored` and `needs_confirmation` as **empty arrays** — fill them with judgment before Step 5:
+If `images/image_manifest.json` does not exist because the source deck has no extracted pictures, omit `--images`. The script joins per slide: `text_blocks` (slot text + geometry), `tables` (cell grid), `charts` (categories + series values), `diagrams` (SmartArt nodes + hierarchy/connections + source layout), and `images` (bound via `image_manifest` `occurrences[].slide_index`, with geometry / `usage_count`). The **frozen source values are inlined**, so the inventory is a self-contained contract, not a pointer back to `slide_library.json`. It emits `ignored` and `needs_confirmation` as **empty arrays** — fill them with judgment before Step 5:
| Field | Fill with |
|---|---|
| `ignored` | hidden slides / shapes, master-only text, image crop / opacity / rotation / mask (not captured upstream) |
-| `needs_confirmation` | combo / dual-axis / waterfall charts (only the first plot type is captured), merged-cell or multi-header tables, density-outlier pages — **either** overcrowded **or** near-empty / title-only (e.g. a divider page with a heading and no body) |
+| `needs_confirmation` | unreadable SmartArt data; combo / dual-axis / waterfall charts; merged-cell or multi-header tables; density-outlier pages — **either** overcrowded **or** near-empty / title-only |
+
+**SmartArt output boundary**: Preserve its extracted wording and semantic relationships, then redraw it through SVG as ordinary editable PowerPoint shapes. Do not attempt to regenerate a native SmartArt object or reuse persisted-drawing text as a second content source.
```markdown
## ✅ Extraction Complete
- [x] `sources/<stem>.md` (from Step 3) holds every source slide's text, in order; extracted pictures, if any, are in `images/` + `images/image_manifest.json`
- [x] `analysis/<stem>.identity.json` has theme + observed identity + canvas aspect
-- [x] `analysis/<stem>.slide_library.json` holds chart + table data for regeneration
+- [x] `analysis/<stem>.slide_library.json` holds chart + table data and SmartArt semantic structure for regeneration
- [x] `analysis/source_profile.json` (multi-deck index) summarizes the source facts in its `decks[]` entry
- [x] `analysis/beautify_inventory.json` ledgers per-slide text / images / data + ignored + needs-confirmation
- [ ] **Next**: Step 5 — Beautify Plan (recommend & confirm)
@@ -145,7 +147,7 @@ This step has two halves:
| Plan item | Recommend from | Default lean |
|---|---|---|
| Identity source | `<stem>.identity.json` `theme` vs `observed` | present **both as color / typography candidates in the confirm UI** so the user picks the one that looks right (theme first when the deck is theme-driven; observed first when slides override heavily) — recommend a default ordering and say why |
-| Preserve scope | inventory `text_blocks` / `images` / `charts` / `tables` | all text verbatim; data values frozen; pictures reused |
+| Preserve scope | inventory `text_blocks` / `images` / `charts` / `tables` / `diagrams` | all text verbatim; data values and SmartArt relationships frozen; pictures reused |
| Ignored | inventory `ignored` | name them so the user sees what drops (hidden / master-only text / image crop / rotation) |
| Needs confirmation | inventory `needs_confirmation` | flag complex charts + overcrowded pages explicitly; ask how to handle |
| Verification level | deck size / risk | recommend the Step 7 per-page checks; user sets strictness |
diff --git a/skills/ppt-master/workflows/template-fill-pptx.md b/skills/ppt-master/workflows/template-fill-pptx.md
index d1973ae7..280468a8 100644
--- a/skills/ppt-master/workflows/template-fill-pptx.md
+++ b/skills/ppt-master/workflows/template-fill-pptx.md
@@ -93,6 +93,7 @@ Read `<project_dir>/analysis/<stem>.slide_library.json` (intake prefixes per-dec
| `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` |
+| `slides[].diagrams[]` | SmartArt layout, semantic nodes, hierarchy/connections, geometry, and extraction status; inventory-only |
**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.
@@ -107,6 +108,9 @@ A page's layout already encodes a rhetorical shape — a single hero statement,
| `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 |
+| `diagrams[].layout` + `nodes` | Understand the SmartArt's source meaning; template-fill preserves it unchanged and cannot map new text into it |
+
+**SmartArt boundary**: A selected source slide keeps its original native SmartArt parts. `check-plan` warns because the fill plan cannot replace SmartArt node text; choose another layout unless the original diagram content is intentionally retained, or explicitly accept the warning.
**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.
@@ -249,6 +253,7 @@ Interpret the report:
| 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 |
+| SmartArt source content remains unchanged | Pick another source slide unless the original SmartArt wording is intended; otherwise record the accepted warning |
| Missing target | Fix `slot_id` / `shape_id`; do not apply the plan |
`check-plan` emits stable `code` fields in its JSON results so warnings can be tracked without parsing message text. Warnings are advisory and do not fail the command; record any intentionally accepted warning in `accepted_warnings` when it matters for review. Errors are blocking and must be fixed before apply.
@@ -334,11 +339,13 @@ If the extracted text is correct but visual overflow is likely, reduce the text
| Replace text in existing text frames | Supported |
| Edit native PowerPoint table cell text | Supported |
| Edit native PowerPoint chart categories / series data | Supported |
+| Read SmartArt node text / hierarchy / layout | Supported in intake and planning |
+| Preserve existing native SmartArt unchanged | Supported by recursive private-part cloning |
| 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 |
+| Edit or generate native SmartArt | Not supported; regenerated visual routes use ordinary editable shapes |
| Automatic visual overflow detection | Not in v1; use text-capacity judgment from the library slots |
| Material-divergence reshaping (§c content strategy) | Not applicable — this workflow fills text into existing slots, it does not author an outline from a source, so the main pipeline's `content_divergence` free-text field has no role here |