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(roundtrip): round-trip authoring tools and retirement of legacy fill/enhance CLIs

hugohe37f000fb8cba3
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 1541301a..dd35feb6 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, direct PPTX template filling, SVG processing, export, recorded narration, and image generation.
+This directory contains user-facing scripts for conversion, project setup, SVG processing, source-preserving PPTX editing, export, recorded narration, and image generation.
## Directory Layout
@@ -11,6 +11,7 @@ This directory contains user-facing scripts for conversion, project setup, direc
- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`
- `scripts/tts_backends/`: internal TTS provider implementations used by `notes_to_audio.py`
- `scripts/template_import/`: internal PPTX reference-preparation helpers used by `pptx_template_import.py`
+- `scripts/pptx_ooxml/`: shared OOXML intake, cloning, and package primitives
- `scripts/svg_finalize/`: internal post-processing helpers used by `finalize_svg.py`
- `scripts/docs/`: topic-focused script documentation
- `scripts/prompt_audit.py` + `scripts/prompt_audit_manifest.json`: maintainer-only prompt budget/governance lint (see [`docs/prompt_audit.md`](docs/prompt_audit.md)); the manifest is audit-only and never loaded as prompt context
@@ -51,7 +52,7 @@ python3 scripts/update_repo.py
| Area | Primary scripts | Documentation |
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `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`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
-| Project management | `project_manager.py`, `workflow_log.py`, `workflow_transcript.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py`, `pptx_delivery_check.py` | [docs/project.md](./docs/project.md) |
+| Project management | `project_manager.py`, `workflow_log.py`, `workflow_transcript.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `pptx_delivery_check.py` | [docs/project.md](./docs/project.md) |
| SVG pipeline | `preset_shape_svg.py`, `shape_boolean_svg.py`, `svg_authoring_view.py`, `authoring_roundtrip.py`, `compact_svg_coordinates.py`, `compact_svg_styles.py`, `stamp_native_fallbacks.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py`, `narration_sync.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native shape authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
@@ -118,6 +119,7 @@ python3 scripts/pptx_template_import.py <template.pptx> --manifest-only
python3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode both
python3 scripts/svg_authoring_view.py <imported-svg-or-dir> -o <output-dir> --projection-kind layered
python3 scripts/svg_authoring_view.py <authoring-dir> --refresh-summary
+python3 scripts/svg_authoring_view.py <authoring-dir> --adopt-object <from.svg>:<element-id> --into <target.svg>
python3 scripts/stamp_native_fallbacks.py <svg-file-or-directory> --write
python3 scripts/svg_quality_checker.py <template_workspace>/templates --template-mode --canonical-authoring
python3 scripts/mirror_template_materialize.py <import_workspace> <template_workspace>
@@ -172,6 +174,11 @@ minimal: top-level `schema: "ppt-master.roundtrip-page-plan.v1"` plus a
non-empty ordered `pages` array; every entry requires one-based
`source_slide` and may name a unique `authoring-svg-flat/` filename in `svg`.
A copied SVG is diffed against the baseline for its declared source slide.
+Move a cross-page object with
+`svg_authoring_view.py <authoring-dir> --adopt-object <from.svg>:<element-id>
+--into <target.svg>` rather than pasting raw SVG. The helper rebuilds the copy
+without source identity, inlines source-owned imported vectors, refuses source
+proxies, resolves id collisions, and refreshes `authoring_summary.json`.
`notes/<svg-stem>.md` implicitly overrides notes for that output page; when it
is absent, source notes travel with the cloned page. Unchanged repeats clone
their private notes/chart/diagram/embedding parts, while media may stay shared;
@@ -180,6 +187,16 @@ identity round trip is unchanged. See
[`docs/svg-pipeline.md`](docs/svg-pipeline.md#round-trip-deck-page-plans) for
the schema, sidecar keying, fail-closed rules, and export receipt.
+Run `python3 scripts/svg_quality_checker.py <workspace> --roundtrip` before a
+round-trip export. The mode resolves the same identity or `page_plan.json`
+output roster as the exporter and checks only new or changed text for supported
+font stacks and sizes, estimated canvas containment, and horizontal capacity
+against its owning `data-pptx-frame` or nearest rect fallback. Capacity is the
+single-line width of each positioned line; the gate does not model vertical
+wrapping. Explicit frame-width or canvas overflow is blocking, warnings are
+advisory, and unchanged source refs, source proxies, plus
+generated-project/template-only contracts are skipped.
+
`mirror_template_materialize.py` is the deterministic Type A mirror
validator/publisher. Template_Designer first reviews and authors the compact
layered `authoring-svg/` tree. The command loads its tool-only manifest and
@@ -217,31 +234,6 @@ The destination must be empty, and the command does not write
`template_preview_pptx.py` reads a template workspace, exports every complete `templates/*.svg` Slide prototype as one structured review slide, and verifies the resulting Master/Layout package. In a project root containing Layout and Deck specs, it previews the active Layout roster. Standalone `layout_<layout_key>.svg` definition files are rejected; every reusable Layout must be represented by a complete Slide prototype. This is an on-demand review action: its default output is `exports/<template_id>_template_preview.pptx`, and that directory need not exist before the command runs. It refuses an existing output unless an intentional re-export passes `--force`.
-Template fill (direct PPTX, no SVG conversion):
-
-```bash
-python3 scripts/project_manager.py init <project_name>
-python3 scripts/project_manager.py import-sources <project_path> <source.pptx> <material...>
-# Manual fallback when import-sources did not produce analysis/<stem>.slide_library.json:
-python3 scripts/template_fill_pptx.py analyze <project_path>/sources/<source.pptx> -o <project_path>/analysis/<stem>.slide_library.json
-python3 scripts/template_fill_pptx.py scaffold <project_path>/analysis/<stem>.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/<stem>.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
-python3 scripts/template_fill_pptx.py validate <project_path>
-```
-
-`apply` requires `fill_plan.json` to have top-level `"status": "confirmed"` unless `--force` is passed. It automatically writes `filled_YYYYMMDD_HHMMSS.pptx` unless the output stem already ends with a timestamp. It preserves source page transitions by default; `--transition <effect>` accepts a canonical effect in the shared native gallery registry documented by [`docs/pptx-transitions.md`](docs/pptx-transitions.md), while old names remain accepted only as compatibility inputs, and `--transition-duration <seconds>` changes a replacement effect's duration. `--transition none` removes the visual effect, `--transition keep` states the preservation policy explicitly, and a per-slide `transition` field in the plan overrides whatever the CLI selects. The object form accepts effect-specific native `effect_options`.
-
-Native existing-PPTX enhancement (direct PPTX, no SVG conversion):
-
-```bash
-python3 scripts/native_enhance_pptx.py init <source.pptx> --name <project_slug>
-python3 scripts/native_enhance_pptx.py plan <project_path>
-python3 scripts/native_enhance_pptx.py validate <project_path>
-python3 scripts/native_enhance_pptx.py apply <project_path>
-python3 scripts/pptx_delivery_check.py <finished.pptx>
-```
-
Native preset shape authoring (one or more registry-backed fragments on stdout):
```bash
@@ -364,7 +356,7 @@ embedded.
`finalize_svg.py` remains mandatory because it creates the self-contained `svg_final/` visual preview. Those SVGs may be opened directly or inserted into PowerPoint as SVG pictures. The only supported generated-PPTX path is `svg_output/` through the project SVG-to-DrawingML converter; `-s final` is diagnostic-only, and PowerPoint's manual Convert-to-Shape operation is unsupported.
-For SVG-authoring routes, `svg_output/` is the complete visible page-design source: every exported text, image, shape, background, and template-derived layout element is present in the page SVG or explicitly referenced by it. Export may translate represented content into Master/Layout/Slide parts or native objects, but it does not retrieve missing visible content from templates or planning files. Speaker notes, animation, narration, transitions, `template-fill-pptx`, and `native-enhance-pptx` remain separately owned capabilities.
+For SVG-authoring routes, `svg_output/` is the complete visible page-design source: every exported text, image, shape, background, and template-derived layout element is present in the page SVG or explicitly referenced by it. Export may translate represented content into Master/Layout/Slide parts or native objects, but it does not retrieve missing visible content from templates or planning files. Speaker notes, animation, narration, and transitions use dedicated sidecars or assets; Edit Native PPTX owns source-preserving existing-deck edits.
Native `svg_to_pptx.py` release export reads the project's explicit structure mode. Free-design, Brand-only, Style-only, and other `template_reuse_scope: style` projects use `flat`, omit Master/Layout mappings and SVG structure metadata, keep every represented object Slide-local, and materialize one clean project-owned Master plus one Blank Layout from the current color/typography lock. Stock content placeholders and unused built-in Layouts are removed; only the standard date/footer/slide-number capability hooks remain. A Deck/Layout application uses `structured` in Default when Strategist derives `template_reuse_scope: mirror|layout` with complete lock rosters, or in Quick when every page of the installed Layout/Deck roster declares the complete lockless Master/Layout/slot contract: each project supplies unique Master/Layout definitions and one Layout assignment per generated page before SVG generation, and every SVG root repeats its assigned identity. An unselected complete template Slide may still supply a reusable Layout definition without becoming a published page. Fixed Master/Layout visuals are direct semantic atoms; ordinary groups are invalid there, while one validated compact authored-preset `<g>` is the sole group exception because it compiles to one native shape. Reusable slots are top-level groups with positive design-zone bounds plus one compatible carrier. Composite `object` regions use explicit proxy binding, and zero-slot Layouts are valid.
diff --git a/skills/ppt-master/scripts/attribution_guard.py b/skills/ppt-master/scripts/attribution_guard.py
index 0680f2ea..35c33131 100644
--- a/skills/ppt-master/scripts/attribution_guard.py
+++ b/skills/ppt-master/scripts/attribution_guard.py
@@ -46,10 +46,6 @@ _REQUIRED_GATE_FILES = (
"scripts/svg_quality/cli.py",
"scripts/svg_to_pptx.py",
"scripts/svg_to_pptx/pptx_package/cli.py",
- "scripts/template_fill_pptx.py",
- "scripts/template_fill_pptx/cli.py",
- "scripts/native_enhance_pptx.py",
- "scripts/native_enhance_pptx_core.py",
"scripts/register_template.py",
"scripts/template_preview_pptx.py",
)
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.py
index 3e748ad9..632897b5 100644
--- a/skills/ppt-master/scripts/authoring_roundtrip.py
+++ b/skills/ppt-master/scripts/authoring_roundtrip.py
@@ -956,7 +956,7 @@ def _collapse_hash_only_groups(root: ET.Element) -> None:
break
-def _normalized_hash(
+def normalized_authoring_subtree_sha256(
element: ET.Element,
assets: dict[str, VectorAssetRecord],
*,
@@ -1018,6 +1018,35 @@ def _normalized_hash(
)
+def authoring_source_ref_is_unchanged(
+ current_element: ET.Element,
+ baseline_element: ET.Element,
+ current_assets: dict[str, VectorAssetRecord],
+ baseline_assets: dict[str, VectorAssetRecord],
+ *,
+ changed_definition_ids: set[str],
+ current_asset: VectorAssetRecord | None = None,
+ baseline_asset: VectorAssetRecord | None = None,
+) -> bool:
+ """Compare one source-ref occurrence exactly as round-trip export does."""
+ return (
+ normalized_authoring_subtree_sha256(
+ current_element,
+ current_assets,
+ asset=current_asset,
+ )
+ == normalized_authoring_subtree_sha256(
+ baseline_element,
+ baseline_assets,
+ asset=baseline_asset,
+ )
+ and not (
+ changed_definition_ids
+ & _referenced_definition_ids(current_element)
+ )
+ )
+
+
def _referenced_assets(
root: ET.Element,
assets: dict[str, VectorAssetRecord],
@@ -1124,12 +1153,12 @@ def _definition_changes(
current_defs = _direct_defs(current_root)
baseline_defs = _direct_defs(baseline_root)
current_hash = (
- _normalized_hash(current_defs, current_assets)
+ normalized_authoring_subtree_sha256(current_defs, current_assets)
if current_defs is not None
else None
)
baseline_hash = (
- _normalized_hash(baseline_defs, baseline_assets)
+ normalized_authoring_subtree_sha256(baseline_defs, baseline_assets)
if baseline_defs is not None
else None
)
@@ -1152,8 +1181,14 @@ def _definition_changes(
for definition_id in set(current_by_id) | set(baseline_by_id)
if definition_id not in current_by_id
or definition_id not in baseline_by_id
- or _normalized_hash(current_by_id[definition_id], current_assets)
- != _normalized_hash(baseline_by_id[definition_id], baseline_assets)
+ or normalized_authoring_subtree_sha256(
+ current_by_id[definition_id],
+ current_assets,
+ )
+ != normalized_authoring_subtree_sha256(
+ baseline_by_id[definition_id],
+ baseline_assets,
+ )
}
return True, changed_ids
@@ -1305,8 +1340,11 @@ def _materialize_document(
baseline_root = _parse_svg(baseline_path)
layered_root = _parse_svg(document.layered_source_path)
document_unchanged = (
- _normalized_hash(current_root, current_assets)
- == _normalized_hash(baseline_root, baseline_assets)
+ normalized_authoring_subtree_sha256(current_root, current_assets)
+ == normalized_authoring_subtree_sha256(
+ baseline_root,
+ baseline_assets,
+ )
)
layered_index = _layered_ref_index(layered_root)
current_referenced_assets = _referenced_assets(
@@ -1387,21 +1425,15 @@ def _materialize_document(
for source_ref, occurrences in current_occurrences.items():
current = occurrences[0]
baseline = baseline_occurrences[source_ref][0]
- current_hash = _normalized_hash(
+ if authoring_source_ref_is_unchanged(
current.element,
- current_assets,
- asset=current.asset,
- )
- baseline_hash = _normalized_hash(
baseline.element,
+ current_assets,
baseline_assets,
- asset=baseline.asset,
- )
- references_changed_def = bool(
- changed_definition_ids
- & _referenced_definition_ids(current.element)
- )
- if current_hash == baseline_hash and not references_changed_def:
+ changed_definition_ids=changed_definition_ids,
+ current_asset=current.asset,
+ baseline_asset=baseline.asset,
+ ):
unchanged_refs.add(source_ref)
else:
edited_refs.add(source_ref)
@@ -1500,7 +1532,7 @@ def _materialize_document(
return [clone]
baseline_unreferenced = Counter(
- _normalized_hash(child, baseline_assets)
+ normalized_authoring_subtree_sha256(child, baseline_assets)
for child in baseline_root
if _local_name(child.tag) != "defs"
and child.get(SOURCE_REF_ATTRIBUTE) is None
@@ -1587,7 +1619,10 @@ def _materialize_document(
child.get(SOURCE_REF_ATTRIBUTE) is None
and _local_name(child.tag) != "use"
):
- child_hash = _normalized_hash(child, current_assets)
+ child_hash = normalized_authoring_subtree_sha256(
+ child,
+ current_assets,
+ )
if baseline_unreferenced[child_hash] > 0:
baseline_unreferenced[child_hash] -= 1
continue
diff --git a/skills/ppt-master/scripts/beautify_inventory.py b/skills/ppt-master/scripts/beautify_inventory.py
index 2ef53fd7..658cae12 100644
--- a/skills/ppt-master/scripts/beautify_inventory.py
+++ b/skills/ppt-master/scripts/beautify_inventory.py
@@ -4,7 +4,7 @@ PPT Master - Beautify Inventory Builder
Mechanically merge a source deck's extracts into one per-slide ledger for the
beautify-pptx profile: text blocks + tables + charts + SmartArt structure (from a
-`template_fill_pptx.py analyze` slide_library.json) joined with the images
+`<stem>.slide_library.json` produced by `pptx_intake.py`) 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
to fill with judgment (hidden shapes, combo charts, overcrowded pages, ...).
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index e4cef2c5..8e019e2d 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -231,12 +231,11 @@ Outputs (per source deck, prefixed by file stem):
- `<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 profile and Fill Native PPTX route stay single-deck and read one chosen deck's `<stem>.*` artifacts.
+`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 profile stays single-deck and reads 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 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/docs/pptx-animations.md b/skills/ppt-master/scripts/docs/pptx-animations.md
index 1b25b6c4..ef6146b2 100644
--- a/skills/ppt-master/scripts/docs/pptx-animations.md
+++ b/skills/ppt-master/scripts/docs/pptx-animations.md
@@ -251,13 +251,6 @@ the existing `tmRoot`, allocates fresh ids, and preserves object animation.
For bounce timing it updates both p14 Choice and Fallback; unsupported nested
timing containers still fail safely instead of being duplicated.
-Direct-PPTX routes run the structural package validator with generated-effect
-enforcement disabled. This permits preservation of source/extension effects and
-legacy group build rows while still rejecting corrupt timing IDs or missing
-targets. Template fill and native enhancement fingerprint the source
-object-animation tree before and after their allowed edits; any semantic change
-fails. These routes have no object-animation write ownership.
-
The conversion trace is also the authoritative input for downstream video
motion. `video_motion_plan.py` preserves the resolved effect/options, direction,
row order, base and repeat-aware playback duration, absolute offset, object
diff --git a/skills/ppt-master/scripts/docs/pptx-transitions.md b/skills/ppt-master/scripts/docs/pptx-transitions.md
index 9756633e..9c729aed 100644
--- a/skills/ppt-master/scripts/docs/pptx-transitions.md
+++ b/skills/ppt-master/scripts/docs/pptx-transitions.md
@@ -11,8 +11,6 @@ read-back validation for every PPTX route.
| Page transition registry | scripts/pptx_transitions.py |
| In-slide object animation | scripts/pptx_animations.py |
| Generated PPTX adapter | svg_to_pptx/pptx_package/builder.py |
-| Template Fill adapter | template_fill_pptx/transitions.py |
-| Native Enhance adapter | native_enhance_pptx_core.py |
| Public workflow | references/animations.md |
**Hard rule**: adapters resolve route policy, then call the shared core. They
@@ -233,8 +231,8 @@ roster expectations are then refreshed. Package read-back requires:
undeclared shared `!!` name on a Morph edge.
Morph without an explicit pair block retains PowerPoint's automatic matching
-behavior. Explicit pairing is generated-route authoring; direct-PPTX routes
-continue to preserve existing object names and transition XML.
+behavior. Explicit pairing is generated-route authoring; source-preserving
+round-trip export keeps existing object names and transition XML.
---
@@ -244,13 +242,10 @@ continue to preserve existing object names and transition XML.
|---|---|---|---|
| Generated PPTX CLI | fade, 0.4s; no sound | click | auto-advance maps to both; an optional sidecar sound is project-local |
| Recorded narration | Preserve resolved enter | narration | none remains visually none |
-| Template Fill | preserve source | preserve source | explicit effects replace; legacy advance_after maps to both |
-| Native Enhance | Confirmed global/per-slide plan effect | Confirmed timing module | With audio off, an enabled global transition or explicit global `none` applies to all pages; with audio on, the scope flag controls non-narrated pages |
+| Edit Native PPTX (`svg_to_pptx.py --roundtrip`) | preserve source | preserve source | `-t` or `animations.json` rows replace per output page as an overlay; `--use-narration-timings` derives advance from narration |
-Template Fill changes source transitions only when its CLI or per-slide plan
-selects a replacement, removal, or timed advance. Native Enhance uses its
-confirmed plan. The public `create_pptx_with_native_svg` Python API retains its
-legacy 0.5s default; the generated-deck CLI explicitly passes 0.4s.
+The public `create_pptx_with_native_svg` Python API retains its legacy 0.5s
+default; the generated-deck CLI explicitly passes 0.4s.
---
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index ccfa0d05..ee239590 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -123,12 +123,26 @@ from its declared `source_slide`, so source-ref restoration, proxy checks, and
edit detection remain source-correct. Every extra authoring SVG must appear in
the plan; an unknown, duplicate, or cross-owned canonical filename fails.
+Move an object between pages before export with the authoring helper:
+
+```bash
+python3 scripts/svg_authoring_view.py <authoring-dir> \
+ --adopt-object <from.svg>:<element-id> --into <target.svg>
+```
+
+The helper appends a copy to the target page, removes its source/native restore
+transport, gives colliding ids fresh local names, inlines any source-owned
+`icons/imported/` vector reference, and refreshes the page-plan-aware summary.
+It refuses a source proxy because that atomic object cannot leave its source
+page. Raw cross-page source refs remain invalid and export reports that the page
+contains unknown source refs.
+
An unchanged planned page keeps the source slide XML and receives its own
relationship graph. Repeated pages clone notes slides, charts, diagrams,
embeddings, and other private structured parts under unique part names while
ordinary media may remain shared. An edited copy overlays only its edited
owners onto its cloned source page. Same-deck slide-jump links follow the
-template-fill contract: a target must map to exactly one output page. An
+page-plan contract: a target must map to exactly one output page. An
omitted or repeated destination is an error; external links remain unchanged.
Dropping any source slide that owns video, audio, or another opaque native
payload also fails instead of discarding that relationship.
@@ -146,6 +160,11 @@ a copied SVG, a present `notes/<svg-stem>.md` overrides its inherited source
notes and an absent file keeps them. Deleting inherited source notes only on a
copy is not supported in v1. The same output-stem rule applies to narration
audio.
+
+Narration audio is keyed by the output SVG stem. A copied output page uses its
+own stem-keyed notes when present and otherwise inherits the declared source
+slide's canonical notes.
+
`-t`, `-a`, `--recorded-narration`, `--use-narration-timings`,
`--no-animations`, and `--no-notes` continue to resolve per output page.
@@ -164,6 +183,18 @@ cloned_passthrough=C patched=M rebuilt=R`. `patched` keeps the source visible
Slide XML and applies only notes or motion overlays; `rebuilt` means the page's
visible authoring changed.
+Before export, run `python3 scripts/svg_quality_checker.py <workspace> --roundtrip`
+as the round-trip text-capacity gate. It resolves the output roster from
+`authoring-svg-flat/` and optional `page_plan.json`, then applies the shared
+font-family, font-size, text-width, and canvas metrics only to new text or
+changed source-ref objects. The gate asserts horizontal capacity: it estimates
+single-line width for each positioned line and does not model vertical
+wrapping. Width beyond an explicit ancestor `data-pptx-frame` is blocking;
+overflow against the nearest-rect-sibling fallback is advisory, while bounds
+leaving the page canvas remain blocking. Other advisories remain non-blocking.
+Unchanged source refs, source proxies, and generated-project-only spec,
+template, canonical-authoring, and resource-manifest checks are excluded.
+
Regenerate the summary after direct edits that do not pass through one of the
in-place normalization tools:
diff --git a/skills/ppt-master/scripts/native_enhance_pptx.py b/skills/ppt-master/scripts/native_enhance_pptx.py
deleted file mode 100644
index 0a87bb16..00000000
--- a/skills/ppt-master/scripts/native_enhance_pptx.py
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/usr/bin/env python3
-"""
-PPT Master - Native Enhance PPTX Entrypoint
-
-Public CLI wrapper for native enhancement of existing PPTX decks. It delegates
-to the shared native core for delivery checks, notes, narration, timings, and
-global or per-slide transitions while keeping the stable workflow command.
-
-Usage:
- python3 scripts/native_enhance_pptx.py init <source.pptx> [--name project_name]
- python3 scripts/native_enhance_pptx.py plan <project_path>
- python3 scripts/native_enhance_pptx.py validate <project_path> [--materials {all,notes}]
- python3 scripts/native_enhance_pptx.py apply <project_path>
-
-Examples:
- python3 scripts/native_enhance_pptx.py init projects/source.pptx --name fire_station
- python3 scripts/native_enhance_pptx.py plan projects/fire_station_native_enhance_20260626
- python3 scripts/native_enhance_pptx.py apply projects/fire_station_native_enhance_20260626
-
-Dependencies:
- Same as native_enhance_pptx_core.py.
-"""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-_SCRIPTS_DIR = Path(__file__).resolve().parent
-if str(_SCRIPTS_DIR) not in sys.path:
- sys.path.insert(0, str(_SCRIPTS_DIR))
-
-from attribution_guard import require_skill_integrity # noqa: E402
-from console_encoding import configure_utf8_stdio # noqa: E402
-from native_enhance_pptx_core import main # noqa: E402
-
-configure_utf8_stdio()
-
-
-if __name__ == "__main__":
- require_skill_integrity()
- raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/native_enhance_pptx_core.py b/skills/ppt-master/scripts/native_enhance_pptx_core.py
deleted file mode 100644
index 54979fe0..00000000
--- a/skills/ppt-master/scripts/native_enhance_pptx_core.py
+++ /dev/null
@@ -1,2587 +0,0 @@
-#!/usr/bin/env python3
-"""
-PPT Master - Native Existing PPTX Enhancer
-
-Implementation core for the public native enhancement CLI and its legacy
-narration compatibility entrypoint. It enhances an existing PPTX without
-entering the SVG generation pipeline or modifying the original file.
-
-Enhancement modules: read-only delivery checks, speaker notes, narration audio,
-slide auto-advance timings, and optional global or per-slide page transitions.
-
-Usage:
- python3 scripts/native_enhance_pptx.py init <source.pptx> [--name project_name]
- python3 scripts/native_enhance_pptx.py apply <project_path> [--output output.pptx]
- python3 scripts/native_enhance_pptx.py validate <project_path> [--materials {all,notes}]
-
-Examples:
- python3 scripts/native_enhance_pptx.py init projects/source.pptx --name fire_station
- python3 scripts/native_enhance_pptx.py apply projects/fire_station_native_enhance_20260626
- python3 scripts/native_enhance_pptx.py validate projects/fire_station_native_enhance_20260626
-
-Dependencies:
- ffprobe for narration decodability and audio-duration validation.
-"""
-
-from __future__ import annotations
-
-import argparse
-import hashlib
-import json
-import posixpath
-import re
-import shutil
-import subprocess
-import sys
-import tempfile
-import zipfile
-from collections.abc import Mapping
-from dataclasses import dataclass
-from datetime import datetime
-from pathlib import Path
-from xml.etree import ElementTree as ET
-
-_SCRIPTS_DIR = Path(__file__).resolve().parent
-if str(_SCRIPTS_DIR) not in sys.path:
- sys.path.insert(0, str(_SCRIPTS_DIR))
-
-from attribution_guard import require_skill_integrity # noqa: E402
-from console_encoding import configure_utf8_stdio # noqa: E402
-from pptx_delivery_check import audit_pptx_delivery # noqa: E402
-from pptx_animations import ( # noqa: E402
- object_animation_fingerprint,
- validate_pptx_animation_package,
-)
-from pptx_transitions import ( # noqa: E402
- AdvanceUpdate,
- EnterUpdate,
- LEGACY_TRANSITION_KEYS,
- NATIVE_TRANSITION_KEYS,
- apply_slide_motion_xml,
- normalize_transition_effect_request,
- read_slide_transition_xml,
- set_directory_use_timings,
- validate_pptx_transition_package,
- validate_seconds,
-)
-from svg_to_pptx.pptx_package.builder import ( # noqa: E402
- _add_default_content_type,
- _append_relationship,
- _ensure_notes_master,
-)
-from svg_to_pptx.pptx_package.narration import ( # noqa: E402
- AUDIO_CONTENT_TYPES,
- AUDIO_MARKER_PNG_BYTES,
- AUDIO_REL_TYPE,
- DEFAULT_NARRATION_START_FLOOR,
- IMAGE_REL_TYPE,
- MEDIA_REL_TYPE,
- NARRATION_EXTENSIONS,
- inject_narration,
- narration_lead_in_seconds,
- next_shape_id,
- probe_audio_duration,
-)
-from svg_to_pptx.pptx_package.notes import ( # noqa: E402
- create_notes_slide_rels_xml,
- create_notes_slide_xml,
- markdown_to_plain_text,
-)
-
-configure_utf8_stdio()
-
-
-PROJECT_SCHEMA = "native_pptx_enhancement_project.v1"
-PLAN_SCHEMA = "native_pptx_enhancement_plan.v1"
-VALIDATION_SCHEMA = "native_pptx_enhancement_validation.v1"
-LEGACY_PROJECT_SCHEMAS = {"native_narration_pptx_project.v1"}
-_WRITABLE_MODULES = ("notes", "audio", "timings", "transitions")
-NOTES_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide"
-PACKAGE_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
-PRESENTATION_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"
-REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
-CONTENT_TYPE_NOTES_SLIDE = (
- "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"
-)
-CONTENT_TYPE_NOTES_MASTER = (
- "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"
-)
-CONTENT_TYPE_THEME = "application/vnd.openxmlformats-officedocument.theme+xml"
-_NOTES_SLIDE_PART_RE = re.compile(
- r"^ppt/notesSlides/notesSlide([1-9]\d*)\.xml$"
-)
-_LEGACY_MISSING_NOTES_MASTER_RE = re.compile(
- r"^ppt/notesSlides/_rels/notesSlide[1-9]\d*\.xml\.rels"
- r" -> ppt/notesmasters/notesmaster[1-9]\d*\.xml$",
- re.IGNORECASE,
-)
-_TRANSITION_MODULE_FIELDS = frozenset(
- {
- "enabled",
- "requires_confirmation",
- "status",
- "effect",
- "duration",
- "effect_options",
- "apply_without_audio",
- "slides",
- }
-)
-_TRANSITION_OVERRIDE_FIELDS = frozenset(
- {"effect", "duration", "effect_options"}
-)
-@dataclass(frozen=True)
-class SlidePart:
- index: int
- part_name: str
- slide_number: int
-
-
-@dataclass
-class MaterialReadiness:
- note_paths: dict[int, Path]
- audio_paths: dict[int, Path]
- audio_durations: dict[int, float]
- notes_count: int
- audio_count: int
- missing_notes: list[int]
- invalid_notes: dict[int, str]
- missing_audio: list[int]
- invalid_audio: dict[int, str]
- module_errors: list[str]
-
- @property
- def ready(self) -> bool:
- return not (
- self.missing_notes
- or self.invalid_notes
- or self.missing_audio
- or self.invalid_audio
- or self.module_errors
- )
-
-
-@dataclass(frozen=True)
-class ResolvedTransitionPlan:
- global_enter: EnterUpdate
- slide_enters: Mapping[int, EnterUpdate]
- apply_without_audio: bool
-
-
-def _sanitize_slug(value: str) -> str:
- slug = re.sub(r"[^0-9A-Za-z_-]+", "_", value).strip("_")
- return slug or "native_enhance"
-
-
-def _positive_seconds_arg(value: str) -> float:
- try:
- return validate_seconds(value, "transition duration", allow_zero=False)
- except ValueError as exc:
- raise argparse.ArgumentTypeError(str(exc)) from exc
-
-
-def _non_negative_seconds_arg(value: str) -> float:
- try:
- return validate_seconds(value, "narration padding", allow_zero=True)
- except ValueError as exc:
- raise argparse.ArgumentTypeError(str(exc)) from exc
-
-
-def _read_json(path: Path) -> dict:
- data = json.loads(path.read_text(encoding="utf-8"))
- if not isinstance(data, dict):
- raise ValueError(f"JSON root must be an object: {path}")
- return data
-
-
-def _write_json(path: Path, data: dict) -> None:
- path.write_text(
- json.dumps(data, ensure_ascii=False, indent=2) + "\n",
- encoding="utf-8",
- )
-
-
-def _write_preflight_report(
- project_path: Path,
- plan: dict,
- modules: set[str],
- *,
- status: str,
- **details: object,
-) -> dict:
- report = {
- "schema": VALIDATION_SCHEMA,
- "status": status,
- "phase": "preflight",
- "plan_status": plan.get("status") or "missing",
- "enabled_modules": sorted(modules),
- **details,
- }
- validation_dir = project_path / "validation"
- validation_dir.mkdir(exist_ok=True)
- _write_json(validation_dir / "report.json", report)
- return report
-
-
-def _delivery_issues(report: dict, field: str) -> list[dict]:
- issues = report.get(field)
- if not isinstance(issues, list):
- return []
- return [issue for issue in issues if isinstance(issue, dict)]
-
-
-def _fatal_source_delivery_messages(report: dict) -> list[str]:
- fatal = [
- issue
- for issue in _delivery_issues(report, "errors")
- if not (
- issue.get("code") == "dangling_internal_relationship"
- and isinstance(issue.get("message"), str)
- and _LEGACY_MISSING_NOTES_MASTER_RE.fullmatch(
- issue["message"]
- )
- is not None
- )
- ]
- if fatal:
- return [
- str(issue.get("message") or issue)
- for issue in fatal
- ]
- if report.get("status") == "failed" and not _delivery_issues(
- report,
- "errors",
- ):
- return ["delivery check failed without structured error details"]
- return []
-
-
-def _new_delivery_errors(source: dict, candidate: dict) -> list[dict]:
- source_keys = {
- json.dumps(issue, ensure_ascii=False, sort_keys=True)
- for issue in _delivery_issues(source, "errors")
- }
- return [
- issue
- for issue in _delivery_issues(candidate, "errors")
- if json.dumps(issue, ensure_ascii=False, sort_keys=True)
- not in source_keys
- ]
-
-
-def _delivery_has_findings(report: dict) -> bool:
- return bool(
- _delivery_issues(report, "errors")
- or _delivery_issues(report, "advisories")
- )
-
-
-def _delivery_hidden_slide_indices(
- report: dict,
-) -> tuple[int, ...] | None:
- slides = report.get("slides")
- hidden = slides.get("hidden") if isinstance(slides, dict) else None
- if not isinstance(hidden, list):
- return None
- indices: list[int] = []
- for item in hidden:
- index = item.get("index") if isinstance(item, dict) else None
- if isinstance(index, bool) or not isinstance(index, int):
- return None
- indices.append(index)
- return tuple(indices)
-
-
-def _file_sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
-
-
-def _is_relative_to(path: Path, parent: Path) -> bool:
- try:
- path.resolve().relative_to(parent.resolve())
- return True
- except ValueError:
- return False
-
-
-def _archive_source_pptx(source_pptx: Path, archived_pptx: Path, projects_root: Path) -> str:
- """Move project-local sources into the project; copy external sources."""
- archived_pptx.parent.mkdir(parents=True, exist_ok=True)
- if source_pptx.resolve() == archived_pptx.resolve():
- return "reuse"
- if _is_relative_to(source_pptx, projects_root):
- shutil.move(str(source_pptx), str(archived_pptx))
- return "move"
- shutil.copy2(source_pptx, archived_pptx)
- return "copy"
-
-
-def _relationship_file_for_part(extract_dir: Path, part_name: str) -> Path:
- part = Path(part_name)
- return extract_dir / part.parent / "_rels" / f"{part.name}.rels"
-
-
-def _ensure_rels_file(path: Path) -> None:
- if path.exists():
- return
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(
- '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
- f'<Relationships xmlns="{PACKAGE_REL_NS}">\n</Relationships>',
- encoding="utf-8",
- )
-
-
-def _target_to_part(target: str) -> str:
- target = target.lstrip("/")
- if target.startswith("ppt/"):
- return target
- return f"ppt/{target}"
-
-
-def _slide_number_from_part(part_name: str) -> int:
- match = re.search(r"slide(\d+)\.xml$", part_name)
- if not match:
- raise ValueError(f"Unsupported slide part name: {part_name}")
- return int(match.group(1))
-
-
-def _resolve_relationship_part(source_part: str, target: str) -> str:
- """Resolve an internal relationship target to a package part name."""
- target_path = target.split("#", 1)[0]
- if target_path.startswith("/"):
- return posixpath.normpath(target_path.lstrip("/"))
- return posixpath.normpath(
- posixpath.join(posixpath.dirname(source_part), target_path)
- )
-
-
-def _notes_slide_index(part_name: str) -> int | None:
- match = _NOTES_SLIDE_PART_RE.fullmatch(part_name)
- return int(match.group(1)) if match else None
-
-
-def _is_notes_slide_part(part_name: str) -> bool:
- """Return whether a relationship target stays in the notesSlides folder."""
- return (
- posixpath.dirname(part_name) == "ppt/notesSlides"
- and posixpath.basename(part_name).endswith(".xml")
- and posixpath.basename(part_name) != ".xml"
- )
-
-
-def _notes_slide_part_for_slide(
- extract_dir: Path,
- slide: SlidePart,
-) -> str | None:
- """Return the notes part currently related to a slide, if present."""
- slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
- if not slide_rels.exists():
- return None
-
- related_parts: list[str] = []
- for rel in ET.parse(slide_rels).getroot():
- if rel.attrib.get("Type") != NOTES_REL_TYPE:
- continue
- if rel.attrib.get("TargetMode", "").lower() == "external":
- raise RuntimeError(
- f"Slide {slide.index} has an external notesSlide relationship"
- )
- target = rel.attrib.get("Target")
- if not target:
- raise RuntimeError(
- f"Slide {slide.index} notesSlide relationship has no Target"
- )
- part_name = _resolve_relationship_part(slide.part_name, target)
- if not _is_notes_slide_part(part_name):
- raise RuntimeError(
- f"Slide {slide.index} has an unsupported notesSlide target: {target}"
- )
- related_parts.append(part_name)
-
- if len(related_parts) > 1:
- raise RuntimeError(
- f"Slide {slide.index} has multiple notesSlide relationships"
- )
- return related_parts[0] if related_parts else None
-
-
-def _used_notes_slide_indices(extract_dir: Path) -> set[int]:
- """Collect every notesSlide number already reserved in the package."""
- used: set[int] = set()
- notes_dir = extract_dir / "ppt" / "notesSlides"
- for path in notes_dir.glob("notesSlide*.xml"):
- index = _notes_slide_index(f"ppt/notesSlides/{path.name}")
- if index is not None:
- used.add(index)
- for path in (notes_dir / "_rels").glob("notesSlide*.xml.rels"):
- index = _notes_slide_index(
- f"ppt/notesSlides/{path.name.removesuffix('.rels')}"
- )
- if index is not None:
- used.add(index)
-
- content_types_path = extract_dir / "[Content_Types].xml"
- if content_types_path.exists():
- content_types = content_types_path.read_text(encoding="utf-8")
- for match in re.finditer(
- r'PartName="/(ppt/notesSlides/notesSlide[1-9]\d*\.xml)"',
- content_types,
- ):
- index = _notes_slide_index(match.group(1))
- if index is not None:
- used.add(index)
-
- slides_rels_dir = extract_dir / "ppt" / "slides" / "_rels"
- for rels_path in slides_rels_dir.glob("slide*.xml.rels"):
- source_part = f"ppt/slides/{rels_path.name.removesuffix('.rels')}"
- for rel in ET.parse(rels_path).getroot():
- if (
- rel.attrib.get("Type") != NOTES_REL_TYPE
- or rel.attrib.get("TargetMode", "").lower() == "external"
- ):
- continue
- target = rel.attrib.get("Target")
- if not target:
- continue
- index = _notes_slide_index(
- _resolve_relationship_part(source_part, target)
- )
- if index is not None:
- used.add(index)
- return used
-
-
-def _allocate_notes_slide_part(extract_dir: Path) -> str:
- used = _used_notes_slide_indices(extract_dir)
- index = max(used, default=0) + 1
- return f"ppt/notesSlides/notesSlide{index}.xml"
-
-
-def read_slide_parts(extract_dir: Path) -> list[SlidePart]:
- presentation_path = extract_dir / "ppt" / "presentation.xml"
- rels_path = extract_dir / "ppt" / "_rels" / "presentation.xml.rels"
- if not presentation_path.exists() or not rels_path.exists():
- raise RuntimeError("PPTX package is missing presentation.xml or its relationships")
-
- rels_root = ET.parse(rels_path).getroot()
- rels: dict[str, str] = {}
- for rel in rels_root.findall(f"{{{PACKAGE_REL_NS}}}Relationship"):
- rel_id = rel.attrib.get("Id")
- target = rel.attrib.get("Target")
- if rel_id and target:
- rels[rel_id] = target
-
- presentation_root = ET.parse(presentation_path).getroot()
- slide_parts: list[SlidePart] = []
- for index, slide_id in enumerate(
- presentation_root.findall(f".//{{{PRESENTATION_NS}}}sldId"),
- 1,
- ):
- rel_id = slide_id.attrib.get(f"{{{REL_NS}}}id")
- if not rel_id or rel_id not in rels:
- continue
- part_name = _target_to_part(rels[rel_id])
- slide_parts.append(
- SlidePart(
- index=index,
- part_name=part_name,
- slide_number=_slide_number_from_part(part_name),
- )
- )
- if not slide_parts:
- raise RuntimeError("No slides found in presentation.xml")
- return slide_parts
-
-
-def _source_state_errors(
- project_path: Path,
- project: dict,
- source_pptx: Path,
- slides: list[SlidePart],
-) -> list[str]:
- """Return source-drift and slide-index consistency errors."""
- errors: list[str] = []
- actual_count = len(slides)
- actual_roster = [slide.part_name for slide in slides]
-
- expected_sha256 = project.get("source_sha256")
- if expected_sha256 is not None:
- if (
- not isinstance(expected_sha256, str)
- or re.fullmatch(r"[0-9a-f]{64}", expected_sha256) is None
- ):
- errors.append("project.json source_sha256 is not a lowercase SHA-256 digest")
- elif _file_sha256(source_pptx) != expected_sha256:
- errors.append("archived source PPTX SHA-256 no longer matches project.json")
-
- expected_project_count = project.get("slide_count")
- if isinstance(expected_project_count, bool) or not isinstance(
- expected_project_count,
- int,
- ):
- errors.append("project.json slide_count is not an integer")
- elif expected_project_count != actual_count:
- errors.append(
- "archived source slide count no longer matches project.json: "
- f"{actual_count} != {expected_project_count}"
- )
-
- expected_project_roster = project.get("slide_part_roster")
- if expected_project_roster is not None:
- if (
- not isinstance(expected_project_roster, list)
- or any(
- not isinstance(part_name, str) or not part_name
- for part_name in expected_project_roster
- )
- ):
- errors.append("project.json slide_part_roster is not an array of part names")
- elif expected_project_roster != actual_roster:
- errors.append(
- "archived source ordered slide-part roster no longer matches "
- "project.json"
- )
-
- slide_index_path = project_path / "analysis" / "slide_index.json"
- if not slide_index_path.is_file():
- errors.append(f"slide index is missing: {slide_index_path}")
- return errors
- try:
- slide_index = _read_json(slide_index_path)
- except (OSError, json.JSONDecodeError) as exc:
- errors.append(f"unable to read slide index: {exc}")
- return errors
-
- expected_index_count = slide_index.get("slide_count")
- if isinstance(expected_index_count, bool) or not isinstance(
- expected_index_count,
- int,
- ):
- errors.append("slide_index.json slide_count is not an integer")
- elif expected_index_count != actual_count:
- errors.append(
- "archived source slide count no longer matches slide_index.json: "
- f"{actual_count} != {expected_index_count}"
- )
-
- indexed_slides = slide_index.get("slides")
- if not isinstance(indexed_slides, list):
- errors.append("slide_index.json slides is not an array")
- return errors
- expected_roster: list[str] = []
- for index, item in enumerate(indexed_slides, 1):
- part_name = item.get("part_name") if isinstance(item, dict) else None
- if not isinstance(part_name, str) or not part_name:
- errors.append(
- f"slide_index.json slides[{index - 1}].part_name is invalid"
- )
- continue
- expected_roster.append(part_name)
- if len(expected_roster) == len(indexed_slides) and expected_roster != actual_roster:
- errors.append(
- "archived source ordered slide-part roster no longer matches "
- "slide_index.json"
- )
- return errors
-
-
-def _zip_dir(source_dir: Path, output_path: Path) -> None:
- output_path.parent.mkdir(parents=True, exist_ok=True)
- with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:
- for path in sorted(source_dir.rglob("*")):
- if path.is_file():
- zf.write(path, path.relative_to(source_dir).as_posix())
-
-
-def _extract_pptx(source_pptx: Path, extract_dir: Path) -> None:
- with zipfile.ZipFile(source_pptx, "r") as zf:
- zf.extractall(extract_dir)
-
-
-def _note_path(notes_dir: Path, index: int) -> Path | None:
- candidates = [
- notes_dir / f"{index:03d}.md",
- notes_dir / f"{index:02d}.md",
- notes_dir / f"{index}.md",
- notes_dir / f"slide{index:03d}.md",
- notes_dir / f"slide{index:02d}.md",
- notes_dir / f"slide{index}.md",
- ]
- for candidate in candidates:
- if candidate.exists():
- return candidate
- return None
-
-
-def _audio_path(audio_dir: Path, index: int) -> Path | None:
- stems = [
- f"{index:03d}",
- f"{index:02d}",
- str(index),
- f"slide{index:03d}",
- f"slide{index:02d}",
- f"slide{index}",
- ]
- for stem in stems:
- matches = [
- audio_dir / f"{stem}{ext}"
- for ext in NARRATION_EXTENSIONS
- if (audio_dir / f"{stem}{ext}").exists()
- ]
- if len(matches) > 1:
- names = ", ".join(path.name for path in matches)
- raise ValueError(
- f"ambiguous audio stem {stem!r}: {names}; "
- "keep exactly one supported extension"
- )
- if matches:
- return matches[0]
- return None
-
-
-def _collect_material_readiness(
- slides: list[SlidePart],
- notes_dir: Path,
- audio_dir: Path,
- modules: set[str],
- *,
- required_modules: set[str] | None = None,
-) -> MaterialReadiness:
- """Inspect enabled-module inputs once for both validation and application."""
- material_modules = modules if required_modules is None else required_modules
- notes_required = "notes" in material_modules
- audio_required = (
- "audio" in material_modules or "timings" in material_modules
- )
- timings_enabled = "timings" in material_modules
- note_paths: dict[int, Path] = {}
- audio_paths: dict[int, Path] = {}
- audio_durations: dict[int, float] = {}
- missing_notes: list[int] = []
- invalid_notes: dict[int, str] = {}
- missing_audio: list[int] = []
- invalid_audio: dict[int, str] = {}
-
- for slide in slides:
- note = _note_path(notes_dir, slide.index)
- if note is None:
- if notes_required:
- missing_notes.append(slide.index)
- else:
- try:
- note_text = markdown_to_plain_text(
- note.read_text(encoding="utf-8")
- )
- except (OSError, UnicodeError) as exc:
- if notes_required:
- invalid_notes[slide.index] = f"unable to read {note.name}: {exc}"
- else:
- if note_text:
- note_paths[slide.index] = note
- elif notes_required:
- invalid_notes[slide.index] = f"{note.name} has no spoken text"
-
- try:
- audio = _audio_path(audio_dir, slide.index)
- except ValueError as exc:
- if audio_required:
- invalid_audio[slide.index] = str(exc)
- continue
- if audio is None:
- if audio_required:
- missing_audio.append(slide.index)
- continue
- try:
- if not audio.is_file() or audio.stat().st_size <= 0:
- raise ValueError(f"{audio.name} is not a non-empty file")
- except (OSError, ValueError) as exc:
- if audio_required:
- invalid_audio[slide.index] = str(exc)
- continue
-
- if audio_required:
- duration = probe_audio_duration(audio)
- if duration is None:
- invalid_audio[slide.index] = (
- f"unable to decode {audio.name} with ffprobe"
- )
- continue
- if timings_enabled:
- audio_durations[slide.index] = duration
- audio_paths[slide.index] = audio
-
- module_errors: list[str] = []
- if timings_enabled and "audio" not in modules:
- module_errors.append("timings requires the audio module")
- return MaterialReadiness(
- note_paths=note_paths,
- audio_paths=audio_paths,
- audio_durations=audio_durations,
- notes_count=len(note_paths),
- audio_count=len(audio_paths),
- missing_notes=missing_notes,
- invalid_notes=invalid_notes,
- missing_audio=missing_audio,
- invalid_audio=invalid_audio,
- module_errors=module_errors,
- )
-
-
-def _material_readiness_messages(readiness: MaterialReadiness) -> list[str]:
- messages = list(readiness.module_errors)
- if readiness.missing_notes:
- messages.append(
- "missing notes for slide(s): "
- + ", ".join(str(index) for index in readiness.missing_notes)
- )
- if readiness.invalid_notes:
- messages.append(
- "invalid notes: "
- + "; ".join(
- f"slide {index}: {reason}"
- for index, reason in sorted(readiness.invalid_notes.items())
- )
- )
- if readiness.missing_audio:
- messages.append(
- "missing audio for slide(s): "
- + ", ".join(str(index) for index in readiness.missing_audio)
- )
- if readiness.invalid_audio:
- messages.append(
- "invalid audio: "
- + "; ".join(
- f"slide {index}: {reason}"
- for index, reason in sorted(readiness.invalid_audio.items())
- )
- )
- return messages
-
-
-def _material_readiness_report_fields(
- readiness: MaterialReadiness,
-) -> dict[str, object]:
- return {
- "notes_count": readiness.notes_count,
- "audio_count": readiness.audio_count,
- "missing_notes": readiness.missing_notes,
- "invalid_notes": sorted(readiness.invalid_notes),
- "invalid_note_reasons": readiness.invalid_notes,
- "missing_audio": readiness.missing_audio,
- "invalid_audio": sorted(readiness.invalid_audio),
- "invalid_audio_reasons": readiness.invalid_audio,
- "module_errors": readiness.module_errors,
- }
-
-
-def _add_override(content_types: str, part_name: str, content_type: str) -> str:
- if re.search(
- rf'<Override\b[^>]*\bPartName="/{re.escape(part_name)}"[^>]*/>',
- content_types,
- ):
- return content_types
- override = f' <Override PartName="/{part_name}" ContentType="{content_type}"/>'
- return content_types.replace("</Types>", override + "\n</Types>")
-
-
-def _add_notes_content_types(content_types: str, note_parts: set[str]) -> str:
- content_types = _add_override(content_types, "ppt/theme/theme2.xml", CONTENT_TYPE_THEME)
- content_types = _add_override(
- content_types,
- "ppt/notesMasters/notesMaster1.xml",
- CONTENT_TYPE_NOTES_MASTER,
- )
- for part_name in sorted(note_parts):
- content_types = _add_override(
- content_types,
- part_name,
- CONTENT_TYPE_NOTES_SLIDE,
- )
- return content_types
-
-
-def _apply_notes(
- extract_dir: Path,
- slide: SlidePart,
- note_md: Path,
-) -> str | None:
- notes_text = markdown_to_plain_text(note_md.read_text(encoding="utf-8"))
- if not notes_text:
- return None
-
- _ensure_notes_master(extract_dir)
- slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
- _ensure_rels_file(slide_rels)
- notes_part = _notes_slide_part_for_slide(extract_dir, slide)
- if notes_part is None:
- notes_part = _allocate_notes_slide_part(extract_dir)
- target = posixpath.relpath(
- notes_part,
- start=posixpath.dirname(slide.part_name),
- )
- _append_relationship(slide_rels, NOTES_REL_TYPE, target)
-
- notes_xml_path = extract_dir / notes_part
- notes_xml_path.parent.mkdir(parents=True, exist_ok=True)
- notes_xml_path.write_text(
- create_notes_slide_xml(slide.slide_number, notes_text),
- encoding="utf-8",
- )
-
- notes_rels_path = _relationship_file_for_part(extract_dir, notes_part)
- notes_rels_path.parent.mkdir(parents=True, exist_ok=True)
- notes_rels_path.write_text(
- create_notes_slide_rels_xml(slide.slide_number),
- encoding="utf-8",
- )
- return notes_part
-
-
-def _native_audio_carriers(
- extract_dir: Path,
- slides: list[SlidePart],
-) -> dict[int, list[str]]:
- """Return existing tool-owned narration carrier names by public slide."""
- carriers: dict[int, list[str]] = {}
- for slide in slides:
- slide_root = ET.parse(extract_dir / slide.part_name).getroot()
- names = sorted(
- {
- name
- for element in slide_root.iter(
- f"{{{PRESENTATION_NS}}}cNvPr"
- )
- if (name := element.attrib.get("name", "")).startswith(
- "native_enhance_audio_"
- )
- }
- )
- if names:
- carriers[slide.index] = names
- return carriers
-
-
-def _allocate_media_name(media_dir: Path, preferred_name: str) -> str:
- preferred_path = media_dir / preferred_name
- if not preferred_path.exists():
- return preferred_name
- stem = preferred_path.stem
- suffix = preferred_path.suffix
- index = 2
- while True:
- candidate_name = f"{stem}_{index}{suffix}"
- if not (media_dir / candidate_name).exists():
- return candidate_name
- index += 1
-
-
-def _ensure_audio_poster(media_dir: Path) -> str:
- preferred_name = "native_enhance_audio_poster.png"
- for candidate in sorted(
- media_dir.glob("native_enhance_audio_poster*.png")
- ):
- if not candidate.is_file():
- continue
- try:
- if candidate.read_bytes() == AUDIO_MARKER_PNG_BYTES:
- return candidate.name
- except OSError:
- continue
- poster_name = _allocate_media_name(media_dir, preferred_name)
- (media_dir / poster_name).write_bytes(AUDIO_MARKER_PNG_BYTES)
- return poster_name
-
-
-def _apply_audio(
- extract_dir: Path,
- slide: SlidePart,
- audio_path: Path,
- *,
- enter: EnterUpdate,
- timings_enabled: bool,
- narration_padding: float,
- narration_start_floor: float,
- audio_duration: float | None = None,
-) -> bool:
- media_dir = extract_dir / "ppt" / "media"
- media_dir.mkdir(parents=True, exist_ok=True)
-
- ext = audio_path.suffix.lower()
- media_name = _allocate_media_name(
- media_dir,
- f"native_enhance_audio_{slide.index:03d}{ext}",
- )
- shutil.copy2(audio_path, media_dir / media_name)
-
- poster_name = _ensure_audio_poster(media_dir)
-
- slide_rels = _relationship_file_for_part(extract_dir, slide.part_name)
- _ensure_rels_file(slide_rels)
- media_rid = _append_relationship(slide_rels, MEDIA_REL_TYPE, f"../media/{media_name}")
- audio_rid = _append_relationship(slide_rels, AUDIO_REL_TYPE, f"../media/{media_name}")
- poster_rid = _append_relationship(slide_rels, IMAGE_REL_TYPE, f"../media/{poster_name}")
-
- slide_xml_path = extract_dir / slide.part_name
- slide_xml = slide_xml_path.read_text(encoding="utf-8")
- source_animation_fingerprint = object_animation_fingerprint(slide_xml)
- source_transition = read_slide_transition_xml(slide_xml)
- if enter.policy == "replace":
- transition_duration = enter.duration
- elif enter.policy == "none":
- transition_duration = 0.0
- else:
- # Legacy spd-only transitions expose no exact milliseconds. Treat
- # those as unknown and keep the full configured floor after the
- # preserved transition rather than guessing an application duration.
- transition_duration = (
- source_transition.duration_ms / 1000
- if source_transition.duration_ms is not None
- else 0.0
- )
- narration_lead_in = narration_lead_in_seconds(
- transition_duration,
- start_floor=narration_start_floor,
- )
- shape_id = next_shape_id(slide_xml)
- slide_xml = inject_narration(
- slide_xml,
- shape_id=shape_id,
- shape_name=media_name,
- audio_rid=audio_rid,
- media_rid=media_rid,
- poster_rid=poster_rid,
- start_delay=narration_lead_in,
- )
-
- advance = AdvanceUpdate(mode="preserve")
- duration = audio_duration
- if duration is None and (
- timings_enabled or source_transition.advance_after_ms is not None
- ):
- duration = probe_audio_duration(audio_path)
- if (
- not timings_enabled
- and source_transition.advance_after_ms is not None
- ):
- if duration is None:
- raise RuntimeError(
- f"Unable to validate narration against slide {slide.index} "
- f"auto-advance with ffprobe: {audio_path}"
- )
- required_playback_ms = round((narration_lead_in + duration) * 1000)
- if source_transition.advance_after_ms < required_playback_ms:
- raise RuntimeError(
- f"Slide {slide.index} advances after "
- f"{source_transition.advance_after_ms} ms, before delayed "
- f"narration can finish at {required_playback_ms} ms; enable "
- "timings or lengthen the source auto-advance"
- )
- if timings_enabled:
- if duration is None:
- raise RuntimeError(f"Unable to read narration duration with ffprobe: {audio_path}")
- advance = AdvanceUpdate(
- mode="narration",
- after=narration_lead_in + duration + narration_padding,
- )
-
- wrote_advance = False
- if enter.policy != "preserve" or timings_enabled:
- slide_xml, wrote_advance = apply_slide_motion_xml(
- slide_xml,
- enter=enter,
- advance=advance,
- )
- if object_animation_fingerprint(slide_xml) != source_animation_fingerprint:
- raise RuntimeError(
- f"Slide {slide.index} object animations changed while adding narration"
- )
- slide_xml_path.write_text(slide_xml, encoding="utf-8")
- return timings_enabled and wrote_advance
-
-
-def _update_content_types(
- extract_dir: Path,
- note_parts: set[str],
- audio_exts: set[str],
-) -> None:
- content_types_path = extract_dir / "[Content_Types].xml"
- content_types = content_types_path.read_text(encoding="utf-8")
- if note_parts:
- content_types = _add_notes_content_types(content_types, note_parts)
- for ext in sorted(audio_exts):
- content_type = AUDIO_CONTENT_TYPES.get(ext)
- if content_type:
- content_types = _add_default_content_type(content_types, ext, content_type)
- if audio_exts:
- content_types = _add_default_content_type(content_types, "png", "image/png")
- content_types_path.write_text(content_types, encoding="utf-8")
-
-
-def _project_paths(project_path: Path) -> tuple[Path, Path, Path, Path]:
- project = _read_json(project_path / "project.json")
- source_pptx = project_path / project["source_pptx"]
- notes_dir = project_path / project["notes_dir"]
- audio_dir = project_path / project["audio_dir"]
- exports_dir = project_path / project["exports_dir"]
- return source_pptx, notes_dir, audio_dir, exports_dir
-
-
-def _output_path_error(
- project_path: Path,
- project: dict,
- source_pptx: Path,
- output_path: Path,
-) -> str | None:
- if output_path.suffix.lower() != ".pptx":
- return f"output must use a .pptx extension: {output_path}"
- if output_path == source_pptx.resolve():
- return "output must not overwrite the archived source PPTX"
-
- source_import = project.get("source_import")
- if isinstance(source_import, dict):
- original_path = source_import.get("original_path")
- if isinstance(original_path, str) and original_path:
- try:
- original = Path(original_path).expanduser().resolve()
- except OSError:
- original = None
- if original is not None and output_path == original:
- return "output must not overwrite the original source PPTX"
-
- protected = (
- project_path / "sources",
- project_path / "analysis",
- project_path / "notes",
- project_path / "audio",
- project_path / "validation",
- )
- for directory in protected:
- if _is_relative_to(output_path, directory):
- return (
- "output must not be written inside native-enhance control "
- f"directory: {directory}"
- )
- return None
-
-
-def _plan_path(project_path: Path) -> Path:
- return project_path / "analysis" / "enhancement_plan.json"
-
-
-def _load_enhancement_plan(project_path: Path) -> dict:
- path = _plan_path(project_path)
- if not path.exists():
- return {}
- return _read_json(path)
-
-
-def _enabled_modules(plan: dict) -> set[str]:
- modules = plan.get("modules")
- if not isinstance(modules, dict):
- return set(_WRITABLE_MODULES)
- enabled: set[str] = set()
- for name in _WRITABLE_MODULES:
- config = modules.get(name)
- if isinstance(config, dict) and config.get("enabled") is True:
- enabled.add(name)
- return enabled
-
-
-def _resolve_enter_update(
- *,
- cli_effect: str | None,
- configured_effect: object,
- configured_effect_options: object = None,
- transitions_enabled: bool,
- duration: float,
-) -> EnterUpdate:
- if cli_effect is None and not transitions_enabled:
- if configured_effect == "none":
- normalize_transition_effect_request(
- configured_effect,
- configured_effect_options,
- )
- return EnterUpdate(policy="none", effect=None, duration=duration)
- return EnterUpdate(policy="preserve", duration=duration)
-
- effect = cli_effect if cli_effect is not None else configured_effect
- if effect == "none":
- normalize_transition_effect_request(
- effect,
- None if cli_effect is not None else configured_effect_options,
- )
- return EnterUpdate(policy="none", effect=None, duration=duration)
- effect, effect_options = normalize_transition_effect_request(
- effect,
- None if cli_effect is not None else configured_effect_options,
- allow_none=False,
- )
-
- return EnterUpdate(
- policy="replace",
- effect=effect,
- duration=duration,
- effect_options=effect_options,
- )
-
-
-def _plan_confirmed(plan: dict) -> bool:
- return plan.get("status") == "confirmed"
-
-
-def _native_transition_config(
- transition: str,
- duration: float,
- effect_options: object = None,
-) -> dict[str, object]:
- if transition == "none":
- normalize_transition_effect_request(transition, effect_options)
- return {"effect": "none", "duration": duration}
- effect, effect_options = normalize_transition_effect_request(
- transition,
- effect_options,
- allow_none=False,
- )
- config: dict[str, object] = {
- "effect": effect,
- "duration": duration,
- }
- if effect_options:
- config["effect_options"] = effect_options
- return config
-
-
-def _module_config(plan: dict, name: str) -> dict:
- modules = plan.get("modules")
- if not isinstance(modules, dict):
- return {}
- config = modules.get(name)
- return config if isinstance(config, dict) else {}
-
-
-def _preserved_enabled(plan: dict, name: str, default: bool) -> bool:
- config = _module_config(plan, name)
- if "enabled" not in config:
- return default
- value = config["enabled"]
- if not isinstance(value, bool):
- raise ValueError(
- f"enhancement plan module {name}.enabled must be a boolean"
- )
- return value
-
-
-def _resolved_draft_transition_config(
- project: dict,
- existing_plan: dict,
- *,
- transition: str | None,
- transition_duration: float | None,
- apply_transition_without_audio: bool | None,
-) -> tuple[bool, dict[str, object]]:
- existing = _module_config(existing_plan, "transitions")
- project_default = (
- project.get("transition")
- if isinstance(project.get("transition"), dict)
- else {}
- )
-
- if transition is not None:
- raw_effect: object = transition
- raw_options: object = None
- elif "effect" in existing:
- raw_effect = existing["effect"]
- raw_options = existing.get("effect_options")
- elif "effect" in project_default:
- raw_effect = project_default["effect"]
- raw_options = project_default.get("effect_options")
- else:
- raw_effect = "fade"
- raw_options = None
-
- if not isinstance(raw_effect, str):
- raise ValueError("transition effect must be a string")
- if transition_duration is not None:
- raw_duration: object = transition_duration
- elif "duration" in existing:
- raw_duration = existing["duration"]
- elif "duration" in project_default:
- raw_duration = project_default["duration"]
- else:
- raw_duration = 0.5
- duration = validate_seconds(
- raw_duration,
- "transition duration",
- allow_zero=False,
- )
- config = _native_transition_config(
- raw_effect,
- duration,
- raw_options,
- )
-
- if apply_transition_without_audio is None:
- raw_apply_without_audio = existing.get(
- "apply_without_audio",
- False,
- )
- else:
- raw_apply_without_audio = apply_transition_without_audio
- if not isinstance(raw_apply_without_audio, bool):
- raise ValueError("transition apply_without_audio must be a boolean")
- config["apply_without_audio"] = raw_apply_without_audio
-
- if "slides" in existing:
- slides = existing["slides"]
- if not isinstance(slides, dict):
- raise ValueError("transition slides must be an object")
- config["slides"] = {
- str(key): dict(value) if isinstance(value, dict) else value
- for key, value in slides.items()
- }
-
- if transition is not None:
- enabled = transition != "none"
- else:
- enabled = _preserved_enabled(
- existing_plan,
- "transitions",
- raw_effect != "none",
- )
- return enabled, config
-
-
-def _build_enhancement_plan(
- project: dict,
- *,
- slide_count: int,
- notes_count: int,
- audio_count: int,
- transition: str | None,
- transition_duration: float | None,
- narration_padding: float | None,
- narration_start_floor: float | None,
- apply_transition_without_audio: bool | None,
- existing_plan: dict | None = None,
-) -> dict:
- previous = existing_plan or {}
- audio_enabled = _preserved_enabled(previous, "audio", True)
- notes_enabled = _preserved_enabled(previous, "notes", True) or audio_enabled
- timings_enabled = _preserved_enabled(previous, "timings", True)
- previous_timings = _module_config(previous, "timings")
- raw_padding: object
- if narration_padding is not None:
- raw_padding = narration_padding
- else:
- raw_padding = previous_timings.get("narration_padding", 0.4)
- resolved_padding = validate_seconds(
- raw_padding,
- "narration padding",
- allow_zero=True,
- )
- raw_start_floor: object
- if narration_start_floor is not None:
- raw_start_floor = narration_start_floor
- else:
- raw_start_floor = previous_timings.get(
- "narration_start_floor",
- DEFAULT_NARRATION_START_FLOOR,
- )
- resolved_start_floor = validate_seconds(
- raw_start_floor,
- "narration start floor",
- allow_zero=True,
- )
- transitions_enabled, transition_config = _resolved_draft_transition_config(
- project,
- previous,
- transition=transition,
- transition_duration=transition_duration,
- apply_transition_without_audio=apply_transition_without_audio,
- )
- return {
- "schema": PLAN_SCHEMA,
- "status": "draft",
- "source_pptx": project.get("source_pptx"),
- "slide_count": slide_count,
- "modules": {
- "notes": {
- "enabled": notes_enabled,
- "requires_confirmation": True,
- "status": (
- "disabled"
- if not notes_enabled
- else (
- "coverage_complete"
- if notes_count == slide_count
- else "needs_notes"
- )
- ),
- "coverage": {"present": notes_count, "total": slide_count},
- },
- "audio": {
- "enabled": audio_enabled,
- "requires_confirmation": True,
- "status": (
- "disabled"
- if not audio_enabled
- else (
- "coverage_complete"
- if audio_count == slide_count
- else "needs_audio"
- )
- ),
- "coverage": {"present": audio_count, "total": slide_count},
- "decodability": "unchecked",
- },
- "timings": {
- "enabled": timings_enabled,
- "requires_confirmation": True,
- "status": (
- "disabled"
- if not timings_enabled
- else (
- "audio_coverage_complete"
- if audio_enabled and audio_count == slide_count
- else "blocked_until_audio"
- )
- ),
- "source": "audio_duration",
- "narration_padding": resolved_padding,
- "narration_start_floor": resolved_start_floor,
- },
- "transitions": {
- "enabled": transitions_enabled,
- "requires_confirmation": True,
- "status": (
- "ready"
- if (
- transitions_enabled
- or transition_config.get("effect") == "none"
- or bool(transition_config.get("slides"))
- )
- else "disabled"
- ),
- **transition_config,
- },
- },
- "not_in_v1": [
- "object_animation",
- "visible_watermark",
- "footer_or_logo_insertion",
- "background_music",
- "media_compression",
- ],
- }
-
-
-def _resolve_slide_enter(
- base: EnterUpdate,
- override: dict,
- *,
- slide_index: int,
-) -> EnterUpdate:
- unknown = sorted(set(override) - _TRANSITION_OVERRIDE_FIELDS)
- if unknown:
- raise ValueError(
- f"transition slides.{slide_index} has unknown field(s): "
- + ", ".join(unknown)
- )
-
- raw_duration = override.get("duration", base.duration)
- duration = validate_seconds(
- raw_duration,
- f"transition slides.{slide_index}.duration",
- allow_zero=False,
- )
- effect = override.get("effect")
- if effect == "preserve":
- if "effect_options" in override:
- raise ValueError(
- f"transition slides.{slide_index} preserve cannot have "
- "effect_options"
- )
- return EnterUpdate(policy="preserve", duration=duration)
-
- if effect is None:
- if base.policy == "preserve":
- if "effect_options" in override:
- raise ValueError(
- f"transition slides.{slide_index} effect_options requires "
- "a native effect"
- )
- return EnterUpdate(policy="preserve", duration=duration)
- if base.policy == "none":
- if "effect_options" in override:
- raise ValueError(
- f"transition slides.{slide_index} none cannot have "
- "effect_options"
- )
- return EnterUpdate(policy="none", effect=None, duration=duration)
- effect = base.effect
- effect_options = override.get(
- "effect_options",
- base.effect_options,
- )
- else:
- if not isinstance(effect, str):
- raise ValueError(
- f"transition slides.{slide_index}.effect must be a string"
- )
- effect_options = override.get("effect_options")
-
- return _resolve_enter_update(
- cli_effect=None,
- configured_effect=effect,
- configured_effect_options=effect_options,
- transitions_enabled=True,
- duration=duration,
- )
-
-
-def _validate_plan_modules(
- plan: dict,
- *,
- allow_legacy_audio_without_notes: bool = False,
-) -> None:
- if plan and plan.get("schema") != PLAN_SCHEMA:
- raise ValueError(
- f"unsupported enhancement plan schema: {plan.get('schema')!r}"
- )
- modules_cfg = plan.get("modules")
- if modules_cfg is None:
- return
- if not isinstance(modules_cfg, dict):
- raise ValueError("enhancement plan modules must be an object")
-
- unknown_modules = sorted(set(modules_cfg) - set(_WRITABLE_MODULES))
- if unknown_modules:
- raise ValueError(
- "enhancement plan has unknown module(s): "
- + ", ".join(unknown_modules)
- )
- if plan.get("schema") == PLAN_SCHEMA:
- missing_modules = [
- name
- for name in _WRITABLE_MODULES
- if name not in modules_cfg
- ]
- if missing_modules:
- raise ValueError(
- "enhancement plan is missing module(s): "
- + ", ".join(missing_modules)
- )
- for name in _WRITABLE_MODULES:
- config = modules_cfg.get(name)
- if config is not None and not isinstance(config, dict):
- raise ValueError(
- f"enhancement plan module {name} must be an object"
- )
- if (
- isinstance(config, dict)
- and (
- "enabled" not in config
- or not isinstance(config["enabled"], bool)
- )
- ):
- raise ValueError(
- f"enhancement plan module {name}.enabled must be a boolean"
- )
- notes_config = modules_cfg.get("notes")
- audio_config = modules_cfg.get("audio")
- legacy_audio_without_notes = (
- allow_legacy_audio_without_notes
- and isinstance(notes_config, dict)
- and notes_config.get("enabled") is False
- )
- if (
- isinstance(audio_config, dict)
- and audio_config.get("enabled") is True
- and not legacy_audio_without_notes
- and (
- not isinstance(notes_config, dict)
- or notes_config.get("enabled") is not True
- )
- ):
- raise ValueError(
- "enhancement plan audio requires notes.enabled: true"
- )
-
-
-def _resolve_transition_plan(
- project: dict,
- plan: dict,
- slides: list[SlidePart],
- *,
- cli_effect: str | None = None,
- cli_duration: float | None = None,
- cli_apply_without_audio: bool = False,
-) -> ResolvedTransitionPlan:
- _validate_plan_modules(plan)
- plan_slide_count = plan.get("slide_count")
- if plan_slide_count is not None and plan_slide_count != len(slides):
- raise ValueError(
- "enhancement plan slide_count no longer matches the archived "
- f"source: {plan_slide_count!r} != {len(slides)}"
- )
-
- modules = _enabled_modules(plan)
- transitions_cfg = _module_config(plan, "transitions")
- unknown = sorted(set(transitions_cfg) - _TRANSITION_MODULE_FIELDS)
- if unknown:
- raise ValueError(
- "transition module has unknown field(s): " + ", ".join(unknown)
- )
-
- project_transition = (
- project.get("transition")
- if isinstance(project.get("transition"), dict)
- else {}
- )
- if (
- cli_effect is None
- and "effect_options" in transitions_cfg
- and "effect" not in transitions_cfg
- ):
- raise ValueError("transition effect_options requires an explicit effect")
- if (
- cli_effect is None
- and "effect_options" in project_transition
- and "effect" not in project_transition
- and "effect" not in transitions_cfg
- ):
- raise ValueError("transition effect_options requires an explicit effect")
-
- if "effect" in transitions_cfg:
- configured_effect = transitions_cfg["effect"]
- configured_options = transitions_cfg.get("effect_options")
- elif "effect" in project_transition:
- configured_effect = project_transition["effect"]
- configured_options = project_transition.get("effect_options")
- else:
- configured_effect = "fade"
- configured_options = None
-
- if cli_duration is not None:
- raw_duration: object = cli_duration
- elif "duration" in transitions_cfg:
- raw_duration = transitions_cfg["duration"]
- elif "duration" in project_transition:
- raw_duration = project_transition["duration"]
- else:
- raw_duration = 0.5
- duration = validate_seconds(
- raw_duration,
- "transition duration",
- allow_zero=False,
- )
-
- selected_base = _resolve_enter_update(
- cli_effect=cli_effect,
- configured_effect=configured_effect,
- configured_effect_options=configured_options,
- transitions_enabled=True,
- duration=duration,
- )
- global_enter = _resolve_enter_update(
- cli_effect=cli_effect,
- configured_effect=configured_effect,
- configured_effect_options=configured_options,
- transitions_enabled="transitions" in modules,
- duration=duration,
- )
-
- raw_apply_without_audio = transitions_cfg.get(
- "apply_without_audio",
- False,
- )
- if not isinstance(raw_apply_without_audio, bool):
- raise ValueError("transition apply_without_audio must be a boolean")
- apply_without_audio = (
- cli_apply_without_audio or raw_apply_without_audio
- )
- if (
- "audio" not in modules
- and (
- "transitions" in modules
- or cli_effect is not None
- or global_enter.policy == "none"
- )
- ):
- # A confirmed global transition is independently actionable. The
- # narrated-only scope switch matters only while audio is enabled.
- # Explicit none remains an action even though the module is disabled.
- apply_without_audio = True
-
- raw_slides = transitions_cfg.get("slides", {})
- if not isinstance(raw_slides, dict):
- raise ValueError("transition slides must be an object")
- valid_indices = {slide.index for slide in slides}
- slide_enters: dict[int, EnterUpdate] = {}
- for raw_index, override in raw_slides.items():
- if (
- not isinstance(raw_index, str)
- or re.fullmatch(r"[1-9]\d*", raw_index) is None
- ):
- raise ValueError(
- f"transition slide key must be a canonical 1-based index: "
- f"{raw_index!r}"
- )
- slide_index = int(raw_index)
- if slide_index not in valid_indices:
- raise ValueError(
- f"transition slide index is outside the source roster: "
- f"{slide_index}"
- )
- if not isinstance(override, dict):
- raise ValueError(
- f"transition slides.{slide_index} must be an object"
- )
- slide_enters[slide_index] = _resolve_slide_enter(
- selected_base,
- override,
- slide_index=slide_index,
- )
-
- return ResolvedTransitionPlan(
- global_enter=global_enter,
- slide_enters=slide_enters,
- apply_without_audio=apply_without_audio,
- )
-
-
-def _apply_transition_only(
- extract_dir: Path,
- slide: SlidePart,
- enter: EnterUpdate,
-) -> bool:
- if enter.policy == "preserve":
- return False
- slide_xml_path = extract_dir / slide.part_name
- slide_xml = slide_xml_path.read_text(encoding="utf-8")
- source_animation_fingerprint = object_animation_fingerprint(slide_xml)
- slide_xml, _uses_timings = apply_slide_motion_xml(
- slide_xml,
- enter=enter,
- advance=AdvanceUpdate(mode="preserve"),
- )
- if object_animation_fingerprint(slide_xml) != source_animation_fingerprint:
- raise RuntimeError(
- f"Slide {slide.index} object animations changed while updating "
- "the transition"
- )
- slide_xml_path.write_text(slide_xml, encoding="utf-8")
- return True
-
-
-def init_project(args: argparse.Namespace) -> int:
- source_pptx = Path(args.source_pptx).expanduser().resolve()
- if not source_pptx.exists() or source_pptx.suffix.lower() != ".pptx":
- print(f"error: expected an existing .pptx file: {source_pptx}", file=sys.stderr)
- return 1
-
- source_delivery = audit_pptx_delivery(source_pptx)
- fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
- if fatal_delivery_messages:
- for message in fatal_delivery_messages:
- print(f"error: {message}", file=sys.stderr)
- return 1
-
- stem = _sanitize_slug(args.name or source_pptx.stem)
- date = datetime.now().strftime("%Y%m%d")
- project_path = (
- Path(args.project_dir).expanduser().resolve()
- if args.project_dir
- else Path(args.projects_root).expanduser().resolve() / f"{stem}_native_enhance_{date}"
- )
- if project_path.exists() and any(project_path.iterdir()):
- print(f"error: project directory already exists and is not empty: {project_path}", file=sys.stderr)
- return 1
-
- for dirname in ("sources", "analysis", "notes", "audio", "exports", "validation"):
- (project_path / dirname).mkdir(parents=True, exist_ok=True)
-
- archived_pptx = project_path / "sources" / source_pptx.name
- projects_root = Path(args.projects_root).expanduser().resolve()
- source_import_mode = _archive_source_pptx(source_pptx, archived_pptx, projects_root)
-
- source_md = project_path / "sources" / f"{source_pptx.stem}.md"
- ppt_to_md = _SCRIPTS_DIR / "source_to_md" / "ppt_to_md.py"
- result = subprocess.run(
- [sys.executable, str(ppt_to_md), str(archived_pptx), "-o", str(source_md)],
- check=False,
- text=True,
- capture_output=True,
- )
- if result.returncode != 0:
- print(result.stderr or result.stdout, file=sys.stderr)
- return result.returncode
-
- with tempfile.TemporaryDirectory(prefix="native-enhance-intake-") as tmp:
- extract_dir = Path(tmp) / "pptx"
- _extract_pptx(archived_pptx, extract_dir)
- slide_parts = read_slide_parts(extract_dir)
- source_sha256 = _file_sha256(archived_pptx)
-
- slide_index = {
- "schema": "native_pptx_enhancement_slide_index.v1",
- "source_pptx": f"sources/{source_pptx.name}",
- "slide_count": len(slide_parts),
- "slides": [
- {
- "index": slide.index,
- "note_file": f"notes/{slide.index:03d}.md",
- "audio_stem": f"{slide.index:03d}",
- "part_name": slide.part_name,
- "slide_number": slide.slide_number,
- }
- for slide in slide_parts
- ],
- }
- _write_json(project_path / "analysis" / "slide_index.json", slide_index)
-
- project = {
- "schema": PROJECT_SCHEMA,
- "kind": "native_pptx_enhancement",
- "modules": [
- "notes",
- "audio",
- "timings",
- "transitions",
- "delivery.check",
- ],
- "source_pptx": f"sources/{source_pptx.name}",
- "source_markdown": f"sources/{source_pptx.stem}.md",
- "source_import": {
- "mode": source_import_mode,
- "original_path": str(source_pptx),
- },
- "source_sha256": source_sha256,
- "slide_count": len(slide_parts),
- "slide_part_roster": [slide.part_name for slide in slide_parts],
- "notes_dir": "notes",
- "audio_dir": "audio",
- "exports_dir": "exports",
- "transition": _native_transition_config(
- args.transition,
- args.transition_duration,
- ),
- "audio": {
- "provider": "",
- "voice": "",
- "rate": "",
- },
- }
- _write_json(project_path / "project.json", project)
- plan = _build_enhancement_plan(
- project,
- slide_count=len(slide_parts),
- notes_count=0,
- audio_count=0,
- transition=args.transition,
- transition_duration=args.transition_duration,
- narration_padding=args.narration_padding,
- narration_start_floor=args.narration_start_floor,
- apply_transition_without_audio=args.apply_transition_without_audio,
- )
- _write_json(_plan_path(project_path), plan)
- source_delivery_file = source_delivery.get("file")
- if isinstance(source_delivery_file, dict):
- source_delivery_file["path"] = str(archived_pptx.resolve())
- _write_json(
- project_path / "validation" / "report.json",
- {
- "schema": VALIDATION_SCHEMA,
- "status": (
- "passed-with-advisories"
- if _delivery_has_findings(source_delivery)
- else "passed"
- ),
- "phase": "intake",
- "source_delivery_policy": "preserve-baseline",
- "delivery_check": source_delivery,
- },
- )
-
- print(f"Project: {project_path}", file=sys.stderr)
- print(f"Slides: {len(slide_parts)}", file=sys.stderr)
- print(f"Source import: {source_import_mode}", file=sys.stderr)
- print(f"Source markdown: {source_md}", file=sys.stderr)
- print(f"Draft enhancement plan: {_plan_path(project_path)}", file=sys.stderr)
- print(
- "Review the plan with the user and set status to \"confirmed\" before generating notes/audio/applying.",
- file=sys.stderr,
- )
- return 0
-
-
-def plan_project(args: argparse.Namespace) -> int:
- project_path = Path(args.project_path).expanduser().resolve()
- project = _read_json(project_path / "project.json")
- if project.get("schema") not in {PROJECT_SCHEMA, *LEGACY_PROJECT_SCHEMAS}:
- print(f"error: not a native PPTX enhancement project: {project_path}", file=sys.stderr)
- return 1
-
- source_pptx, notes_dir, audio_dir, _exports_dir = _project_paths(project_path)
- source_delivery = audit_pptx_delivery(source_pptx)
- fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
- if fatal_delivery_messages:
- for message in fatal_delivery_messages:
- print(f"error: {message}", file=sys.stderr)
- return 1
-
- with tempfile.TemporaryDirectory(prefix="native-enhance-plan-") as tmp:
- extract_dir = Path(tmp) / "pptx"
- _extract_pptx(source_pptx, extract_dir)
- slides = read_slide_parts(extract_dir)
-
- source_errors = _source_state_errors(
- project_path,
- project,
- source_pptx,
- slides,
- )
- if source_errors:
- for error in source_errors:
- print(f"error: {error}", file=sys.stderr)
- return 1
-
- existing_plan = _load_enhancement_plan(project_path)
- try:
- _validate_plan_modules(
- existing_plan,
- allow_legacy_audio_without_notes=True,
- )
- readiness = _collect_material_readiness(
- slides,
- notes_dir,
- audio_dir,
- set(),
- )
- plan = _build_enhancement_plan(
- project,
- slide_count=len(slides),
- notes_count=readiness.notes_count,
- audio_count=readiness.audio_count,
- transition=args.transition,
- transition_duration=args.transition_duration,
- narration_padding=args.narration_padding,
- narration_start_floor=args.narration_start_floor,
- apply_transition_without_audio=args.apply_transition_without_audio,
- existing_plan=existing_plan,
- )
- _resolve_transition_plan(project, plan, slides)
- except ValueError as exc:
- print(f"error: {exc}", file=sys.stderr)
- return 1
- _write_json(_plan_path(project_path), plan)
- print(json.dumps(plan, ensure_ascii=False, indent=2))
- print(f"Plan written: {_plan_path(project_path)}", file=sys.stderr)
- print(
- "Confirm by editing status to \"confirmed\" after user approval, then run apply.",
- file=sys.stderr,
- )
- return 0
-
-
-def apply_project(args: argparse.Namespace) -> int:
- project_path = Path(args.project_path).expanduser().resolve()
- project = _read_json(project_path / "project.json")
- if project.get("schema") not in {PROJECT_SCHEMA, *LEGACY_PROJECT_SCHEMAS}:
- print(f"error: not a native PPTX enhancement project: {project_path}", file=sys.stderr)
- return 1
-
- source_pptx, notes_dir, audio_dir, exports_dir = _project_paths(project_path)
- plan = _load_enhancement_plan(project_path)
- modules = _enabled_modules(plan)
-
- def fail_preflight(
- messages: list[str],
- *,
- status: str = "failed",
- **details: object,
- ) -> int:
- _write_preflight_report(
- project_path,
- plan,
- modules,
- status=status,
- errors=messages,
- **details,
- )
- for message in messages:
- print(f"error: {message}", file=sys.stderr)
- return 1
-
- _write_preflight_report(
- project_path,
- plan,
- modules,
- status="running",
- )
- if not _plan_confirmed(plan) and not args.force:
- return fail_preflight(
- [
- f"enhancement plan is not confirmed: {_plan_path(project_path)} "
- "(run plan, get user confirmation, set status to "
- "\"confirmed\", or pass --force)"
- ]
- )
-
- try:
- _validate_plan_modules(plan)
- except ValueError as exc:
- return fail_preflight(
- [str(exc)],
- plan_errors=[str(exc)],
- )
-
- source_delivery = audit_pptx_delivery(source_pptx)
- fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
- if fatal_delivery_messages:
- return fail_preflight(
- fatal_delivery_messages,
- fatal_delivery_errors=fatal_delivery_messages,
- delivery_check=source_delivery,
- )
-
- modules_cfg = plan.get("modules") if isinstance(plan.get("modules"), dict) else {}
- timings_cfg = modules_cfg.get("timings", {})
- if not isinstance(timings_cfg, dict):
- timings_cfg = {}
-
- if args.narration_padding is not None:
- raw_narration_padding = args.narration_padding
- elif "narration_padding" in timings_cfg:
- raw_narration_padding = timings_cfg["narration_padding"]
- else:
- raw_narration_padding = 0.4
-
- try:
- if "timings" in modules:
- narration_padding = validate_seconds(
- raw_narration_padding,
- "narration padding",
- allow_zero=True,
- )
- else:
- narration_padding = 0.4
- except ValueError as exc:
- return fail_preflight([str(exc)])
-
- if args.narration_start_floor is not None:
- raw_narration_start_floor = args.narration_start_floor
- elif "narration_start_floor" in timings_cfg:
- raw_narration_start_floor = timings_cfg["narration_start_floor"]
- else:
- raw_narration_start_floor = DEFAULT_NARRATION_START_FLOOR
-
- try:
- if "audio" in modules:
- narration_start_floor = validate_seconds(
- raw_narration_start_floor,
- "narration start floor",
- allow_zero=True,
- )
- else:
- narration_start_floor = DEFAULT_NARRATION_START_FLOOR
- except ValueError as exc:
- return fail_preflight([str(exc)])
-
- output_path = (
- Path(args.output).expanduser().resolve()
- if args.output
- else exports_dir / f"{source_pptx.stem}_enhanced.pptx"
- )
- output_error = _output_path_error(
- project_path,
- project,
- source_pptx,
- output_path,
- )
- if output_error:
- return fail_preflight([output_error])
- if output_path.exists() and not args.overwrite:
- return fail_preflight(
- [f"output already exists, pass --overwrite: {output_path}"]
- )
-
- with tempfile.TemporaryDirectory(prefix="native-enhance-pptx-") as tmp:
- extract_dir = Path(tmp) / "pptx"
- _extract_pptx(source_pptx, extract_dir)
- slides = read_slide_parts(extract_dir)
-
- source_errors = _source_state_errors(
- project_path,
- project,
- source_pptx,
- slides,
- )
- if source_errors:
- return fail_preflight(
- source_errors,
- source_errors=source_errors,
- delivery_check=source_delivery,
- )
-
- try:
- resolved_transitions = _resolve_transition_plan(
- project,
- plan,
- slides,
- cli_effect=args.transition,
- cli_duration=args.transition_duration,
- cli_apply_without_audio=args.apply_transition_without_audio,
- )
- except ValueError as exc:
- return fail_preflight(
- [str(exc)],
- transition_errors=[str(exc)],
- delivery_check=source_delivery,
- )
-
- readiness = _collect_material_readiness(
- slides,
- notes_dir,
- audio_dir,
- modules,
- )
- if not readiness.ready:
- return fail_preflight(
- _material_readiness_messages(readiness),
- status=(
- "failed"
- if readiness.module_errors
- else "needs-materials"
- ),
- notes_required="notes" in modules,
- audio_required=(
- "audio" in modules or "timings" in modules
- ),
- delivery_check=source_delivery,
- **_material_readiness_report_fields(readiness),
- )
-
- if "audio" in modules:
- existing_carriers = _native_audio_carriers(extract_dir, slides)
- if existing_carriers:
- details = "; ".join(
- f"slide {index}: {', '.join(names)}"
- for index, names in sorted(existing_carriers.items())
- )
- return fail_preflight(
- [
- "source PPTX already contains native-enhance narration "
- "carrier(s); refusing to append duplicate audio: "
- + details
- ],
- existing_native_audio_carriers=existing_carriers,
- delivery_check=source_delivery,
- )
-
- note_parts: set[str] = set()
- audio_exts: set[str] = set()
- audio_count = 0
- transition_only_count = 0
- wrote_auto_advance = False
- for slide in slides:
- has_slide_transition = (
- slide.index in resolved_transitions.slide_enters
- )
- enter_update = resolved_transitions.slide_enters.get(
- slide.index,
- resolved_transitions.global_enter,
- )
- note = readiness.note_paths.get(slide.index)
- if "notes" in modules and note:
- notes_part = _apply_notes(extract_dir, slide, note)
- if notes_part is not None:
- note_parts.add(notes_part)
-
- audio = readiness.audio_paths.get(slide.index)
- if "audio" in modules and audio:
- wrote_auto_advance = _apply_audio(
- extract_dir,
- slide,
- audio,
- enter=enter_update,
- timings_enabled="timings" in modules,
- narration_padding=narration_padding,
- narration_start_floor=narration_start_floor,
- audio_duration=readiness.audio_durations.get(slide.index),
- ) or wrote_auto_advance
- audio_exts.add(audio.suffix.lower())
- audio_count += 1
- continue
-
- if (
- has_slide_transition
- or resolved_transitions.apply_without_audio
- ):
- transition_only_count += int(
- _apply_transition_only(
- extract_dir,
- slide,
- enter_update,
- )
- )
-
- _update_content_types(extract_dir, note_parts, audio_exts)
- if wrote_auto_advance:
- set_directory_use_timings(extract_dir)
- output_path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.TemporaryDirectory(
- prefix="native-enhance-output-",
- dir=output_path.parent,
- ) as output_tmp:
- candidate_path = Path(output_tmp) / output_path.name
- _zip_dir(extract_dir, candidate_path)
- try:
- validate_pptx_transition_package(
- candidate_path,
- require_use_timings=wrote_auto_advance,
- )
- except ValueError as exc:
- raise RuntimeError(
- f"PPTX transition package validation failed: {exc}"
- ) from exc
- try:
- validate_pptx_animation_package(
- candidate_path,
- require_supported_effects=False,
- )
- except ValueError as exc:
- raise RuntimeError(
- f"PPTX animation/timing package validation failed: {exc}"
- ) from exc
- candidate_delivery = audit_pptx_delivery(candidate_path)
- introduced_delivery_errors = _new_delivery_errors(
- source_delivery,
- candidate_delivery,
- )
- if introduced_delivery_errors:
- raise RuntimeError(
- "PPTX delivery postflight introduced structural error(s): "
- + "; ".join(
- str(issue.get("message") or issue)
- for issue in introduced_delivery_errors
- )
- )
- candidate_slides = candidate_delivery.get("slides")
- candidate_slide_count = (
- candidate_slides.get("count")
- if isinstance(candidate_slides, dict)
- else None
- )
- if candidate_slide_count != len(slides):
- raise RuntimeError(
- "PPTX delivery postflight slide count changed: "
- f"{candidate_slide_count!r} != {len(slides)}"
- )
- source_hidden_slides = _delivery_hidden_slide_indices(
- source_delivery
- )
- candidate_hidden_slides = _delivery_hidden_slide_indices(
- candidate_delivery
- )
- if (
- source_hidden_slides is None
- or candidate_hidden_slides is None
- or candidate_hidden_slides != source_hidden_slides
- ):
- raise RuntimeError(
- "PPTX delivery postflight changed or could not verify "
- "hidden-slide state"
- )
- candidate_path.replace(output_path)
-
- candidate_file = candidate_delivery.get("file")
- if isinstance(candidate_file, dict):
- candidate_file["path"] = str(output_path.resolve())
- report_status = (
- "passed-with-advisories"
- if (
- _delivery_has_findings(source_delivery)
- or _delivery_has_findings(candidate_delivery)
- )
- else "passed"
- )
- validation_dir = project_path / "validation"
- validation_dir.mkdir(exist_ok=True)
- _write_json(
- validation_dir / "report.json",
- {
- "schema": VALIDATION_SCHEMA,
- "status": report_status,
- "phase": "postflight",
- "plan_status": plan.get("status") or "missing",
- "enabled_modules": sorted(modules),
- "slide_count": len(slides),
- "applied": {
- "notes": len(note_parts),
- "audio": audio_count,
- "transition_only_slides": transition_only_count,
- "automatic_advance": wrote_auto_advance,
- },
- "transition_scope": {
- "global_enabled": "transitions" in modules,
- "global_policy": (
- resolved_transitions.global_enter.policy
- ),
- "apply_without_audio": (
- resolved_transitions.apply_without_audio
- ),
- "selected_slides": sorted(
- resolved_transitions.slide_enters
- ),
- },
- "source_delivery_check": source_delivery,
- "output_delivery_check": candidate_delivery,
- "source_delivery_policy": "preserve-baseline",
- "introduced_delivery_errors": introduced_delivery_errors,
- },
- )
-
- print(f"Output: {output_path}", file=sys.stderr)
- print(f"Notes applied: {len(note_parts)}", file=sys.stderr)
- print(f"Audio embedded: {audio_count}", file=sys.stderr)
- if transition_only_count:
- print(f"Transition-only slides: {transition_only_count}", file=sys.stderr)
- return 0
-
-
-def validate_project(args: argparse.Namespace) -> int:
- project_path = Path(args.project_path).expanduser().resolve()
- project = _read_json(project_path / "project.json")
- if project.get("schema") not in {PROJECT_SCHEMA, *LEGACY_PROJECT_SCHEMAS}:
- print(f"error: not a native PPTX enhancement project: {project_path}", file=sys.stderr)
- return 1
-
- source_pptx, notes_dir, audio_dir, _exports_dir = _project_paths(project_path)
- plan = _load_enhancement_plan(project_path)
- modules = _enabled_modules(plan)
- material_modules = {"notes"} if args.materials == "notes" else modules
- source_delivery = audit_pptx_delivery(source_pptx)
- validation_dir = project_path / "validation"
- validation_dir.mkdir(exist_ok=True)
- fatal_delivery_messages = _fatal_source_delivery_messages(source_delivery)
- if fatal_delivery_messages:
- report = _write_preflight_report(
- project_path,
- plan,
- modules,
- status="failed",
- material_scope=args.materials,
- fatal_delivery_errors=fatal_delivery_messages,
- delivery_check=source_delivery,
- )
- print(json.dumps(report, ensure_ascii=False, indent=2))
- return 1
-
- with tempfile.TemporaryDirectory(prefix="native-enhance-validate-") as tmp:
- extract_dir = Path(tmp) / "pptx"
- _extract_pptx(source_pptx, extract_dir)
- slides = read_slide_parts(extract_dir)
- existing_carriers = (
- _native_audio_carriers(extract_dir, slides)
- if "audio" in modules
- else {}
- )
-
- source_errors = _source_state_errors(
- project_path,
- project,
- source_pptx,
- slides,
- )
- try:
- _validate_plan_modules(plan)
- except ValueError as exc:
- plan_errors = [str(exc)]
- else:
- plan_errors = []
- try:
- resolved_transitions = (
- _resolve_transition_plan(
- project,
- plan,
- slides,
- )
- if not plan_errors
- else None
- )
- except ValueError as exc:
- transition_errors = [str(exc)]
- transition_slide_count = 0
- transition_scope = None
- else:
- transition_errors = []
- if resolved_transitions is None:
- transition_slide_count = 0
- transition_scope = None
- else:
- transition_slide_count = len(
- resolved_transitions.slide_enters
- )
- transition_scope = {
- "global_enabled": "transitions" in modules,
- "global_policy": resolved_transitions.global_enter.policy,
- "apply_without_audio": (
- resolved_transitions.apply_without_audio
- ),
- "selected_slides": sorted(
- resolved_transitions.slide_enters
- ),
- }
- readiness = _collect_material_readiness(
- slides,
- notes_dir,
- audio_dir,
- modules,
- required_modules=material_modules,
- )
- hard_failure = bool(
- source_errors
- or readiness.module_errors
- or plan_errors
- or transition_errors
- or existing_carriers
- )
- if hard_failure:
- status = "failed"
- elif not readiness.ready:
- status = "needs-materials"
- else:
- status = (
- "passed-with-advisories"
- if _delivery_has_findings(source_delivery)
- else "passed"
- )
- report = _write_preflight_report(
- project_path,
- plan,
- modules,
- status=status,
- material_scope=args.materials,
- slide_count=len(slides),
- notes_required="notes" in material_modules,
- audio_required=(
- "audio" in material_modules or "timings" in material_modules
- ),
- plan_errors=plan_errors,
- transition_errors=transition_errors,
- transition_override_count=transition_slide_count,
- transition_scope=transition_scope,
- source_errors=source_errors,
- existing_native_audio_carriers=existing_carriers,
- source_delivery_policy="preserve-baseline",
- delivery_check=source_delivery,
- **_material_readiness_report_fields(readiness),
- )
- print(json.dumps(report, ensure_ascii=False, indent=2))
- if hard_failure:
- return 1
- return 0 if readiness.ready else 2
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- description="Create/apply a native existing-PPTX enhancement project without SVG conversion.",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- )
- subparsers = parser.add_subparsers(dest="command", required=True)
-
- init = subparsers.add_parser("init", help="create a native PPTX enhancement project")
- init.add_argument("source_pptx", help="source .pptx file")
- init.add_argument("--name", default=None, help="ASCII project name slug")
- init.add_argument("--project-dir", default=None, help="explicit project directory")
- init.add_argument("--projects-root", default="projects", help="projects root (default: projects)")
- init.add_argument(
- "--transition",
- default="fade",
- choices=[*NATIVE_TRANSITION_KEYS, *LEGACY_TRANSITION_KEYS, "none"],
- help="PowerPoint-native effect; old names are compatibility inputs",
- )
- init.add_argument("--transition-duration", type=_positive_seconds_arg, default=0.5)
- init.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=0.4)
- init.add_argument(
- "--narration-start-floor",
- type=_non_negative_seconds_arg,
- default=DEFAULT_NARRATION_START_FLOOR,
- help="minimum seconds from transition start to narration start",
- )
- init.add_argument(
- "--apply-transition-without-audio",
- action="store_true",
- help=(
- "when audio is enabled, draft transitions for slides without audio "
- "as well"
- ),
- )
- init.set_defaults(func=init_project)
-
- plan = subparsers.add_parser("plan", help="draft an enhancement module plan")
- plan.add_argument("project_path", help="native enhancement project directory")
- plan.add_argument(
- "--transition",
- default=None,
- choices=[*NATIVE_TRANSITION_KEYS, *LEGACY_TRANSITION_KEYS, "none"],
- help=(
- "replace the saved global PowerPoint-native effect; omitted values "
- "preserve the current plan"
- ),
- )
- plan.add_argument(
- "--transition-duration",
- type=_positive_seconds_arg,
- default=None,
- )
- plan.add_argument(
- "--narration-padding",
- type=_non_negative_seconds_arg,
- default=None,
- )
- plan.add_argument(
- "--narration-start-floor",
- type=_non_negative_seconds_arg,
- default=None,
- help="replace the saved narration start floor; omitted values preserve it",
- )
- plan.add_argument(
- "--apply-transition-without-audio",
- action="store_true",
- default=None,
- help=(
- "when audio is enabled, include page transitions for slides "
- "without audio"
- ),
- )
- plan.set_defaults(func=plan_project)
-
- apply = subparsers.add_parser(
- "apply",
- help="patch confirmed notes/audio/timings/transitions into a copied PPTX",
- )
- apply.add_argument("project_path", help="native enhancement project directory")
- apply.add_argument("-o", "--output", default=None, help="output .pptx path")
- apply.add_argument("--overwrite", action="store_true", help="overwrite output if it exists")
- apply.add_argument(
- "--transition",
- default=None,
- choices=[*NATIVE_TRANSITION_KEYS, *LEGACY_TRANSITION_KEYS, "none"],
- help="PowerPoint-native effect; old names are compatibility inputs",
- )
- apply.add_argument("--transition-duration", type=_positive_seconds_arg, default=None)
- apply.add_argument("--narration-padding", type=_non_negative_seconds_arg, default=None)
- apply.add_argument(
- "--narration-start-floor",
- type=_non_negative_seconds_arg,
- default=None,
- help="override the confirmed narration start floor for this export",
- )
- apply.add_argument("--force", action="store_true", help="apply without a confirmed enhancement plan")
- apply.add_argument(
- "--apply-transition-without-audio",
- action="store_true",
- help=(
- "when audio is enabled, also write page transitions on slides "
- "without audio"
- ),
- )
- apply.set_defaults(func=apply_project)
-
- validate = subparsers.add_parser(
- "validate",
- help="check source integrity, plan semantics, and material readiness",
- )
- validate.add_argument("project_path", help="native enhancement project directory")
- validate.add_argument(
- "--materials",
- choices=("all", "notes"),
- default="all",
- help=(
- "required material scope: all enabled modules, or notes only "
- "before narration audio exists (default: all)"
- ),
- )
- validate.set_defaults(func=validate_project)
- return parser
-
-
-def _record_preflight_exception(
- args: argparse.Namespace,
- exc: Exception,
-) -> None:
- command = str(args.command)
- try:
- project_path = Path(args.project_path).expanduser().resolve()
- project = _read_json(project_path / "project.json")
- except (OSError, ValueError, KeyError, json.JSONDecodeError) as project_exc:
- if (
- project_path.is_dir()
- and (project_path / "validation").is_dir()
- ):
- try:
- _write_preflight_report(
- project_path,
- {},
- set(),
- status="failed",
- errors=[f"{command} aborted: {exc}"],
- project_errors=[
- f"unable to read project.json: {project_exc}"
- ],
- )
- except OSError:
- pass
- return
- if project.get("schema") not in {
- PROJECT_SCHEMA,
- *LEGACY_PROJECT_SCHEMAS,
- }:
- return
- plan_errors: list[str] = []
- try:
- plan = _load_enhancement_plan(project_path)
- except (OSError, ValueError, json.JSONDecodeError) as plan_exc:
- plan = {}
- plan_errors.append(f"unable to read enhancement plan: {plan_exc}")
- try:
- _write_preflight_report(
- project_path,
- plan,
- set() if plan_errors else _enabled_modules(plan),
- status="failed",
- errors=[f"{command} aborted: {exc}"],
- plan_errors=plan_errors,
- )
- except OSError:
- return
-
-
-def main(argv: list[str] | None = None) -> int:
- require_skill_integrity()
- parser = build_parser()
- args = parser.parse_args(argv)
- try:
- return args.func(args)
- except (
- OSError,
- RuntimeError,
- ValueError,
- zipfile.BadZipFile,
- ET.ParseError,
- ) as exc:
- if args.command in {"apply", "validate"}:
- _record_preflight_exception(args, exc)
- print(f"error: {exc}", file=sys.stderr)
- return 1
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/native_narration_pptx.py b/skills/ppt-master/scripts/native_narration_pptx.py
deleted file mode 100644
index e9d0c604..00000000
--- a/skills/ppt-master/scripts/native_narration_pptx.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env python3
-"""
-PPT Master - Native Narration PPTX Compatibility Entrypoint
-
-Backward-compatible CLI for callers that still use the retired narration
-script name. New calls use native_enhance_pptx.py.
-
-Usage:
- python3 scripts/native_narration_pptx.py init <source.pptx> [--name project_name]
- python3 scripts/native_narration_pptx.py plan <project_path>
- python3 scripts/native_narration_pptx.py validate <project_path>
- python3 scripts/native_narration_pptx.py apply <project_path>
-
-Examples:
- python3 scripts/native_narration_pptx.py validate projects/native_enhance_project
-
-Dependencies:
- Same as native_enhance_pptx_core.py.
-"""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-_SCRIPTS_DIR = Path(__file__).resolve().parent
-if str(_SCRIPTS_DIR) not in sys.path:
- sys.path.insert(0, str(_SCRIPTS_DIR))
-
-from console_encoding import configure_utf8_stdio # noqa: E402
-from native_enhance_pptx_core import main # noqa: E402
-
-configure_utf8_stdio()
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/notes_to_audio.py b/skills/ppt-master/scripts/notes_to_audio.py
index e75353c5..8d38d9fa 100644
--- a/skills/ppt-master/scripts/notes_to_audio.py
+++ b/skills/ppt-master/scripts/notes_to_audio.py
@@ -38,8 +38,13 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
+import authoring_roundtrip
from console_encoding import configure_utf8_stdio
from config import load_prefixed_env_file
+from pptx_workspace import (
+ AUTHORING_SVG_FLAT_DIR,
+ ROUNDTRIP_MANIFEST_PATH,
+)
from slide_roster import discover_slide_svgs
from tts_backends import (
backend_cosyvoice,
@@ -137,7 +142,11 @@ def _prepare_audio_jobs(
def _expected_note_roster(project: Path) -> list[NoteRosterEntry]:
- """Resolve the owning route's complete per-slide notes roster."""
+ """Resolve the owning route's complete per-slide notes roster.
+
+ Round-trip workspaces follow their validated page plan or identity roster,
+ including source-note inheritance for copied output pages.
+ """
notes_dir = project / "notes"
svg_files = discover_slide_svgs(project / "svg_output")
if svg_files:
@@ -204,6 +213,43 @@ def _expected_note_roster(project: Path) -> list[NoteRosterEntry]:
)
return note_roster
+ roundtrip_manifest_path = project / ROUNDTRIP_MANIFEST_PATH
+ authoring_dir = project / AUTHORING_SVG_FLAT_DIR
+ if roundtrip_manifest_path.is_file() and authoring_dir.is_dir():
+ try:
+ _, _, documents, _, _ = authoring_roundtrip._load_documents(
+ project.resolve(),
+ authoring_dir.resolve(),
+ )
+ pages, _ = authoring_roundtrip._load_page_plan(
+ project.resolve(),
+ authoring_dir.resolve(),
+ documents,
+ )
+ except authoring_roundtrip.AuthoringRoundtripError as exc:
+ raise ValueError(f"invalid round-trip notes roster: {exc}") from exc
+
+ note_roster: list[NoteRosterEntry] = []
+ missing_stems: list[str] = []
+ for page in pages:
+ note_path = notes_dir / f"{page.svg_stem}.md"
+ if not note_path.is_file() and page.svg_name != page.source_svg_name:
+ source_stem = Path(page.source_svg_name).stem
+ note_path = notes_dir / f"{source_stem}.md"
+ if not note_path.is_file():
+ missing_stems.append(page.svg_stem)
+ continue
+ note_roster.append(NoteRosterEntry(
+ note_path=note_path,
+ output_stem=page.svg_stem,
+ ))
+ if missing_stems:
+ raise ValueError(
+ "round-trip per-slide notes are incomplete; missing stems: "
+ + ", ".join(missing_stems)
+ )
+ return note_roster
+
return [
NoteRosterEntry(
note_path=path,
diff --git a/skills/ppt-master/scripts/pptx_intake.py b/skills/ppt-master/scripts/pptx_intake.py
index 63610b03..42747d83 100644
--- a/skills/ppt-master/scripts/pptx_intake.py
+++ b/skills/ppt-master/scripts/pptx_intake.py
@@ -44,7 +44,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
from console_encoding import configure_utf8_stdio # noqa: E402
from beautify_identity import extract_identity # noqa: E402
-from template_fill_pptx.analyzer import analyze_pptx # noqa: E402
+from pptx_ooxml.analyzer import analyze_pptx # noqa: E402
configure_utf8_stdio()
@@ -182,16 +182,12 @@ def build_source_profile(
"standard_generation": (
"Use identity and slide-library fields as source facts and recommendation "
"candidates only; do not preserve original page count, order, or coordinates "
- "unless the user selected the beautify profile or Fill Native PPTX route."
+ "unless the user selected the beautify profile."
),
"beautify": (
"Promote source text, page order, page count, colors, fonts, and font sizes "
"into locked constraints after user confirmation."
),
- "template_fill": (
- "Use slide slots, tables, charts, diagrams, and geometry as the native PPTX "
- "fill contract; diagrams are inventory-only and remain unchanged."
- ),
},
"artifacts": {
"identity": f"{stem}.identity.json",
diff --git a/skills/ppt-master/scripts/pptx_ooxml/__init__.py b/skills/ppt-master/scripts/pptx_ooxml/__init__.py
new file mode 100644
index 00000000..6b8adfc5
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_ooxml/__init__.py
@@ -0,0 +1,20 @@
+"""Reusable OOXML readers and source-preserving package primitives."""
+
+from __future__ import annotations
+
+from .analyzer import analyze_pptx
+from .chart_read import empty_chart_data, read_chart_data
+from .clone import clone_presentation_slides, deep_clone_slide_private_parts
+from .diagram_read import read_smartart_diagrams, smartart_to_markdown
+from .package import prune_unreferenced_directory_parts
+
+__all__ = [
+ "analyze_pptx",
+ "clone_presentation_slides",
+ "deep_clone_slide_private_parts",
+ "empty_chart_data",
+ "prune_unreferenced_directory_parts",
+ "read_chart_data",
+ "read_smartart_diagrams",
+ "smartart_to_markdown",
+]
diff --git a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py b/skills/ppt-master/scripts/pptx_ooxml/analyzer.py
similarity index 86%
rename from skills/ppt-master/scripts/template_fill_pptx/analyzer.py
rename to skills/ppt-master/scripts/pptx_ooxml/analyzer.py
index 9d8860d2..d87ce30b 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/analyzer.py
@@ -103,14 +103,14 @@ def _analyze_charts(zf: zipfile.ZipFile, slide_root: ET.Element, slide_ref: Slid
payload["plot_types"] = ["chartEx"]
payload["edit_capability"] = _unsupported_chart_capability(
"chart_edit_chartex_unsupported",
- "template-fill chart edits do not support ChartEx",
+ "OOXML chart edits do not support ChartEx",
)
charts.append(payload)
continue
if chart_kind != "classic":
payload["edit_capability"] = _unsupported_chart_capability(
"chart_edit_plot_type_unsupported",
- "template-fill chart edits require a classic DrawingML chart reference",
+ "OOXML chart edits require a classic DrawingML chart reference",
)
charts.append(payload)
continue
@@ -126,12 +126,12 @@ def _analyze_charts(zf: zipfile.ZipFile, slide_root: ET.Element, slide_ref: Slid
payload.update(empty_chart_data())
payload["edit_capability"] = _unsupported_chart_capability(
"chart_edit_part_unavailable",
- "template-fill could not read the classic chart part",
+ "PPTX intake could not read the classic chart part",
)
else:
payload["edit_capability"] = _unsupported_chart_capability(
"chart_edit_relationship_unsupported",
- "template-fill chart edits require a classic chart relationship",
+ "OOXML chart edits require a classic chart relationship",
)
charts.append(payload)
return charts
@@ -205,10 +205,10 @@ def _fill_risk(
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.
+ """Return a fill-risk descriptor for non-text content needing explicit edits.
- 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.
+ Tables and charts may be covered by explicit edits. SmartArt is
+ inventory-only, so source text may remain visible in preserved objects.
"""
kinds: list[str] = []
if tables:
@@ -234,7 +234,7 @@ def _fill_risk(
def analyze_pptx(pptx_path: Path) -> dict[str, Any]:
- """Extract a slide library with text replacement slots."""
+ """Extract a slide library with text, geometry, and native-object facts."""
with zipfile.ZipFile(pptx_path) as zf:
pres_root = _read_xml(zf, "ppt/presentation.xml")
slide_refs = _parse_slide_refs(zf)
@@ -294,37 +294,9 @@ def analyze_pptx(pptx_path: Path) -> dict[str, Any]:
slides.append(slide)
return {
- "schema": "template_fill_pptx_library.v1",
+ "schema": "pptx_intake_slide_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/chart_read.py b/skills/ppt-master/scripts/pptx_ooxml/chart_read.py
similarity index 92%
rename from skills/ppt-master/scripts/template_fill_pptx/chart_read.py
rename to skills/ppt-master/scripts/pptx_ooxml/chart_read.py
index e3d9e65c..59047be7 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/chart_read.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/chart_read.py
@@ -1,8 +1,7 @@
-"""Read native PowerPoint chart display caches for slide-library analysis.
+"""Read native PowerPoint chart display caches for PPTX intake.
-The template-fill workflow edits chart data from explicit fill plans. This
-module only reads the data currently visible in a chart XML part, keeping
-workbook parsing out of the analyzer.
+This module reads the data currently visible in a chart XML part while keeping
+workbook parsing out of the slide-library analyzer.
"""
from __future__ import annotations
diff --git a/skills/ppt-master/scripts/template_fill_pptx/clone.py b/skills/ppt-master/scripts/pptx_ooxml/clone.py
similarity index 65%
rename from skills/ppt-master/scripts/template_fill_pptx/clone.py
rename to skills/ppt-master/scripts/pptx_ooxml/clone.py
index f8eb521c..5dfcecc2 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/clone.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/clone.py
@@ -1,49 +1,49 @@
-"""apply: deep-clone a cloned slide's structured private dependency parts.
+"""Clone a page-plan slide and its 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
+When the same source slide is reused for several output slides, 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.
+This helper gives each cloned slide its own copy of every private dependency and
+rewrites the relationship targets. Cloning is recursive, so a private part's
+own 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, for template-fill callers, 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. Deck-level
- round-trip cloning opts embeddings and model3d parts into private cloning.
-
-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.
+* **Media blobs** — targets under ``ppt/media/`` remain shared. Embeddings,
+ model3d, customXml, tags, comments, ink, notes, charts, diagrams, and their
+ dependency graphs remain private even when a ``Default`` extension rule
+ supplies their content type.
+
+Slide relationships are remapped separately after the final page roster is
+known, so recursive private-part cloning skips only that back-reference type.
"""
from __future__ import annotations
import copy
import posixpath
-import re
+import tempfile
import zipfile
from pathlib import Path
from typing import Callable
+from xml.parsers import expat
from xml.etree import ElementTree as ET
from hyperlink_contract import SLIDE_JUMP_ACTION
+from pptx_opc_validation import (
+ canonical_opc_part_path,
+ resolve_internal_opc_target,
+ verify_internal_relationships,
+)
from .ooxml import (
- CHART_REL_TYPE,
CT_NS,
NS,
- NOTES_SLIDE_REL_TYPE,
+ NOTES_SLIDE_CONTENT_TYPE,
REL_NS,
SLIDE_REL_TYPE,
SlideRef,
@@ -69,11 +69,11 @@ _REL_TYPE_BASE = "http://schemas.openxmlformats.org/officeDocument/2006/relation
# ``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")
+ for name in ("slideLayout", "slideMaster", "notesMaster", "theme")
)
-# 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})
+# Slide relationships are remapped against the complete page plan separately.
+SKIPPED_REL_TYPES = frozenset({SLIDE_REL_TYPE})
def _make_part_allocator(entries: dict[str, bytes]) -> Callable[[str], str]:
@@ -99,11 +99,7 @@ def _make_part_allocator(entries: dict[str, bytes]) -> Callable[[str], str]:
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.
- """
+ """Return the part's explicit content-type ``Override``, or ``None``."""
part_pn = "/" + part.lstrip("/")
for override in content_root.findall(_qn(CT_NS, "Override")):
if override.attrib.get("PartName") == part_pn:
@@ -111,6 +107,28 @@ def _override_content_type(content_root: ET.Element, part: str) -> str | None:
return None
+def _part_content_type(content_root: ET.Element, part: str) -> str | None:
+ override = _override_content_type(content_root, part)
+ if override is not None:
+ return override
+ extension = posixpath.splitext(part)[1].lstrip(".").lower()
+ if not extension:
+ return None
+ for default in content_root.findall(_qn(CT_NS, "Default")):
+ if (default.attrib.get("Extension") or "").lower() == extension:
+ return default.attrib.get("ContentType")
+ return None
+
+
+def _part_is_xml(content_root: ET.Element, part: str) -> bool:
+ content_type = (_part_content_type(content_root, part) or "").lower()
+ return (
+ content_type.endswith("+xml")
+ or content_type in {"application/xml", "text/xml"}
+ or posixpath.splitext(part)[1].lower() in {".xml", ".vml"}
+ )
+
+
def _is_shared(rel_type: str | None) -> bool:
return bool(rel_type) and rel_type in SHARED_REL_TYPES
@@ -124,8 +142,6 @@ def _clone_part_private_deps(
allocate: Callable[[str], str],
cloned: dict[str, str],
skipped_rel_types: frozenset[str],
- clone_default_part_prefixes: tuple[str, ...],
- back_references: dict[str, str],
) -> None:
"""Rewrite ``rels_root`` in place, cloning each private target it references.
@@ -133,30 +149,25 @@ def _clone_part_private_deps(
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":
+ if (rel.attrib.get("TargetMode") or "").strip().lower() == "external":
continue
rel_type = rel.attrib.get("Type")
target = rel.attrib.get("Target")
if not target:
- continue
+ raise RuntimeError(
+ f"{owner_part} relationship {rel.attrib.get('Id')!r} has no Target"
+ )
source_part = _normalize_part(target, owner_part)
- back_reference = back_references.get(source_part)
- if rel_type == SLIDE_REL_TYPE and back_reference is not None:
- rel.set("Target", _relative_target(owner_part, back_reference))
- continue
+ if source_part not in entries:
+ raise RuntimeError(
+ f"{owner_part} relationship {rel.attrib.get('Id')!r} targets "
+ f"missing part {source_part}"
+ )
if _is_shared(rel_type) or rel_type in skipped_rel_types:
continue
- if source_part not in entries:
+ if source_part.startswith("ppt/media/"):
continue
content_type = _override_content_type(content_root, source_part)
- clone_default_part = any(
- source_part.startswith(prefix)
- for prefix in clone_default_part_prefixes
- )
- if content_type is None and not clone_default_part:
- # 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:
@@ -166,9 +177,15 @@ def _clone_part_private_deps(
if content_type is not None:
_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)
+ sub_rels_name = _rels_name_for_part(source_part)
+ sub_rels_data = entries.get(sub_rels_name)
+ if sub_rels_data is not None:
+ try:
+ sub_rels_root = ET.fromstring(sub_rels_data)
+ except ET.ParseError as exc:
+ raise RuntimeError(
+ f"Cannot parse relationships part {sub_rels_name}: {exc}"
+ ) from exc
_clone_part_private_deps(
sub_rels_root,
owner_part=new_part,
@@ -177,8 +194,6 @@ def _clone_part_private_deps(
allocate=allocate,
cloned=cloned,
skipped_rel_types=skipped_rel_types,
- clone_default_part_prefixes=clone_default_part_prefixes,
- back_references=back_references,
)
entries[_rels_name_for_part(new_part)] = _xml_bytes(sub_rels_root)
@@ -193,26 +208,25 @@ def deep_clone_slide_private_parts(
content_root: ET.Element,
allocate: Callable[[str], str],
skipped_rel_types: frozenset[str] = SKIPPED_REL_TYPES,
- clone_default_part_prefixes: tuple[str, ...] = (),
- back_references: dict[str, str] | None = None,
-) -> None:
+) -> dict[str, str]:
"""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.
+ every slide in the run so minted names never collide. Returns the complete
+ source-part to clone-part map for this output slide.
"""
+ cloned: dict[str, str] = {}
_clone_part_private_deps(
slide_rels_root,
owner_part=new_slide_part,
entries=entries,
content_root=content_root,
allocate=allocate,
- cloned={},
+ cloned=cloned,
skipped_rel_types=skipped_rel_types,
- clone_default_part_prefixes=clone_default_part_prefixes,
- back_references=back_references or {},
)
+ return cloned
_SLIDE_LAYOUT_REL_TYPE = (
@@ -223,15 +237,28 @@ _SLIDE_MASTER_REL_TYPE = (
)
-def _slide_jump_relationship_ids(part_root: ET.Element) -> set[str]:
- """Return relationship ids used by actual same-deck click actions."""
+def _slide_jump_relationship_ids(
+ part_root: ET.Element,
+ *,
+ owner_label: str,
+) -> set[str]:
+ """Return relationship ids used by same-deck click or mouse-over actions."""
relationship_attr = _qn(NS["r"], "id")
- return {
- relationship_id
- for link in part_root.iter(_qn(NS["a"], "hlinkClick"))
- if (link.attrib.get("action") or "").strip() == SLIDE_JUMP_ACTION
- if (relationship_id := (link.attrib.get(relationship_attr) or "").strip())
- }
+ relationship_ids: set[str] = set()
+ for tag in ("hlinkClick", "hlinkMouseOver"):
+ for link in part_root.iter(_qn(NS["a"], tag)):
+ if (link.attrib.get("action") or "").strip() != SLIDE_JUMP_ACTION:
+ continue
+ relationship_id = (
+ link.attrib.get(relationship_attr) or ""
+ ).strip()
+ if not relationship_id:
+ raise RuntimeError(
+ f"{owner_label} has a {tag} slide jump without a "
+ "relationship id"
+ )
+ relationship_ids.add(relationship_id)
+ return relationship_ids
def _remap_slide_jump_relationships(
@@ -246,9 +273,13 @@ def _remap_slide_jump_relationships(
self_source_part: str | None = None,
self_output_part: str | None = None,
fail_on_non_jump_slide_relationships: bool = False,
+ allow_self_non_jump_retarget: bool = False,
) -> bool:
"""Point referenced slide-jump relationships at final output slides."""
- relationship_ids = _slide_jump_relationship_ids(part_root)
+ relationship_ids = _slide_jump_relationship_ids(
+ part_root,
+ owner_label=owner_label,
+ )
relationships = {
rel.attrib.get("Id", ""): rel
for rel in relationships_root.findall(_qn(REL_NS, "Relationship"))
@@ -266,7 +297,7 @@ def _remap_slide_jump_relationships(
f"{owner_label} slide jump {relationship_id!r} does not use "
"a slide relationship"
)
- if rel.attrib.get("TargetMode") == "External":
+ if (rel.attrib.get("TargetMode") or "").strip().lower() == "external":
raise RuntimeError(
f"{owner_label} has an external slide relationship"
)
@@ -313,7 +344,7 @@ def _remap_slide_jump_relationships(
or rel.attrib.get("Type") != SLIDE_REL_TYPE
):
continue
- if rel.attrib.get("TargetMode") == "External":
+ if (rel.attrib.get("TargetMode") or "").strip().lower() == "external":
raise RuntimeError(
f"{owner_label} has external non-jump slide relationship "
f"{relationship_id!r}; page-plan export refuses slide "
@@ -332,11 +363,12 @@ def _remap_slide_jump_relationships(
if source_target_ref is not None
else source_target_part
)
- if (
+ is_self_target = (
self_source_part is not None
and self_output_part is not None
and source_target_part == self_source_part
- ):
+ )
+ if is_self_target:
output_targets = [self_output_part]
else:
output_targets = outputs_by_source_part.get(
@@ -361,6 +393,10 @@ def _remap_slide_jump_relationships(
output_targets[0],
)
if rel.attrib.get("Target") != output_target:
+ if is_self_target and allow_self_non_jump_retarget:
+ rel.set("Target", output_target)
+ changed = True
+ continue
raise RuntimeError(
f"{owner_label} has non-jump slide relationship "
f"{relationship_id!r} to {target_label} that would require "
@@ -427,6 +463,99 @@ def _remap_reachable_shared_layer_slide_jumps(
pending.append(_normalize_part(target, part_name))
+def _remap_cloned_xml_part_slide_jumps(
+ entries: dict[str, bytes],
+ cloned_parts: dict[str, str],
+ content_root: ET.Element,
+ *,
+ output_part: str,
+ outputs_by_source_part: dict[str, list[str]],
+ source_ref_by_part: dict[str, SlideRef],
+ source_slide_part: str,
+) -> None:
+ """Validate and remap slide links in every cloned XML dependency."""
+ for source_part, cloned_part in sorted(cloned_parts.items()):
+ if not _part_is_xml(content_root, cloned_part):
+ continue
+ try:
+ part_root = ET.fromstring(entries[cloned_part])
+ except ET.ParseError as exc:
+ raise RuntimeError(
+ f"Cannot parse cloned XML part {cloned_part}: {exc}"
+ ) from exc
+ rels_name = _rels_name_for_part(cloned_part)
+ rels_data = entries.get(rels_name)
+ if rels_data is None:
+ rels_root = _empty_relationships_root()
+ else:
+ try:
+ rels_root = ET.fromstring(rels_data)
+ except ET.ParseError as exc:
+ raise RuntimeError(
+ f"Cannot parse relationships part {rels_name}: {exc}"
+ ) from exc
+ changed = _remap_slide_jump_relationships(
+ part_root,
+ rels_root,
+ source_owner_part=source_part,
+ output_owner_part=cloned_part,
+ owner_label=f"Cloned part {cloned_part}",
+ outputs_by_source_part=outputs_by_source_part,
+ source_ref_by_part=source_ref_by_part,
+ self_source_part=source_slide_part,
+ self_output_part=output_part,
+ fail_on_non_jump_slide_relationships=True,
+ allow_self_non_jump_retarget=(
+ _part_content_type(content_root, cloned_part)
+ == NOTES_SLIDE_CONTENT_TYPE
+ ),
+ )
+ if changed:
+ if rels_data is None:
+ raise RuntimeError(
+ f"Cloned part {cloned_part} changed a missing relationship part"
+ )
+ entries[rels_name] = _xml_bytes(rels_root)
+
+
+def _validate_internal_relationship_targets(entries: dict[str, bytes]) -> None:
+ """Fail before cloning when any internal relationship target is absent."""
+ canonical_parts = {
+ canonical
+ for part_name in entries
+ if (canonical := canonical_opc_part_path(part_name)) is not None
+ }
+ for rels_name in sorted(
+ name for name in entries if name.endswith(".rels")
+ ):
+ try:
+ rels_root = ET.fromstring(entries[rels_name])
+ except ET.ParseError as exc:
+ raise RuntimeError(
+ f"Cannot parse relationships part {rels_name}: {exc}"
+ ) from exc
+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):
+ if (rel.attrib.get("TargetMode") or "").strip().lower() == "external":
+ continue
+ target = (rel.attrib.get("Target") or "").strip()
+ if not target:
+ raise RuntimeError(
+ f"{rels_name} relationship {rel.attrib.get('Id')!r} "
+ "has no Target"
+ )
+ resolved = resolve_internal_opc_target(rels_name, target)
+ if resolved is None:
+ raise RuntimeError(
+ f"{rels_name} relationship {rel.attrib.get('Id')!r} has "
+ f"invalid Target {target!r}"
+ )
+ if resolved not in canonical_parts:
+ raise RuntimeError(
+ f"{rels_name} relationship {rel.attrib.get('Id')!r} targets "
+ f"missing part {resolved}"
+ )
+
+
def _remove_stale_slide_order_metadata(presentation_root: ET.Element) -> None:
"""Drop source-only custom-show and section rosters after page planning."""
custom_shows = presentation_root.find("p:custShowLst", NS)
@@ -447,16 +576,74 @@ def _update_app_slide_count(entries: dict[str, bytes], slide_count: int) -> None
payload = entries.get(app_part)
if payload is None:
return
+
+ declaration: dict[str, object] = {
+ "seen": False,
+ "encoding": None,
+ }
+
+ def xml_decl(
+ _version: str,
+ encoding: str | None,
+ _standalone: int,
+ ) -> None:
+ declaration["seen"] = True
+ declaration["encoding"] = encoding
+
+ declaration_parser = expat.ParserCreate()
+ declaration_parser.XmlDeclHandler = xml_decl
try:
- text = payload.decode("utf-8")
- except UnicodeDecodeError:
+ declaration_parser.Parse(payload, True)
+ root = ET.fromstring(payload)
+ except (expat.ExpatError, ET.ParseError) as exc:
+ raise RuntimeError(f"Cannot parse {app_part}: {exc}") from exc
+ slides = next(
+ (
+ element
+ for element in root.iter()
+ if isinstance(element.tag, str)
+ and element.tag.rsplit("}", 1)[-1] == "Slides"
+ ),
+ None,
+ )
+ if slides is None:
return
- entries[app_part] = re.sub(
- r"<Slides>.*?</Slides>",
- f"<Slides>{slide_count}</Slides>",
- text,
- count=1,
- ).encode("utf-8")
+ slides.text = str(slide_count)
+ encoding = declaration["encoding"]
+ entries[app_part] = ET.tostring(
+ root,
+ encoding=str(encoding or "utf-8"),
+ xml_declaration=bool(declaration["seen"]),
+ )
+
+
+def _verify_entries_before_zip(
+ entries: dict[str, bytes],
+ output_path: Path,
+) -> None:
+ """Run the shared OPC verifier before publishing the cloned ZIP."""
+ with tempfile.TemporaryDirectory(
+ prefix=".pptx-clone-verify-",
+ dir=output_path.parent,
+ ) as temporary:
+ extract_dir = Path(temporary)
+ for part_name, payload in entries.items():
+ part_path = (extract_dir / part_name).resolve()
+ try:
+ part_path.relative_to(extract_dir.resolve())
+ except ValueError as exc:
+ raise RuntimeError(
+ f"PPTX package part escapes the archive root: {part_name!r}"
+ ) from exc
+ part_path.parent.mkdir(parents=True, exist_ok=True)
+ part_path.write_bytes(payload)
+ problems = verify_internal_relationships(extract_dir)
+ if problems:
+ preview = "; ".join(problems[:8])
+ suffix = "" if len(problems) <= 8 else f"; +{len(problems) - 8} more"
+ raise RuntimeError(
+ f"Cloned PPTX package has invalid relationships: {preview}{suffix}"
+ )
def clone_presentation_slides(
@@ -470,7 +657,7 @@ def clone_presentation_slides(
Structured private dependencies, including notes, charts, diagrams, and
embeddings, are cloned per output page. Shared layout/master/theme parts and
- ordinary media remain shared. Same-deck hyperlinks use the template-fill
+ ordinary media remain shared. Same-deck hyperlinks use the page-plan
omitted/ambiguous destination contract.
"""
if not source_slides:
@@ -491,6 +678,7 @@ def clone_presentation_slides(
f"Round-trip resource override names a missing source part: {part_name}"
)
entries[part_name] = payload
+ _validate_internal_relationship_targets(entries)
missing = sorted(set(source_slides) - set(slide_refs))
if missing:
@@ -538,7 +726,6 @@ def clone_presentation_slides(
outputs_by_source_part.setdefault(source_ref.part_name, []).append(
output_part
)
-
source_entries = dict(entries)
for output_index, source_index in enumerate(source_slides, start=1):
source_ref = slide_refs[source_index]
@@ -563,18 +750,22 @@ def clone_presentation_slides(
self_output_part=output_part,
fail_on_non_jump_slide_relationships=True,
)
- deep_clone_slide_private_parts(
+ cloned_parts = deep_clone_slide_private_parts(
relationships_root,
new_slide_part=output_part,
entries=entries,
content_root=content_root,
allocate=allocate,
skipped_rel_types=frozenset({SLIDE_REL_TYPE}),
- clone_default_part_prefixes=(
- "ppt/embeddings/",
- "ppt/model3d/",
- ),
- back_references={source_ref.part_name: output_part},
+ )
+ _remap_cloned_xml_part_slide_jumps(
+ entries,
+ cloned_parts,
+ content_root,
+ output_part=output_part,
+ outputs_by_source_part=outputs_by_source_part,
+ source_ref_by_part=source_ref_by_part,
+ source_slide_part=source_ref.part_name,
)
entries[output_part] = source_slide_xml
entries[output_rels] = _xml_bytes(relationships_root)
@@ -616,6 +807,7 @@ def clone_presentation_slides(
_update_app_slide_count(entries, len(source_slides))
output_path.parent.mkdir(parents=True, exist_ok=True)
+ _verify_entries_before_zip(entries, output_path)
with zipfile.ZipFile(
output_path,
"w",
diff --git a/skills/ppt-master/scripts/template_fill_pptx/diagram_read.py b/skills/ppt-master/scripts/pptx_ooxml/diagram_read.py
similarity index 100%
rename from skills/ppt-master/scripts/template_fill_pptx/diagram_read.py
rename to skills/ppt-master/scripts/pptx_ooxml/diagram_read.py
diff --git a/skills/ppt-master/scripts/template_fill_pptx/edit_safety.py b/skills/ppt-master/scripts/pptx_ooxml/edit_safety.py
similarity index 90%
rename from skills/ppt-master/scripts/template_fill_pptx/edit_safety.py
rename to skills/ppt-master/scripts/pptx_ooxml/edit_safety.py
index e3146910..c372e5c6 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/edit_safety.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/edit_safety.py
@@ -1,4 +1,4 @@
-"""Classify template-fill chart and table edits before package mutation."""
+"""Classify supported chart and table edits before package mutation."""
from __future__ import annotations
@@ -78,19 +78,19 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if "chartex" in root_namespace.lower():
return _unsupported_chart_capability(
"chart_edit_chartex_unsupported",
- "template-fill chart edits do not support ChartEx",
+ "OOXML chart edits do not support ChartEx",
)
if root_namespace != NS["c"]:
return _unsupported_chart_capability(
"chart_edit_plot_type_unsupported",
- "template-fill chart edits require a classic DrawingML chart part",
+ "OOXML chart edits require a classic DrawingML chart part",
)
plot_area = chart_root.find(".//c:plotArea", NS)
if plot_area is None:
return _unsupported_chart_capability(
"chart_edit_plot_type_unsupported",
- "template-fill chart edits require a classic chart plotArea",
+ "OOXML chart edits require a classic chart plotArea",
)
plot_nodes = [
@@ -101,13 +101,13 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if len(plot_nodes) > 1:
return _unsupported_chart_capability(
"chart_edit_multi_plot_unsupported",
- "template-fill chart edits do not support multi-plot or combination charts",
+ "OOXML chart edits do not support multi-plot or combination charts",
plot_count=len(plot_nodes),
)
if not plot_nodes:
return _unsupported_chart_capability(
"chart_edit_plot_type_unsupported",
- "template-fill chart edits require exactly one recognized chart plot",
+ "OOXML chart edits require exactly one recognized chart plot",
)
plot = plot_nodes[0]
@@ -115,7 +115,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if plot_type == "scatterChart":
return _unsupported_chart_capability(
"chart_edit_scatter_unsupported",
- "template-fill chart edits do not support scatter xVal/yVal data",
+ "OOXML chart edits do not support scatter xVal/yVal data",
plot_type=plot_type,
plot_count=1,
data_model="xy",
@@ -123,7 +123,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if plot_type == "bubbleChart":
return _unsupported_chart_capability(
"chart_edit_bubble_unsupported",
- "template-fill chart edits do not support bubble xVal/yVal/bubbleSize data",
+ "OOXML chart edits do not support bubble xVal/yVal/bubbleSize data",
plot_type=plot_type,
plot_count=1,
data_model="bubble",
@@ -132,7 +132,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if not series_nodes:
return _unsupported_chart_capability(
"chart_edit_no_series",
- "template-fill chart edits require at least one editable series",
+ "OOXML chart edits require at least one editable series",
plot_type=plot_type,
plot_count=1,
data_model="category",
@@ -144,7 +144,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
):
return _unsupported_chart_capability(
"chart_edit_data_model_unsupported",
- "template-fill chart edits require c:cat/c:val series",
+ "OOXML chart edits require c:cat/c:val series",
plot_type=plot_type,
plot_count=1,
)
@@ -153,7 +153,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
if category is None or values is None:
return _unsupported_chart_capability(
"chart_edit_data_model_unsupported",
- "template-fill chart edits require c:cat/c:val on every series",
+ "OOXML chart edits require c:cat/c:val on every series",
plot_type=plot_type,
plot_count=1,
)
@@ -163,7 +163,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
{
"code": "chart_edit_date_axis_flattened",
"message": (
- "template-fill will flatten date-axis categories to the "
+ "OOXML chart editing will flatten date-axis categories to the "
"replacement single-level category cache"
),
}
@@ -176,7 +176,7 @@ def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:
{
"code": "chart_edit_multilevel_categories_flattened",
"message": (
- "template-fill will flatten multi-level categories to the "
+ "OOXML chart editing will flatten multi-level categories to the "
"replacement single-level category cache"
),
}
diff --git a/skills/ppt-master/scripts/template_fill_pptx/ooxml.py b/skills/ppt-master/scripts/pptx_ooxml/ooxml.py
similarity index 99%
rename from skills/ppt-master/scripts/template_fill_pptx/ooxml.py
rename to skills/ppt-master/scripts/pptx_ooxml/ooxml.py
index 5dbdc6ec..b37c11eb 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/ooxml.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/ooxml.py
@@ -1,4 +1,4 @@
-"""Shared OOXML primitives for the template-fill pipeline.
+"""Shared OOXML primitives for PPTX intake and source-preserving export.
Read-side helpers only: namespaces and content-type constants, part /
relationship resolution, EMU unit conversion, slide-shape discovery, and small
diff --git a/skills/ppt-master/scripts/template_fill_pptx/package.py b/skills/ppt-master/scripts/pptx_ooxml/package.py
similarity index 80%
rename from skills/ppt-master/scripts/template_fill_pptx/package.py
rename to skills/ppt-master/scripts/pptx_ooxml/package.py
index 48d6b9ed..f76825b5 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/package.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/package.py
@@ -1,4 +1,4 @@
-"""Write-side OOXML package plumbing for the apply stage.
+"""Write-side OOXML package plumbing for source-preserving slide cloning.
Content-type override insertion, relationship-element construction / lookup, and
part-number allocation used when cloning slides into a new package.
@@ -13,8 +13,6 @@ from xml.etree import ElementTree as ET
from .ooxml import (
CT_NS,
- NOTES_SLIDE_CONTENT_TYPE,
- NS,
REL_NS,
SLIDE_CONTENT_TYPE,
_normalize_part,
@@ -46,35 +44,14 @@ 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")):
@@ -85,16 +62,6 @@ def _max_numeric_rid(root: ET.Element) -> int:
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,
@@ -102,14 +69,16 @@ def _enqueue_rel_targets(
queue: list[str],
) -> None:
data = entries.get(rels_part)
- if not data:
+ if data is None:
return
try:
root = ET.fromstring(data)
- except ET.ParseError:
- return
+ except ET.ParseError as exc:
+ raise RuntimeError(
+ f"Cannot parse relationships part {rels_part}: {exc}"
+ ) from exc
for rel in root.findall(_qn(REL_NS, "Relationship")):
- if rel.attrib.get("TargetMode") == "External":
+ if (rel.attrib.get("TargetMode") or "").strip().lower() == "external":
continue
target = rel.attrib.get("Target")
if target:
diff --git a/skills/ppt-master/scripts/pptx_transitions.py b/skills/ppt-master/scripts/pptx_transitions.py
index 348c2b3e..2850cf8a 100644
--- a/skills/ppt-master/scripts/pptx_transitions.py
+++ b/skills/ppt-master/scripts/pptx_transitions.py
@@ -3,8 +3,8 @@
PPT Master - PPTX Transition Core
Provide one strict PowerPoint-native transition registry, a compatibility input
-map, and shared OOXML read/write helpers for generated slides, template-filled
-PPTX files, and native PPTX enhancement.
+map, and shared OOXML read/write helpers for generated and source-preserving
+round-trip PPTX files.
See references/animations.md for the public workflow and
scripts/docs/pptx-transitions.md for the OOXML contract.
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index 3e3392b2..a94769b7 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -121,7 +121,7 @@
"max_tokens": 83000
},
"route.create-template.layout": {
- "description": "Create Layout standard/fidelity path through Template_Designer, the strategy-triggered native-shape bundle, SVG core, and the structured PPTX interface; mirror excludes the authored bundle.",
+ "description": "Create Layout standard/fidelity path through Template_Designer, the strategy-triggered native-shape bundle, SVG core, and the structured PPTX interface; mirror excludes the authored bundle. Ceiling raised after BUDGET_LOAD_SET reported 76053 tokens.",
"scope": "cumulative",
"include": [
"bootstrap.routing"
@@ -138,27 +138,16 @@
"skills/ppt-master/templates/README.md",
"skills/ppt-master/templates/layouts/README.md"
],
- "max_tokens": 76000
+ "max_tokens": 77000
},
- "route.enhance-native-pptx": {
- "description": "Finished-PPTX native enhancement route.",
+ "route.edit-native-pptx": {
+ "description": "Edit Native PPTX route: fill, edit, restructure, or enhance an existing deck through the source-preserving round-trip workspace.",
"scope": "cumulative",
"include": [
"bootstrap.routing"
],
"files": [
- "skills/ppt-master/workflows/native-enhance-pptx.md"
- ],
- "max_tokens": 13000
- },
- "route.fill-native-pptx": {
- "description": "Raw-PPTX native fill route.",
- "scope": "cumulative",
- "include": [
- "bootstrap.routing"
- ],
- "files": [
- "skills/ppt-master/workflows/template-fill-pptx.md"
+ "skills/ppt-master/workflows/edit-native-pptx.md"
],
"max_tokens": 14000
},
@@ -628,11 +617,44 @@
"files": [],
"max_tokens": 215000
},
- "route.enhance-native-pptx.audio": {
- "description": "Enhance Native PPTX with the shared narration-audio stage.",
+ "route.edit-native-pptx.edit": {
+ "description": "Edit Native PPTX with the always-loaded shared standards for page editing.",
+ "scope": "cumulative",
+ "include": [
+ "route.edit-native-pptx"
+ ],
+ "files": [
+ "skills/ppt-master/references/shared-standards-core.md"
+ ],
+ "max_tokens": 26000
+ },
+ "route.edit-native-pptx.edit-effects": {
+ "description": "Edit Native PPTX page editing that authors new visual elements.",
+ "scope": "cumulative",
+ "include": [
+ "route.edit-native-pptx.edit"
+ ],
+ "files": [
+ "skills/ppt-master/references/svg-effects.md"
+ ],
+ "max_tokens": 42000
+ },
+ "route.edit-native-pptx.edit-native-data": {
+ "description": "Edit Native PPTX page editing that changes native chart or table data.",
"scope": "cumulative",
"include": [
- "route.enhance-native-pptx",
+ "route.edit-native-pptx.edit"
+ ],
+ "files": [
+ "skills/ppt-master/references/native-data-interface.md"
+ ],
+ "max_tokens": 34000
+ },
+ "route.edit-native-pptx.audio": {
+ "description": "Edit Native PPTX with the shared narration-audio stage.",
+ "scope": "cumulative",
+ "include": [
+ "route.edit-native-pptx",
"stage.shared.generate-audio"
],
"files": [],
@@ -1534,14 +1556,9 @@
"to": "skills/ppt-master/workflows/create-template.md"
},
{
- "concern": "fill-native-pptx-workflow",
- "from": "skills/ppt-master/workflows/routing.md",
- "to": "skills/ppt-master/workflows/template-fill-pptx.md"
- },
- {
- "concern": "enhance-native-pptx-workflow",
+ "concern": "edit-native-pptx-workflow",
"from": "skills/ppt-master/workflows/routing.md",
- "to": "skills/ppt-master/workflows/native-enhance-pptx.md"
+ "to": "skills/ppt-master/workflows/edit-native-pptx.md"
},
{
"concern": "image-to-pptx-profile",
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 febd3e47..24622245 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
@@ -45,7 +45,7 @@ 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
+from pptx_ooxml.diagram_read import ( # noqa: E402
read_smartart_diagrams,
smartart_to_markdown,
)
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index 33a9acac..691dd847 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -52,6 +52,14 @@ from xml.etree import ElementTree as ET
from compact_svg_coordinates import compact_svg_tree
from console_encoding import configure_utf8_stdio
+from native_payloads import (
+ CUSTOM_GEOMETRY_ATTRIBUTE,
+ CUSTOM_GEOMETRY_REF_ATTRIBUTE,
+ NATIVE_RECORD_REF_ATTRIBUTE,
+ SHAPE_STYLE_ATTRIBUTE,
+ SHAPE_STYLE_REF_ATTRIBUTE,
+ TXBODY_REF_ATTRIBUTE,
+)
from pptx_shapes import (
NATIVE_FALLBACK_SHA256_ATTR,
svg_native_fallback_fingerprint,
@@ -139,6 +147,24 @@ AUTHORING_OMITTED_SOURCE_ATTRIBUTES = {
"data-pptx-shape-style",
}
+ADOPT_OBJECT_STRIPPED_ATTRIBUTES = frozenset(
+ AUTHORING_OMITTED_SOURCE_ATTRIBUTES
+ | {
+ SOURCE_REF_ATTRIBUTE,
+ SOURCE_PROXY_ATTRIBUTE,
+ NATIVE_RECORD_REF_ATTRIBUTE,
+ TXBODY_REF_ATTRIBUTE,
+ SHAPE_STYLE_ATTRIBUTE,
+ SHAPE_STYLE_REF_ATTRIBUTE,
+ CUSTOM_GEOMETRY_ATTRIBUTE,
+ CUSTOM_GEOMETRY_REF_ATTRIBUTE,
+ "data-pptx-encoding",
+ "data-pptx-ooxml-sha256",
+ "data-pptx-part",
+ "data-pptx-text-sha256",
+ }
+)
+
_TSPAN_INHERITED_ATTRIBUTES = frozenset({
"fill",
"fill-opacity",
@@ -1486,6 +1512,8 @@ def _authoring_document_kind(path: Path) -> str:
def _authoring_summary_document(
path: Path,
relative_name: str,
+ *,
+ source_slide: int | None = None,
) -> dict[str, object]:
try:
root = ET.parse(path).getroot()
@@ -1504,9 +1532,13 @@ def _authoring_summary_document(
element for element in elements
if _local_name(element.tag) == "text"
]
- return {
+ summary: dict[str, object] = {
"file": relative_name,
"kind": _authoring_document_kind(path),
+ }
+ if source_slide is not None:
+ summary["source_slide"] = source_slide
+ summary.update({
"bytes": path.stat().st_size,
"viewBox": root.get("viewBox"),
"elements": len(elements),
@@ -1549,12 +1581,13 @@ def _authoring_summary_document(
element.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND
for element in elements
),
- }
+ })
+ return summary
def _load_authoring_summary_manifest(
authoring_dir: Path,
-) -> tuple[dict[str, object], list[str]]:
+) -> tuple[dict[str, object], list[str], dict[str, int] | None]:
manifest_path = authoring_dir / AUTHORING_MANIFEST_NAME
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
@@ -1598,6 +1631,40 @@ def _load_authoring_summary_manifest(
if len(names) != len(set(names)):
raise ValueError("Authoring manifest contains duplicate document names")
+ from pptx_workspace import ROUNDTRIP_PAGE_PLAN_PATH
+
+ project_path = authoring_dir.parent
+ if (project_path / ROUNDTRIP_PAGE_PLAN_PATH).exists():
+ from authoring_roundtrip import (
+ AuthoringRoundtripError,
+ _load_documents,
+ _load_page_plan,
+ )
+
+ try:
+ _, _, roundtrip_documents, _, _ = _load_documents(
+ project_path,
+ authoring_dir,
+ )
+ pages, _ = _load_page_plan(
+ project_path,
+ authoring_dir,
+ roundtrip_documents,
+ )
+ except AuthoringRoundtripError as exc:
+ raise ValueError(
+ f"Cannot build page-plan-aware authoring summary: {exc}"
+ ) from exc
+ source_slides = {
+ name: document.source_slide
+ for name, document in roundtrip_documents.items()
+ }
+ source_slides.update({
+ page.svg_name: page.source_slide
+ for page in pages
+ })
+ return manifest, sorted(source_slides), source_slides
+
actual_names = sorted(
path.relative_to(authoring_dir).as_posix()
for path in authoring_dir.rglob("*.svg")
@@ -1607,13 +1674,25 @@ def _load_authoring_summary_manifest(
raise ValueError(
"Authoring manifest/file roster differs while building summary"
)
- return manifest, sorted(names)
+ return manifest, sorted(names), None
def _authoring_summary_bytes(authoring_dir: Path) -> bytes:
- manifest, document_names = _load_authoring_summary_manifest(authoring_dir)
+ (
+ manifest,
+ document_names,
+ source_slides,
+ ) = _load_authoring_summary_manifest(authoring_dir)
documents = [
- _authoring_summary_document(authoring_dir / name, name)
+ _authoring_summary_document(
+ authoring_dir / name,
+ name,
+ source_slide=(
+ source_slides[name]
+ if source_slides is not None
+ else None
+ ),
+ )
for name in document_names
]
total_icon_assets = {
@@ -1714,6 +1793,302 @@ def write_authoring_summary(authoring_dir: Path) -> Path:
return summary_path
+def _parse_adopt_source(value: str) -> tuple[str, str]:
+ match = re.fullmatch(r"([^/\\]+\.svg):(.+)", value, flags=re.IGNORECASE)
+ if match is None:
+ raise ValueError(
+ "--adopt-object must use <from.svg>:<element-id>"
+ )
+ source_name, element_id = match.groups()
+ if not element_id.strip() or element_id != element_id.strip():
+ raise ValueError("--adopt-object element id must be non-empty and trimmed")
+ return source_name, element_id
+
+
+def _authoring_page_path(
+ authoring_dir: Path,
+ name: str,
+ *,
+ label: str,
+) -> Path:
+ relative = Path(name)
+ if (
+ "/" in name
+ or "\\" in name
+ or relative.name != name
+ or relative.suffix.lower() != ".svg"
+ or name in {".", ".."}
+ ):
+ raise ValueError(f"{label} must name one SVG directly in {authoring_dir}")
+ path = (authoring_dir / name).resolve()
+ try:
+ path.relative_to(authoring_dir.resolve())
+ except ValueError as exc:
+ raise ValueError(f"{label} escapes the authoring directory: {name!r}") from exc
+ if not path.is_file():
+ raise ValueError(f"{label} does not exist: {path}")
+ return path
+
+
+def _parse_authoring_svg(path: Path) -> ET.Element:
+ parser = ET.XMLParser(
+ target=ET.TreeBuilder(insert_comments=True, insert_pis=True),
+ )
+ try:
+ root = ET.fromstring(path.read_bytes(), parser=parser)
+ except (OSError, ET.ParseError) as exc:
+ raise ValueError(f"Cannot parse authoring SVG {path}: {exc}") from exc
+ if _local_name(root.tag) != "svg":
+ raise ValueError(f"Authoring document root is not <svg>: {path}")
+ return root
+
+
+def _rewrite_adopted_fragment_ids(
+ element: ET.Element,
+ target_ids: set[str],
+) -> dict[str, str]:
+ subtree_ids = [
+ item_id
+ for item in element.iter()
+ if (item_id := item.get("id"))
+ ]
+ duplicates = sorted(
+ item_id
+ for item_id, count in Counter(subtree_ids).items()
+ if count > 1
+ )
+ if duplicates:
+ raise ValueError(
+ "Adopted subtree contains duplicate id(s): "
+ + ", ".join(duplicates[:8])
+ )
+
+ reserved = set(target_ids) | set(subtree_ids)
+ replacements: dict[str, str] = {}
+ for item_id in subtree_ids:
+ if item_id not in target_ids:
+ continue
+ base = f"{item_id}-adopted"
+ candidate = base
+ suffix = 2
+ while candidate in reserved:
+ candidate = f"{base}-{suffix}"
+ suffix += 1
+ replacements[item_id] = candidate
+ reserved.add(candidate)
+
+ if not replacements:
+ return replacements
+
+ def rewrite_url(match: re.Match[str]) -> str:
+ quote, ref_id = match.group(1), match.group(2)
+ return f"url({quote}#{replacements.get(ref_id, ref_id)}{quote})"
+
+ for item in element.iter():
+ item_id = item.get("id")
+ if item_id in replacements:
+ item.set("id", replacements[item_id])
+ for name, value in list(item.attrib.items()):
+ rewritten = _URL_ID_RE.sub(rewrite_url, value)
+ if _local_name(name) == "href" and value.startswith("#"):
+ rewritten = "#" + replacements.get(value[1:], value[1:])
+ if rewritten != value:
+ item.set(name, rewritten)
+ return replacements
+
+
+def _strip_adopted_transport(element: ET.Element) -> tuple[set[str], int]:
+ stripped: set[str] = set()
+ removed_metadata = 0
+
+ def visit(parent: ET.Element) -> None:
+ nonlocal removed_metadata
+ for child in list(parent):
+ original_part = child.get("data-pptx-part")
+ has_transport = any(
+ name in ADOPT_OBJECT_STRIPPED_ATTRIBUTES
+ for name in child.attrib
+ )
+ is_json_metadata = (
+ _local_name(child.tag) == "metadata"
+ and child.get("type") == "application/json"
+ )
+ if (
+ _local_name(child.tag) == "metadata"
+ and not is_json_metadata
+ and (original_part is not None or has_transport)
+ ):
+ stripped.update(
+ name
+ for name in child.attrib
+ if name in ADOPT_OBJECT_STRIPPED_ATTRIBUTES
+ )
+ parent.remove(child)
+ removed_metadata += 1
+ continue
+ visit(child)
+
+ visit(element)
+ for item in element.iter():
+ for name in list(item.attrib):
+ if name not in ADOPT_OBJECT_STRIPPED_ATTRIBUTES:
+ continue
+ stripped.add(name)
+ item.attrib.pop(name, None)
+ if item.get(SEMANTIC_OBJECT_ATTRIBUTE) == SEMANTIC_SHAPE_KIND:
+ stripped.add(SEMANTIC_OBJECT_ATTRIBUTE)
+ item.attrib.pop(SEMANTIC_OBJECT_ATTRIBUTE, None)
+ return stripped, removed_metadata
+
+
+def _write_svg_atomically(path: Path, root: ET.Element) -> None:
+ payload = _serialize_svg(root)
+ if not payload.endswith(b"\n"):
+ payload += b"\n"
+ with tempfile.NamedTemporaryFile(
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ dir=path.parent,
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ handle.write(payload)
+ try:
+ temporary_path.chmod(path.stat().st_mode)
+ temporary_path.replace(path)
+ except OSError:
+ temporary_path.unlink(missing_ok=True)
+ raise
+
+
+def adopt_authoring_object(
+ authoring_dir: Path,
+ source_spec: str,
+ target_name: str,
+) -> dict[str, object]:
+ """Copy one cross-page object as authored SVG with no source identity."""
+ authoring_dir = authoring_dir.resolve()
+ if not authoring_dir.is_dir():
+ raise ValueError(f"Authoring directory not found: {authoring_dir}")
+ _load_authoring_summary_manifest(authoring_dir)
+ source_name, element_id = _parse_adopt_source(source_spec)
+ source_path = _authoring_page_path(
+ authoring_dir,
+ source_name,
+ label="--adopt-object source",
+ )
+ target_path = _authoring_page_path(
+ authoring_dir,
+ target_name,
+ label="--into target",
+ )
+ if source_path == target_path:
+ raise ValueError("--adopt-object source and --into target must differ")
+
+ source_root = _parse_authoring_svg(source_path)
+ target_root = _parse_authoring_svg(target_path)
+ matches = [
+ item
+ for item in source_root.iter()
+ if item.get("id") == element_id
+ ]
+ if not matches:
+ raise ValueError(f"{source_name} has no element id {element_id!r}")
+ if len(matches) > 1:
+ raise ValueError(f"{source_name} repeats element id {element_id!r}")
+ source_element = matches[0]
+ if any(
+ item.get(SOURCE_PROXY_ATTRIBUTE) == SOURCE_PROXY_KIND
+ for item in source_element.iter()
+ ):
+ raise ValueError(
+ f"Cannot adopt source proxy {source_name}:{element_id}; "
+ "source proxies cannot move between pages"
+ )
+
+ adopted = copy.deepcopy(source_element)
+ adopted.tail = None
+ imported_icons = [
+ item
+ for item in adopted.iter()
+ if _local_name(item.tag) == "use"
+ and (item.get("data-icon") or "").startswith("imported/")
+ ]
+ inlined_icons = 0
+ if imported_icons:
+ from svg_to_pptx.use_expander import (
+ UseExpansionError,
+ expand_use_data_icons,
+ )
+
+ container = ET.Element(f"{{{SVG_NS}}}g")
+ container.append(adopted)
+ try:
+ inlined_icons = expand_use_data_icons(
+ container,
+ authoring_dir.parent / "icons",
+ )
+ except UseExpansionError as exc:
+ raise ValueError(
+ f"Cannot inline source-page vector asset: {exc}"
+ ) from exc
+ adopted = container[0]
+ if adopted.get("id") is None:
+ adopted.set("id", element_id)
+ residual_imports = sorted({
+ icon
+ for item in adopted.iter()
+ if (icon := item.get("data-icon"))
+ and icon.startswith("imported/")
+ })
+ if residual_imports:
+ raise ValueError(
+ "Adopted object retains source-owned imported vector(s): "
+ + ", ".join(residual_imports)
+ )
+
+ stripped, removed_metadata = _strip_adopted_transport(adopted)
+ target_ids = {
+ item_id
+ for item in target_root.iter()
+ if (item_id := item.get("id"))
+ }
+ replacements = _rewrite_adopted_fragment_ids(adopted, target_ids)
+ adopted_id = adopted.get("id")
+ if not adopted_id:
+ raise ValueError("Adopted object lost its required id")
+ target_root.append(adopted)
+
+ original_target = target_path.read_bytes()
+ try:
+ _write_svg_atomically(target_path, target_root)
+ summary_path = write_authoring_summary(authoring_dir)
+ except (OSError, ValueError):
+ with tempfile.NamedTemporaryFile(
+ prefix=f".{target_path.name}.rollback.",
+ suffix=".tmp",
+ dir=target_path.parent,
+ delete=False,
+ ) as handle:
+ rollback_path = Path(handle.name)
+ handle.write(original_target)
+ rollback_path.chmod(target_path.stat().st_mode)
+ rollback_path.replace(target_path)
+ raise
+
+ return {
+ "authoring_dir": str(authoring_dir),
+ "source": f"{source_name}:{element_id}",
+ "target": target_name,
+ "adopted_id": adopted_id,
+ "renamed_ids": dict(sorted(replacements.items())),
+ "inlined_imported_vectors": inlined_icons,
+ "stripped_attributes": sorted(stripped),
+ "removed_native_metadata": removed_metadata,
+ "summary": str(summary_path),
+ }
+
+
def _nearest_existing_directory(path: Path) -> Path:
candidate = path
while not os.path.lexists(candidate):
@@ -1997,6 +2372,19 @@ def build_parser() -> argparse.ArgumentParser:
"bundle; input must be that bundle directory and -o is omitted"
),
)
+ parser.add_argument(
+ "--adopt-object",
+ metavar="<from.svg>:<element-id>",
+ help=(
+ "Copy one object from another page as authored SVG, strip its "
+ "source/native transport, and refresh the bundle summary"
+ ),
+ )
+ parser.add_argument(
+ "--into",
+ metavar="<target.svg>",
+ help="Target page for --adopt-object",
+ )
parser.add_argument(
"--force",
action="store_true",
@@ -2022,6 +2410,30 @@ def main(argv: Optional[list[str]] = None) -> int:
if not input_path.exists():
print(f"Error: input does not exist: {input_path}", file=sys.stderr)
return 1
+ if args.refresh_summary and args.adopt_object is not None:
+ parser.error("--refresh-summary and --adopt-object are mutually exclusive")
+ if args.adopt_object is not None:
+ if args.into is None:
+ parser.error("--adopt-object requires --into <target.svg>")
+ if args.output_dir is not None:
+ parser.error("--adopt-object does not accept -o/--output-dir")
+ if args.force:
+ parser.error("--adopt-object does not accept --force")
+ if args.projection_kind != "generic":
+ parser.error("--adopt-object does not accept --projection-kind")
+ try:
+ result = adopt_authoring_object(
+ input_path,
+ args.adopt_object,
+ args.into,
+ )
+ except (OSError, ValueError) as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0
+ if args.into is not None:
+ parser.error("--into requires --adopt-object")
if args.refresh_summary:
if args.output_dir is not None:
print(
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 79d1ec8f..28ecbb58 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -1395,7 +1395,10 @@ class SVGQualityChecker:
result['errors'].append(f"Failed to read file: {e}")
result['passed'] = False
- # Update statistics
+ return self._record_result(result)
+
+ def _record_result(self, result: Dict) -> Dict:
+ """Append one file result and update aggregate counters."""
self.summary['total'] += 1
if result['passed']:
if result['warnings']:
@@ -1412,6 +1415,485 @@ class SVGQualityChecker:
self.results.append(result)
return result
+ def check_roundtrip_workspace(self, workspace: str) -> List[Dict]:
+ """Check edited text on the resolved round-trip output page roster."""
+ from authoring_roundtrip import (
+ AuthoringRoundtripError,
+ _generate_baseline_bundle,
+ _load_current_assets,
+ _load_documents,
+ _load_page_plan,
+ _parse_svg,
+ )
+
+ project_path = Path(workspace).resolve()
+ authoring_dir = project_path / 'authoring-svg-flat'
+ self._has_incomplete_page_roster = False
+ if not project_path.is_dir():
+ print(f"[ERROR] Round-trip workspace does not exist: {project_path}")
+ self.summary['errors'] += 1
+ self.issue_types['Input issues'] += 1
+ return []
+ if not authoring_dir.is_dir():
+ print(
+ "[ERROR] Round-trip workspace has no authoring-svg-flat/: "
+ f"{project_path}"
+ )
+ self.summary['errors'] += 1
+ self.issue_types['Input issues'] += 1
+ return []
+
+ try:
+ source_root, source_proxy_dir, documents, _, _ = _load_documents(
+ project_path,
+ authoring_dir,
+ )
+ pages, _ = _load_page_plan(
+ project_path,
+ authoring_dir,
+ documents,
+ )
+ current_assets, inventory = _load_current_assets(
+ project_path,
+ authoring_dir,
+ documents,
+ )
+ baseline_temporary, baseline_dir, baseline_assets = (
+ _generate_baseline_bundle(
+ project_path,
+ source_root,
+ source_proxy_dir,
+ documents,
+ inventory,
+ )
+ )
+ except (AuthoringRoundtripError, OSError, ValueError) as exc:
+ print(f"[ERROR] Invalid round-trip workspace: {exc}")
+ self.summary['errors'] += 1
+ self.issue_types['Input issues'] += 1
+ return []
+
+ documents_by_slide = {
+ document.source_slide: document
+ for document in documents.values()
+ }
+ self._active_slide_count = len(pages)
+ print(
+ f"\n[SCAN] Checking {len(pages)} round-trip output SVG page(s) "
+ "for edited-text horizontal capacity (single-line width per "
+ "positioned line; vertical wrapping is not modeled)...\n"
+ )
+ try:
+ baseline_roots = {
+ source_slide: _parse_svg(
+ baseline_dir / document.name,
+ )
+ for source_slide, document in documents_by_slide.items()
+ }
+ for page in pages:
+ result = self._check_roundtrip_file(
+ authoring_dir / page.svg_name,
+ documents_by_slide[page.source_slide],
+ baseline_roots[page.source_slide],
+ current_assets,
+ baseline_assets,
+ output_index=page.output_index,
+ source_slide=page.source_slide,
+ )
+ self._print_result(result)
+ finally:
+ baseline_temporary.cleanup()
+ return self.results
+
+ def _check_roundtrip_file(
+ self,
+ svg_path: Path,
+ source_document,
+ baseline_root: ET.Element,
+ current_assets,
+ baseline_assets,
+ *,
+ output_index: int,
+ source_slide: int,
+ ) -> Dict:
+ """Run only edited-text checks for one resolved round-trip page."""
+ result = {
+ 'file': svg_path.name,
+ 'path': str(svg_path),
+ 'exists': svg_path.is_file(),
+ 'errors': [],
+ 'warnings': [],
+ 'info': {
+ 'output_page': output_index,
+ 'source_slide': source_slide,
+ },
+ 'passed': True,
+ }
+ if not svg_path.is_file():
+ result['errors'].append('File does not exist')
+ result['passed'] = False
+ return self._record_result(result)
+
+ try:
+ source_bytes = svg_path.read_bytes()
+ result['source_sha256'] = hashlib.sha256(source_bytes).hexdigest()
+ content = source_bytes.decode('utf-8')
+ root = self._parse_xml_root(content, result)
+ if root is not None:
+ self._check_viewbox(root, svg_path, result, None)
+ included_text_ids = self._roundtrip_edited_text_ids(
+ root,
+ source_document,
+ baseline_root,
+ current_assets,
+ baseline_assets,
+ )
+ result['info']['edited_text_elements'] = len(included_text_ids)
+ if included_text_ids:
+ scoped_content = self._roundtrip_text_scope_content(
+ root,
+ included_text_ids,
+ )
+ svg_contracts.check_font_size_values(scoped_content, result)
+ self._check_fonts(scoped_content, result)
+ self._check_text_output_geometry(
+ root,
+ result,
+ included_text_ids=included_text_ids,
+ )
+ self._check_text_bounds(
+ root,
+ result,
+ included_text_ids=included_text_ids,
+ )
+ self._check_roundtrip_text_frames(
+ root,
+ result,
+ included_text_ids,
+ )
+ result['passed'] = len(result['errors']) == 0
+ except Exception as exc:
+ result['errors'].append(f"Failed to read file: {exc}")
+ result['passed'] = False
+ return self._record_result(result)
+
+ @staticmethod
+ def _roundtrip_edited_text_ids(
+ root: ET.Element,
+ source_document,
+ baseline_root: ET.Element,
+ current_assets,
+ baseline_assets,
+ ) -> set[int]:
+ """Return text carriers outside unchanged refs and source proxies."""
+ from authoring_roundtrip import (
+ _definition_changes,
+ authoring_source_ref_is_unchanged,
+ )
+ from svg_authoring_view import (
+ SOURCE_PROXY_ATTRIBUTE,
+ SOURCE_PROXY_KIND,
+ SOURCE_REF_ATTRIBUTE,
+ )
+
+ baseline_by_ref: Dict[str, ET.Element] = {}
+ for element in baseline_root.iter():
+ source_ref = element.get(SOURCE_REF_ATTRIBUTE)
+ if source_ref is None:
+ continue
+ if source_ref in baseline_by_ref:
+ raise ValueError(
+ f"Regenerated baseline repeats source ref {source_ref!r}"
+ )
+ baseline_by_ref[source_ref] = element
+ _, changed_definition_ids = _definition_changes(
+ root,
+ baseline_root,
+ current_assets,
+ baseline_assets,
+ )
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ unchanged_by_owner: Dict[int, bool] = {}
+ included: set[int] = set()
+ for text_element in root.iter(f'{{{SVG_NS}}}text'):
+ current: ET.Element | None = text_element
+ source_owner: ET.Element | None = None
+ source_ref: str | None = None
+ source_proxy = False
+ while current is not None:
+ if (
+ current.get(SOURCE_PROXY_ATTRIBUTE)
+ == SOURCE_PROXY_KIND
+ ):
+ source_proxy = True
+ if source_owner is None:
+ candidate = current.get(SOURCE_REF_ATTRIBUTE)
+ if candidate:
+ source_owner = current
+ source_ref = candidate
+ current = parent_by_id.get(id(current))
+ if source_proxy:
+ continue
+ if source_owner is not None and source_ref is not None:
+ record = source_document.source_refs.get(source_ref)
+ if record is not None and record.representation == 'source-proxy':
+ continue
+ owner_key = id(source_owner)
+ unchanged = unchanged_by_owner.get(owner_key)
+ if unchanged is None:
+ baseline_owner = baseline_by_ref.get(source_ref)
+ unchanged = bool(
+ record is not None
+ and baseline_owner is not None
+ and authoring_source_ref_is_unchanged(
+ source_owner,
+ baseline_owner,
+ current_assets,
+ baseline_assets,
+ changed_definition_ids=changed_definition_ids,
+ )
+ )
+ unchanged_by_owner[owner_key] = unchanged
+ if unchanged:
+ continue
+ included.add(id(text_element))
+ return included
+
+ @staticmethod
+ def _roundtrip_text_scope_content(
+ root: ET.Element,
+ included_text_ids: set[int],
+ ) -> str:
+ """Serialize only edited text and its inherited presentation chain."""
+ def clone_relevant(element: ET.Element) -> ET.Element | None:
+ if (
+ _local_name(element) == 'text'
+ and id(element) in included_text_ids
+ ):
+ return copy.deepcopy(element)
+ children = [
+ clone
+ for child in list(element)
+ if (clone := clone_relevant(child)) is not None
+ ]
+ if element is not root and not children:
+ return None
+ clone = ET.Element(element.tag, dict(element.attrib))
+ for child in children:
+ clone.append(child)
+ return clone
+
+ scoped_root = clone_relevant(root)
+ if scoped_root is None:
+ return ''
+ return ET.tostring(scoped_root, encoding='unicode')
+
+ def _check_roundtrip_text_frames(
+ self,
+ root: ET.Element,
+ result: Dict,
+ included_text_ids: set[int],
+ ) -> None:
+ """Report edited text whose estimated width leaves its owning frame."""
+ helpers = (
+ _estimate_single_line_text_frame_width,
+ _parse_project_font_weight,
+ _parse_project_geometry_length,
+ _parse_project_text_anchor,
+ _resolve_project_font_sizes,
+ _resolve_project_letter_spacings,
+ )
+ if any(helper is None for helper in helpers):
+ result['warnings'].append(
+ 'Unable to import text metrics; skipped edited-text frame-fit check'
+ )
+ return
+ try:
+ font_sizes = _resolve_project_font_sizes(root)
+ letter_spacings = _resolve_project_letter_spacings(
+ root,
+ font_sizes,
+ )
+ except ValueError:
+ return
+
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ for text_element in root.iter(f'{{{SVG_NS}}}text'):
+ if id(text_element) not in included_text_ids:
+ continue
+ if self._has_non_visual_ancestor(
+ text_element,
+ root,
+ parent_by_id,
+ ):
+ continue
+ if (
+ self._is_hidden_element(text_element, parent_by_id)
+ or self._has_zero_opacity(text_element, parent_by_id)
+ ):
+ continue
+ visible_text = ''.join(text_element.itertext())
+ if (
+ not visible_text.strip()
+ or ('{{' in visible_text and '}}' in visible_text)
+ ):
+ continue
+ estimated = self._estimated_text_bounds(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ include_headroom=True,
+ )
+ if estimated is None:
+ continue
+ frame_label, frame, frame_error, frame_is_inferred = (
+ self._roundtrip_text_frame(
+ text_element,
+ parent_by_id,
+ )
+ )
+ text_label = self._text_diagnostic_label(text_element)
+ if frame is None:
+ detail = f': {frame_error}' if frame_error else ''
+ result['warnings'].append(
+ f'Cannot verify owning frame for edited {text_label}{detail}; '
+ 'keep data-pptx-frame on the logical object or place a '
+ 'rect frame beside the text'
+ )
+ continue
+ metrics = self._bounds_overflow_metrics(estimated, frame)
+ if metrics is None or metrics[1] <= 0:
+ continue
+ _axes, horizontal_ratio, _vertical_ratio = metrics
+ left, top, right, bottom = estimated
+ frame_left, frame_top, frame_right, frame_bottom = frame
+ finding = (
+ f'{text_label} exceeds owning frame {frame_label} on the '
+ f'horizontal axis: estimated text ({left:.1f}, {top:.1f})-'
+ f'({right:.1f}, {bottom:.1f}), frame ({frame_left:.1f}, '
+ f'{frame_top:.1f})-({frame_right:.1f}, {frame_bottom:.1f}), '
+ f'overflow horizontal {horizontal_ratio:.1%}; shorten or '
+ 'reflow the edited text, or '
+ 'enlarge its owning frame'
+ )
+ if frame_is_inferred:
+ result['warnings'].append(
+ f'{finding}; frame inferred from nearest rect sibling; '
+ 'add data-pptx-frame to make this blocking'
+ )
+ else:
+ result['errors'].append(finding)
+
+ @classmethod
+ def _roundtrip_text_frame(
+ cls,
+ text_element: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[
+ str | None,
+ Tuple[float, float, float, float] | None,
+ str | None,
+ bool,
+ ]:
+ """Resolve an explicit logical frame or the nearest rect sibling."""
+ current: ET.Element | None = text_element
+ while current is not None:
+ raw_frame = current.get('data-pptx-frame')
+ if raw_frame is not None:
+ label = f'{_element_label(current)} data-pptx-frame'
+ try:
+ frame = _parse_positive_bounds(raw_frame)
+ except ValueError as exc:
+ return label, None, f'{label} {exc}', False
+ transformed = cls._transformed_rect_bounds(
+ current,
+ frame,
+ parent_by_id,
+ )
+ if transformed is None:
+ return (
+ label,
+ None,
+ f'{label} has an unresolved transform',
+ False,
+ )
+ return label, transformed, None, False
+ current = parent_by_id.get(id(current))
+
+ if _parse_project_geometry_length is None:
+ return None, None, 'the SVG length parser is unavailable', False
+ current = text_element
+ rect_errors: List[str] = []
+ while current is not None:
+ parent = parent_by_id.get(id(current))
+ if parent is None:
+ break
+ siblings = list(parent)
+ try:
+ current_index = siblings.index(current)
+ except ValueError:
+ current_index = 0
+ rects = sorted(
+ (
+ (abs(index - current_index), index, sibling)
+ for index, sibling in enumerate(siblings)
+ if _local_name(sibling) == 'rect'
+ ),
+ key=lambda item: (item[0], item[1]),
+ )
+ for _distance, _index, rect in rects:
+ label = _element_label(rect)
+ try:
+ x = _parse_project_geometry_length(
+ rect.get('x') or '0',
+ 'x',
+ )
+ y = _parse_project_geometry_length(
+ rect.get('y') or '0',
+ 'y',
+ )
+ width = _parse_project_geometry_length(
+ rect.get('width'),
+ 'width',
+ )
+ height = _parse_project_geometry_length(
+ rect.get('height'),
+ 'height',
+ )
+ if (
+ not all(math.isfinite(value) for value in (x, y, width, height))
+ or width <= 0
+ or height <= 0
+ ):
+ raise ValueError('must use finite positive width and height')
+ except (TypeError, ValueError) as exc:
+ rect_errors.append(f'{label} {exc}')
+ continue
+ transformed = cls._transformed_rect_bounds(
+ rect,
+ (x, y, width, height),
+ parent_by_id,
+ )
+ if transformed is not None:
+ return label, transformed, None, True
+ rect_errors.append(f'{label} has an unresolved transform')
+ current = parent
+ return (
+ None,
+ None,
+ rect_errors[0] if rect_errors else None,
+ False,
+ )
+
def _check_canonical_authoring(
self,
root: ET.Element,
@@ -2233,6 +2715,8 @@ class SVGQualityChecker:
self,
root: ET.Element,
result: Dict,
+ *,
+ included_text_ids: set[int] | None = None,
) -> None:
"""Reject measurable run advances or frames with non-positive geometry."""
helpers = (
@@ -2259,6 +2743,11 @@ class SVGQualityChecker:
unchanged_groups = self._unchanged_txbody_group_ids(root)
errors: List[str] = []
for text_el in root.iter(f'{{{SVG_NS}}}text'):
+ if (
+ included_text_ids is not None
+ and id(text_el) not in included_text_ids
+ ):
+ continue
chain: List[ET.Element] = []
current: ET.Element | None = text_el
while current is not None:
@@ -3205,6 +3694,8 @@ class SVGQualityChecker:
self,
root: ET.Element,
result: Dict,
+ *,
+ included_text_ids: set[int] | None = None,
) -> None:
"""Validate visible text against page and root-module bounds."""
helpers = (
@@ -3245,6 +3736,11 @@ class SVGQualityChecker:
page_overflow_text_ids: set[int] = set()
unverified: List[str] = []
for text_element in root.iter(f'{{{SVG_NS}}}text'):
+ if (
+ included_text_ids is not None
+ and id(text_element) not in included_text_ids
+ ):
+ continue
if self._has_ancestor_id(
text_element,
parent_by_id,
diff --git a/skills/ppt-master/scripts/svg_quality/cli.py b/skills/ppt-master/scripts/svg_quality/cli.py
index 3cc41e67..427689f2 100644
--- a/skills/ppt-master/scripts/svg_quality/cli.py
+++ b/skills/ppt-master/scripts/svg_quality/cli.py
@@ -103,6 +103,7 @@ def print_usage() -> None:
print("Usage:")
print(" python3 scripts/svg_quality_checker.py <svg_file>")
print(" python3 scripts/svg_quality_checker.py <directory>")
+ print(" python3 scripts/svg_quality_checker.py <roundtrip-workspace> --roundtrip")
print(" python3 scripts/svg_quality_checker.py <workspace>/templates --template-mode")
print(" python3 scripts/svg_quality_checker.py --all projects")
print("\nExamples:")
@@ -127,6 +128,10 @@ def print_usage() -> None:
print(" --quick-generate Validate lockless Quick SVGs; infer flat or")
print(" structured output from the complete roster;")
print(" ignore design_spec.md and spec_lock.md.")
+ print(" --roundtrip Validate edited-text capacity on the resolved")
+ print(" authoring-svg-flat/ output roster; uses")
+ print(" page_plan.json when present and skips")
+ print(" generated-project/template-only contracts.")
print(" --canonical-authoring Require compact authoring syntax as written;")
print(" the checker never rewrites source SVG.")
print(" --template-mode Validate a template workspace's templates/ directory:")
@@ -160,9 +165,16 @@ def main() -> None:
template_mode = "--template-mode" in sys.argv
quick_generate = "--quick-generate" in sys.argv
canonical_authoring = "--canonical-authoring" in sys.argv
+ roundtrip = "--roundtrip" in sys.argv
if template_mode and quick_generate:
print("[ERROR] --template-mode cannot be combined with --quick-generate")
sys.exit(1)
+ if roundtrip and (template_mode or quick_generate or canonical_authoring):
+ print(
+ "[ERROR] --roundtrip cannot be combined with --template-mode, "
+ "--quick-generate, or --canonical-authoring"
+ )
+ sys.exit(1)
checker = SVGQualityChecker(
template_mode=template_mode,
quick_generate=quick_generate,
@@ -199,8 +211,17 @@ def main() -> None:
if stage != "page" and page is not None:
print("[ERROR] --page is supported only with --stage page")
sys.exit(1)
+ if roundtrip and any(
+ option in sys.argv
+ for option in ("--format", "--stage", "--page")
+ ):
+ print("[ERROR] --roundtrip does not support --format, --stage, or --page")
+ sys.exit(1)
if target == "--all":
+ if roundtrip:
+ print("[ERROR] --roundtrip does not support --all")
+ sys.exit(1)
if quick_generate:
print("[ERROR] --quick-generate does not support --all")
sys.exit(1)
@@ -218,7 +239,9 @@ def main() -> None:
print("=" * 80)
checker.check_directory(str(project))
else:
- if stage == "first-page":
+ if roundtrip:
+ checker.check_roundtrip_workspace(target)
+ elif stage == "first-page":
check_target = _first_page_target(target)
elif stage == "page":
try:
@@ -228,9 +251,10 @@ def main() -> None:
sys.exit(1)
else:
check_target = target
- checker.check_directory(check_target, expected_format)
+ if not roundtrip:
+ checker.check_directory(check_target, expected_format)
- if stage == "final" and Path(target).is_dir():
+ if not roundtrip and stage == "final" and Path(target).is_dir():
if checker._has_incomplete_page_roster:
print(
"[TIP] This final-stage run found an incomplete page roster. "
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 0c7c4001..e716ad97 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -7,10 +7,12 @@ Implementation lives in ``svg_quality/``.
Usage:
python3 scripts/svg_quality_checker.py <svg_file>
python3 scripts/svg_quality_checker.py <directory>
+ python3 scripts/svg_quality_checker.py <roundtrip_workspace> --roundtrip
python3 scripts/svg_quality_checker.py --all projects
Examples:
python3 scripts/svg_quality_checker.py projects/demo --stage final --json
+ python3 scripts/svg_quality_checker.py /path/to/import --roundtrip
Dependencies:
Same as svg_quality.cli.
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
index b6ec3f3b..c30f0b73 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
@@ -67,8 +67,8 @@ from pptx_opc_validation import (
verify_internal_relationships,
)
from pptx_workspace import WorkspaceResourceSpec
-from template_fill_pptx.clone import clone_presentation_slides
-from template_fill_pptx.package import prune_unreferenced_directory_parts
+from pptx_ooxml.clone import clone_presentation_slides
+from pptx_ooxml.package import prune_unreferenced_directory_parts
from language_tags import normalize_language_tag
from hyperlink_contract import (
HYPERLINK_REL_TYPE,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
index f3abdc2b..3dbda44a 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py
@@ -201,13 +201,56 @@ def _roundtrip_animation_config_for_pages(
if not isinstance(raw_slides, dict):
raise RuntimeError("Round-trip animation sidecar slides must be an object")
output_slides: dict[str, object] = {}
- for page in pages:
+ for page_index, page in enumerate(pages):
output_stem = page.svg_stem
source_stem = Path(page.source_svg_name).stem
if output_stem in raw_slides:
- output_slides[output_stem] = raw_slides[output_stem]
+ selected = copy.deepcopy(raw_slides[output_stem])
+ row_origin = "declares"
elif source_stem in raw_slides:
- output_slides[output_stem] = copy.deepcopy(raw_slides[source_stem])
+ selected = copy.deepcopy(raw_slides[source_stem])
+ row_origin = "inherits"
+ else:
+ continue
+ if isinstance(selected, dict):
+ morph = selected.get("morph")
+ if isinstance(morph, dict):
+ original_from = morph.get("from")
+ previous_page = pages[page_index - 1] if page_index else None
+ previous_source_stem = (
+ Path(previous_page.source_svg_name).stem
+ if previous_page is not None
+ else None
+ )
+ if (
+ isinstance(original_from, str)
+ and original_from.strip()
+ and previous_page is not None
+ and original_from == previous_page.svg_stem
+ ):
+ pass
+ elif (
+ isinstance(original_from, str)
+ and original_from.strip()
+ and previous_page is not None
+ and original_from == previous_source_stem
+ ):
+ morph["from"] = previous_page.svg_stem
+ elif isinstance(original_from, str) and original_from.strip():
+ previous_label = (
+ f'"{previous_page.svg_stem}" from '
+ f'"{previous_source_stem}"'
+ if previous_page is not None
+ else "no previous output page"
+ )
+ raise RuntimeError(
+ f'Round-trip output page "{output_stem}" {row_origin} '
+ f'Morph from "{original_from}", but it follows '
+ f'{previous_label}; add an explicit animations.json '
+ f'row for "{output_stem}" that overrides morph.from '
+ 'for this output adjacency, or remove that Morph row'
+ )
+ output_slides[output_stem] = selected
expanded["slides"] = output_slides
return expanded
diff --git a/skills/ppt-master/scripts/template_fill_pptx.py b/skills/ppt-master/scripts/template_fill_pptx.py
deleted file mode 100644
index 80baef83..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/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 <stem>.slide_library.json
- python3 scripts/template_fill_pptx.py scaffold <stem>.slide_library.json -o fill_plan.json
- python3 scripts/template_fill_pptx.py check-plan <stem>.slide_library.json fill_plan.json
- python3 scripts/template_fill_pptx.py apply <deck.pptx> fill_plan.json -o output.pptx
- python3 scripts/template_fill_pptx.py validate <project>
-
-Implementation lives in the template_fill_pptx/ package (ooxml, analyzer,
-scaffolder, checker, text_fill, table_fill, chart_fill, transitions, notes,
-package, applier, validator, 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 attribution_guard import require_skill_integrity
-from console_encoding import configure_utf8_stdio
-from template_fill_pptx import main
-
-configure_utf8_stdio()
-
-if __name__ == "__main__":
- require_skill_integrity()
- raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/template_fill_pptx/__init__.py b/skills/ppt-master/scripts/template_fill_pptx/__init__.py
deleted file mode 100644
index 8f3a682c..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/__init__.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""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. CLI stages mirror the direct-PPTX workflow:
-analyze -> scaffold -> check-plan -> apply -> validate.
-
-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
-from .validator import print_validate_report, validate_project
-
-__all__ = [
- "analyze_pptx",
- "scaffold_plan",
- "check_plan",
- "print_check_report",
- "apply_plan",
- "validate_project",
- "print_validate_report",
- "main",
-]
diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.py
deleted file mode 100644
index 4fbe926e..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py
+++ /dev/null
@@ -1,343 +0,0 @@
-"""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 tempfile
-import zipfile
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any
-from xml.etree import ElementTree as ET
-
-from pptx_animations import (
- object_animation_fingerprint,
- validate_pptx_animation_package,
-)
-from pptx_transitions import (
- parse_source_xml,
- serialize_source_xml,
- set_package_use_timings,
- validate_pptx_transition_package,
-)
-
-from .chart_fill import (
- _apply_chart_edits_to_slide_package,
- _max_chart_part_number,
- _max_embedding_part_number,
-)
-from .clone import (
- _make_part_allocator,
- _remap_reachable_shared_layer_slide_jumps,
- _remap_slide_jump_relationships,
- deep_clone_slide_private_parts,
-)
-from .notes import _find_notes_master_target, _slide_rels_with_notes
-from .ooxml import (
- NS,
- REL_NS,
- SLIDE_REL_TYPE,
- SlideRef,
- _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,
-)
-
-
-@dataclass(frozen=True)
-class _PlannedSlideClone:
- """One output slide resolved before any source relationship is rewritten."""
-
- offset: int
- item: dict[str, Any]
- source_slide: int
- source_ref: SlideRef
- slide_number: int
- part_name: str
- rels_name: str
- presentation_rid: str
-
-
-def _build_clone_roster(
- plan_slides: list[Any],
- slide_refs: dict[int, SlideRef],
- *,
- next_slide_number: int,
- next_rel_number: int,
-) -> list[_PlannedSlideClone]:
- """Resolve every planned output slide before cloning begins."""
- roster: list[_PlannedSlideClone] = []
- for offset, raw_item in enumerate(plan_slides):
- if not isinstance(raw_item, dict):
- raise RuntimeError(f"Plan slide {offset + 1} must be an object")
- source_slide = int(raw_item.get("source_slide", 0))
- if source_slide not in slide_refs:
- raise RuntimeError(f"Plan references a missing source slide: {source_slide}")
- slide_number = next_slide_number + offset
- roster.append(
- _PlannedSlideClone(
- offset=offset,
- item=raw_item,
- source_slide=source_slide,
- source_ref=slide_refs[source_slide],
- slide_number=slide_number,
- part_name=f"ppt/slides/slide{slide_number}.xml",
- rels_name=f"ppt/slides/_rels/slide{slide_number}.xml.rels",
- presentation_rid=f"rId{next_rel_number + offset}",
- )
- )
- return roster
-
-
-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)
- allocate_part = _make_part_allocator(entries)
- wrote_auto_advance = False
-
- clone_roster = _build_clone_roster(
- plan_slides,
- slide_refs,
- next_slide_number=next_slide_number,
- next_rel_number=next_rel_number,
- )
- source_ref_by_part = {ref.part_name: ref for ref in slide_refs.values()}
- outputs_by_source_part: dict[str, list[str]] = {}
- for clone in clone_roster:
- outputs_by_source_part.setdefault(clone.source_ref.part_name, []).append(clone.part_name)
-
- for clone in clone_roster:
- item = clone.item
- source_slide = clone.source_slide
- source_ref = clone.source_ref
- new_slide_number = clone.slide_number
- new_part = clone.part_name
- new_rels = clone.rels_name
- new_rid = clone.presentation_rid
-
- source_slide_xml = entries[source_ref.part_name]
- source_animation_fingerprint = object_animation_fingerprint(
- source_slide_xml
- )
- slide_root = parse_source_xml(source_slide_xml)
- 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_effect_options,
- slide_duration,
- slide_advance,
- ) = _resolve_slide_transition(
- item,
- default_effect=transition,
- default_duration=transition_duration,
- )
- slide_has_auto_advance = _set_slide_transition(
- slide_root,
- effect=slide_effect,
- effect_options=slide_effect_options,
- duration=slide_duration,
- advance_after=slide_advance,
- )
- if slide_advance is not None and slide_has_auto_advance:
- wrote_auto_advance = True
-
- source_rels = entries.get(source_ref.rels_name)
- slide_rels_root = ET.fromstring(source_rels) if source_rels else _empty_relationships_root()
- _remap_slide_jump_relationships(
- slide_root,
- slide_rels_root,
- source_owner_part=source_ref.part_name,
- output_owner_part=new_part,
- owner_label=f"Source slide {source_slide}",
- outputs_by_source_part=outputs_by_source_part,
- source_ref_by_part=source_ref_by_part,
- self_source_part=source_ref.part_name,
- self_output_part=new_part,
- )
- 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")
- 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,
- )
- try:
- serialized_slide = serialize_source_xml(
- slide_root,
- source_slide_xml,
- )
- except ValueError as exc:
- raise RuntimeError(str(exc)) from exc
- if (
- object_animation_fingerprint(serialized_slide)
- != source_animation_fingerprint
- ):
- raise RuntimeError(
- f'Slide {source_slide} object animations changed during template fill'
- )
- entries[new_part] = serialized_slide
- 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 + clone.offset),
- _qn(NS["r"], "id"): new_rid,
- },
- )
-
- _remap_reachable_shared_layer_slide_jumps(
- entries,
- [
- (clone.part_name, clone.rels_name)
- for clone in clone_roster
- ],
- outputs_by_source_part=outputs_by_source_part,
- source_ref_by_part=source_ref_by_part,
- )
-
- 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)
- if wrote_auto_advance:
- try:
- set_package_use_timings(entries)
- except ValueError as exc:
- raise RuntimeError(str(exc)) from exc
-
- output_path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.TemporaryDirectory(
- prefix="template-fill-pptx-",
- dir=output_path.parent,
- ) as temp_dir:
- candidate_path = Path(temp_dir) / output_path.name
- with zipfile.ZipFile(
- candidate_path,
- "w",
- compression=zipfile.ZIP_DEFLATED,
- ) as out:
- for name, data in entries.items():
- out.writestr(name, data)
- try:
- validate_pptx_transition_package(
- candidate_path,
- require_use_timings=wrote_auto_advance,
- )
- except ValueError as exc:
- raise RuntimeError(
- f"PPTX transition package validation failed: {exc}"
- ) from exc
- try:
- validate_pptx_animation_package(
- candidate_path,
- require_supported_effects=False,
- )
- except ValueError as exc:
- raise RuntimeError(
- f"PPTX animation/timing package validation failed: {exc}"
- ) from exc
- candidate_path.replace(output_path)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py b/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py
deleted file mode 100644
index d3c33257..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py
+++ /dev/null
@@ -1,401 +0,0 @@
-"""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 sys
-import zipfile
-from typing import Any
-from xml.etree import ElementTree as ET
-
-from .edit_safety import (
- _chart_frames,
- _chart_reference,
- _require_supported_chart_edit,
-)
-from .ooxml import (
- CHART_CONTENT_TYPE,
- CHART_REL_TYPE,
- NS,
- PACKAGE_REL_TYPE,
- REL_NS,
- XLSX_CONTENT_TYPE,
- _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_frames(slide_root), start=1):
- shape_id, shape_name = _shape_identity(container, order)
- chart_kind, rel_id = _chart_reference(container)
- info = {
- "shape_id": shape_id,
- "shape_name": shape_name,
- "rel_id": rel_id,
- "chart_kind": chart_kind,
- }
- 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")
- chart_types: list[ET.Element] = []
- for child in list(plot_area):
- if child.tag.endswith("Chart") and child.findall("c:ser", NS):
- chart_types.append(child)
- if len(chart_types) > 1:
- raise RuntimeError(
- "template-fill chart edits do not support multi-plot / combination charts; "
- "use beautify/main pipeline to redraw the chart, or leave the native chart untouched"
- )
- if chart_types:
- return chart_types[0]
- 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:
- capability = _require_supported_chart_edit(chart_root)
- for warning in capability.get("warnings", []):
- if not isinstance(warning, dict):
- continue
- code = warning.get("code") or "chart_edit_category_flattened"
- message = warning.get("message") or "chart categories will be flattened"
- print(f" Warning: {message} [{code}]", file=sys.stderr)
- 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
- chart_kind = chart_info.get("chart_kind", "")
- if chart_kind != "classic":
- code = (
- "chart_edit_chartex_unsupported"
- if chart_kind == "chartex"
- else "chart_edit_plot_type_unsupported"
- )
- raise RuntimeError(
- "template-fill chart edits require a supported classic chart "
- f"[{code}]"
- )
- 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_number
diff --git a/skills/ppt-master/scripts/template_fill_pptx/checker.py b/skills/ppt-master/scripts/template_fill_pptx/checker.py
deleted file mode 100644
index 61cda269..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/checker.py
+++ /dev/null
@@ -1,719 +0,0 @@
-"""Check planned text/table/chart edits and preserved SmartArt source risks."""
-
-from __future__ import annotations
-
-import unicodedata
-from typing import Any
-
-from .edit_safety import _is_verified_category_capability
-from .selectors import (
- _chart_selectors,
- _replacement_selectors,
- _replacement_text,
- _table_selectors,
-)
-from .transitions import transition_unknown_fields
-
-
-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 _table_cell_lookup(table: dict[str, Any]) -> dict[tuple[int, int], dict[str, Any]]:
- lookup: dict[tuple[int, int], dict[str, Any]] = {}
- for row in table.get("rows", []):
- for cell in row.get("cells", []):
- if not isinstance(cell, dict):
- continue
- try:
- key = (int(cell.get("row", -1)), int(cell.get("col", -1)))
- except (TypeError, ValueError):
- continue
- lookup[key] = cell
- return lookup
-
-
-def _table_merge_slave_lookup(
- table: dict[str, Any],
-) -> dict[tuple[int, int], dict[str, int] | None]:
- lookup: dict[tuple[int, int], dict[str, int] | None] = {}
- topology = table.get("merge_topology")
- if isinstance(topology, dict):
- for slave in topology.get("slave_cells", []):
- if not isinstance(slave, dict):
- continue
- try:
- key = (int(slave.get("row", -1)), int(slave.get("col", -1)))
- except (TypeError, ValueError):
- continue
- anchor = slave.get("anchor")
- lookup[key] = anchor if isinstance(anchor, dict) else None
-
- for key, cell in _table_cell_lookup(table).items():
- if cell.get("is_merge_slave") is True or cell.get("merge_role") == "slave":
- anchor = cell.get("merge_anchor")
- lookup.setdefault(key, anchor if isinstance(anchor, dict) else None)
- return lookup
-
-
-def _chart_edit_capability_review(
- chart: dict[str, Any],
-) -> tuple[tuple[str, str] | None, list[tuple[str, str]]]:
- capability = chart.get("edit_capability")
- if not isinstance(capability, dict):
- return None, [
- (
- "chart_edit_capability_unknown",
- "chart edit capability is missing; runtime will inspect the actual "
- "chart XML before mutation, and re-running template analysis is recommended",
- )
- ]
- if capability.get("supported") is not True:
- return (
- str(capability.get("code") or "chart_edit_capability_unknown"),
- str(capability.get("message") or "chart edit capability is unsupported"),
- ), []
- if not _is_verified_category_capability(capability):
- return (
- "chart_edit_capability_unknown",
- "chart edit capability is not the verified single-plot c:cat/c:val model",
- ), []
-
- capability_warnings: list[tuple[str, str]] = []
- raw_warnings = capability.get("warnings")
- if isinstance(raw_warnings, list):
- for item in raw_warnings:
- if not isinstance(item, dict):
- continue
- code = str(item.get("code") or "chart_edit_category_flattened")
- message = str(item.get("message") or "chart categories will be flattened")
- capability_warnings.append((code, message))
- return None, capability_warnings
-
-
-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_width: float,
- new_width: float,
- old_paragraphs: int,
- new_paragraphs: int,
- geometry: dict[str, Any],
- text_metrics: dict[str, Any],
-) -> tuple[str, str]:
- old_width = max(old_width, 1.0)
- ratio = new_width / old_width
- width = 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_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:
- 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.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"
-
- 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
- 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 _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 _library_slide_index(library: dict[str, Any]) -> dict[int, dict[str, Any]]:
- """Build a mapping from slide_index to slide dict for O(1) lookup."""
- return {int(s.get("slide_index", 0)): s for s in library.get("slides", [])}
-
-
-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))
- transition = slide.get("transition")
- if isinstance(transition, dict):
- unknown_transition_fields = transition_unknown_fields(transition)
- if unknown_transition_fields:
- results.append(
- {
- "status": "ERROR",
- "code": "transition_unknown_fields",
- "plan_slide": slide_index,
- "source_slide": source_slide,
- "fields": unknown_transition_fields,
- "message": (
- "transition has unknown field(s): "
- + ", ".join(unknown_transition_fields)
- ),
- }
- )
- summary["error"] += 1
- replacements = slide.get("replacements", [])
- if not isinstance(replacements, list):
- results.append(
- {
- "status": "ERROR",
- "code": "replacements_not_list",
- "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",
- "code": "replacement_target_not_found",
- "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_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_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"] += 1
- results.append(
- {
- "status": status,
- "code": "text_capacity" if status == "WARN" else "text_fit",
- "plan_slide": slide_index,
- "source_slide": source_slide,
- "slot_id": slot.get("slot_id"),
- "role": slot.get("role"),
- "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,
- "old_text": old_text,
- "new_text": text,
- }
- )
- table_edits = slide.get("table_edits", [])
- if not isinstance(table_edits, list):
- results.append(
- {
- "status": "ERROR",
- "code": "table_edits_not_list",
- "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",
- "code": "table_target_not_found",
- "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",
- "code": "table_cells_not_list",
- "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)
- table_cells = _table_cell_lookup(table)
- merge_slaves = _table_merge_slave_lookup(table)
- 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
- or (table_cells and (row, col) not in table_cells)
- ):
- results.append(
- {
- "status": "ERROR",
- "code": "table_cell_out_of_bounds",
- "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
- if (row, col) in merge_slaves:
- anchor = merge_slaves[(row, col)]
- anchor_hint = ""
- if anchor is not None:
- anchor_hint = (
- f"; edit merge anchor row={anchor.get('row')} "
- f"col={anchor.get('col')} instead"
- )
- results.append(
- {
- "status": "ERROR",
- "code": "table_cell_is_merge_slave",
- "plan_slide": slide_index,
- "source_slide": source_slide,
- "selector": selectors[0] if selectors else "",
- "table_id": table.get("table_id"),
- "row": row,
- "col": col,
- "message": (
- f"table cell row={row} col={col} is a merged-cell slave"
- f"{anchor_hint}"
- ),
- }
- )
- summary["error"] += 1
- continue
- summary["ok"] += 1
- results.append(
- {
- "status": "OK",
- "code": "table_target_exists",
- "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",
- "code": "chart_edits_not_list",
- "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",
- "code": "chart_target_not_found",
- "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
- capability_error, capability_warnings = _chart_edit_capability_review(chart)
- if capability_error is not None:
- error_code, error_message = capability_error
- results.append(
- {
- "status": "ERROR",
- "code": error_code,
- "plan_slide": slide_index,
- "source_slide": source_slide,
- "selector": selectors[0] if selectors else "",
- "chart_id": chart.get("chart_id"),
- "message": error_message,
- }
- )
- summary["error"] += 1
- continue
- for warning_code, warning_message in capability_warnings:
- results.append(
- {
- "status": "WARN",
- "code": warning_code,
- "plan_slide": slide_index,
- "source_slide": source_slide,
- "selector": selectors[0] if selectors else "",
- "chart_id": chart.get("chart_id"),
- "message": warning_message,
- }
- )
- summary["warn"] += 1
- 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",
- "code": "chart_data_invalid",
- "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",
- "code": "chart_series_length_mismatch",
- "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",
- "code": "chart_target_valid",
- "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",
- }
- )
- # --- Guardrail 2: source slides with non-text content not covered by edits ---
- # 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))
- lib_slide = lib_slides.get(source_slide)
- if lib_slide is None:
- continue
- lib_tables = lib_slide.get("tables", [])
- lib_charts = lib_slide.get("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"))
- has_chart_edits = bool(slide.get("chart_edits"))
- uncovered_kinds: list[str] = []
- if lib_tables and not has_table_edits:
- 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(
- {
- "status": "WARN",
- "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}) "
- "outside the plan's supported edits; template-fill leaves it untouched "
- f"and original template content may show through ({guidance})"
- ),
- }
- )
-
- # --- Guardrail 1: same source slide reused too many times while unused layouts exist ---
- # Use a relative condition rather than an absolute threshold: only warn when
- # (a) a source slide is reused >= REUSE_WARN_THRESHOLD times, AND
- # (b) there are library slides that the plan never uses at all.
- # Rationale: a small template where every layout is referenced is fine even at
- # high per-slide reuse; "15-page template where only 1 page is ever cloned and
- # the rest sit idle" is the real smell we want to surface.
- # Threshold of 3: any source appearing 3+ times in a plan is meaningful reuse
- # (cover / TOC / ending typically appear at most twice), so >= 3 is a practical
- # signal without being overly sensitive.
- REUSE_WARN_THRESHOLD = 3
- source_use_counts: dict[int, int] = {}
- for slide in plan.get("slides", []):
- src = int(slide.get("source_slide", 0))
- if src:
- source_use_counts[src] = source_use_counts.get(src, 0) + 1
- all_lib_indices = {int(s.get("slide_index", 0)) for s in library.get("slides", []) if s.get("slide_index")}
- used_lib_indices = set(source_use_counts.keys())
- unused_lib_indices = sorted(all_lib_indices - used_lib_indices)
- if unused_lib_indices:
- for src, count in sorted(source_use_counts.items()):
- if count >= REUSE_WARN_THRESHOLD:
- unused_list = ", ".join(str(i) for i in unused_lib_indices)
- summary["warn"] += 1
- results.append(
- {
- "status": "WARN",
- "code": "source_reuse_concentration",
- "source_slide": src,
- "reuse_count": count,
- "unused_source_slides": unused_lib_indices,
- "message": (
- f"source slide {src} is reused {count} times while "
- f"{len(unused_lib_indices)} source layout(s) are never used "
- f"(indices: {unused_list}); "
- "consider using other layouts for more variety"
- ),
- }
- )
-
- 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)
- )
- elif "plan_slide" in item:
- 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()
- )
- else:
- # Guardrail 1 WARNs are source-level (no plan_slide); print source + message.
- line = f"{item['status']} source={item.get('source_slide', '?')}: {item['message']}"
- print(line)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/cli.py b/skills/ppt-master/scripts/template_fill_pptx/cli.py
deleted file mode 100644
index 53b5ce85..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/cli.py
+++ /dev/null
@@ -1,227 +0,0 @@
-"""Command-line interface: analyze / scaffold / check-plan / apply / validate."""
-
-from __future__ import annotations
-
-import argparse
-import re
-import sys
-from datetime import datetime
-from pathlib import Path
-
-_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
-if str(_SCRIPTS_DIR) not in sys.path:
- sys.path.insert(0, str(_SCRIPTS_DIR))
-
-from attribution_guard import require_skill_integrity # noqa: E402
-from console_encoding import configure_utf8_stdio # noqa: E402
-from pptx_transitions import ( # noqa: E402
- LEGACY_TRANSITION_KEYS,
- NATIVE_TRANSITION_KEYS,
-)
-
-configure_utf8_stdio()
-
-if __package__ in {None, ''}:
- import types
-
- package_dir = Path(__file__).resolve().parent
- while str(package_dir) in sys.path:
- sys.path.remove(str(package_dir))
- scripts_dir = Path(__file__).resolve().parents[1]
- if str(scripts_dir) not in sys.path:
- sys.path.insert(0, str(scripts_dir))
- package = types.ModuleType("template_fill_pptx")
- package.__path__ = [str(package_dir)] # type: ignore[attr-defined]
- sys.modules.setdefault("template_fill_pptx", package)
- __package__ = "template_fill_pptx"
-
-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,
-)
-from .validator import print_validate_report, validate_project
-
-
-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 _plan_confirmed(plan: dict) -> bool:
- return plan.get("status") == "confirmed"
-
-
-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 <stem>.slide_library.json path")
-
- scaffold = subparsers.add_parser("scaffold", help="Create an editable fill plan skeleton")
- scaffold.add_argument("library_json", help="<stem>.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="<stem>.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=[
- *NATIVE_TRANSITION_KEYS,
- *LEGACY_TRANSITION_KEYS,
- "none",
- KEEP_TRANSITION,
- ],
- default=DEFAULT_TRANSITION,
- help=(
- "Page-to-page transition policy for every cloned slide "
- "(per-slide 'transition' in the plan overrides this). "
- "Use a PowerPoint-native key; old names are compatibility inputs. "
- f"Default: {DEFAULT_TRANSITION} (preserve the source). "
- "Use 'none' to remove visual motion."
- ),
- )
- apply.add_argument(
- "--transition-duration",
- type=float,
- default=DEFAULT_TRANSITION_DURATION,
- help="Transition duration in seconds (default: 0.5).",
- )
- apply.add_argument(
- "--force",
- action="store_true",
- help="apply without a confirmed fill plan (deliberate recovery/debug only)",
- )
-
- validate = subparsers.add_parser("validate", help="Read back and validate the latest project export")
- validate.add_argument("project_path", help="Template-fill project directory")
-
- return parser
-
-
-def main(argv: list[str] | None = None) -> int:
- require_skill_integrity()
- 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())
- if not _plan_confirmed(plan) and not args.force:
- print(
- "Error: fill plan is not confirmed: "
- f"{Path(args.plan_json).expanduser().resolve()} "
- '(set status to "confirmed" after user approval, or pass --force)',
- file=sys.stderr,
- )
- return 1
- 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
-
- if args.command == "validate":
- report = validate_project(Path(args.project_path))
- print_validate_report(report)
- return 0 if report["summary"]["error"] == 0 else 1
- except RuntimeError as exc:
- print(f"Error: {exc}", file=sys.stderr)
- return 1
-
- parser.print_help()
- return 1
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/template_fill_pptx/notes.py b/skills/ppt-master/scripts/template_fill_pptx/notes.py
deleted file mode 100644
index 80705407..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/notes.py
+++ /dev/null
@@ -1,114 +0,0 @@
-"""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_package.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_entries
diff --git a/skills/ppt-master/scripts/template_fill_pptx/scaffolder.py b/skills/ppt-master/scripts/template_fill_pptx/scaffolder.py
deleted file mode 100644
index 0560711c..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/scaffolder.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""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": chart.get("categories", []),
- "series": chart.get("series") or [{"name": "系列1", "values": []}],
- }
- )
- slides.append(
- {
- "source_slide": slide["slide_index"],
- "purpose": slide.get("page_type", "content_candidate"),
- "layout_rationale": {
- "layout_pattern": "",
- "why_fit": "",
- "risk": "",
- },
- "replacements": replacements,
- "table_edits": table_edits,
- "chart_edits": chart_edits,
- }
- )
-
- return {
- "schema": "template_fill_pptx_plan.v1",
- "status": "draft",
- "source_pptx": library.get("source_pptx"),
- "accepted_warnings": [],
- "slides": slides,
- }
diff --git a/skills/ppt-master/scripts/template_fill_pptx/selectors.py b/skills/ppt-master/scripts/template_fill_pptx/selectors.py
deleted file mode 100644
index 2934006c..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/selectors.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""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.py
deleted file mode 100644
index 7d43605c..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/table_fill.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""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 .edit_safety import _table_cell_merge_info
-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] = []
- pending_edits: list[tuple[ET.Element, 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
- target_cell = row_cells[col_index]
- if _table_cell_merge_info(target_cell)["is_merge_slave"]:
- target = selectors[0] if selectors else "<table>"
- errors.append(
- f"{target} row={row_index} col={col_index} is a merged-cell slave "
- "[table_cell_is_merge_slave]; edit the merge anchor instead"
- )
- continue
- pending_edits.append((target_cell, _table_cell_text(cell_edit)))
- if errors:
- raise RuntimeError(f"Invalid table edit target(s) on slide {source_slide}: {'; '.join(errors)}")
- for target_cell, text in pending_edits:
- _set_container_text(target_cell, text)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/text_fill.py b/skills/ppt-master/scripts/template_fill_pptx/text_fill.py
deleted file mode 100644
index d441325a..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/text_fill.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""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.py
deleted file mode 100644
index b59110d1..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/transitions.py
+++ /dev/null
@@ -1,150 +0,0 @@
-"""apply: page-to-page transitions for cloned slides.
-
-Template Fill preserves each source transition unless the CLI or a per-slide
-plan entry requests a replacement. Effects and OOXML mutation come from the
-shared ``pptx_transitions`` core so every PPTX path uses the same writer.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-from xml.etree import ElementTree as ET
-
-from pptx_transitions import (
- AdvanceUpdate,
- EnterUpdate,
- apply_slide_motion,
- normalize_transition_effect_request,
- validate_seconds,
-)
-
-KEEP_TRANSITION = "keep"
-# Preserve source transitions unless the CLI or a per-slide plan entry selects
-# a replacement. The duration is consumed only when a visual effect is written.
-DEFAULT_TRANSITION = KEEP_TRANSITION
-DEFAULT_TRANSITION_DURATION = 0.5
-TRANSITION_OBJECT_FIELDS = frozenset(
- {
- "effect",
- "effect_options",
- "duration",
- "advance_after",
- }
-)
-
-_UNSET = object()
-
-
-def transition_unknown_fields(raw: dict[str, Any]) -> list[str]:
- """Return unsupported fields from a per-slide transition object."""
- return sorted(set(raw) - TRANSITION_OBJECT_FIELDS)
-
-
-def _set_slide_transition(
- slide_root: ET.Element,
- *,
- effect: str | None,
- duration: float,
- effect_options: dict[str, object] | None = None,
- advance_after: float | None = None,
-) -> bool:
- """Apply a legacy template-fill transition through the shared core.
-
- ``None`` and ``keep`` preserve the source transition. ``none`` removes the
- visual transition while retaining an explicitly requested auto-advance.
- Legacy ``advance_after`` allowed both click and timed advance, so it maps to
- ``both`` rather than the stricter ``after`` mode. The return value reports
- whether the resulting slide contains an automatic advance.
- """
- if effect is None or effect == KEEP_TRANSITION:
- enter = EnterUpdate(policy="preserve")
- advance = AdvanceUpdate(
- mode="preserve" if advance_after is None else "both",
- after=advance_after,
- )
- elif effect == "none":
- enter = EnterUpdate(policy="none", effect=None, duration=duration)
- advance = AdvanceUpdate(
- mode="click" if advance_after is None else "both",
- after=advance_after,
- )
- else:
- enter = EnterUpdate(
- policy="replace",
- effect=effect,
- duration=duration,
- effect_options=effect_options,
- )
- advance = AdvanceUpdate(
- mode="click" if advance_after is None else "both",
- after=advance_after,
- )
-
- try:
- return apply_slide_motion(
- slide_root,
- enter=enter,
- advance=advance,
- )
- except ValueError as exc:
- raise RuntimeError(str(exc)) from exc
-
-
-def _resolve_slide_transition(
- item: dict[str, Any],
- *,
- default_effect: str | None,
- default_duration: float,
-) -> tuple[str | None, dict[str, object], 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:
- if default_effect in (None, "none", KEEP_TRANSITION):
- return default_effect, {}, default_duration, None
- effect, effect_options = normalize_transition_effect_request(
- default_effect,
- allow_none=False,
- )
- return effect, effect_options, default_duration, None
- if isinstance(raw, dict):
- unknown = transition_unknown_fields(raw)
- if unknown:
- raise RuntimeError(
- "Transition has unknown field(s): " + ", ".join(unknown)
- )
- effect = raw.get("effect", default_effect)
- raw_options = raw.get("effect_options")
- if raw_options is not None and "effect" not in raw:
- raise RuntimeError(
- "Transition effect_options requires an explicit effect"
- )
- duration = raw.get("duration", default_duration)
- advance_after = raw.get("advance_after")
- else:
- effect = None if raw is None else str(raw)
- raw_options = None
- duration = default_duration
- advance_after = None
- effect_options: dict[str, object] = {}
- if effect is not None and effect not in ("none", KEEP_TRANSITION):
- try:
- effect, effect_options = normalize_transition_effect_request(
- effect,
- raw_options,
- allow_none=False,
- )
- except ValueError as exc:
- raise RuntimeError(str(exc)) from exc
- elif raw_options not in (None, {}):
- raise RuntimeError(
- "Transition effect_options requires an explicit native effect"
- )
- try:
- resolved_duration = validate_seconds(
- duration,
- "transition duration",
- allow_zero=False,
- )
- except ValueError as exc:
- raise RuntimeError(str(exc)) from exc
- return effect, effect_options, resolved_duration, advance_after
diff --git a/skills/ppt-master/scripts/template_fill_pptx/validator.py b/skills/ppt-master/scripts/template_fill_pptx/validator.py
deleted file mode 100644
index 492593e0..00000000
--- a/skills/ppt-master/scripts/template_fill_pptx/validator.py
+++ /dev/null
@@ -1,491 +0,0 @@
-"""validate: read back the latest template-fill export and check core contract."""
-
-from __future__ import annotations
-
-import re
-import subprocess
-import sys
-from pathlib import Path
-from typing import Any, Callable
-
-from .checker import _chart_lookup, _slot_lookup, _table_lookup
-from .ooxml import _load_json, _write_json
-from .selectors import (
- _chart_selectors,
- _replacement_selectors,
- _replacement_text,
- _table_cell_text,
- _table_selectors,
-)
-
-
-_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
-_SLIDE_HEADING_RE = re.compile(r"^## Slide\s+(\d+)\s*$", re.MULTILINE)
-_SPEAKER_NOTES_RE = re.compile(r"^### Speaker Notes\s*$", re.MULTILINE)
-_MARKDOWN_LINK_RE = re.compile(r"(?<!!)\[([^\]]+)\]\([^)]+\)")
-_LIST_PREFIX_RE = re.compile(r"^\s*(?:[-+*]|\d+[.)])\s+")
-_TABLE_BREAK_RE = re.compile(r"<br\s*/?>", re.IGNORECASE)
-_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")
-_ESCAPED_READBACK_CONTROL_RE = re.compile(
- r"^\\(## Slide\s+\d+|### Speaker Notes)$"
-)
-
-
-def _latest_export(project_path: Path) -> Path:
- exports_dir = project_path / "exports"
- candidates = [path for path in exports_dir.glob("*.pptx") if path.is_file()]
- if not candidates:
- raise RuntimeError(f"No PPTX exports found in: {exports_dir}")
- return max(candidates, key=lambda path: path.stat().st_mtime)
-
-
-def _readback_slide_count(markdown: str) -> int:
- return len(_SLIDE_HEADING_RE.findall(markdown))
-
-
-def _slide_sections(markdown: str) -> dict[int, str]:
- matches = list(_SLIDE_HEADING_RE.finditer(markdown))
- sections: dict[int, str] = {}
- for index, match in enumerate(matches):
- end = (
- matches[index + 1].start()
- if index + 1 < len(matches)
- else len(markdown)
- )
- sections[int(match.group(1))] = markdown[match.end():end].strip()
- return sections
-
-
-def _split_notes(section: str) -> tuple[str, str]:
- match = _SPEAKER_NOTES_RE.search(section)
- if match is None:
- return section, ""
- return section[:match.start()].strip(), section[match.end():].strip()
-
-
-def _normalize_line(value: str) -> str:
- return re.sub(r"\s+", " ", value).strip()
-
-
-def _unescape_readback_control_line(value: str) -> str:
- """Restore the display text of an escaped read-back section marker."""
- match = _ESCAPED_READBACK_CONTROL_RE.fullmatch(value)
- return match.group(1) if match else value
-
-
-def _paragraph_lines(value: object) -> list[str]:
- text = str(value or "").replace("\r\n", "\n").replace("\r", "\n")
- return [
- normalized
- for line in text.split("\n")
- if (normalized := _normalize_line(line))
- ]
-
-
-def _markdown_line_variants(markdown: str) -> list[set[str] | None]:
- variants: list[set[str] | None] = []
- for raw_line in markdown.splitlines():
- stripped = raw_line.strip()
- if (
- not stripped
- or stripped.startswith("|")
- or stripped.startswith("![")
- or stripped.startswith("> [Chart")
- or stripped == "_No extractable text content._"
- ):
- variants.append(None)
- continue
- display = _MARKDOWN_LINK_RE.sub(r"\1", stripped)
- without_prefix = _LIST_PREFIX_RE.sub("", display, count=1)
- line_variants = {
- _unescape_readback_control_line(_normalize_line(candidate))
- for candidate in (stripped, display, without_prefix)
- }
- line_variants.discard("")
- variants.append(line_variants)
- return variants
-
-
-def _contains_paragraphs(markdown: str, value: str) -> bool:
- expected = _paragraph_lines(value)
- if not expected:
- return True
- actual = _markdown_line_variants(markdown)
- if len(expected) > len(actual):
- return False
- for start in range(len(actual) - len(expected) + 1):
- if all(
- actual[start + offset] is not None
- and expected[offset] in actual[start + offset]
- for offset in range(len(expected))
- ):
- return True
- return False
-
-
-def _table_cells(markdown: str) -> list[list[str]]:
- cells: list[list[str]] = []
- for raw_line in markdown.splitlines():
- stripped = raw_line.strip()
- if not (stripped.startswith("|") and stripped.endswith("|")):
- continue
- values = re.split(r"(?<!\\)\|", stripped[1:-1])
- normalized_values = [
- value.strip().replace(r"\|", "|")
- for value in values
- ]
- if normalized_values and all(
- _TABLE_SEPARATOR_RE.fullmatch(value) is not None
- for value in normalized_values
- ):
- continue
- for value in normalized_values:
- cells.append(_paragraph_lines(_TABLE_BREAK_RE.sub("\n", value)))
- return cells
-
-
-def _contains_table_cell(markdown: str, value: str) -> bool:
- expected = _paragraph_lines(value)
- if not expected:
- return True
- return expected in _table_cells(markdown)
-
-
-def _contains_chart_text(markdown: str, value: str) -> bool:
- return (
- _contains_paragraphs(markdown, value)
- or _contains_table_cell(markdown, value)
- )
-
-
-def _first_library(project_path: Path) -> dict[str, Any] | None:
- libraries = sorted((project_path / "analysis").glob("*.slide_library.json"))
- if not libraries:
- return None
- return _load_json(libraries[0])
-
-
-def _matched_library_target(
- lookup: dict[tuple[int, str], dict[str, Any]] | None,
- source_slide: int,
- selectors: list[str],
-) -> dict[str, Any] | None:
- """Return the first library target matched by the runtime selector order."""
- if lookup is None:
- return None
- return next(
- (
- target
- for selector in selectors
- if (target := lookup.get((source_slide, selector))) is not None
- ),
- None,
- )
-
-
-def _replacement_tokens(
- plan: dict[str, Any],
- library: dict[str, Any] | None,
-) -> list[tuple[int, str, str, str]]:
- tokens: list[tuple[int, str, str, str]] = []
- slot_lookup = _slot_lookup(library) if library is not None else None
- for plan_slide, 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):
- continue
- slide_tokens: list[tuple[str, bool]] = []
- for replacement in replacements:
- if not isinstance(replacement, dict):
- continue
- text = _replacement_text(replacement)
- if not _paragraph_lines(text):
- continue
- slot = _matched_library_target(
- slot_lookup,
- source_slide,
- _replacement_selectors(replacement),
- )
- if (
- library is not None
- and replacement.get("optional")
- and slot is None
- ):
- continue
- is_title = (
- slot is not None
- and str(slot.get("role") or "") == "title_candidate"
- )
- slide_tokens.append((text, is_title))
- if (
- library is None
- and slide_tokens
- and not any(is_title for _, is_title in slide_tokens)
- ):
- first_text, _ = slide_tokens[0]
- slide_tokens[0] = (first_text, True)
- for text, is_title in slide_tokens:
- tokens.append(
- (
- plan_slide,
- text,
- (
- "title_missing_in_readback"
- if is_title
- else "body_text_missing_in_readback"
- ),
- "title" if is_title else "replacement text",
- )
- )
- return tokens
-
-
-def _table_tokens(
- plan: dict[str, Any],
- library: dict[str, Any] | None,
-) -> list[tuple[int, str]]:
- tokens: list[tuple[int, str]] = []
- table_lookup = _table_lookup(library) if library is not None else None
- for plan_slide, slide in enumerate(plan.get("slides", []), start=1):
- source_slide = int(slide.get("source_slide", 0))
- for table_edit in slide.get("table_edits", []) or []:
- table = _matched_library_target(
- table_lookup,
- source_slide,
- _table_selectors(table_edit),
- )
- if (
- library is not None
- and table_edit.get("optional")
- and table is None
- ):
- continue
- for cell in table_edit.get("cells", []) or []:
- text = _table_cell_text(cell)
- if _paragraph_lines(text):
- tokens.append((plan_slide, text))
- return tokens
-
-
-def _format_chart_series_value(value: object) -> str:
- """Match ppt_to_md's display formatting for chart series values."""
- if value is None:
- return ""
- if isinstance(value, float) and value.is_integer():
- return str(int(value))
- return str(value)
-
-
-def _chart_tokens(
- plan: dict[str, Any],
- library: dict[str, Any] | None,
-) -> list[tuple[int, str]]:
- tokens: list[tuple[int, str]] = []
- chart_lookup = _chart_lookup(library) if library is not None else None
- for plan_slide, slide in enumerate(plan.get("slides", []), start=1):
- source_slide = int(slide.get("source_slide", 0))
- for chart_edit in slide.get("chart_edits", []) or []:
- chart = _matched_library_target(
- chart_lookup,
- source_slide,
- _chart_selectors(chart_edit),
- )
- if (
- library is not None
- and chart_edit.get("optional")
- and chart is None
- ):
- continue
- for category in chart_edit.get("categories", []) or []:
- if str(category).strip():
- tokens.append((plan_slide, str(category)))
- for series in chart_edit.get("series", []) or []:
- name = str(series.get("name") or "").strip()
- if name:
- tokens.append((plan_slide, name))
- for value in series.get("values", []) or []:
- text = _format_chart_series_value(value)
- if text:
- tokens.append((plan_slide, text))
- return tokens
-
-
-def _append_page_token_checks(
- *,
- results: list[dict[str, Any]],
- summary: dict[str, int],
- sections: dict[int, str],
- tokens: list[tuple[int, str, str, str]],
- status: str,
- matcher: Callable[[str, str], bool],
-) -> None:
- summary_key = status.lower()
- for plan_slide, text, code, label in tokens:
- body, _ = _split_notes(sections.get(plan_slide, ""))
- if matcher(body, text):
- summary["ok"] += 1
- continue
- summary[summary_key] += 1
- results.append(
- {
- "status": status,
- "code": code,
- "plan_slide": plan_slide,
- "message": f"{label} not found on the corresponding read-back slide",
- "text": text,
- }
- )
-
-
-def validate_project(project_path: Path) -> dict[str, Any]:
- """Run read-back validation for a template-fill project."""
- project_path = project_path.expanduser().resolve()
- plan_path = project_path / "analysis" / "fill_plan.json"
- if not plan_path.is_file():
- raise RuntimeError(f"Missing fill plan: {plan_path}")
-
- plan = _load_json(plan_path)
- output_path = _latest_export(project_path)
- validation_dir = project_path / "validation"
- validation_dir.mkdir(parents=True, exist_ok=True)
- readback_path = validation_dir / "readback.md"
-
- ppt_to_md = _SCRIPTS_DIR / "source_to_md" / "ppt_to_md.py"
- try:
- subprocess.run(
- [sys.executable, str(ppt_to_md), str(output_path), "-o", str(readback_path)],
- cwd=_SCRIPTS_DIR.parents[2],
- check=True,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- except FileNotFoundError as exc:
- raise RuntimeError(f"Missing executable: {sys.executable}") from exc
- except subprocess.CalledProcessError as exc:
- details = (exc.stderr or exc.stdout or "").strip()
- raise RuntimeError(details or "ppt_to_md read-back failed") from exc
-
- markdown = readback_path.read_text(encoding="utf-8", errors="replace")
- results: list[dict[str, Any]] = []
- summary = {"ok": 0, "warn": 0, "error": 0}
- sections = _slide_sections(markdown)
-
- expected_slides = len(plan.get("slides", []) or [])
- actual_slides = _readback_slide_count(markdown)
- if expected_slides == actual_slides:
- summary["ok"] += 1
- else:
- summary["error"] += 1
- results.append(
- {
- "status": "ERROR",
- "code": "slide_count_mismatch",
- "expected": expected_slides,
- "actual": actual_slides,
- "message": "read-back slide count does not match fill_plan.slides",
- }
- )
-
- for plan_slide in range(1, expected_slides + 1):
- if plan_slide in sections:
- continue
- summary["error"] += 1
- results.append(
- {
- "status": "ERROR",
- "code": "slide_missing_in_readback",
- "plan_slide": plan_slide,
- "message": "planned slide section is missing from read-back Markdown",
- }
- )
-
- library = _first_library(project_path)
- _append_page_token_checks(
- results=results,
- summary=summary,
- sections=sections,
- tokens=_replacement_tokens(plan, library),
- status="ERROR",
- matcher=_contains_paragraphs,
- )
- _append_page_token_checks(
- results=results,
- summary=summary,
- sections=sections,
- tokens=[
- (plan_slide, text, "table_text_missing_in_readback", "table cell text")
- for plan_slide, text in _table_tokens(plan, library)
- ],
- status="ERROR",
- matcher=_contains_table_cell,
- )
- _append_page_token_checks(
- results=results,
- summary=summary,
- sections=sections,
- tokens=[
- (plan_slide, text, "chart_text_missing_in_readback", "chart text")
- for plan_slide, text in _chart_tokens(plan, library)
- ],
- status="WARN",
- matcher=_contains_chart_text,
- )
-
- for plan_slide, slide in enumerate(plan.get("slides", []) or [], start=1):
- _, notes = _split_notes(sections.get(plan_slide, ""))
- planned_notes = str(slide.get("notes") or slide.get("speaker_notes") or "")
- if _paragraph_lines(planned_notes):
- if _contains_paragraphs(notes, planned_notes):
- summary["ok"] += 1
- continue
- summary["error"] += 1
- results.append(
- {
- "status": "ERROR",
- "code": "notes_missing_in_readback",
- "plan_slide": plan_slide,
- "message": (
- "planned speaker notes not found on the corresponding "
- "read-back slide"
- ),
- "text": planned_notes,
- }
- )
- elif notes.strip():
- summary["warn"] += 1
- results.append(
- {
- "status": "WARN",
- "code": "unexpected_notes_in_readback",
- "plan_slide": plan_slide,
- "message": (
- "read-back slide contains speaker notes although the "
- "plan slide has no notes field"
- ),
- }
- )
-
- report = {
- "schema": "template_fill_pptx_validate.v1",
- "project": str(project_path),
- "export": str(output_path),
- "readback": str(readback_path),
- "summary": summary,
- "results": results,
- }
- _write_json(validation_dir / "validate_report.json", report)
- return report
-
-
-def print_validate_report(report: dict[str, Any]) -> None:
- """Print a compact validation report."""
- summary = report["summary"]
- print(f"validate: ok={summary['ok']} warn={summary['warn']} error={summary['error']}")
- print(f"export: {report['export']}")
- print(f"readback: {report['readback']}")
- for item in report["results"]:
- text = item.get("text")
- suffix = f" text={text!r}" if text else ""
- print(f"{item['status']} {item['code']}: {item['message']}{suffix}")
diff --git a/skills/ppt-master/workflows/native-enhance-pptx.md b/skills/ppt-master/workflows/native-enhance-pptx.md
deleted file mode 100644
index b34ce9ed..00000000
--- a/skills/ppt-master/workflows/native-enhance-pptx.md
+++ /dev/null
@@ -1,409 +0,0 @@
----
-description: Native enhancement platform for existing PPTX files, with delivery checks and scoped OOXML updates without SVG conversion
----
-
-# Enhance Native PPTX Route
-
-> Top-level route for enhancing an existing PowerPoint deck without regenerating it. The current write scope is speaker notes, narration audio, slide auto-advance timings, and global or per-slide page transitions; read-only delivery checks always run.
-
-This route treats a `.pptx` as the artifact to preserve. It archives the source file into a lightweight project, uses `ppt_to_md.py` only to understand slide content, then patches the archived PPTX package directly through OOXML zip operations.
-
----
-
-## 1. Platform Contract
-
-| Rule | Contract |
-|---|---|
-| Source file | If already under `projects/`, move it into the enhancement project; otherwise copy it |
-| Visible slides | Do not rewrite existing text, shapes, images, charts, tables, masters, or layouts |
-| Existing hyperlinks | Preserve hyperlink XML and relationships unchanged |
-| Route | Direct PPTX package patching; no SVG conversion |
-| Output | A new `.pptx` under `<project>/exports/` |
-| Project kind | `native_pptx_enhancement` |
-
-**Hard rule**: Native enhancement is append-oriented. It may add notes, media, timings, transitions, relationships, and content-type records. It must not regenerate slides.
-
-**Forbidden — SVG pipeline**:
-- Do not run `pptx_template_import.py`
-- Do not create `svg_output/`
-- Do not run `finalize_svg.py`
-- Do not run `svg_to_pptx.py`
-
-**Hard rule — public entrypoint**: Route and document all new work through
-`native_enhance_pptx.py`. The legacy `native_narration_pptx.py` command remains
-only as a thin CLI compatibility shim; it is not a separate route. The core
-continues to accept the legacy `native_narration_pptx_project.v1` project schema.
-
-**OOXML execution model**:
-
-```text
-source.pptx
-→ unzip to temporary work directory
-→ patch only required package parts
-→ rezip to exports/<source>_enhanced.pptx
-```
-
----
-
-## 2. Module Scope
-
-| Module | V1 status | Behavior |
-|---|---:|---|
-| `narration.notes` | Enabled | Add or replace speaker notes generated from slide content |
-| `narration.audio` | Enabled | Embed one audio file per slide |
-| `narration.timings` | Enabled | Set narrated slides to auto-advance from page-start lead-in, audio duration, and page-tail padding |
-| `narration.transitions` | Enabled | Add page-level transitions for narrated/selected slides |
-| `delivery.check` | Enabled | Read-only package/font/media/hidden-slide/file-size and existing-motion audit |
-| `delivery.compress` | Planned | Reduce embedded media size for oversized packages; the audit above already reports them |
-| `presenter` | Planned | Q&A notes, speaker cues, rehearsal artifacts |
-| `animation` | Planned | Explicit object-level animation only |
-| `visible-stamp` | Planned | Watermark/footer/logo; requires explicit confirmation |
-
-**Default — current write scope only**: Do not implement planned write modules inside this route yet. Keep mutations limited to notes, narration audio, timings, and page transitions.
-
-**Object animation boundary**: `delivery.check` reports existing object-animation presence, and apply proves its fingerprint is unchanged. It does not author or edit object animations. The shared animation writer builds a complete timing tree for generated slides and is not safe to append to an arbitrary native slide.
-
----
-
-## 3. When to Run
-
-| Condition | Action |
-|---|---|
-| Existing `.pptx` + wants notes / narration / voiceover / auto-play / page transitions while keeping format stable | Run this route |
-| Existing `.pptx` + asks to optimize it but says not to change existing content or layout | Run this route only for V1 narration enhancements; clarify any visible-slide request |
-| Existing `.pptx` + asks to beautify or re-layout | Enter Generate PPTX with the [`beautify-pptx`](./profiles/beautify-pptx.md) profile |
-| Existing `.pptx` + asks to fill new content into the design | Use [`template-fill-pptx`](./template-fill-pptx.md) |
-| PPT Master generated project with `svg_output/` | Stay in Generate PPTX and run the shared [`generate-audio`](./stages/generate-audio.md) stage |
-
----
-
-## 4. Create the Project and Draft Plan
-
-🚧 **GATE**: User provided an existing `.pptx`.
-
-Run:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py init "<source.pptx>" --name "<project_slug>"
-```
-
-Project layout:
-
-| Path | Purpose |
-|---|---|
-| `<project>/project.json` | Project schema, kind, enabled modules, source paths, defaults |
-| `<project>/sources/<source>.pptx` | Archived source PPTX used for package patching |
-| `<project>/sources/<source>.md` | `ppt_to_md.py` output for slide understanding |
-| `<project>/analysis/slide_index.json` | Slide order and PPTX slide part mapping |
-| `<project>/notes/` | Per-slide spoken notes, named `001.md`, `002.md`, ... |
-| `<project>/audio/` | Per-slide narration media, named `001.mp3`, `002.mp3`, ... |
-| `<project>/exports/` | Enhanced PPTX copies |
-| `<project>/validation/` | Delivery checks, readiness reports, and read-back artifacts |
-
-**Validation**: `project.json` contains `schema: native_pptx_enhancement_project.v1`, `kind: native_pptx_enhancement`, and `modules` containing `notes`, `audio`, `timings`, `transitions`, and `delivery.check`.
-
-`init` records the archived source SHA-256 and ordered slide-part roster, then writes the intake audit to `<project>/validation/report.json`. Package-integrity, OPC part/content-type/relationship, XML, slide-inventory, transition, or object-animation errors stop before a project-local source is moved. The only retained historical structural baseline is the narrowly recognized legacy notes-slide relationship to a missing notes master; it remains visible in the report and apply may not add any new structural error.
-
-**Source import rule**: When `<source.pptx>` is inside the repo's `projects/` tree, `init` moves it into `<project>/sources/`. When it is outside `projects/`, `init` copies it into `<project>/sources/`. The mode is recorded in `project.json` as `source_import.mode`.
-
-The `init` command also writes:
-
-```text
-<project>/analysis/enhancement_plan.json
-```
-
-**Hard rule**: Treat this draft plan as the first user-facing artifact. Do not generate notes, list voices, generate audio, or apply package patches before the user confirms which enhancements to add.
-
----
-
-## 5. Enhancement Plan Confirmation
-
-🚧 **GATE**: Step 4 complete; `<project>/analysis/enhancement_plan.json` exists.
-
-If the project already existed or notes/audio coverage changed, refresh the draft:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py plan "<project>"
-```
-
-`plan` preserves module settings, refreshes coverage, and emits a
-reconfirmation `draft`. It changes `audio.enabled: true` /
-`notes.enabled: false` to `notes.enabled: true`; `validate`/`apply` reject the
-old state. Audio remains unchecked until `validate` runs ffprobe. Supplied CLI
-flags override.
-
-Present the plan to the user before generating notes or audio:
-
-| Module | Recommended default | Confirmation question |
-|---|---|---|
-| `notes` | Enabled; required whenever audio is enabled | Add/replace speaker notes generated from slide content? |
-| `audio` | Enabled when user wants narration/video/autoplay | After notes are complete, generate one narration audio file per slide? |
-| `timings` | Enabled with audio; 0.8s page-start floor and 0.4s page-tail padding | Set slide auto-advance from narration timing? |
-| `transitions` | Enabled, `fade` 0.5s | Add page transitions? Which canonical native effect, Effect Options, and duration? |
-| `delivery.check` | Always on, read-only | No confirmation required; review errors and advisories |
-
-**⛔ BLOCKING**: Stop here and wait for explicit user confirmation. Do not generate notes, generate audio, or patch the PPTX until the user confirms the module plan.
-
-**Hard dependency — notes before audio**: Confirming `audio.enabled: true`
-also requires `notes.enabled: true`. If complete per-slide notes do not already
-exist, run Step 6 and generate them before entering audio configuration or
-audio generation. Never generate narration directly from slide text or bypass
-the notes artifact.
-
-**Transition/timing ownership**:
-
-| Confirmed state | Enter transition | Slide advance |
-|---|---|---|
-| Transitions enabled with an effect | Replace with that exact effect and duration | Preserve unless timings is enabled |
-| Transitions disabled with a non-`none` configured effect | Preserve the source effect, including unknown `AlternateContent` | Preserve unless timings is enabled |
-| Explicit `none` | Remove the visual effect | Preserve, or write timing-only advance when timings is enabled |
-| Timings enabled with audio | Keep the resolved enter policy | Use page-start lead-in plus audio duration plus page-tail padding; click disabled |
-| Timings disabled | Apply the confirmed enter policy only | Use duration only to reject source auto-advance that would truncate narration; do not derive, add, or change `advTm` / `useTimings` |
-
-The timing module's `narration_start_floor` and `narration_padding` are
-independent optional values. When omitted, use `0.8` and `0.4` seconds
-respectively. For a destination-page transition of `T` seconds, the
-post-transition lead-in is
-`max(0, narration_start_floor - T)`: narration does not begin during the
-transition, and the transition duration itself remains unchanged. A start
-floor of `0` means start immediately after the transition completes. A
-preserved legacy transition that exposes only `spd` has no exact millisecond
-duration; keep the full configured floor after that transition instead of
-guessing a PowerPoint-specific duration. When timings are disabled, preserve
-source `advTm`, but fail if it would advance before the delayed narration ends.
-
-The confirmed `modules.transitions` object may include `effect_options` beside
-an explicit canonical `effect`. Use
-`pptx_animations.py --describe-transition <effect>` for its exact fields.
-Old names remain accepted only when reading compatibility input; a newly
-written plan stores the canonical effect and any implied options.
-
-For explicit page selection or page-specific settings, add `slides` keyed by
-the 1-based `index` in `analysis/slide_index.json`:
-
-```json
-{
- "modules": {
- "transitions": {
- "enabled": false,
- "effect": "fade",
- "duration": 0.5,
- "apply_without_audio": false,
- "slides": {
- "2": {},
- "3": {"duration": 0.8},
- "4": {
- "effect": "push",
- "effect_options": {"direction": "left"}
- },
- "5": {"effect": "none"},
- "6": {"effect": "preserve"}
- }
- }
- }
-}
-```
-
-| Per-slide entry | Behavior |
-|---|---|
-| `{}` | Select the page and inherit the global effect/options/duration |
-| Partial object | Inherit omitted global fields; a new explicit effect uses its own default options |
-| `effect: none` | Remove the visual transition; timings remain independently owned |
-| `effect: preserve` | Preserve the source visual transition; narration timing may still update advance |
-
-A `slides` entry always selects that page. Without audio, enabled global effects
-and explicit global `none` apply deck-wide; `apply_without_audio` is ignored.
-With audio, the flag extends the global policy from narrated to all pages.
-Disabled non-`none` effects preserve unlisted pages. Morph uses PowerPoint
-automatic matching; this route does not rename native objects for deterministic
-pairs.
-
-**Hard rule — no silent downgrade**: a requested native effect must be written with its complete validated Effect Options. Unknown effects or inapplicable options fail; unknown source effects are preserved when the transition module is disabled.
-
-After confirmation, update `<project>/analysis/enhancement_plan.json`:
-
-```json
-{
- "status": "confirmed"
-}
-```
-
-Also set each confirmed module's `enabled` value. Disabled modules must stay in the file with `enabled: false`, not be deleted.
-
----
-
-## 6. Generate Notes From Existing Slides
-
-🚧 **GATE**: Step 5 confirmed; `notes.enabled` is true; `<project>/sources/<source>.md` exists.
-
-Read:
-
-| File | Use |
-|---|---|
-| `<project>/sources/<source>.md` | Visible slide text, tables, extracted notes, image references |
-| `<project>/analysis/slide_index.json` | Exact slide count and target note filenames |
-
-Write:
-
-```text
-<project>/notes/001.md
-<project>/notes/002.md
-...
-```
-
-**Hard rule**: Notes are spoken narration only. Do not include stage directions, implementation comments, timing labels, markdown tables, or visible-slide rewrite instructions.
-
-**Hard rule**: Notes must be faithful to the slide. They may explain visible content, but must not add unsupported facts.
-
-| Slide type | Notes length |
-|---|---|
-| Cover / section divider | 1-2 short sentences |
-| Dense content page | 2-4 sentences |
-| Chart / table page | Explain the reading path, then state the takeaway |
-| Ending page | One concise close |
-
-Run coverage check:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py validate "<project>" --materials notes
-```
-
-> Note: This keeps source/plan/transition/carrier checks but does not require
-> audio. Missing/invalid notes return `2`; structural/semantic errors return
-> `1`. Step 8 runs full validation after audio.
-
----
-
-## 7. Shared Audio Configuration
-
-🚧 **GATE**: Step 6 complete; `audio.enabled` is true.
-
-Run [`generate-audio`](./stages/generate-audio.md) Steps 1–3. That shared stage exclusively owns language selection, provider/voice catalog lookup, recommendation rules, and the one-shot confirmation. Do not repeat or fork those rules here.
-
-Record the confirmed config into `project.json`:
-
-```json
-{
- "audio": {
- "provider": "edge",
- "voice": "zh-CN-YunjianNeural",
- "rate": "+0%"
- }
-}
-```
-
----
-
-## 8. Run the Shared Audio Stage
-
-🚧 **GATE**: Step 7 confirmed; complete non-empty notes files exist under
-`<project>/notes/` for every slide.
-
-Run [`generate-audio`](./stages/generate-audio.md) Step 4 with `<project>` and the confirmed values. Stop after audio generation; do not run its Generate-PPTX-only `svg_to_pptx.py --recorded-narration` integration. This route integrates audio through Step 9 instead.
-
-**Naming contract**: Audio stems match note stems: `001.md` → `001.mp3`.
-
-Validate:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py validate "<project>"
-```
-
----
-
-## 9. Apply V1 Enhancements
-
-🚧 **GATE**: Enhancement plan is confirmed; notes are ready if requested; audio is ready if requested.
-
-Run:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py apply "<project>"
-```
-
-Optional:
-
-```bash
-python3 skills/ppt-master/scripts/native_enhance_pptx.py apply "<project>" \
- --transition fade \
- --transition-duration 0.5 \
- --narration-start-floor 0.8 \
- --narration-padding 0.4 \
- --apply-transition-without-audio \
- --overwrite
-```
-
-`--apply-transition-without-audio` matters only with audio enabled: it extends
-the global enter policy from narrated slides to all slides. Explicit slide
-entries always opt in. Without audio, enabled transitions apply to every slide.
-
-`apply` reruns the same source/readiness/plan checks as `validate`. Enabling
-audio always requires every selected file to be decodable by ffprobe; enabling
-timings additionally consumes that duration for `advTm`. It refuses
-partial requested material, a changed source hash/slide roster, or a source
-that already contains a `native_enhance_audio_*` carrier. New audio/poster
-parts use collision-free names; an existing poster is reused only when its
-bytes match the tool marker exactly. Output must be a new `.pptx` under
-`exports/` or an external location; apply never overwrites either source or
-writes into project control directories. Every apply attempt invalidates the
-previous validation receipt, and a failed preflight records its current errors
-instead of leaving stale passed evidence.
-
-Patch scope:
-
-| Package area | Append/update |
-|---|---|
-| `ppt/notesSlides/` | Notes slide parts |
-| `ppt/notesMasters/` | Notes master only when needed |
-| `ppt/slides/_rels/slideN.xml.rels` | Relationships for notes/audio/media/poster |
-| `ppt/media/` | Narration audio and transparent poster |
-| `ppt/slides/slideN.xml` | Hidden autoplay audio shape and page timing |
-| `ppt/presProps.xml` | `showPr useTimings=1` only when this run writes automatic slide advance |
-| `[Content_Types].xml` | Required content types |
-
-**Hard rule**: Do not modify existing slide shapes, text bodies, images, chart
-data, master/layout parts, hyperlink XML/relationships, or existing non-target
-relationships.
-
-Before publishing the candidate, apply validates transitions, timing/object
-animation structure, ZIP integrity, unique parts, internal relationships,
-slide count, and hidden-slide state. The narrowly allowed legacy missing
-notes-master finding may remain exactly equivalent, but the candidate must not
-introduce any structural error. Apply then writes both audits and the
-introduced-error delta to `<project>/validation/report.json`.
-
----
-
-## 10. Validate Output
-
-Run read-back:
-
-```bash
-python3 skills/ppt-master/scripts/source_to_md/ppt_to_md.py \
- "<project>/exports/<source>_enhanced.pptx" \
- -o "<project>/validation/readback.md"
-```
-
-Check:
-
-| Check | Expected |
-|---|---|
-| Slide count | Same as source |
-| Visible content | No intentional changes |
-| Notes | Present on intended slides |
-| Audio media | Present under `ppt/media/` when generated |
-| Auto-play | Narrated slides wait for the resolved page-start lead-in, then advance after audio duration plus page-tail padding |
-| Transition | Requested effect remains exact; preserved `AlternateContent` keeps its primary and fallback branches |
-| Timings disabled | Source `advTm` and package `useTimings` are not changed |
-| Delivery check | No newly introduced structural errors; source baseline and font/media/hidden-slide advisories reviewed |
-
-```markdown
-## ✅ Native PPTX Enhancement V1 Complete
-
-- [x] Project initialized at `<project>`
-- [x] Source PPTX archived into `<project>/sources/`
-- [x] Confirmed native enhancement modules applied
-- [x] Enhanced PPTX exported to `<project>/exports/<file>.pptx`
-- [x] Delivery postflight written to `<project>/validation/report.json`
-- [x] Read-back validation written to `<project>/validation/readback.md`
-```
diff --git a/skills/ppt-master/workflows/template-fill-pptx.md b/skills/ppt-master/workflows/template-fill-pptx.md
deleted file mode 100644
index b3202ad1..00000000
--- a/skills/ppt-master/workflows/template-fill-pptx.md
+++ /dev/null
@@ -1,379 +0,0 @@
----
-description: Fill Native PPTX route — use a native PowerPoint template deck, select fitting pages, and fill new material back without SVG conversion
----
-
-# Fill Native PPTX Route
-
-> Run when the user provides a raw `.pptx` template plus new content / a new topic and asks to generate a `.pptx` from that template. Typical requests include "use this PPT template to generate a PPTX", "fill this deck with the new content", "fill this back into the template", "replace the copy in this PowerPoint", or "keep the original PowerPoint pages and swap in this material". This route treats the existing `.pptx` as a native slide library and produces a new `.pptx` by selecting, cloning, and patching source slides.
-
-This route 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.
-
-**Boundary against template-based generation**: run this route for raw PPTX template + generated PPTX requests. Skip this route only when the user explicitly wants a reusable template workspace or an SVG-generated deck that can freely select / repeat / skip / adapt template pages. In that case, they must run [`create-template.md`](./create-template.md) first and then provide the generated workspace root to Generate PPTX.
-
-| User wants | Route |
-|---|---|
-| Generate a PPTX from a raw PPTX template | This route |
-| Directly edit / fill cloned PPTX slides | This route |
-| Create a reusable design asset from the PPTX | `create-template` |
-| Generate a new PPT from a reusable template package | Main pipeline Step 3 with the explicit template directory path |
-| Generate through the SVG pipeline directly from a raw PPTX "template" | Not allowed; create the template package first |
-
-## When to Run
-
-Recognize requests that combine an existing PowerPoint template with new content or a topic and ask for a generated `.pptx` without explicitly requesting the reusable SVG/template-package route:
-
-| Pattern | Example |
-|---|---|
-| Existing `.pptx` + "fill back" intent | "Use this deck and fill in the attached material" |
-| Raw PPTX template + generated PPTX | "Use this PowerPoint template to generate a PPTX about this topic" |
-| Existing `.pptx` + selective reuse | "Do not keep every page; only use the slides that fit" |
-| Existing `.pptx` + copywriting replacement | "Keep the original design and replace the copy with this text" |
-| Native PPT template fill | "Use this PowerPoint template for this content and fill the slides directly" |
-| Direct wording | "Fill this deck with the new content" |
-
-**Hard rule**: Do not run `pptx_to_svg.py`, `pptx_template_import.py`, `finalize_svg.py`, or `svg_to_pptx.py` for this route. SVG conversion is for presentation generation / template creation; this route is direct PowerPoint editing.
-
-**Deterministic routing rule**: do not ask a route-choice question for raw PPTX template + generated PPTX requests; route them here. If the user asks for SVG/template-workspace generation from a raw PPTX, state that `create-template` must run first and stop this route until they provide the generated workspace root.
-
----
-
-## 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. Reuse the standard project manager so source import rules stay consistent with the rest of the repository:
-
-```bash
-python3 skills/ppt-master/scripts/project_manager.py init "<project_name>"
-python3 skills/ppt-master/scripts/project_manager.py import-sources "<project_dir>" "<source.pptx>" "<material...>"
-```
-
-The source PPTX slide size remains the native canvas authority. Do not add an
-initialization `--format` unless that source canvas has already been verified
-as an exact registered format.
-
-**Source import rule**: `project_manager.py import-sources` moves only sources under repository `projects/` and copies all others. `--copy` preserves a projects-local input; `--move` never widens that scope. Reuse this path.
-
-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 PPTX Intake Bundle
-
-`project_manager.py import-sources` automatically runs the standard PPTX intake for imported PowerPoint files and writes `<stem>.slide_library.json` into `<project_dir>/analysis/`. If you are working from a manually assembled project that does not have the intake artifact, run the template-fill analyzer directly:
-
-```bash
-python3 skills/ppt-master/scripts/template_fill_pptx.py analyze "<project_dir>/sources/<source.pptx>" -o "<project_dir>/analysis/<stem>.slide_library.json"
-```
-
-Read `<project_dir>/analysis/<stem>.slide_library.json` (intake prefixes per-deck artifacts by the template deck's file stem) 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, per-cell coordinates/text, and merge anchor/slave topology |
-| `slides[].charts[]` | Native PowerPoint charts with `chart_id` and an `edit_capability` safety result derived from the actual chart XML |
-| `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.
-
-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 `<stem>.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 |
-| `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.
-
-**Required mapping pass**: Record a concise page-to-layout rationale in each planned slide before finalizing the plan. Use the per-slide `layout_rationale` object in `fill_plan.json` with `layout_pattern`, `why_fit`, and `risk`. This is human-review evidence that selection came from template structure rather than sequential replacement; it is not a mechanical checker gate.
-
----
-
-## Step 4: Build the Fill Plan
-
-Create a scaffold:
-
-```bash
-python3 skills/ppt-master/scripts/template_fill_pptx.py scaffold "<project_dir>/analysis/<stem>.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.
-
-**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 `<stem>.slide_library.json`; do not let scaffold output constrain the deck structure.
-
-The plan structure:
-
-```json
-{
- "schema": "template_fill_pptx_plan.v1",
- "status": "draft",
- "source_pptx": "projects/source.pptx",
- "accepted_warnings": [
- {
- "plan_slide": 3,
- "slot_id": "s03_sh5",
- "code": "text_capacity",
- "reason": "User accepted dense wording"
- }
- ],
- "slides": [
- {
- "source_slide": 1,
- "purpose": "cover",
- "layout_rationale": {
- "layout_pattern": "hero cover",
- "why_fit": "Large title and subtitle slots fit the opening message without redesign.",
- "risk": "Subtitle must stay short."
- },
- "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 |
-|---|---|
-| `status` | Keep `"draft"` until the user has reviewed the page sequence / reuse / deletion decisions. Set to `"confirmed"` only after approval. |
-| `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 |
-| `layout_rationale` | Human review aid for page selection. Include `layout_pattern`, `why_fit`, and `risk`; it is not a mechanical checker gate. |
-| `accepted_warnings` | Optional audit trail for warnings the user or agent explicitly accepts. `check-plan` warnings remain non-blocking; errors must be fixed. |
-| `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. New plans use one canonical native gallery effect from [`animations.md`](../references/animations.md) §3; old names remain read-compatible. Accepts `none` to remove the visual effect, `keep` to preserve the source, or an object containing only `effect`, `effect_options`, `duration`, and `advance_after`, such as `{ "effect": "push", "effect_options": { "direction": "left" }, "duration": 0.6, "advance_after": 5 }`. `check-plan` and `apply` reject unknown object fields. |
-| `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, 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; edit ordinary cells or a merge anchor only. A merge slave is not visible and is rejected by both `check-plan` and `apply`. This route never changes table structure. |
-| Native charts | Each series `values` list must match the category count. Single-plot classic charts whose every series uses `c:cat/c:val` are editable; analyzer/checker preflight the structure and the runtime writer revalidates the actual chart XML before mutation. |
-| Chart edit boundary | A single classic plot is editable when every series uses `c:cat/c:val`, including stock, 3D, surface, and other classic plot types. Date-axis and multi-level categories are accepted with a warning because replacement categories are flattened to one level. Scatter, bubble, ChartEx/unknown frames, multi-plot/combo charts, missing-series charts, and non-`c:cat/c:val` data models are rejected. Use beautify / main pipeline to redraw unsupported charts, or leave the native chart untouched. |
-| 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.
-- 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:
-
-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/<stem>.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 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.
-
-**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.
-
----
-
-## Step 6: Apply the Plan
-
-⛔ **BLOCKING GATE**: The user has reviewed the planned output order, omitted pages, reused pages, and material-to-layout fit. Set `<project_dir>/analysis/fill_plan.json` top-level `status` to `"confirmed"` only after that review. `apply` rejects an unconfirmed plan by default; `--force` exists only for deliberate recovery/debug use.
-
-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` preserves every cloned slide's existing transition. Select
-`--transition <effect>` to replace it with a canonical gallery effect from
-[`animations.md`](../references/animations.md) §3, and use
-`--transition-duration <seconds>` for the replacement duration; old names
-remain accepted only as compatibility CLI inputs. Pass `--transition none` for
-no visual motion. `--transition keep` states the default preservation policy
-explicitly. A per-slide `transition` field overrides the CLI and may include
-native `effect_options`; these require an explicit effect and are validated
-effect-by-effect. `advance_after` keeps click advance enabled and adds timed
-advance; it also works with `none` (timing-only transition) and `keep` (source
-effect preserved, Choice/Fallback timing updated together).
-
-`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` | Applies the requested visual-transition and slide-advance policy; `keep` may preserve no carrier and `none` may remove it |
-| 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) |
-
-**Hyperlink preservation**: External hyperlinks remain unchanged. A same-deck
-slide jump is retargeted only when its source destination maps unambiguously to
-one output slide; a self-link maps to the current clone. If the destination was
-omitted or reused into multiple output slides, `apply` fails instead of linking
-to an orphan or choosing a target silently.
-
-**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). It also preserves source page transitions by default.
-Use `apply --transition` or a per-slide `transition` field only when the user
-requests a replacement or removal. `keep` preserves direct and
-`mc:AlternateContent` transition effects without converting unknown effects to
-`fade`; explicit replacement removes the old logical carrier before writing one
-new carrier. 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/template_fill_pptx.py validate "<project_dir>"
-```
-
-The validator finds the latest PPTX in `<project_dir>/exports/`, runs `ppt_to_md.py` into `<project_dir>/validation/readback.md`, and writes `<project_dir>/validation/validate_report.json`. `exports/` must contain 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 readable from the extracted Markdown when `ppt_to_md.py` can surface them |
-| Multi-line body text | Preserves intended line / paragraph breaks |
-| Speaker notes | Read-back note count matches planned `notes` fields |
-| 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] Standard PPTX intake extracted from the source deck, including `<stem>.slide_library.json`
-- [x] `fill_plan.json` selects only pages that fit the target story
-- [x] User reviewed the story structure and `fill_plan.json` has `status: "confirmed"`
-- [x] `check-plan` run; errors fixed; warnings reviewed / optionally recorded in `accepted_warnings`
-- [x] Output PPTX generated through direct OOXML text replacement
-- [x] Speaker notes embedded when `notes` fields are present
-- [x] `template_fill_pptx.py validate` read-back 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 for ordinary cells and merge anchors; merge slaves fail closed |
-| Edit native PowerPoint chart categories / series data | Supported for single-plot classic `c:cat/c:val` charts; runtime XML validation remains authoritative |
-| 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 animations | Not authored in v1; entrance, emphasis, motion-path, and exit effects are preserved from source only and handled as a separate task |
-| Edit chart formatting / axes / legend layout | 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 route fills text into existing slots, it does not author an outline from a source, so the Generate PPTX `content_divergence` free-text field has no role here |