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): add deck-level page plans to round-trip export

hugohe3a2d356a87214
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index ab7bc0bd..1541301a 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -166,6 +166,20 @@ deterministic extraction baseline, restores unchanged refs from the immutable
layered backing, and sends the temporary result through preserve export while
leaving edited/deleted/new authoring content in place.
+An imported round-trip workspace may optionally add root `page_plan.json` to
+select, reorder, repeat, or omit source slides during export. The v1 shape is
+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.
+`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;
+slide-jump targets must map to exactly one output page. Without the file, the
+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.
+
`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
diff --git a/skills/ppt-master/scripts/authoring_roundtrip.py b/skills/ppt-master/scripts/authoring_roundtrip.py
index f99bf68f..3e748ad9 100644
--- a/skills/ppt-master/scripts/authoring_roundtrip.py
+++ b/skills/ppt-master/scripts/authoring_roundtrip.py
@@ -35,7 +35,10 @@ from extract_svg_assets import (
VECTOR_INVENTORY_SCHEMA,
extract_file,
)
-from pptx_workspace import ROUNDTRIP_MANIFEST_PATH
+from pptx_workspace import (
+ ROUNDTRIP_MANIFEST_PATH,
+ ROUNDTRIP_PAGE_PLAN_PATH,
+)
from slide_roster import discover_slide_svgs
from svg_authoring_view import (
AUTHORING_OMITTED_SOURCE_ATTRIBUTES,
@@ -53,6 +56,7 @@ from svg_compatibility import normalize_single_child_group_filters
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
IMPORTED_ICON_NAMESPACE = "imported"
+ROUNDTRIP_PAGE_PLAN_SCHEMA = "ppt-master.roundtrip-page-plan.v1"
_URL_ID_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"\s]+)\1\s*\)")
_PRESERVED_EFFECT_ATTRIBUTES = frozenset({
"data-pptx-effect-ooxml",
@@ -81,6 +85,8 @@ class SourceRefRecord:
@dataclass(frozen=True)
class AuthoringDocument:
name: str
+ source_name: str
+ source_slide: int
authoring_path: Path
flat_source_path: Path
layered_source_path: Path
@@ -122,9 +128,26 @@ class RefOccurrence:
@dataclass(frozen=True)
class AuthoringRoundtripResult:
svg_files: tuple[Path, ...]
+ authoring_files: tuple[Path, ...]
+ pages: tuple["RoundtripPage", ...]
+ page_plan_present: bool
report: dict[str, Any]
+@dataclass(frozen=True)
+class RoundtripPage:
+ """One output page resolved from the optional deck-level plan."""
+
+ output_index: int
+ source_slide: int
+ svg_name: str
+ source_svg_name: str
+
+ @property
+ def svg_stem(self) -> str:
+ return Path(self.svg_name).stem
+
+
def _local_name(name: object) -> str:
return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""
@@ -202,10 +225,62 @@ def is_flat_authoring_bundle(authoring_dir: Path) -> bool:
)
+def _roundtrip_source_svg_names(
+ manifest: dict[str, Any],
+) -> dict[int, str]:
+ """Map every source slide index to its canonical flat SVG basename."""
+ raw_slides = manifest.get("slides")
+ if not isinstance(raw_slides, list) or not raw_slides:
+ raise AuthoringRoundtripError(
+ "Round-trip workspace manifest slides must be a non-empty array"
+ )
+ names: dict[int, str] = {}
+ for offset, raw in enumerate(raw_slides):
+ context = f"round-trip slides[{offset}]"
+ if not isinstance(raw, dict):
+ raise AuthoringRoundtripError(f"{context} must be an object")
+ index = raw.get("index")
+ flat_svg = raw.get("flatSvg")
+ if (
+ not isinstance(index, int)
+ or isinstance(index, bool)
+ or index < 1
+ ):
+ raise AuthoringRoundtripError(
+ f"{context}.index must be a positive integer"
+ )
+ if not isinstance(flat_svg, str) or not flat_svg:
+ raise AuthoringRoundtripError(
+ f"{context}.flatSvg must be a non-empty string"
+ )
+ name = Path(flat_svg).name
+ if Path(name).suffix.lower() != ".svg":
+ raise AuthoringRoundtripError(
+ f"{context}.flatSvg must name an SVG file"
+ )
+ if index in names:
+ raise AuthoringRoundtripError(
+ f"Round-trip workspace repeats source slide {index}"
+ )
+ names[index] = name
+ expected = set(range(1, len(names) + 1))
+ if set(names) != expected:
+ raise AuthoringRoundtripError(
+ "Round-trip source slide indices must be contiguous from 1"
+ )
+ return names
+
+
def _load_documents(
project_path: Path,
authoring_dir: Path,
-) -> tuple[Path, Path, dict[str, AuthoringDocument], dict[str, Any]]:
+) -> tuple[
+ Path,
+ Path,
+ dict[str, AuthoringDocument],
+ dict[str, Any],
+ dict[str, Any],
+]:
manifest_path = authoring_dir / AUTHORING_MANIFEST_NAME
manifest = _load_json(manifest_path, context="flat authoring manifest")
if manifest.get("schema") != AUTHORING_SCHEMA:
@@ -295,6 +370,12 @@ def _load_documents(
f"Round-trip layered SVG backing directory is missing: {layered_root}"
)
+ source_svg_names = _roundtrip_source_svg_names(roundtrip_manifest)
+ source_slide_by_name = {
+ name: index
+ for index, name in source_svg_names.items()
+ }
+
documents_raw = manifest.get("documents")
if not isinstance(documents_raw, list):
raise AuthoringRoundtripError(
@@ -318,6 +399,12 @@ def _load_documents(
raise AuthoringRoundtripError(
f"Duplicate authoring manifest document: {authoring_name}"
)
+ source_slide = source_slide_by_name.get(authoring_name)
+ if source_slide is None:
+ raise AuthoringRoundtripError(
+ "Authoring manifest document is not registered by the round-trip "
+ f"source roster: {authoring_name}"
+ )
authoring_path = _resolve_inside(
authoring_dir,
authoring_name,
@@ -441,6 +528,8 @@ def _load_documents(
)
documents[authoring_name] = AuthoringDocument(
name=authoring_name,
+ source_name=authoring_name,
+ source_slide=source_slide,
authoring_path=authoring_path,
flat_source_path=flat_source_path,
layered_source_path=layered_source_path,
@@ -448,16 +537,11 @@ def _load_documents(
source_refs=refs,
)
- actual_files = {
- path.relative_to(authoring_dir).as_posix()
- for path in authoring_dir.rglob("*.svg")
- if path.is_file()
- }
- if actual_files != set(documents):
+ if set(documents) != set(source_slide_by_name):
raise AuthoringRoundtripError(
- "Authoring manifest/file roster differs; missing="
- f"{sorted(set(documents) - actual_files)}, "
- f"extra={sorted(actual_files - set(documents))}"
+ "Authoring manifest/source slide roster differs; missing="
+ f"{sorted(set(source_slide_by_name) - set(documents))}, "
+ f"extra={sorted(set(documents) - set(source_slide_by_name))}"
)
if manifest.get("file_count") != len(documents):
raise AuthoringRoundtripError(
@@ -468,7 +552,183 @@ def _load_documents(
raise AuthoringRoundtripError(
"authoring_manifest.json source_ref_count does not match documents"
)
- return source_root, proxy_root, documents, manifest
+ return source_root, proxy_root, documents, manifest, roundtrip_manifest
+
+
+def _identity_pages(
+ documents: dict[str, AuthoringDocument],
+) -> tuple[RoundtripPage, ...]:
+ by_slide = {
+ document.source_slide: document
+ for document in documents.values()
+ }
+ return tuple(
+ RoundtripPage(
+ output_index=index,
+ source_slide=index,
+ svg_name=by_slide[index].name,
+ source_svg_name=by_slide[index].name,
+ )
+ for index in range(1, len(by_slide) + 1)
+ )
+
+
+def _load_page_plan(
+ project_path: Path,
+ authoring_dir: Path,
+ documents: dict[str, AuthoringDocument],
+) -> tuple[tuple[RoundtripPage, ...], bool]:
+ """Load the optional strict page plan or return the identity page order."""
+ plan_path = project_path / ROUNDTRIP_PAGE_PLAN_PATH
+ if not plan_path.exists():
+ actual_files = {
+ path.relative_to(authoring_dir).as_posix()
+ for path in authoring_dir.rglob("*.svg")
+ if path.is_file()
+ }
+ if actual_files != set(documents):
+ raise AuthoringRoundtripError(
+ "Authoring manifest/file roster differs; missing="
+ f"{sorted(set(documents) - actual_files)}, "
+ f"extra={sorted(actual_files - set(documents))}"
+ )
+ return _identity_pages(documents), False
+ if not plan_path.is_file():
+ raise AuthoringRoundtripError(
+ f"Round-trip page plan must be a file: {plan_path}"
+ )
+ payload = _load_json(plan_path, context="round-trip page plan")
+ unknown_root_fields = sorted(set(payload) - {"schema", "pages"})
+ if unknown_root_fields:
+ raise AuthoringRoundtripError(
+ "Round-trip page plan has unsupported field(s): "
+ + ", ".join(unknown_root_fields)
+ )
+ if payload.get("schema") != ROUNDTRIP_PAGE_PLAN_SCHEMA:
+ raise AuthoringRoundtripError(
+ "Unsupported round-trip page plan schema: "
+ f"{payload.get('schema')!r}; expected {ROUNDTRIP_PAGE_PLAN_SCHEMA!r}"
+ )
+ raw_pages = payload.get("pages")
+ if not isinstance(raw_pages, list) or not raw_pages:
+ raise AuthoringRoundtripError(
+ "Round-trip page plan pages must be a non-empty array"
+ )
+
+ documents_by_slide = {
+ document.source_slide: document
+ for document in documents.values()
+ }
+ source_count = len(documents_by_slide)
+ pages: list[RoundtripPage] = []
+ seen_svg_names: dict[str, int] = {}
+ for output_index, raw in enumerate(raw_pages, start=1):
+ context = f"page_plan.json pages[{output_index - 1}]"
+ if not isinstance(raw, dict):
+ raise AuthoringRoundtripError(f"{context} must be an object")
+ unknown_fields = sorted(set(raw) - {"source_slide", "svg"})
+ if unknown_fields:
+ raise AuthoringRoundtripError(
+ f"{context} has unsupported field(s): "
+ + ", ".join(unknown_fields)
+ )
+ source_slide = raw.get("source_slide")
+ if (
+ not isinstance(source_slide, int)
+ or isinstance(source_slide, bool)
+ or source_slide < 1
+ or source_slide > source_count
+ ):
+ raise AuthoringRoundtripError(
+ f"{context}.source_slide must be between 1 and {source_count}"
+ )
+ source_document = documents_by_slide[source_slide]
+ svg_value = raw.get("svg", source_document.name)
+ if not isinstance(svg_value, str) or not svg_value:
+ raise AuthoringRoundtripError(
+ f"{context}.svg must be a non-empty authoring SVG filename"
+ )
+ svg_path_value = Path(svg_value)
+ if (
+ svg_path_value.name != svg_value
+ or svg_path_value.suffix.lower() != ".svg"
+ or svg_value in {".", ".."}
+ ):
+ raise AuthoringRoundtripError(
+ f"{context}.svg must be one authoring-svg-flat SVG filename"
+ )
+ svg_key = svg_value.casefold()
+ if svg_key in seen_svg_names:
+ raise AuthoringRoundtripError(
+ f"{context}.svg repeats {svg_value!r}; already used by output "
+ f"page {seen_svg_names[svg_key]}"
+ )
+ authoring_path = _resolve_inside(
+ authoring_dir,
+ svg_value,
+ context=f"{context}.svg",
+ )
+ if not authoring_path.is_file():
+ raise AuthoringRoundtripError(
+ f"{context}.svg names an unknown authoring SVG file: {svg_value}"
+ )
+ canonical_owner = documents.get(svg_value)
+ if (
+ canonical_owner is not None
+ and canonical_owner.source_slide != source_slide
+ ):
+ raise AuthoringRoundtripError(
+ f"{context}.svg {svg_value!r} belongs to source slide "
+ f"{canonical_owner.source_slide}, not {source_slide}"
+ )
+
+ pages.append(RoundtripPage(
+ output_index=output_index,
+ source_slide=source_slide,
+ svg_name=svg_value,
+ source_svg_name=source_document.name,
+ ))
+ seen_svg_names[svg_key] = output_index
+
+ expected_files = set(documents) | {page.svg_name for page in pages}
+ actual_files = {
+ path.relative_to(authoring_dir).as_posix()
+ for path in authoring_dir.rglob("*.svg")
+ if path.is_file()
+ }
+ if actual_files != expected_files:
+ raise AuthoringRoundtripError(
+ "Authoring manifest/page-plan file roster differs; missing="
+ f"{sorted(expected_files - actual_files)}, "
+ f"extra={sorted(actual_files - expected_files)}"
+ )
+ return tuple(pages), True
+
+
+def _output_documents(
+ pages: tuple[RoundtripPage, ...],
+ documents: dict[str, AuthoringDocument],
+ authoring_dir: Path,
+) -> tuple[AuthoringDocument, ...]:
+ """Bind every output authoring file to its declared source document."""
+ documents_by_slide = {
+ document.source_slide: document
+ for document in documents.values()
+ }
+ output: list[AuthoringDocument] = []
+ for page in pages:
+ source = documents_by_slide[page.source_slide]
+ output.append(AuthoringDocument(
+ name=page.svg_name,
+ source_name=source.name,
+ source_slide=page.source_slide,
+ authoring_path=(authoring_dir / page.svg_name).resolve(),
+ flat_source_path=source.flat_source_path,
+ layered_source_path=source.layered_source_path,
+ initial_authoring_sha256=source.initial_authoring_sha256,
+ source_refs=source.source_refs,
+ ))
+ return tuple(output)
def _load_current_assets(
@@ -763,6 +1023,7 @@ def _referenced_assets(
assets: dict[str, VectorAssetRecord],
*,
document_name: str,
+ origin_document: str | None = None,
) -> dict[str, tuple[VectorAssetRecord, ET.Element]]:
referenced: dict[str, tuple[VectorAssetRecord, ET.Element]] = {}
for element in root.iter():
@@ -785,7 +1046,8 @@ def _referenced_assets(
"without an inventory record"
)
continue
- if record.origin_document != document_name:
+ expected_origin = origin_document or document_name
+ if record.origin_document != expected_origin:
raise AuthoringRoundtripError(
f"{document_name} references {icon!r} owned by "
f"{record.origin_document}"
@@ -960,6 +1222,8 @@ def _merge_defs(
def _serialize_svg(root: ET.Element) -> bytes:
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
payload = ET.tostring(root, encoding="utf-8", xml_declaration=True)
return payload if payload.endswith(b"\n") else payload + b"\n"
@@ -1049,11 +1313,13 @@ def _materialize_document(
current_root,
current_assets,
document_name=document.name,
+ origin_document=document.source_name,
)
baseline_referenced_assets = _referenced_assets(
baseline_root,
baseline_assets,
document_name=document.name,
+ origin_document=document.source_name,
)
current_occurrences = _ref_occurrences(
current_root,
@@ -1344,6 +1610,8 @@ def _materialize_document(
output_path.write_bytes(_serialize_svg(output_root))
return {
"file": document.name,
+ "source_file": document.source_name,
+ "source_slide": document.source_slide,
"document_unchanged": document_unchanged,
"source_ref_count": len(expected_refs),
"source_ref_ids": sorted(expected_refs),
@@ -1385,10 +1653,22 @@ def materialize_flat_authoring_roundtrip(
)
output_dir.mkdir(parents=True, exist_ok=True)
- source_root, source_proxy_dir, documents, manifest = _load_documents(
+ (
+ source_root,
+ source_proxy_dir,
+ documents,
+ manifest,
+ _roundtrip_manifest,
+ ) = _load_documents(
project_path,
authoring_dir,
)
+ pages, page_plan_present = _load_page_plan(
+ project_path,
+ authoring_dir,
+ documents,
+ )
+ output_documents = _output_documents(pages, documents, authoring_dir)
current_assets, inventory = _load_current_assets(
project_path,
authoring_dir,
@@ -1414,20 +1694,24 @@ def materialize_flat_authoring_roundtrip(
_materialize_document(
project_path,
document,
- baseline_root / document.name,
+ baseline_root / document.source_name,
output_dir / document.name,
current_assets,
baseline_assets,
)
- for document in sorted(documents.values(), key=lambda item: item.name)
+ for document in output_documents
]
finally:
baseline_temporary.cleanup()
- svg_files = tuple(discover_slide_svgs(output_dir))
- if len(svg_files) != len(documents):
+ svg_files = (
+ tuple(output_dir / page.svg_name for page in pages)
+ if page_plan_present
+ else tuple(discover_slide_svgs(output_dir))
+ )
+ if len(svg_files) != len(pages):
raise AuthoringRoundtripError(
- "Materialized slide roster does not match the authoring manifest"
+ "Materialized slide roster does not match the output page plan"
)
totals = {
key: sum(int(item[key]) for item in document_reports)
@@ -1446,7 +1730,32 @@ def materialize_flat_authoring_roundtrip(
"manifest_schema": manifest.get("schema"),
"projection_kind": manifest.get("projection_kind"),
"materialized_slide_count": len(svg_files),
+ "page_plan": (
+ {
+ "schema": ROUNDTRIP_PAGE_PLAN_SCHEMA,
+ "output_pages": len(pages),
+ "pages": [
+ {
+ "output_index": page.output_index,
+ "source_slide": page.source_slide,
+ "svg": page.svg_name,
+ }
+ for page in pages
+ ],
+ }
+ if page_plan_present
+ else None
+ ),
"totals": totals,
"documents": document_reports,
}
- return AuthoringRoundtripResult(svg_files=svg_files, report=report)
+ return AuthoringRoundtripResult(
+ svg_files=svg_files,
+ authoring_files=tuple(
+ authoring_dir / page.svg_name
+ for page in pages
+ ),
+ pages=pages,
+ page_plan_present=page_plan_present,
+ report=report,
+ )
diff --git a/skills/ppt-master/scripts/compact_svg_styles.py b/skills/ppt-master/scripts/compact_svg_styles.py
index a89eff5e..57629105 100644
--- a/skills/ppt-master/scripts/compact_svg_styles.py
+++ b/skills/ppt-master/scripts/compact_svg_styles.py
@@ -38,6 +38,7 @@ from svg_to_pptx.drawingml.utils import INHERITABLE_ATTRS
configure_utf8_stdio()
SVG_NS = "http://www.w3.org/2000/svg"
+XLINK_NS = "http://www.w3.org/1999/xlink"
INHERITABLE_ATTRIBUTES = tuple(INHERITABLE_ATTRS)
_DEFINITION_SUBTREES = frozenset({
"clipPath",
@@ -491,6 +492,8 @@ def _compact_svg_bytes(
stats = compact_svg_style_tree(root)
if stats.changed_declarations == 0:
return original, stats
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
payload = ET.tostring(
root,
encoding="utf-8",
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index f4842d61..193f7681 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -94,6 +94,76 @@ through byte-for-byte; an edit rebuilds only its owner. Resource hrefs resolve
exactly relative to the page or extracted asset and must remain inside the
workspace.
+### Round-trip deck page plans
+
+`page_plan.json` is an optional, model-authored file at the root of a
+`pptx_to_svg.py --roundtrip` workspace. Without it, export uses the existing
+identity roster and preserves the no-plan package behavior. With it, the
+`pages` array is the complete output order and may select, reorder, repeat, or
+omit source slides:
+
+```json
+{
+ "schema": "ppt-master.roundtrip-page-plan.v1",
+ "pages": [
+ {"source_slide": 3},
+ {"source_slide": 1, "svg": "intro.svg"},
+ {"source_slide": 3, "svg": "intro_b.svg"}
+ ]
+}
+```
+
+`source_slide` is the one-based source presentation index. `svg` defaults to
+that source slide's canonical imported filename, normally `slide_03.svg`, and
+must name one file directly inside `authoring-svg-flat/`. Each output entry
+must use a different SVG filename. To author independent edits from one source
+page, copy its SVG to a new filename and list that filename on the repeated
+entry. The exporter always compares the copy with the baseline regenerated
+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.
+
+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
+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.
+With a plan present, presentation-level `sectionLst` and custom-show rosters
+are dropped, output `p:sldId` values are renumbered, and the slide count in
+`docProps/app.xml` is updated.
+
+Output-page sidecars are keyed by the authoring SVG stem. A repeated copy
+inherits its source row from `animations.json` unless that output stem has its
+own row. Canonical pages keep identity notes semantics: a manifest `notes.file`
+must equal `notes/<svg-stem>.md`; deleting that file removes the source notes,
+different bytes override them, and matching bytes remain unchanged. A canonical
+page without source notes treats a present stem-keyed file as an addition. For
+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.
+`-t`, `-a`, `--recorded-narration`, `--use-narration-timings`,
+`--no-animations`, and `--no-notes` continue to resolve per output page.
+
+Import and export from the repository root:
+
+```bash
+python3 skills/ppt-master/scripts/pptx_to_svg.py source.pptx \
+ -o /path/to/workspace --inheritance-mode both --roundtrip
+python3 skills/ppt-master/scripts/svg_to_pptx.py /path/to/workspace \
+ --roundtrip -o /path/to/output.pptx
+```
+
+Successful round-trip export prints one deck receipt:
+`Round-trip export summary: output_pages=N passthrough=P
+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.
+
Regenerate the summary after direct edits that do not pass through one of the
in-place normalization tools:
@@ -756,7 +826,7 @@ Behavior:
- `--no-merge`: each dy-stacked line becomes an independent frame with its own placement.
- Detection is conservative: mixed-layout `<text>` falls back to per-line frames. Use `--reflow-text` only for resizable body copy and `--no-merge` only for independent line objects or absolute line positions.
- Native release export reads `svg_output/`; `-s <directory>` selects another project-relative SVG source. `-s final` remains an explicit diagnostic comparison against post-processed SVGs and does not change artifact ownership. `--enable-dangerous-nonconforming-svg-export` is a separate, explicitly requested flat compatibility path for either the default or selected source; it forces flat structure, restores no imported source object, and cannot combine with `--roundtrip` or `--quick-generate`.
-- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, and rebuilds only edited owners. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement.
+- `--roundtrip` accepts only `authoring-svg-flat/` and the source/contracts emitted by `pptx_to_svg.py --roundtrip`; predecessor root sidecars and alternate `-s` inputs fail. It restores unchanged refs from `analysis/roundtrip-svg/`, preserves unchanged Slide XML/relationships and source resources byte-for-byte, and rebuilds only edited owners. Closed unchanged chart packages recover exactly; editing their fallback disables stale replacement. Optional root `page_plan.json` uses the versioned deck-plan contract above; the no-plan path remains the identity export. Explicit `-t <effect>` without `--transition-duration` on a source without transitions uses the default duration.
- `svg_final/` may be opened directly or inserted into PowerPoint as an SVG picture. PowerPoint's manual Convert-to-Shape operation is outside the compatibility contract.
- On every SVG-authoring route, each file in `svg_output/` is the complete visible
page-design source. Templates and locks may guide authoring, but finalize/export
diff --git a/skills/ppt-master/scripts/extract_svg_assets.py b/skills/ppt-master/scripts/extract_svg_assets.py
index 6bc3be5d..58706f54 100644
--- a/skills/ppt-master/scripts/extract_svg_assets.py
+++ b/skills/ppt-master/scripts/extract_svg_assets.py
@@ -60,6 +60,7 @@ from svg_authoring_contract import normalize_compact_authoring_tree
configure_utf8_stdio()
SVG_NS = "http://www.w3.org/2000/svg"
+XLINK_NS = "http://www.w3.org/1999/xlink"
DRAWABLE = {"path", "polygon", "polyline", "rect", "circle", "ellipse", "line"}
SEMANTIC_CONTENT = {"text", "tspan", "foreignObject"}
SEMANTIC_MARKER_ATTRIBUTES = {
@@ -96,10 +97,14 @@ def _drawable_count(elem: ET.Element) -> int:
def _xml_size(elem: ET.Element) -> int:
if not any(item.get(SOURCE_REF_ATTRIBUTE) for item in elem.iter()):
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
return len(ET.tostring(elem, encoding="utf-8"))
measured = copy.deepcopy(elem)
for item in measured.iter():
item.attrib.pop(SOURCE_REF_ATTRIBUTE, None)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
return len(ET.tostring(measured, encoding="utf-8"))
@@ -286,6 +291,8 @@ def _definition_signature(elem: ET.Element) -> bytes:
"""Return definition semantics without its document-local id."""
normalized = copy.deepcopy(elem)
normalized.attrib.pop("id", None)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
return ET.tostring(normalized, encoding="utf-8")
@@ -467,6 +474,8 @@ def _asset_svg(
defs.append(dependency)
svg.append(group)
normalize_compact_authoring_tree(svg)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
return ET.tostring(svg, encoding="utf-8", xml_declaration=True)
@@ -809,6 +818,8 @@ def extract_file(
_normalize_authoring_tree(root, fresh_native_markers)
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
return []
@@ -844,6 +855,8 @@ def extract_file(
_normalize_authoring_tree(root, fresh_native_markers)
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
return []
@@ -948,6 +961,8 @@ def extract_file(
_normalize_authoring_tree(root, fresh_native_markers)
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
return entries
diff --git a/skills/ppt-master/scripts/pptx_workspace.py b/skills/ppt-master/scripts/pptx_workspace.py
index d0380402..8ef3f672 100644
--- a/skills/ppt-master/scripts/pptx_workspace.py
+++ b/skills/ppt-master/scripts/pptx_workspace.py
@@ -32,6 +32,7 @@ from xml.etree import ElementTree as ET
SOURCE_PPTX_PATH = Path("sources/source.pptx")
NATIVE_STRUCTURE_PATH = Path("analysis/native_structure.json")
ROUNDTRIP_MANIFEST_PATH = Path("analysis/roundtrip_manifest.json")
+ROUNDTRIP_PAGE_PLAN_PATH = Path("page_plan.json")
TEMPLATE_MANIFEST_PATH = Path("analysis/manifest.json")
CONVERSION_REPORT_PATH = Path("validation/conversion-report.json")
AUTHORING_SVG_FLAT_DIR = Path("authoring-svg-flat")
@@ -106,6 +107,11 @@ def native_structure_path(workspace: Path) -> Path:
return workspace / NATIVE_STRUCTURE_PATH
+def roundtrip_page_plan_path(workspace: Path) -> Path:
+ """Return the optional deck-level round-trip page-plan path."""
+ return workspace / ROUNDTRIP_PAGE_PLAN_PATH
+
+
def template_manifest_path(workspace: Path) -> Path:
"""Return the semantic template-import manifest path."""
return workspace / TEMPLATE_MANIFEST_PATH
@@ -564,6 +570,7 @@ __all__ = [
"PackageResource",
"PackageResourceInventory",
"ROUNDTRIP_MANIFEST_PATH",
+ "ROUNDTRIP_PAGE_PLAN_PATH",
"SOURCE_PPTX_PATH",
"TEMPLATE_MANIFEST_PATH",
"VIDEO_EXTENSIONS",
@@ -573,6 +580,7 @@ __all__ = [
"load_roundtrip_manifest",
"native_structure_path",
"reject_removed_workspace_layout",
+ "roundtrip_page_plan_path",
"source_pptx_path",
"slide_animation_config_sha256",
"template_manifest_path",
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index dc35a8be..33a9acac 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -110,6 +110,13 @@ _SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
ET.register_namespace("", SVG_NS)
ET.register_namespace("xlink", XLINK_NS)
+
+def _serialize_svg(element: ET.Element) -> bytes:
+ """Serialize SVG independently of namespace registrations from other tools."""
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
+ return ET.tostring(element, encoding="utf-8", xml_declaration=False)
+
# These fields identify source OOXML objects or carry opaque paint/effect
# payloads. They belong in the complete import SVG, not its lightweight view.
AUTHORING_OMITTED_SOURCE_ATTRIBUTES = {
@@ -1110,7 +1117,7 @@ def _source_proxy_asset_bytes(
stats.coordinate_attributes_compacted += compact_svg_tree(
asset_root,
).changed_attributes
- payload = ET.tostring(asset_root, encoding="utf-8", xml_declaration=False)
+ payload = _serialize_svg(asset_root)
return payload if payload.endswith(b"\n") else payload + b"\n"
@@ -1281,7 +1288,7 @@ def _externalize_large_source_objects(
SEMANTIC_TABLE_KIND,
}:
continue
- original_bytes = len(ET.tostring(element, encoding="utf-8"))
+ original_bytes = len(_serialize_svg(element))
if (
original_bytes < SOURCE_PROXY_MIN_BYTES
or _contains_authoring_semantics(element)
@@ -1404,7 +1411,7 @@ def _render_projection(
+ "; ".join(contract_errors)
)
- projected = ET.tostring(root, encoding="utf-8", xml_declaration=False)
+ projected = _serialize_svg(root)
if not projected.endswith(b"\n"):
projected += b"\n"
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 2c8f052c..71bcb031 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -15,6 +15,7 @@ configure_utf8_stdio()
SVG_NS = "http://www.w3.org/2000/svg"
+XLINK_NS = "http://www.w3.org/1999/xlink"
NSMAP = {"svg": SVG_NS}
# Ensure pretty element names without ns0 prefix on write
@@ -827,6 +828,8 @@ def process_svg_file(
os.makedirs(os.path.dirname(dst_path), exist_ok=True)
# Write out XML without XML declaration to mimic input style
+ ET.register_namespace("", SVG_NS)
+ ET.register_namespace("xlink", XLINK_NS)
tree.write(dst_path, encoding="utf-8", xml_declaration=False, method="xml")
return changed
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 bf5acad3..b6ec3f3b 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
@@ -35,8 +35,11 @@ from pptx_embedded_fonts import (
embedded_font_typefaces,
)
from pptx_transitions import (
+ AdvanceUpdate,
+ EnterUpdate,
MorphPairExpectation,
NATIVE_TRANSITIONS,
+ apply_slide_motion_xml,
create_transition_xml,
normalize_transition_effect_request,
serialize_source_xml,
@@ -53,6 +56,7 @@ from pptx_animations import (
normalize_animation_effect,
normalize_animation_effect_request,
normalize_animation_trigger,
+ object_animation_fingerprint,
pick_animation_effect,
validate_generated_animation_xml,
validate_pptx_animation_package,
@@ -63,6 +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 language_tags import normalize_language_tag
from hyperlink_contract import (
HYPERLINK_REL_TYPE,
@@ -214,6 +220,7 @@ class RoundtripSlidePatch:
source_ref_ids: frozenset[str]
edited_ref_ids: frozenset[str]
deleted_ref_ids: frozenset[str]
+ visual_changed: bool
motion_changed: bool
notes_changed: bool
@@ -864,6 +871,9 @@ def _append_shape_to_part(part_path: Path, elem: ET.Element) -> None:
def _write_xml_tree(path: Path, tree: ET.ElementTree) -> None:
+ root = tree.getroot()
+ if root.tag == f"{{{PACKAGE_REL_NS}}}Relationships":
+ ET.register_namespace("", PACKAGE_REL_NS)
tree.write(path, encoding="utf-8", xml_declaration=True)
@@ -1003,6 +1013,53 @@ def _replace_roundtrip_motion(
source_root.insert(insert_at, clone)
+def _apply_roundtrip_transition_overlay(
+ slide_path: Path,
+ *,
+ effect: str | None,
+ effect_options: dict[str, object],
+ duration: float,
+ auto_advance: float | None,
+) -> bool:
+ """Patch only transition/advance state while preserving source timing."""
+ source_xml = slide_path.read_text(encoding="utf-8")
+ source_animation = object_animation_fingerprint(source_xml)
+ enter = (
+ EnterUpdate(policy="none", effect=None, duration=duration)
+ if effect is None
+ else EnterUpdate(
+ policy="replace",
+ effect=effect,
+ duration=duration,
+ effect_options=effect_options,
+ )
+ )
+ advance = (
+ AdvanceUpdate(mode="click")
+ if auto_advance is None
+ else AdvanceUpdate(mode="both", after=auto_advance)
+ )
+ updated_xml, uses_timings = apply_slide_motion_xml(
+ source_xml,
+ enter=enter,
+ advance=advance,
+ )
+ if object_animation_fingerprint(updated_xml) != source_animation:
+ raise RuntimeError(
+ "Round-trip transition overlay changed source object animations"
+ )
+ validate_generated_transition_xml(
+ updated_xml,
+ effect=effect,
+ effect_options=effect_options,
+ duration=duration,
+ advance_on_click=True,
+ advance_after=auto_advance,
+ )
+ slide_path.write_text(updated_xml, encoding="utf-8")
+ return uses_timings
+
+
def _shape_ids_in_element(element: ET.Element) -> set[str]:
"""Return every non-visual DrawingML id owned by one shape subtree."""
return {
@@ -1012,13 +1069,29 @@ def _shape_ids_in_element(element: ET.Element) -> set[str]:
}
+def _rewrite_roundtrip_timing_shape_ids(
+ slide_root: ET.Element,
+ id_map: dict[str, str],
+) -> None:
+ """Rewrite every timing reference to a remapped Slide-local shape id."""
+ if not id_map:
+ return
+ timing = slide_root.find(f"{{{PML_NS}}}timing")
+ if timing is None:
+ return
+ for node in timing.iter():
+ old_id = node.get("spid")
+ if old_id in id_map:
+ node.set("spid", id_map[old_id])
+
+
def _renumber_roundtrip_generated_shapes(
generated_shapes: list[ET.Element],
retained_source_nodes: list[ET.Element],
slide_root: ET.Element,
*,
rewrite_timing: bool,
-) -> None:
+) -> dict[str, str]:
"""Keep generated additions disjoint from retained source shape ids."""
used_ids = {
value
@@ -1049,7 +1122,7 @@ def _renumber_roundtrip_generated_shapes(
used_ids.add(old_id)
if not id_map:
- return
+ return {}
for element in generated_shapes:
for connector_tag in ("stCxn", "endCxn"):
for connector in element.iter(f"{{{PML_NS}}}{connector_tag}"):
@@ -1057,12 +1130,8 @@ def _renumber_roundtrip_generated_shapes(
if old_id in id_map:
connector.set("id", id_map[old_id])
if rewrite_timing:
- for target in slide_root.findall(
- f".//{{{PML_NS}}}timing//{{{PML_NS}}}spTgt"
- ):
- old_id = target.get("spid")
- if old_id in id_map:
- target.set("spid", id_map[old_id])
+ _rewrite_roundtrip_timing_shape_ids(slide_root, id_map)
+ return id_map
def _apply_roundtrip_slide_overlay(
@@ -1072,7 +1141,7 @@ def _apply_roundtrip_slide_overlay(
generated_rels_path: Path,
patch: RoundtripSlidePatch,
conversion_trace: dict[str, Any] | None,
-) -> None:
+) -> dict[int, int]:
"""Overlay authored Slide objects onto the exact source slide package part."""
try:
source_root = ET.fromstring(source_slide)
@@ -1272,7 +1341,18 @@ def _apply_roundtrip_slide_overlay(
)
if patch.motion_changed:
_replace_roundtrip_motion(source_root, generated_root)
- _renumber_roundtrip_generated_shapes(
+ restored_shape_id_map = {
+ generated_top_id: source_id
+ for generated_top_id, source_id in source_id_by_generated_top_id.items()
+ if source_id not in affected_top_ids
+ and generated_top_id != source_id
+ }
+ if patch.motion_changed:
+ _rewrite_roundtrip_timing_shape_ids(
+ source_root,
+ restored_shape_id_map,
+ )
+ renumbered_shape_id_map = _renumber_roundtrip_generated_shapes(
generated_nodes,
retained_source_nodes,
source_root,
@@ -1300,6 +1380,15 @@ def _apply_roundtrip_slide_overlay(
generated_slide_path.write_bytes(
serialize_source_xml(source_root, source_slide)
)
+ combined_id_map = {
+ **restored_shape_id_map,
+ **renumbered_shape_id_map,
+ }
+ return {
+ int(old_id): int(new_id)
+ for old_id, new_id in combined_id_map.items()
+ if old_id.isdigit() and new_id.isdigit()
+ }
def _remove_relationships_by_type(rels_path: Path, rel_type: str) -> int:
@@ -1317,21 +1406,60 @@ def _remove_relationships_by_type(rels_path: Path, rel_type: str) -> int:
return removed
-def _reinject_roundtrip_resources(
+def _apply_slide_notes(
extract_dir: Path,
+ rels_path: Path,
+ slide_num: int,
+ notes_content: str,
+ primary_language: str | None,
+ *,
+ enable_notes: bool,
+) -> bool:
+ """Replace one slide's notes relationship and return whether notes were added."""
+ _remove_relationships_by_type(rels_path, NOTES_SLIDE_REL_TYPE)
+ if not enable_notes:
+ return False
+ notes_text = markdown_to_plain_text(notes_content) if notes_content else ''
+ if not notes_text:
+ return False
+
+ _ensure_notes_master(extract_dir, primary_language)
+ notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'
+ notes_slides_dir.mkdir(exist_ok=True)
+ notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'
+ notes_xml_path.write_text(
+ create_notes_slide_xml(slide_num, notes_text, primary_language),
+ encoding='utf-8',
+ )
+ notes_rels_dir = notes_slides_dir / '_rels'
+ notes_rels_dir.mkdir(exist_ok=True)
+ notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'
+ notes_rels_path.write_text(
+ create_notes_slide_rels_xml(slide_num),
+ encoding='utf-8',
+ )
+ _ensure_relationship(
+ rels_path,
+ NOTES_SLIDE_REL_TYPE,
+ f'../notesSlides/notesSlide{slide_num}.xml',
+ )
+ return True
+
+
+def _roundtrip_resource_payloads(
resource_root: Path | None,
resources: tuple[WorkspaceResourceSpec, ...],
-) -> int:
- """Write semantic resource bytes back to their exact source package parts."""
+) -> dict[str, bytes]:
+ """Read validated materialized round-trip resources by package part."""
materialized = [resource for resource in resources if resource.materialized]
if not materialized:
- return 0
+ return {}
if resource_root is None:
raise TemplateStructureError(
"Round-trip resource reinjection requires an explicit project root"
)
workspace = resource_root.resolve()
- written = 0
+ payloads: dict[str, bytes] = {}
for resource in materialized:
source = (workspace / resource.workspace_path).resolve()
try:
@@ -1346,13 +1474,26 @@ def _reinject_roundtrip_resources(
"Materialized round-trip resource is missing: "
f"{resource.workspace_path.as_posix()}"
)
- target = extract_dir.joinpath(*PurePosixPath(resource.package_part).parts)
+ payloads[resource.package_part] = source.read_bytes()
+ return payloads
+
+
+def _reinject_roundtrip_resources(
+ extract_dir: Path,
+ resource_root: Path | None,
+ resources: tuple[WorkspaceResourceSpec, ...],
+) -> int:
+ """Write semantic resource bytes back to their exact source package parts."""
+ payloads = _roundtrip_resource_payloads(resource_root, resources)
+ written = 0
+ for package_part, payload in payloads.items():
+ target = extract_dir.joinpath(*PurePosixPath(package_part).parts)
if not target.is_file():
raise TemplateStructureError(
"Round-trip source package part is missing: "
- f"{resource.package_part}"
+ f"{package_part}"
)
- shutil.copyfile(source, target)
+ target.write_bytes(payload)
written += 1
return written
@@ -5293,8 +5434,41 @@ def _create_preserved_base_pptx(
specs: list[TemplateSlideSpec],
output_path: Path,
slide_size_emu: tuple[int, int],
+ *,
+ roundtrip_page_sources: tuple[int, ...] | None = None,
+ package_overrides: dict[str, bytes] | None = None,
) -> bool:
"""Create the preserve base and report whether source Slides were retained."""
+ if roundtrip_page_sources is not None:
+ if len(roundtrip_page_sources) != len(specs):
+ raise TemplateStructureError(
+ "Round-trip page plan length does not match the SVG roster"
+ )
+ if contract.slide_size_emu != slide_size_emu:
+ raise TemplateStructureError(
+ "Generated SVG canvas does not match the preserved source template size"
+ )
+ for spec, source_index in zip(specs, roundtrip_page_sources):
+ source_slide = contract.slide(source_index)
+ if spec.layout_key != source_slide.layout_key:
+ raise TemplateStructureError(
+ f"{spec.svg_path.name} declares layout {spec.layout_key!r}, "
+ f"but source slide {source_index} uses "
+ f"{source_slide.layout_key!r}"
+ )
+ try:
+ clone_presentation_slides(
+ contract.source_template,
+ roundtrip_page_sources,
+ output_path,
+ package_overrides=package_overrides,
+ )
+ except (OSError, RuntimeError, zipfile.BadZipFile) as exc:
+ raise TemplateStructureError(
+ f"Round-trip page-plan cloning failed: {exc}"
+ ) from exc
+ return True
+
source_roster_matches = (
len(specs) == len(contract.slides)
and all(
@@ -5572,6 +5746,7 @@ def create_pptx_with_native_svg(
roundtrip_passthrough_slides: set[int] | None = None,
roundtrip_slide_patches: dict[int, RoundtripSlidePatch] | None = None,
roundtrip_resources: tuple[WorkspaceResourceSpec, ...] = (),
+ roundtrip_page_sources: tuple[int, ...] | None = None,
theme_font_spec: ThemeFontSpec | None = None,
master_text_style_spec: MasterTextStyleSpec | None = None,
theme_color_spec: ThemeColorSpec | None = None,
@@ -5674,6 +5849,8 @@ def create_pptx_with_native_svg(
overlay edited objects onto their preserved source slide parts.
roundtrip_resources: Semantic workspace payloads copied back to their
exact source package parts after slide conversion.
+ roundtrip_page_sources: Optional output-order tuple of one-based source
+ slide indices. Presence activates deck-level source slide cloning.
theme_font_spec: Locked project major/minor fonts for flat/structured
release-theme inheritance. Direct diagnostic flat callers may omit it.
master_text_style_spec: Required declared or inferred title/body anchors
@@ -5710,8 +5887,12 @@ def create_pptx_with_native_svg(
passthrough_slides = set(roundtrip_passthrough_slides or set())
slide_patches = dict(roundtrip_slide_patches or {})
overlay_slides = set(slide_patches)
+ page_plan_export = roundtrip_page_sources is not None
roundtrip_export = bool(
- passthrough_slides or overlay_slides or roundtrip_resources
+ passthrough_slides
+ or overlay_slides
+ or roundtrip_resources
+ or page_plan_export
)
source_motion_slides = passthrough_slides | {
index
@@ -5752,6 +5933,15 @@ def create_pptx_with_native_svg(
raise ValueError(
"Round-trip overlays and resource reinjection require preserve mode"
)
+ if page_plan_export:
+ if pptx_structure != "preserve":
+ raise ValueError(
+ "Round-trip page plans are available only in preserve mode"
+ )
+ if len(roundtrip_page_sources) != len(public_svg_files):
+ raise ValueError(
+ "Round-trip page-plan source roster differs from the SVG roster"
+ )
definition_svg_files = list(layout_definition_files or [])
public_slide_names = [path.stem for path in public_svg_files]
morph_pairs = resolve_morph_pairs(
@@ -5989,6 +6179,14 @@ def create_pptx_with_native_svg(
try:
base_pptx = temp_dir / 'base.pptx'
preserved_source_slides = False
+ page_plan_package_overrides = (
+ _roundtrip_resource_payloads(resource_root, roundtrip_resources)
+ if page_plan_export
+ else None
+ )
+ late_roundtrip_resources = (
+ () if page_plan_export else roundtrip_resources
+ )
if (
use_native_shapes
and pptx_structure == "preserve"
@@ -6000,6 +6198,8 @@ def create_pptx_with_native_svg(
template_specs,
base_pptx,
(width_emu, height_emu),
+ roundtrip_page_sources=roundtrip_page_sources,
+ package_overrides=page_plan_package_overrides,
)
else:
# Create the standard base PPTX with python-pptx.
@@ -6037,7 +6237,10 @@ def create_pptx_with_native_svg(
):
_clear_preserved_slide_collections(extract_dir)
if (
- passthrough_slides or overlay_slides or roundtrip_resources
+ passthrough_slides
+ or overlay_slides
+ or roundtrip_resources
+ or page_plan_export
) and not preserved_source_slides:
raise TemplateStructureError(
"Round-trip export requires the original source package roster"
@@ -6187,6 +6390,129 @@ def create_pptx_with_native_svg(
)
success_count += 1
continue
+ if (
+ slide_patch is not None
+ and not slide_patch.visual_changed
+ and slide_patch.motion_changed
+ ):
+ overlay_slide_cfg = _slide_config(
+ animation_config,
+ svg_path.stem,
+ )
+ overlay_groups = overlay_slide_cfg.get("groups", {})
+ if not isinstance(overlay_groups, dict):
+ raise ValueError(
+ "animations.json slide groups must be an object"
+ )
+ (
+ overlay_transition,
+ overlay_transition_options,
+ overlay_transition_duration,
+ overlay_auto_advance,
+ overlay_transition_sound,
+ ) = _slide_transition_settings(
+ default_transition_cfg,
+ overlay_slide_cfg,
+ transition,
+ transition_effect_options,
+ transition_duration,
+ auto_advance,
+ transition_sound,
+ animation_cli_overrides,
+ )
+ (
+ overlay_animation,
+ _overlay_animation_duration,
+ _overlay_animation_stagger,
+ _overlay_animation_trigger,
+ _overlay_animation_cfg,
+ ) = _slide_animation_settings(
+ overlay_slide_cfg,
+ default_animation_cfg,
+ animation,
+ animation_duration,
+ animation_stagger,
+ animation_trigger,
+ animation_cli_overrides,
+ )
+ animation_override_requested = any(
+ animation_cli_overrides.get(key, False)
+ for key in (
+ "animation",
+ "animation_duration",
+ "animation_stagger",
+ "animation_trigger",
+ )
+ )
+ direct_transition_overlay = (
+ overlay_animation is None
+ and not overlay_groups
+ and not animation_override_requested
+ and overlay_transition_sound is None
+ and not morph_group_overrides_by_slide.get(
+ svg_path.stem
+ )
+ and not (
+ narration_audio
+ and narration_audio.get(svg_path.stem) is not None
+ )
+ and not use_narration_timings
+ )
+ if direct_transition_overlay:
+ if _apply_roundtrip_transition_overlay(
+ slide_xml_path,
+ effect=overlay_transition,
+ effect_options=overlay_transition_options,
+ duration=overlay_transition_duration,
+ auto_advance=overlay_auto_advance,
+ ):
+ package_uses_timings = True
+ if slide_patch.notes_changed:
+ notes_content = (
+ notes.get(svg_path.stem, '') if notes else ''
+ )
+ if _apply_slide_notes(
+ extract_dir,
+ rels_path,
+ slide_num,
+ notes_content,
+ primary_language,
+ enable_notes=enable_notes,
+ ):
+ notes_slides_created.add(slide_num)
+ if verbose:
+ print(
+ f" {progress_label} {svg_path.name} "
+ "(Source slide motion overlay)"
+ )
+ success_count += 1
+ continue
+ if (
+ slide_patch is not None
+ and slide_patch.notes_changed
+ and not slide_patch.visual_changed
+ and not slide_patch.motion_changed
+ ):
+ notes_content = (
+ notes.get(svg_path.stem, '') if notes else ''
+ )
+ notes_added = _apply_slide_notes(
+ extract_dir,
+ rels_path,
+ slide_num,
+ notes_content,
+ primary_language,
+ enable_notes=enable_notes,
+ )
+ if notes_added:
+ notes_slides_created.add(slide_num)
+ if verbose:
+ print(
+ f" {progress_label} {svg_path.name} "
+ "(Source slide notes overlay)"
+ )
+ success_count += 1
+ continue
# ---- Native shapes mode ----
if use_native_shapes:
@@ -6639,7 +6965,7 @@ def create_pptx_with_native_svg(
),
None,
)
- _apply_roundtrip_slide_overlay(
+ overlay_shape_id_map = _apply_roundtrip_slide_overlay(
source_slide_bytes,
source_rels_bytes,
slide_xml_path,
@@ -6647,49 +6973,43 @@ def create_pptx_with_native_svg(
slide_patch,
slide_conversion_trace,
)
+ for target in expected_animation_targets:
+ for field in ("shape_id", "trigger_shape_id"):
+ shape_id = target.get(field)
+ if (
+ isinstance(shape_id, int)
+ and not isinstance(shape_id, bool)
+ and shape_id in overlay_shape_id_map
+ ):
+ target[field] = overlay_shape_id_map[shape_id]
+ for morph_key, shape_id in tuple(
+ morph_shape_ids.items()
+ ):
+ if (
+ morph_key[0] == svg_path.stem
+ and shape_id in overlay_shape_id_map
+ ):
+ morph_shape_ids[morph_key] = (
+ overlay_shape_id_map[shape_id]
+ )
resolved_advance_after = slide_auto_advance
resolved_advance_on_click = True
# --- Process notes (shared between native and legacy mode) ---
- notes_content = ''
notes_changed = slide_patch is None or slide_patch.notes_changed
- if slide_patch is not None and slide_patch.notes_changed:
- _remove_relationships_by_type(
- rels_path,
- NOTES_SLIDE_REL_TYPE,
+ if not is_layout_definition and notes_changed:
+ notes_content = (
+ notes.get(svg_path.stem, '') if notes else ''
)
- if enable_notes and not is_layout_definition and notes_changed:
- svg_stem = svg_path.stem
- notes_content = notes.get(svg_stem, '') if notes else ''
- notes_text = markdown_to_plain_text(notes_content) if notes_content else ''
- if notes_text:
- _ensure_notes_master(extract_dir, primary_language)
-
- notes_slides_dir = extract_dir / 'ppt' / 'notesSlides'
- notes_slides_dir.mkdir(exist_ok=True)
-
- notes_xml_path = notes_slides_dir / f'notesSlide{slide_num}.xml'
- notes_xml = create_notes_slide_xml(
- slide_num,
- notes_text,
- primary_language,
- )
- with open(notes_xml_path, 'w', encoding='utf-8') as f:
- f.write(notes_xml)
-
- notes_rels_dir = notes_slides_dir / '_rels'
- notes_rels_dir.mkdir(exist_ok=True)
- notes_rels_path = notes_rels_dir / f'notesSlide{slide_num}.xml.rels'
- notes_rels_xml = create_notes_slide_rels_xml(slide_num)
- with open(notes_rels_path, 'w', encoding='utf-8') as f:
- f.write(notes_rels_xml)
-
- _ensure_relationship(
- rels_path,
- NOTES_SLIDE_REL_TYPE,
- f'../notesSlides/notesSlide{slide_num}.xml',
- )
+ if _apply_slide_notes(
+ extract_dir,
+ rels_path,
+ slide_num,
+ notes_content,
+ primary_language,
+ enable_notes=enable_notes,
+ ):
notes_slides_created.add(slide_num)
# --- Process narration audio (shared between native and legacy mode) ---
@@ -7092,31 +7412,24 @@ def create_pptx_with_native_svg(
# Add notes master / slides content types
if enable_notes and notes_slides_created:
- notes_theme_override = (
- ' <Override PartName="/ppt/theme/theme2.xml" '
- 'ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>'
+ content_types = _add_content_type_override(
+ content_types,
+ '/ppt/theme/theme2.xml',
+ 'application/vnd.openxmlformats-officedocument.theme+xml',
)
- if notes_theme_override not in content_types:
- content_types = content_types.replace(
- '</Types>',
- notes_theme_override + '\n</Types>',
- )
- notes_master_override = (
- ' <Override PartName="/ppt/notesMasters/notesMaster1.xml" '
- 'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml"/>'
+ content_types = _add_content_type_override(
+ content_types,
+ '/ppt/notesMasters/notesMaster1.xml',
+ 'application/vnd.openxmlformats-officedocument.presentationml.'
+ 'notesMaster+xml',
)
- if notes_master_override not in content_types:
- content_types = content_types.replace(
- '</Types>',
- notes_master_override + '\n</Types>',
- )
for i in sorted(notes_slides_created):
- override = (
- f' <Override PartName="/ppt/notesSlides/notesSlide{i}.xml" '
- f'ContentType="application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml"/>'
+ content_types = _add_content_type_override(
+ content_types,
+ f'/ppt/notesSlides/notesSlide{i}.xml',
+ 'application/vnd.openxmlformats-officedocument.presentationml.'
+ 'notesSlide+xml',
)
- if override not in content_types:
- content_types = content_types.replace('</Types>', override + '\n</Types>')
with open(content_types_path, 'w', encoding='utf-8') as f:
f.write(content_types)
@@ -7128,13 +7441,23 @@ def create_pptx_with_native_svg(
):
content_types_path.write_bytes(source_content_types_bytes)
+ if page_plan_export:
+ pruned_page_plan_parts = prune_unreferenced_directory_parts(
+ extract_dir
+ )
+ if verbose and pruned_page_plan_parts:
+ print(
+ " Round-trip page plan: pruned "
+ f"{pruned_page_plan_parts} unreachable package part(s)"
+ )
+
if package_uses_timings:
set_directory_use_timings(extract_dir)
reinjected_resources = _reinject_roundtrip_resources(
extract_dir,
resource_root,
- roundtrip_resources,
+ late_roundtrip_resources,
)
if verbose and reinjected_resources:
print(
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 2c3c0f02..f3abdc2b 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
@@ -5,6 +5,7 @@ from __future__ import annotations
import argparse
import base64
import binascii
+import copy
import hashlib
import json
import math
@@ -25,6 +26,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
from attribution_guard import require_skill_integrity # noqa: E402
from authoring_roundtrip import ( # noqa: E402
AuthoringRoundtripError,
+ RoundtripPage,
is_flat_authoring_bundle,
materialize_flat_authoring_roundtrip,
)
@@ -46,6 +48,7 @@ from pptx_animations import ( # noqa: E402
normalize_animation_trigger,
)
from pptx_transitions import ( # noqa: E402
+ DEFAULT_TRANSITION_DURATION,
LEGACY_TRANSITION_KEYS,
NATIVE_TRANSITION_KEYS,
normalize_transition_effect_request,
@@ -53,6 +56,8 @@ from pptx_transitions import ( # noqa: E402
)
from pptx_workspace import ( # noqa: E402
AUTHORING_SVG_FLAT_DIR,
+ ROUNDTRIP_MANIFEST_PATH,
+ ROUNDTRIP_PAGE_PLAN_PATH,
WorkspaceResourceSpec,
conversion_report_path,
load_roundtrip_manifest,
@@ -186,9 +191,71 @@ def _resource_slide_indices(
}
+def _roundtrip_animation_config_for_pages(
+ config: dict[str, object],
+ pages: tuple[RoundtripPage, ...],
+) -> dict[str, object]:
+ """Key per-slide motion by output SVG stem, inheriting source rows for copies."""
+ expanded = copy.deepcopy(config)
+ raw_slides = expanded.get("slides")
+ 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:
+ 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]
+ elif source_stem in raw_slides:
+ output_slides[output_stem] = copy.deepcopy(raw_slides[source_stem])
+ expanded["slides"] = output_slides
+ return expanded
+
+
+def _roundtrip_note_changed(
+ project_path: Path,
+ row: dict[str, object],
+ page: RoundtripPage,
+) -> bool:
+ """Return whether one output page changes its inherited source notes."""
+ relative = Path("notes") / f"{page.svg_stem}.md"
+ output_note = project_path / relative
+ if page.svg_name != page.source_svg_name:
+ return output_note.is_file()
+
+ note = row.get("notes")
+ if note is None:
+ return output_note.is_file()
+ if not isinstance(note, dict):
+ raise RuntimeError(
+ f"Round-trip manifest slide {page.source_slide} notes metadata "
+ "must be an object"
+ )
+ note_file = note.get("file")
+ if not isinstance(note_file, str) or not note_file:
+ raise RuntimeError(
+ f"Round-trip manifest slide {page.source_slide} notes metadata "
+ "must declare notes.file"
+ )
+ expected_file = relative.as_posix()
+ if note_file != expected_file:
+ raise RuntimeError(
+ f"Round-trip manifest slide {page.source_slide} notes.file must be "
+ f"{expected_file!r} for {page.svg_name}; got {note_file!r}"
+ )
+ expected_sha = note.get("sha256")
+ if not isinstance(expected_sha, str):
+ raise RuntimeError(
+ f"Round-trip manifest slide {page.source_slide} notes metadata "
+ "must declare notes.sha256"
+ )
+ return not output_note.is_file() or _path_sha256(output_note) != expected_sha
+
+
def _roundtrip_passthrough_candidates(
project_path: Path,
native_files: list[Path],
+ pages: tuple[RoundtripPage, ...],
*,
source_dir: str,
authoring_report: dict[str, object] | None,
@@ -208,8 +275,10 @@ def _roundtrip_passthrough_candidates(
for row in raw_slides
if isinstance(row, dict) and isinstance(row.get('index'), int)
}
- if len(slide_rows) != len(native_files):
- return set()
+ if len(pages) != len(native_files):
+ raise RuntimeError(
+ "Round-trip output page roster differs from materialized SVG files"
+ )
candidates: set[int] = set()
if authoring_report is not None:
@@ -221,8 +290,12 @@ def _roundtrip_passthrough_candidates(
for row in raw_documents
if isinstance(row, dict) and isinstance(row.get('file'), str)
}
- for index in slide_rows:
- report = reports.get(f'slide_{index:02d}.svg')
+ for page in pages:
+ if page.source_slide not in slide_rows:
+ raise RuntimeError(
+ f"Round-trip manifest has no source slide {page.source_slide}"
+ )
+ report = reports.get(page.svg_name)
if not isinstance(report, dict):
continue
if (
@@ -235,17 +308,18 @@ def _roundtrip_passthrough_candidates(
and int(report.get('authored_unreferenced') or 0) == 0
and report.get('defs_changed') is False
):
- candidates.add(index)
+ candidates.add(page.output_index)
elif source_dir == 'svg':
files_by_name = {path.name: path for path in native_files}
- for index, row in slide_rows.items():
+ for page in pages:
+ row = slide_rows[page.source_slide]
relative = row.get('layeredSvg')
expected = row.get('layeredSvgSha256')
if not isinstance(relative, str) or not isinstance(expected, str):
continue
path = files_by_name.get(Path(relative).name)
if path is not None and _path_sha256(path) == expected:
- candidates.add(index)
+ candidates.add(page.output_index)
else:
return set()
@@ -273,39 +347,36 @@ def _roundtrip_passthrough_candidates(
raise RuntimeError(
f"Round-trip animation sidecar must be a JSON object: {current_animation}"
)
+ expanded_animation_config = _roundtrip_animation_config_for_pages(
+ current_animation_config,
+ pages,
+ )
+ pages_by_output = {page.output_index: page for page in pages}
for index in tuple(candidates):
- expected = slide_rows[index].get("animationSha256")
+ page = pages_by_output[index]
+ expected = slide_rows[page.source_slide].get("animationSha256")
if not isinstance(expected, str):
raise RuntimeError(
- f"Round-trip manifest slide {index} lacks animationSha256"
+ f"Round-trip manifest slide {page.source_slide} lacks "
+ "animationSha256"
)
actual = slide_animation_config_sha256(
- current_animation_config,
- f"slide_{index:02d}",
+ expanded_animation_config,
+ page.svg_stem,
)
if actual != expected:
candidates.discard(index)
- notes_dir = project_path / 'notes'
for index in tuple(candidates):
- row = slide_rows[index]
- note = row.get('notes')
- canonical_note = notes_dir / f'slide_{index:02d}.md'
- if isinstance(note, dict):
- note_file = note.get('file')
- note_sha = note.get('sha256')
- if not isinstance(note_file, str) or not isinstance(note_sha, str):
- candidates.discard(index)
- continue
- current_note = project_path / note_file
- if not current_note.is_file() or _path_sha256(current_note) != note_sha:
- candidates.discard(index)
- elif canonical_note.is_file():
+ page = pages_by_output[index]
+ row = slide_rows[page.source_slide]
+ if _roundtrip_note_changed(project_path, row, page):
candidates.discard(index)
derived = row.get("derivedResources")
if not isinstance(derived, list):
raise RuntimeError(
- f"Round-trip manifest slide {index} lacks derivedResources"
+ f"Round-trip manifest slide {page.source_slide} lacks "
+ "derivedResources"
)
for resource_index, raw in enumerate(derived):
if not isinstance(raw, dict):
@@ -332,30 +403,13 @@ def _roundtrip_passthrough_candidates(
return candidates
-def _roundtrip_note_changed(
- project_path: Path,
- row: dict[str, object],
- index: int,
-) -> bool:
- """Return whether one canonical per-slide notes source changed."""
- note = row.get("notes")
- if isinstance(note, dict):
- relative = note.get("file")
- expected_sha = note.get("sha256")
- if not isinstance(relative, str) or not isinstance(expected_sha, str):
- raise RuntimeError(
- f"Round-trip manifest slide {index} has incomplete notes metadata"
- )
- current = project_path / relative
- return not current.is_file() or _path_sha256(current) != expected_sha
- return (project_path / "notes" / f"slide_{index:02d}.md").is_file()
-
-
def _roundtrip_slide_patches(
project_path: Path,
authoring_report: dict[str, object] | None,
passthrough_slides: set[int],
+ pages: tuple[RoundtripPage, ...],
*,
+ force_visual_changed: bool,
force_motion_changed: bool,
force_notes_changed: bool,
) -> dict[int, RoundtripSlidePatch]:
@@ -390,36 +444,51 @@ def _roundtrip_slide_patches(
) from exc
if not isinstance(animation_config, dict):
raise RuntimeError("Round-trip animation sidecar must be a JSON object")
+ animation_config = _roundtrip_animation_config_for_pages(
+ animation_config,
+ pages,
+ )
documents = authoring_report.get("documents")
if not isinstance(documents, list):
raise RuntimeError("Authoring round-trip report documents must be an array")
+ pages_by_file = {page.svg_name: page for page in pages}
+ if len(documents) != len(pages):
+ raise RuntimeError(
+ "Authoring round-trip report differs from the output page plan"
+ )
patches: dict[int, RoundtripSlidePatch] = {}
for raw in documents:
if not isinstance(raw, dict) or not isinstance(raw.get("file"), str):
raise RuntimeError("Authoring round-trip document report is incomplete")
- match = re.fullmatch(r"slide_(\d+)\.svg", str(raw["file"]))
- if match is None:
+ page = pages_by_file.get(str(raw["file"]))
+ if page is None:
raise RuntimeError(
f"Unexpected authoring round-trip slide name: {raw['file']}"
)
- index = int(match.group(1))
+ if raw.get("source_slide") != page.source_slide:
+ raise RuntimeError(
+ f"Authoring round-trip source mapping changed for {page.svg_name}"
+ )
+ index = page.output_index
if index in passthrough_slides:
continue
- row = slide_rows.get(index)
+ row = slide_rows.get(page.source_slide)
if row is None:
raise RuntimeError(
- f"Round-trip manifest has no slide {index} for authoring overlay"
+ f"Round-trip manifest has no source slide {page.source_slide} "
+ "for authoring overlay"
)
expected_animation = row.get("animationSha256")
if not isinstance(expected_animation, str):
raise RuntimeError(
- f"Round-trip manifest slide {index} lacks animationSha256"
+ f"Round-trip manifest slide {page.source_slide} lacks "
+ "animationSha256"
)
motion_changed = force_motion_changed or (
slide_animation_config_sha256(
animation_config,
- f"slide_{index:02d}",
+ page.svg_stem,
)
!= expected_animation
)
@@ -438,10 +507,17 @@ def _roundtrip_slide_patches(
source_ref_ids=_ref_set("source_ref_ids"),
edited_ref_ids=_ref_set("edited_ref_ids"),
deleted_ref_ids=_ref_set("deleted_ref_ids"),
+ visual_changed=(
+ force_visual_changed
+ or int(raw.get("edited_refs") or 0) > 0
+ or int(raw.get("deleted_refs") or 0) > 0
+ or int(raw.get("authored_unreferenced") or 0) > 0
+ or raw.get("defs_changed") is True
+ ),
motion_changed=motion_changed,
notes_changed=(
force_notes_changed
- or _roundtrip_note_changed(project_path, row, index)
+ or _roundtrip_note_changed(project_path, row, page)
),
)
return patches
@@ -719,7 +795,7 @@ def _package_part_counts(pptx_path: Path) -> dict[str, object]:
'zip_integrity': 'passed' if bad_member is None else 'failed',
'corrupt_member': bad_member,
'slides': count(r'ppt/slides/slide\d+\.xml'),
- 'notes': count(r'ppt/notesSlides/notesSlide\d+\.xml'),
+ 'notes': count(r'ppt/notesSlides/notesSlide[^/]+\.xml'),
'masters': count(r'ppt/slideMasters/slideMaster\d+\.xml'),
'layouts': count(r'ppt/slideLayouts/slideLayout\d+\.xml'),
}
@@ -1870,6 +1946,33 @@ Recorded narration:
if not project_path.exists():
print(f"Error: Path does not exist: {project_path}")
return 1
+ page_plan_path = project_path / ROUNDTRIP_PAGE_PLAN_PATH
+ if page_plan_path.exists() and not args.roundtrip:
+ print(
+ "Error: page_plan.json is valid only for --roundtrip export from "
+ "a pptx_to_svg.py --roundtrip workspace",
+ file=sys.stderr,
+ )
+ return 1
+ if page_plan_path.exists() and args.roundtrip:
+ required_roundtrip_paths = (
+ ROUNDTRIP_MANIFEST_PATH,
+ native_structure_path(project_path).relative_to(project_path),
+ source_pptx_path(project_path).relative_to(project_path),
+ )
+ missing_roundtrip_paths = [
+ relative.as_posix()
+ for relative in required_roundtrip_paths
+ if not (project_path / relative).is_file()
+ ]
+ if missing_roundtrip_paths:
+ print(
+ "Error: page_plan.json requires a pptx_to_svg.py --roundtrip "
+ "workspace; missing: "
+ + ", ".join(missing_roundtrip_paths),
+ file=sys.stderr,
+ )
+ return 1
structure_lock = None
native_structure_contract = None
@@ -2189,6 +2292,9 @@ Recorded narration:
ref_files = native_files
authoring_roundtrip_temporary: tempfile.TemporaryDirectory[str] | None = None
authoring_roundtrip_report: dict[str, object] | None = None
+ roundtrip_pages: tuple[RoundtripPage, ...] = ()
+ roundtrip_page_plan_present = False
+ roundtrip_page_sources: tuple[int, ...] | None = None
if args.roundtrip:
authoring_source_dir = project_path / native_source_dir
if not is_flat_authoring_bundle(authoring_source_dir):
@@ -2214,6 +2320,14 @@ Recorded narration:
print(f"Error: {exc}", file=sys.stderr)
return 1
native_files = list(materialized.svg_files)
+ ref_files = list(materialized.authoring_files)
+ roundtrip_pages = materialized.pages
+ roundtrip_page_plan_present = materialized.page_plan_present
+ if roundtrip_page_plan_present:
+ roundtrip_page_sources = tuple(
+ page.source_slide
+ for page in roundtrip_pages
+ )
authoring_roundtrip_report = materialized.report
totals = materialized.report.get('totals')
if isinstance(totals, dict):
@@ -2224,6 +2338,12 @@ Recorded narration:
f"{totals.get('edited_refs', 0)} edited ref(s), "
f"{totals.get('deleted_refs', 0)} deleted ref(s)"
)
+ if roundtrip_page_plan_present:
+ print(
+ " Round-trip page plan: "
+ f"{len(roundtrip_pages)} output page(s) from "
+ f"{len(set(roundtrip_page_sources or ()))} source slide(s)"
+ )
roundtrip_passthrough_slides: set[int] = set()
roundtrip_slide_patches: dict[int, RoundtripSlidePatch] = {}
@@ -2250,6 +2370,7 @@ Recorded narration:
roundtrip_passthrough_slides = _roundtrip_passthrough_candidates(
project_path.resolve(),
native_files,
+ roundtrip_pages,
source_dir=args.source or native_source_dir,
authoring_report=authoring_roundtrip_report,
)
@@ -2288,6 +2409,11 @@ Recorded narration:
project_path.resolve(),
authoring_roundtrip_report,
roundtrip_passthrough_slides,
+ roundtrip_pages,
+ force_visual_changed=(
+ args.image_sizing == 'display'
+ or args.text_flow != TEXT_FLOW_PRESERVE
+ ),
force_motion_changed=roundtrip_motion_overridden,
force_notes_changed=args.no_notes,
)
@@ -2302,29 +2428,104 @@ Recorded narration:
print(f"Error: {exc}", file=sys.stderr)
return 1
blocked_dependencies = {
- index: paths
- for index, paths in opaque_dependencies.items()
- if index not in roundtrip_passthrough_slides
- and index not in roundtrip_slide_patches
+ page.output_index: (
+ page.source_slide,
+ opaque_dependencies[page.source_slide],
+ )
+ for page in roundtrip_pages
+ if page.source_slide in opaque_dependencies
+ and page.output_index not in roundtrip_passthrough_slides
+ and page.output_index not in roundtrip_slide_patches
}
- if blocked_dependencies:
+ omitted_opaque_dependencies = (
+ {
+ source_slide: paths
+ for source_slide, paths in opaque_dependencies.items()
+ if source_slide not in {
+ page.source_slide
+ for page in roundtrip_pages
+ }
+ }
+ if roundtrip_page_plan_present
+ else {}
+ )
+ if blocked_dependencies or omitted_opaque_dependencies:
print(
- "Error: direct layered-SVG rebuild would drop source video, "
- "audio, or opaque native payload relationships:",
+ "Error: round-trip page export would drop source video, audio, "
+ "or opaque native payload relationships:",
file=sys.stderr,
)
- for index, paths in sorted(blocked_dependencies.items()):
+ for index, (source_slide, paths) in sorted(
+ blocked_dependencies.items()
+ ):
print(
- f" slide {index}: " + ", ".join(paths),
+ f" output page {index} (source slide {source_slide}): "
+ + ", ".join(paths),
+ file=sys.stderr,
+ )
+ for source_slide, paths in sorted(
+ omitted_opaque_dependencies.items()
+ ):
+ print(
+ f" omitted source slide {source_slide}: "
+ + ", ".join(paths),
file=sys.stderr,
)
print(
- "Use the imported authoring-svg-flat bundle so edited objects "
- "can overlay the preserved source slide.",
+ "Keep each listed source slide in page_plan.json, or remove the "
+ "opaque relationship from the source deck before importing.",
file=sys.stderr,
)
return 1
+ direct_passthrough_count = (
+ 0
+ if roundtrip_page_plan_present
+ else len(roundtrip_passthrough_slides)
+ )
+ cloned_passthrough_count = (
+ len(roundtrip_passthrough_slides)
+ if roundtrip_page_plan_present
+ else 0
+ )
+ patched_count = sum(
+ not patch.visual_changed
+ for patch in roundtrip_slide_patches.values()
+ )
+ rebuilt_count = sum(
+ patch.visual_changed
+ for patch in roundtrip_slide_patches.values()
+ )
+ classified_pages = (
+ direct_passthrough_count
+ + cloned_passthrough_count
+ + patched_count
+ + rebuilt_count
+ )
+ if classified_pages != len(roundtrip_pages):
+ print(
+ "Error: round-trip export summary could not classify every "
+ "output page",
+ file=sys.stderr,
+ )
+ return 1
+ print(
+ " Round-trip export summary: "
+ f"output_pages={len(roundtrip_pages)} "
+ f"passthrough={direct_passthrough_count} "
+ f"cloned_passthrough={cloned_passthrough_count} "
+ f"patched={patched_count} "
+ f"rebuilt={rebuilt_count}"
+ )
+ if authoring_roundtrip_report is not None:
+ authoring_roundtrip_report["export_summary"] = {
+ "output_pages": len(roundtrip_pages),
+ "passthrough": direct_passthrough_count,
+ "cloned_passthrough": cloned_passthrough_count,
+ "patched": patched_count,
+ "rebuilt": rebuilt_count,
+ }
+
release_quality_gate = (
args.quick_generate
or args.source in {None, 'output'}
@@ -2611,6 +2812,15 @@ Recorded narration:
except Exception as exc:
print(f"Error: Failed to load animation config: {exc}", file=sys.stderr)
return 1
+ if animation_config and roundtrip_page_plan_present:
+ try:
+ animation_config = _roundtrip_animation_config_for_pages(
+ animation_config,
+ roundtrip_pages,
+ )
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
config_errors: list[str] = []
if animation_config:
config_errors.extend(validate_transition_config(animation_config))
@@ -2702,6 +2912,12 @@ Recorded narration:
),
)
)
+ explicit_transition_uses_default_duration = (
+ args.roundtrip
+ and args.transition is not None
+ and args.transition_duration is None
+ and transition is not None
+ )
transition_duration = validate_seconds(
(
args.transition_duration
@@ -2713,8 +2929,13 @@ Recorded narration:
)
),
"transition duration",
- allow_zero=transition is None,
+ allow_zero=(
+ transition is None
+ or explicit_transition_uses_default_duration
+ ),
)
+ if explicit_transition_uses_default_duration and transition_duration == 0:
+ transition_duration = DEFAULT_TRANSITION_DURATION
auto_advance = (
args.auto_advance
if args.auto_advance is not None
@@ -2832,6 +3053,7 @@ Recorded narration:
),
'transition_duration': (
args.transition_duration is not None
+ or explicit_transition_uses_default_duration
or inherited_overrides.get('transition_duration') is True
),
'auto_advance': (
@@ -2958,6 +3180,7 @@ Recorded narration:
roundtrip_passthrough_slides=roundtrip_passthrough_slides,
roundtrip_slide_patches=roundtrip_slide_patches,
roundtrip_resources=roundtrip_resources,
+ roundtrip_page_sources=roundtrip_page_sources,
theme_font_spec=theme_font_spec,
master_text_style_spec=master_text_style_spec,
theme_color_spec=theme_color_spec,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
index 253f6304..e3ff6ca7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/use_expander.py
@@ -493,6 +493,8 @@ def _build_replacement_g(
Invalid or unresolved project-local references are blocking input errors.
"""
+ ET.register_namespace('', SVG_NS)
+ ET.register_namespace('xlink', XLINK_NS)
use_str = ET.tostring(use_elem, encoding='unicode')
attrs = embed_icons_mod.parse_use_element(use_str)
if 'icon' not in attrs:
diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.py
index f97718f9..4fbe926e 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py
@@ -13,7 +13,6 @@ from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET
-from hyperlink_contract import SLIDE_JUMP_ACTION
from pptx_animations import (
object_animation_fingerprint,
validate_pptx_animation_package,
@@ -30,17 +29,20 @@ from .chart_fill import (
_max_chart_part_number,
_max_embedding_part_number,
)
-from .clone import _make_part_allocator, deep_clone_slide_private_parts
+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,
- _normalize_part,
_parse_slide_refs,
_qn,
- _rels_name_for_part,
_xml_bytes,
)
from .package import (
@@ -52,7 +54,6 @@ from .package import (
_max_slide_id,
_max_slide_part_number,
_prune_unreferenced_parts,
- _relative_target,
)
from .table_fill import _apply_table_edits_to_slide
from .text_fill import _apply_replacements_to_slide
@@ -109,156 +110,6 @@ def _build_clone_roster(
return roster
-_SLIDE_LAYOUT_REL_TYPE = (
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
-)
-_SLIDE_MASTER_REL_TYPE = (
- "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"
-)
-
-
-def _slide_jump_relationship_ids(part_root: ET.Element) -> set[str]:
- """Return relationship ids used by actual same-deck click 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())
- }
-
-
-def _remap_slide_jump_relationships(
- part_root: ET.Element,
- relationships_root: ET.Element,
- *,
- source_owner_part: str,
- output_owner_part: str,
- owner_label: str,
- outputs_by_source_part: dict[str, list[str]],
- source_ref_by_part: dict[str, SlideRef],
- self_source_part: str | None = None,
- self_output_part: str | None = None,
-) -> bool:
- """Point referenced slide-jump relationships at final output slides.
-
- Unreferenced ``/slide`` relationships are left untouched. A cloned slide's
- self-link follows that clone; shared layout/master links require one unique
- output for the referenced source slide.
- """
- relationship_ids = _slide_jump_relationship_ids(part_root)
- relationships = {
- rel.attrib.get("Id", ""): rel
- for rel in relationships_root.findall(_qn(REL_NS, "Relationship"))
- }
- changed = False
- for relationship_id in sorted(relationship_ids):
- rel = relationships.get(relationship_id)
- if rel is None:
- raise RuntimeError(
- f"{owner_label} has a slide jump with missing relationship "
- f"{relationship_id!r}"
- )
- if rel.attrib.get("Type") != SLIDE_REL_TYPE:
- raise RuntimeError(
- f"{owner_label} slide jump {relationship_id!r} does not use "
- "a slide relationship"
- )
- if rel.attrib.get("TargetMode") == "External":
- raise RuntimeError(
- f"{owner_label} has an external slide relationship"
- )
- target = rel.attrib.get("Target")
- if not target:
- raise RuntimeError(
- f"{owner_label} has a slide relationship without a target"
- )
- source_target_part = _normalize_part(target, source_owner_part)
- if (
- self_source_part is not None
- and self_output_part is not None
- and source_target_part == self_source_part
- ):
- output_target_part = self_output_part
- else:
- output_targets = outputs_by_source_part.get(source_target_part, [])
- source_target_ref = source_ref_by_part.get(source_target_part)
- target_label = (
- f"source slide {source_target_ref.index}"
- if source_target_ref is not None
- else source_target_part
- )
- if not output_targets:
- raise RuntimeError(
- f"{owner_label} links to omitted {target_label}; "
- "include the target exactly once or remove the link"
- )
- if len(output_targets) > 1:
- raise RuntimeError(
- f"{owner_label} links to repeated {target_label}; "
- "the output target is ambiguous"
- )
- output_target_part = output_targets[0]
- output_target = _relative_target(output_owner_part, output_target_part)
- if rel.attrib.get("Target") != output_target:
- rel.set("Target", output_target)
- changed = True
- return changed
-
-
-def _remap_reachable_shared_layer_slide_jumps(
- entries: dict[str, bytes],
- clone_roster: list[_PlannedSlideClone],
- *,
- outputs_by_source_part: dict[str, list[str]],
- source_ref_by_part: dict[str, SlideRef],
-) -> None:
- """Remap links inherited from layouts and masters used by output slides."""
- pending: list[str] = []
- for clone in clone_roster:
- rels_data = entries.get(clone.rels_name)
- if not rels_data:
- continue
- rels_root = ET.fromstring(rels_data)
- for rel in rels_root.findall(_qn(REL_NS, "Relationship")):
- if rel.attrib.get("Type") != _SLIDE_LAYOUT_REL_TYPE:
- continue
- target = rel.attrib.get("Target")
- if target:
- pending.append(_normalize_part(target, clone.part_name))
-
- visited: set[str] = set()
- while pending:
- part_name = pending.pop()
- if part_name in visited:
- continue
- visited.add(part_name)
- part_data = entries.get(part_name)
- rels_name = _rels_name_for_part(part_name)
- rels_data = entries.get(rels_name)
- if not part_data or not rels_data:
- continue
- part_root = ET.fromstring(part_data)
- rels_root = ET.fromstring(rels_data)
- changed = _remap_slide_jump_relationships(
- part_root,
- rels_root,
- source_owner_part=part_name,
- output_owner_part=part_name,
- owner_label=part_name,
- outputs_by_source_part=outputs_by_source_part,
- source_ref_by_part=source_ref_by_part,
- )
- if changed:
- entries[rels_name] = _xml_bytes(rels_root)
- for rel in rels_root.findall(_qn(REL_NS, "Relationship")):
- if rel.attrib.get("Type") != _SLIDE_MASTER_REL_TYPE:
- continue
- target = rel.attrib.get("Target")
- if target:
- pending.append(_normalize_part(target, part_name))
-
-
def apply_plan(
pptx_path: Path,
plan: dict[str, Any],
@@ -440,7 +291,10 @@ def apply_plan(
_remap_reachable_shared_layer_slide_jumps(
entries,
- clone_roster,
+ [
+ (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,
)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/clone.py b/skills/ppt-master/scripts/template_fill_pptx/clone.py
index 2790007f..f8eb521c 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/clone.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/clone.py
@@ -16,10 +16,11 @@ Two classes of target are deliberately left shared:
* **Shared structure** — slide layout / master / theme / notes master.
* **Binary blobs typed by a ``Default`` extension rule** — media (png / jpeg /
- emf ...) and OLE embeddings. Picture/object edits happen in PowerPoint, which
- mints a new part and repoints only the edited shape's relationship, so sharing
- never bleeds — and it avoids duplicating large media when one source page
- drives many output slides.
+ 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``;
@@ -28,22 +29,39 @@ both relationship types are skipped here.
from __future__ import annotations
+import copy
import posixpath
+import re
+import zipfile
+from pathlib import Path
from typing import Callable
from xml.etree import ElementTree as ET
+from hyperlink_contract import SLIDE_JUMP_ACTION
+
from .ooxml import (
CHART_REL_TYPE,
CT_NS,
+ NS,
NOTES_SLIDE_REL_TYPE,
REL_NS,
SLIDE_REL_TYPE,
+ SlideRef,
_normalize_part,
+ _parse_slide_refs,
_qn,
_rels_name_for_part,
_xml_bytes,
)
-from .package import _add_content_type_override, _relative_target
+from .package import (
+ _add_content_type_override,
+ _add_slide_override,
+ _content_type_root,
+ _empty_relationships_root,
+ _max_numeric_rid,
+ _prune_unreferenced_parts,
+ _relative_target,
+)
_REL_TYPE_BASE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
@@ -105,6 +123,9 @@ def _clone_part_private_deps(
content_root: ET.Element,
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.
@@ -115,16 +136,24 @@ def _clone_part_private_deps(
if rel.attrib.get("TargetMode") == "External":
continue
rel_type = rel.attrib.get("Type")
- if _is_shared(rel_type) or rel_type in SKIPPED_REL_TYPES:
- continue
target = rel.attrib.get("Target")
if not target:
continue
source_part = _normalize_part(target, owner_part)
+ 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 _is_shared(rel_type) or rel_type in skipped_rel_types:
+ continue
if source_part not in entries:
continue
content_type = _override_content_type(content_root, source_part)
- if content_type is None:
+ 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
@@ -134,7 +163,8 @@ def _clone_part_private_deps(
new_part = allocate(source_part)
entries[new_part] = entries[source_part]
cloned[source_part] = new_part
- _add_content_type_override(content_root, new_part, content_type)
+ 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:
@@ -146,6 +176,9 @@ def _clone_part_private_deps(
content_root=content_root,
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)
@@ -159,6 +192,9 @@ def deep_clone_slide_private_parts(
entries: dict[str, bytes],
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:
"""Give one cloned slide private copies of its private dependency parts.
@@ -173,4 +209,417 @@ def deep_clone_slide_private_parts(
content_root=content_root,
allocate=allocate,
cloned={},
+ skipped_rel_types=skipped_rel_types,
+ clone_default_part_prefixes=clone_default_part_prefixes,
+ back_references=back_references or {},
+ )
+
+
+_SLIDE_LAYOUT_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
+)
+_SLIDE_MASTER_REL_TYPE = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"
+)
+
+
+def _slide_jump_relationship_ids(part_root: ET.Element) -> set[str]:
+ """Return relationship ids used by actual same-deck click 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())
+ }
+
+
+def _remap_slide_jump_relationships(
+ part_root: ET.Element,
+ relationships_root: ET.Element,
+ *,
+ source_owner_part: str,
+ output_owner_part: str,
+ owner_label: str,
+ outputs_by_source_part: dict[str, list[str]],
+ source_ref_by_part: dict[str, SlideRef],
+ self_source_part: str | None = None,
+ self_output_part: str | None = None,
+ fail_on_non_jump_slide_relationships: bool = False,
+) -> bool:
+ """Point referenced slide-jump relationships at final output slides."""
+ relationship_ids = _slide_jump_relationship_ids(part_root)
+ relationships = {
+ rel.attrib.get("Id", ""): rel
+ for rel in relationships_root.findall(_qn(REL_NS, "Relationship"))
+ }
+ changed = False
+ for relationship_id in sorted(relationship_ids):
+ rel = relationships.get(relationship_id)
+ if rel is None:
+ raise RuntimeError(
+ f"{owner_label} has a slide jump with missing relationship "
+ f"{relationship_id!r}"
+ )
+ if rel.attrib.get("Type") != SLIDE_REL_TYPE:
+ raise RuntimeError(
+ f"{owner_label} slide jump {relationship_id!r} does not use "
+ "a slide relationship"
+ )
+ if rel.attrib.get("TargetMode") == "External":
+ raise RuntimeError(
+ f"{owner_label} has an external slide relationship"
+ )
+ target = rel.attrib.get("Target")
+ if not target:
+ raise RuntimeError(
+ f"{owner_label} has a slide relationship without a target"
+ )
+ source_target_part = _normalize_part(target, source_owner_part)
+ if (
+ self_source_part is not None
+ and self_output_part is not None
+ and source_target_part == self_source_part
+ ):
+ output_target_part = self_output_part
+ else:
+ output_targets = outputs_by_source_part.get(source_target_part, [])
+ source_target_ref = source_ref_by_part.get(source_target_part)
+ target_label = (
+ f"source slide {source_target_ref.index}"
+ if source_target_ref is not None
+ else source_target_part
+ )
+ if not output_targets:
+ raise RuntimeError(
+ f"{owner_label} links to omitted {target_label}; "
+ "include the target exactly once or remove the link"
+ )
+ if len(output_targets) > 1:
+ raise RuntimeError(
+ f"{owner_label} links to repeated {target_label}; "
+ "the output target is ambiguous"
+ )
+ output_target_part = output_targets[0]
+ output_target = _relative_target(output_owner_part, output_target_part)
+ if rel.attrib.get("Target") != output_target:
+ rel.set("Target", output_target)
+ changed = True
+
+ if fail_on_non_jump_slide_relationships:
+ for relationship_id, rel in sorted(relationships.items()):
+ if (
+ relationship_id in relationship_ids
+ or rel.attrib.get("Type") != SLIDE_REL_TYPE
+ ):
+ continue
+ if rel.attrib.get("TargetMode") == "External":
+ raise RuntimeError(
+ f"{owner_label} has external non-jump slide relationship "
+ f"{relationship_id!r}; page-plan export refuses slide "
+ "relationships without a slide-jump action"
+ )
+ target = rel.attrib.get("Target")
+ if not target:
+ raise RuntimeError(
+ f"{owner_label} has non-jump slide relationship "
+ f"{relationship_id!r} without a target"
+ )
+ source_target_part = _normalize_part(target, source_owner_part)
+ source_target_ref = source_ref_by_part.get(source_target_part)
+ target_label = (
+ f"source slide {source_target_ref.index}"
+ if source_target_ref is not None
+ else source_target_part
+ )
+ if (
+ self_source_part is not None
+ and self_output_part is not None
+ and source_target_part == self_source_part
+ ):
+ output_targets = [self_output_part]
+ else:
+ output_targets = outputs_by_source_part.get(
+ source_target_part,
+ [],
+ )
+ if not output_targets:
+ raise RuntimeError(
+ f"{owner_label} has non-jump slide relationship "
+ f"{relationship_id!r} to omitted {target_label}; "
+ "page-plan export refuses slide relationships without a "
+ "slide-jump action"
+ )
+ if len(output_targets) > 1:
+ raise RuntimeError(
+ f"{owner_label} has non-jump slide relationship "
+ f"{relationship_id!r} to repeated {target_label}; "
+ "the output target is ambiguous"
+ )
+ output_target = _relative_target(
+ output_owner_part,
+ output_targets[0],
+ )
+ if rel.attrib.get("Target") != output_target:
+ raise RuntimeError(
+ f"{owner_label} has non-jump slide relationship "
+ f"{relationship_id!r} to {target_label} that would require "
+ "retargeting after page planning; page-plan export refuses "
+ "slide relationships without a slide-jump action"
+ )
+ return changed
+
+
+def _remap_reachable_shared_layer_slide_jumps(
+ entries: dict[str, bytes],
+ output_slides: list[tuple[str, str]],
+ *,
+ outputs_by_source_part: dict[str, list[str]],
+ source_ref_by_part: dict[str, SlideRef],
+ fail_on_non_jump_slide_relationships: bool = False,
+) -> None:
+ """Remap links inherited from layouts and masters used by output slides."""
+ pending: list[str] = []
+ for part_name, rels_name in output_slides:
+ rels_data = entries.get(rels_name)
+ if not rels_data:
+ continue
+ rels_root = ET.fromstring(rels_data)
+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):
+ if rel.attrib.get("Type") != _SLIDE_LAYOUT_REL_TYPE:
+ continue
+ target = rel.attrib.get("Target")
+ if target:
+ pending.append(_normalize_part(target, part_name))
+
+ visited: set[str] = set()
+ while pending:
+ part_name = pending.pop()
+ if part_name in visited:
+ continue
+ visited.add(part_name)
+ part_data = entries.get(part_name)
+ rels_name = _rels_name_for_part(part_name)
+ rels_data = entries.get(rels_name)
+ if not part_data or not rels_data:
+ continue
+ part_root = ET.fromstring(part_data)
+ rels_root = ET.fromstring(rels_data)
+ changed = _remap_slide_jump_relationships(
+ part_root,
+ rels_root,
+ source_owner_part=part_name,
+ output_owner_part=part_name,
+ owner_label=part_name,
+ outputs_by_source_part=outputs_by_source_part,
+ source_ref_by_part=source_ref_by_part,
+ fail_on_non_jump_slide_relationships=(
+ fail_on_non_jump_slide_relationships
+ ),
+ )
+ if changed:
+ entries[rels_name] = _xml_bytes(rels_root)
+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):
+ if rel.attrib.get("Type") != _SLIDE_MASTER_REL_TYPE:
+ continue
+ target = rel.attrib.get("Target")
+ if target:
+ pending.append(_normalize_part(target, part_name))
+
+
+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)
+ if custom_shows is not None:
+ presentation_root.remove(custom_shows)
+ for extension_list in presentation_root.findall(".//p:extLst", NS):
+ for extension in list(extension_list):
+ if any(
+ isinstance(child.tag, str)
+ and child.tag.rsplit("}", 1)[-1] == "sectionLst"
+ for child in extension.iter()
+ ):
+ extension_list.remove(extension)
+
+
+def _update_app_slide_count(entries: dict[str, bytes], slide_count: int) -> None:
+ app_part = "docProps/app.xml"
+ payload = entries.get(app_part)
+ if payload is None:
+ return
+ try:
+ text = payload.decode("utf-8")
+ except UnicodeDecodeError:
+ return
+ entries[app_part] = re.sub(
+ r"<Slides>.*?</Slides>",
+ f"<Slides>{slide_count}</Slides>",
+ text,
+ count=1,
+ ).encode("utf-8")
+
+
+def clone_presentation_slides(
+ source_pptx: Path,
+ source_slides: tuple[int, ...],
+ output_path: Path,
+ *,
+ package_overrides: dict[str, bytes] | None = None,
+) -> None:
+ """Clone an ordered source-slide roster into canonical output slide parts.
+
+ 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
+ omitted/ambiguous destination contract.
+ """
+ if not source_slides:
+ raise RuntimeError("Round-trip page plan must contain at least one slide")
+ with zipfile.ZipFile(source_pptx) as archive:
+ entries = {
+ info.filename: archive.read(info.filename)
+ for info in archive.infolist()
+ if not info.is_dir()
+ }
+ slide_refs = {
+ slide.index: slide
+ for slide in _parse_slide_refs(archive)
+ }
+ for part_name, payload in (package_overrides or {}).items():
+ if part_name not in entries:
+ raise RuntimeError(
+ f"Round-trip resource override names a missing source part: {part_name}"
+ )
+ entries[part_name] = payload
+
+ missing = sorted(set(source_slides) - set(slide_refs))
+ if missing:
+ raise RuntimeError(
+ "Round-trip page plan references missing source slide(s): "
+ + ", ".join(str(index) for index in missing)
+ )
+
+ presentation_root = ET.fromstring(entries["ppt/presentation.xml"])
+ presentation_rels_root = ET.fromstring(
+ entries["ppt/_rels/presentation.xml.rels"]
+ )
+ content_root = _content_type_root(
+ ET.fromstring(entries["[Content_Types].xml"])
)
+ slide_list = presentation_root.find("p:sldIdLst", NS)
+ if slide_list is None:
+ raise RuntimeError("Source presentation.xml has no p:sldIdLst")
+ source_slide_ids = {
+ entry.attrib.get(_qn(NS["r"], "id"), ""): copy.deepcopy(entry)
+ for entry in slide_list.findall("p:sldId", NS)
+ }
+ for child in list(slide_list):
+ slide_list.remove(child)
+ for rel in list(
+ presentation_rels_root.findall(_qn(REL_NS, "Relationship"))
+ ):
+ if rel.attrib.get("Type") == SLIDE_REL_TYPE:
+ presentation_rels_root.remove(rel)
+ _remove_stale_slide_order_metadata(presentation_root)
+
+ next_rid = _max_numeric_rid(presentation_rels_root) + 1
+ allocate = _make_part_allocator(entries)
+ source_ref_by_part = {
+ reference.part_name: reference
+ for reference in slide_refs.values()
+ }
+ output_slides: list[tuple[str, str]] = []
+ outputs_by_source_part: dict[str, list[str]] = {}
+ for output_index, source_index in enumerate(source_slides, start=1):
+ source_ref = slide_refs[source_index]
+ output_part = f"ppt/slides/slide{output_index}.xml"
+ output_rels = _rels_name_for_part(output_part)
+ output_slides.append((output_part, output_rels))
+ 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]
+ output_part, output_rels = output_slides[output_index - 1]
+ source_slide_xml = source_entries[source_ref.part_name]
+ source_rels_xml = source_entries.get(source_ref.rels_name)
+ slide_root = ET.fromstring(source_slide_xml)
+ relationships_root = (
+ ET.fromstring(source_rels_xml)
+ if source_rels_xml is not None
+ else _empty_relationships_root()
+ )
+ _remap_slide_jump_relationships(
+ slide_root,
+ relationships_root,
+ source_owner_part=source_ref.part_name,
+ output_owner_part=output_part,
+ owner_label=f"Source slide {source_index}",
+ 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=output_part,
+ fail_on_non_jump_slide_relationships=True,
+ )
+ 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},
+ )
+ entries[output_part] = source_slide_xml
+ entries[output_rels] = _xml_bytes(relationships_root)
+ _add_slide_override(content_root, output_part)
+
+ relationship_id = f"rId{next_rid + output_index - 1}"
+ ET.SubElement(
+ presentation_rels_root,
+ _qn(REL_NS, "Relationship"),
+ {
+ "Id": relationship_id,
+ "Type": SLIDE_REL_TYPE,
+ "Target": f"slides/slide{output_index}.xml",
+ },
+ )
+ source_slide_id_template = source_slide_ids.get(source_ref.rel_id)
+ if source_slide_id_template is None:
+ raise RuntimeError(
+ f"Source slide {source_index} has no p:sldId entry"
+ )
+ source_slide_id = copy.deepcopy(source_slide_id_template)
+ source_slide_id.set("id", str(255 + output_index))
+ source_slide_id.set(_qn(NS["r"], "id"), relationship_id)
+ slide_list.append(source_slide_id)
+
+ _remap_reachable_shared_layer_slide_jumps(
+ entries,
+ output_slides,
+ outputs_by_source_part=outputs_by_source_part,
+ source_ref_by_part=source_ref_by_part,
+ fail_on_non_jump_slide_relationships=True,
+ )
+ entries["ppt/presentation.xml"] = _xml_bytes(presentation_root)
+ entries["ppt/_rels/presentation.xml.rels"] = _xml_bytes(
+ presentation_rels_root
+ )
+ _prune_unreferenced_parts(entries, content_root)
+ entries["[Content_Types].xml"] = _xml_bytes(content_root)
+ _update_app_slide_count(entries, len(source_slides))
+
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(
+ output_path,
+ "w",
+ compression=zipfile.ZIP_DEFLATED,
+ ) as output:
+ for part_name, payload in entries.items():
+ output.writestr(part_name, payload)
diff --git a/skills/ppt-master/scripts/template_fill_pptx/package.py b/skills/ppt-master/scripts/template_fill_pptx/package.py
index 8f728c9c..48d6b9ed 100644
--- a/skills/ppt-master/scripts/template_fill_pptx/package.py
+++ b/skills/ppt-master/scripts/template_fill_pptx/package.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import posixpath
import re
+from pathlib import Path
from xml.etree import ElementTree as ET
from .ooxml import (
@@ -19,6 +20,7 @@ from .ooxml import (
_normalize_part,
_qn,
_rels_name_for_part,
+ _xml_bytes,
)
@@ -153,3 +155,25 @@ def _prune_unreferenced_parts(entries: dict[str, bytes], content_root: ET.Elemen
part_name = (override.attrib.get("PartName") or "").lstrip("/")
if part_name and part_name not in reachable:
content_root.remove(override)
+
+
+def prune_unreferenced_directory_parts(package_root: Path) -> int:
+ """Prune unreachable parts from one extracted OOXML package directory."""
+ entries = {
+ path.relative_to(package_root).as_posix(): path.read_bytes()
+ for path in package_root.rglob("*")
+ if path.is_file()
+ }
+ content_types = entries.get("[Content_Types].xml")
+ if content_types is None:
+ raise RuntimeError("Extracted PPTX package has no [Content_Types].xml")
+ content_root = _content_type_root(ET.fromstring(content_types))
+ before = set(entries)
+ _prune_unreferenced_parts(entries, content_root)
+ removed = before - set(entries)
+ for part_name in sorted(removed):
+ target = package_root.joinpath(*part_name.split("/"))
+ if target.is_file():
+ target.unlink()
+ (package_root / "[Content_Types].xml").write_bytes(_xml_bytes(content_root))
+ return len(removed)