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(create-template): compact SVG coordinates and preserve upright mirrored text

hugohe32ddea7efadbe
diff --git a/AGENTS.md b/AGENTS.md
index c25cd0fd..723b7699 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,6 +71,8 @@ python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --im
python3 skills/ppt-master/scripts/slice_images.py <project_path>/images/<sheet>.png --grid RxC --names a,b,c --trim --alpha
python3 skills/ppt-master/scripts/svg_editor/server.py <project_path> --live --daemon
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
+# Shared create-template coordinate compaction before template validation
+python3 skills/ppt-master/scripts/compact_svg_coordinates.py "<template_workspace>/templates" --inplace --keep-native-frames
# Explicit create-template normalization: selected complex <g> -> one SVG picture asset / <image>
python3 skills/ppt-master/scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<workspace>/picture-assets" --inplace
# Type A create-template mirror: validated authoring IR -> deterministic structured template workspace
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 414b97a9..2dc48927 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -95,6 +95,7 @@ description: >
| `${SKILL_DIR}/scripts/image_gen.py` | AI image generation (multi-provider) |
| `${SKILL_DIR}/scripts/slice_images.py` | Slice one AI illustration sheet into individual spot-illustration elements |
| `${SKILL_DIR}/scripts/svg_authoring_view.py` | Create a lightweight editable authoring IR bundle, model-readable summary, and tool-only provenance manifest from PPTX-imported SVGs |
+| `${SKILL_DIR}/scripts/compact_svg_coordinates.py` | Compact safe model-facing page-space metadata and transform coordinates to at most two decimals |
| `${SKILL_DIR}/scripts/svg_quality_checker.py` | SVG quality check |
| `${SKILL_DIR}/scripts/preset_shape_svg.py` | Print one compact registry-backed native PowerPoint preset `<g>` to stdout for page or template insertion |
| `${SKILL_DIR}/scripts/total_md_split.py` | Speaker notes splitting |
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.md
index 38eb91ab..86735146 100644
--- a/skills/ppt-master/references/shared-standards.md
+++ b/skills/ppt-master/references/shared-standards.md
@@ -274,7 +274,7 @@ attributes, and no separate source-payload opt-in marker exists.
|---|---|---|
| `data-pptx-object` | Logical `<g>` and native carrier | `shape`, `connector`, `group`, or `picture`; never infer the object kind from path appearance. |
| `data-pptx-shape-id` + `data-pptx-shape-scope` | Logical `<g>` and carrier | Preserve the source part-scoped identity. Export remaps duplicate Master/Layout/Slide ids into page-unique ids before rebinding connector references. |
-| `data-pptx-frame="x y width height"` | Logical `<g>` and carrier | Own native `a:xfrm` position and size. Values use sufficient precision for exact EMU recovery; path bounds, stroke, markers, shadows, and text glyph bounds never replace this frame. |
+| `data-pptx-frame="x y width height"` | Logical `<g>` and carrier | Own native `a:xfrm` position and size. Lossless import SVGs and tool-side native records use sufficient precision for exact EMU recovery; the model-facing authoring IR may use the compact page-coordinate spelling defined below. Path bounds, stroke, markers, shadows, and text glyph bounds never replace this frame. |
| `data-pptx-prst` | Preset carrier and logical `<g>` | One of the locked 187 DrawingML `ST_ShapeType` values. |
| `data-pptx-av-*` | Preset carrier and logical `<g>` | Preserve the complete validated DrawingML adjustment formula, including non-`val` formulas. |
| `data-pptx-part="geometry"` | One hidden carrier path | The single native export authority for frame, base fill/line/effect, preset/custom geometry, and object identity. |
@@ -309,10 +309,19 @@ one. This array is still diagnostic metadata, not an authoring surface.
| Representation | Contract |
|---|---|
| Lossless import SVG | Keep complete native payload, hidden carriers, and preview evidence in the temporary analysis workspace. It is immutable native-payload backing, not the editable template source. |
-| Authoring IR bundle | Keep editable SVGs plus model-readable `authoring_summary.json` and tool-only `authoring_manifest.json`. Exclude opaque payload and duplicate hidden carriers from model context while retaining visible shape intent and a stable document-local `data-pptx-source-ref` on each imported logical object. The summary owns the compact current-file index; the manifest owns source paths and initial hashes and never enters model context. |
+| Authoring IR bundle | Keep editable SVGs plus model-readable `authoring_summary.json` and tool-only `authoring_manifest.json`. Exclude opaque payload and duplicate hidden carriers from model context while retaining visible shape intent and a stable document-local `data-pptx-source-ref` on each imported logical object. Compact model-facing imported frames and safe transform page coordinates to at most two decimals before hashing the IR. The summary owns the compact current-file index; the manifest owns source paths and initial hashes and never enters model context. |
| `standard` / `fidelity` output | Use the compact authored-preset contract (§1.5) for newly authored stock shapes; do not transplant opaque import payload or source topology. |
| `mirror` output | Materialize from the edited authoring IR. Rehydrate supported imported metadata only when a Slide-local/slot object's source ref and initial authoring hash still match; otherwise keep the current SVG fallback. Expand fixed Master/Layout group wrappers into direct semantic atoms while preserving source ownership, paint order, and visible appearance. |
+**Hard rule — model-facing page-coordinate precision**:
+
+| Surface | Precision contract |
+|---|---|
+| Imported `data-pptx-frame` in authoring IR | At most two decimals. An unchanged mirror source ref recovers the exact lossless frame before tool-side native-record externalization. |
+| `data-pptx-placeholder-bounds` in final template SVG | At most two decimals. |
+| `translate(...)`, `rotate(... cx cy)`, and `matrix(... e f)` | Translation values and rotation centers use at most two decimals. Keep the rotation angle and matrix `a b c d` coefficients unchanged. |
+| Protected values | Do not apply this compaction to path/points geometry, normalized crop or nested `viewBox` ratios, gradient offsets, opacity, scale arguments, canonical authored-preset frames, or lossless/tool-side native frames. |
+
**Hard rule — authoring source refs**: `data-pptx-source-ref` is reserved for
the create-template authoring IR. Its value is unique within one authoring SVG,
not across the workspace, and must be resolved through that document's
@@ -1142,6 +1151,9 @@ adjacent operations without a separator, units, unknown functions, and
incomplete input fail quality check and export. Generated numeric tokens use
ordinary decimals; a supported leading `+`, exponent, or trailing decimal point
remains compatible input and receives a non-blocking normalization warning.
+Model-facing translation values, rotation centers, and matrix `e/f` use at
+most two decimals under §1.4; angles, scale arguments, and matrix `a/b/c/d`
+retain the precision required by the transform.
Set text size/position directly. A text transform is either a translate-only
list or one rotate operation; do not scale, matrix-transform, or mix operations
@@ -1155,7 +1167,10 @@ finite, non-zero, and orthogonal; importer/live-editor matrices do not expand
the hand-authored contract.
Mirror around vertical pivot `cx` with
`translate(cx 0) scale(-1 1) translate(-cx 0)`; use the analogous Y sequence
-for a horizontal pivot.
+for a horizontal pivot. During mirror materialization, imported PowerPoint
+groups with an axis flip keep their geometry reflection, while each descendant
+SVG text node receives the matching counter-reflection so browser previews keep
+glyphs upright. The tool-side native record retains the source group flip.
Layer back-to-front: background/image → scrim/shadow → main geometry → labels /
icons → top annotation. Finalization and native export independently expand
@@ -1816,7 +1831,7 @@ prototype size remain unchanged.
| `data-pptx-layer="layout"` | direct semantic atom | Moves one repeated static object/background into the selected Layout; ordinary `<g>` is forbidden, while one validated compact authored-preset `<g>` (§1.5) is an atomic exception |
| `data-pptx-layer="slide"` | direct full-canvas solid `<rect>` only | Writes a one-page override as Slide `p:bg` |
| `data-pptx-placeholder="..."` | direct slot `<g id>` | Declares a reusable Layout slot whose visible content remains Slide-local |
-| `data-pptx-placeholder-bounds="x y width height"` | slot `<g>` | Supplies the positive reusable design-zone frame in SVG user units |
+| `data-pptx-placeholder-bounds="x y width height"` | slot `<g>` | Supplies the positive reusable design-zone frame in SVG user units with at most two decimals per value |
| `data-pptx-placeholder-idx="1"` | slot `<g>` | Retains an imported source Layout placeholder index; optional for reconstructed layouts |
| `data-pptx-placeholder-carrier="true"` | one compatible direct child of a normal slot | Binds that visible child as the real Slide placeholder carrier |
| `data-pptx-placeholder-binding="proxy"` | composite `object` slot `<g>` only | Keeps the visible group ordinary and creates one hidden transparent binding proxy |
diff --git a/skills/ppt-master/references/template-designer.md b/skills/ppt-master/references/template-designer.md
index 8db7571a..a6e55773 100644
--- a/skills/ppt-master/references/template-designer.md
+++ b/skills/ppt-master/references/template-designer.md
@@ -393,7 +393,7 @@ identity exactly when the importer supports them. Do not replace source
assign stable indices only when repeated roles need disambiguation inside the
new Layout.
-**Hard rule — explicit design-zone bounds**: Every slot carries `data-pptx-placeholder-bounds="x y width height"`. Mirror uses the source Layout placeholder frame. `standard` / `fidelity` author bounds from the intended safe area, column, panel inset, or media frame. Do not use character count, glyph width, current wrapping, or the tight sample-content box. An authored Layout may intentionally have zero slots.
+**Hard rule — explicit design-zone bounds**: Every slot carries `data-pptx-placeholder-bounds="x y width height"` with at most two decimals per value. Mirror uses the source Layout placeholder frame. `standard` / `fidelity` author bounds from the intended safe area, column, panel inset, or media frame. Do not use character count, glyph width, current wrapping, or the tight sample-content box. An authored Layout may intentionally have zero slots.
### 3. Placeholder Markers
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index 539f0b16..4b3dc28a 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -45,7 +45,7 @@ python3 scripts/update_repo.py
|------|-----------------|---------------|
| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
-| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
+| SVG pipeline | `preset_shape_svg.py`, `svg_authoring_view.py`, `compact_svg_coordinates.py`, `mirror_template_materialize.py`, `finalize_svg.py`, `svg_to_pptx.py`, `template_preview_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `extract_svg_pictures.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md); [native preset authoring](../references/native-shape-authoring.md) |
| PPTX transitions | `pptx_transitions.py` | [docs/pptx-transitions.md](./docs/pptx-transitions.md) |
| PPTX animations | `pptx_animations.py`, `animation_config.py` | [docs/pptx-animations.md](./docs/pptx-animations.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
@@ -83,6 +83,7 @@ python3 scripts/pptx_template_import.py <template.pptx> --manifest-only
python3 scripts/pptx_template_import.py <template.pptx> --inheritance-mode both
python3 scripts/svg_authoring_view.py <imported-svg-or-dir> -o <output-dir> --projection-kind layered
python3 scripts/svg_authoring_view.py <authoring-dir> --refresh-summary
+python3 scripts/compact_svg_coordinates.py <template_workspace>/templates --inplace --keep-native-frames
python3 scripts/mirror_template_materialize.py <import_workspace> <empty_template_workspace>
python3 scripts/template_preview_pptx.py <template_workspace>
python3 scripts/template_preview_pptx.py <legacy_template_workspace> --visual-only
@@ -103,7 +104,9 @@ Relative local image references are rewritten so the projected copy still
renders from its new location. The bundle's `authoring_summary.json` is the
model-readable current-file index; `authoring_manifest.json` records
source/authoring hashes and object paths for tools without duplicating opaque
-payload and does not enter model context. In-place vector/picture extraction
+payload and does not enter model context. Imported model-facing frames and safe
+transform page coordinates use at most two decimals; immutable lossless SVGs
+retain the original precision. In-place vector/picture extraction
refreshes the summary automatically; use `--refresh-summary` after other direct
IR edits. The full imported SVG remains unchanged as native-payload backing.
Template creation edits the IR and materializes validated `templates/*.svg`;
@@ -183,6 +186,7 @@ Create-template/source normalization (optional; never part of automatic export):
python3 scripts/extract_svg_assets.py <layered_svg_dir> --icons-dir <icons_dir> --icon-namespace imported --inplace --id-prefix layered
python3 scripts/extract_svg_assets.py <flat_svg_dir> --icons-dir <icons_dir> --icon-namespace imported --reuse-inventory <layered_inventory.json> --inplace --id-prefix flat
python3 scripts/extract_svg_pictures.py "<svg_file>" --select "<group_id>" --resource-root "<workspace>" --images-dir "<picture_assets_dir>" --inplace # optional create-template normalization: one selected group -> one SVG picture
+python3 scripts/compact_svg_coordinates.py <template_workspace>/templates --inplace --keep-native-frames
python3 scripts/mirror_template_materialize.py <import_workspace> <empty_template_workspace> # Type A mirror only
```
diff --git a/skills/ppt-master/scripts/compact_svg_coordinates.py b/skills/ppt-master/scripts/compact_svg_coordinates.py
new file mode 100644
index 00000000..858ccfed
--- /dev/null
+++ b/skills/ppt-master/scripts/compact_svg_coordinates.py
@@ -0,0 +1,341 @@
+#!/usr/bin/env python3
+"""
+PPT Master - SVG Coordinate Compactor
+
+Compact model-facing page-space SVG coordinates to at most two decimal places
+without rounding normalized crop ratios or transform linear coefficients.
+
+Usage:
+ python3 scripts/compact_svg_coordinates.py <svg-file-or-directory> [--inplace]
+
+Examples:
+ python3 scripts/compact_svg_coordinates.py projects/example/templates --inplace
+ python3 scripts/compact_svg_coordinates.py imported/authoring-svg
+
+Dependencies:
+ None (standard library only).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import re
+import stat
+import sys
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional
+from xml.etree import ElementTree as ET
+
+from console_encoding import configure_utf8_stdio
+
+configure_utf8_stdio()
+
+COORDINATE_DECIMAL_PLACES = 2
+_NUMBER_TOKEN = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
+_NUMBER_RE = re.compile(rf"^{_NUMBER_TOKEN}$")
+_TRANSFORM_FUNCTION_RE = re.compile(r"([A-Za-z]+)\s*\(([^)]*)\)")
+_COMPACTABLE_ATTRIBUTE_RE = re.compile(
+ r"(?<![A-Za-z0-9_.:-])"
+ r"(?P<name>data-pptx-frame|data-pptx-placeholder-bounds|transform)"
+ r"(?P<spacing>\s*=\s*)"
+ r"(?P<quote>[\"'])"
+ r"(?P<value>.*?)"
+ r"(?P=quote)",
+ re.DOTALL,
+)
+
+
+@dataclass
+class CoordinateCompactionStats:
+ """Count safely compacted coordinate-bearing SVG attributes."""
+
+ native_frames: int = 0
+ placeholder_bounds: int = 0
+ transforms: int = 0
+
+ @property
+ def changed_attributes(self) -> int:
+ return self.native_frames + self.placeholder_bounds + self.transforms
+
+ def merge(self, other: "CoordinateCompactionStats") -> None:
+ self.native_frames += other.native_frames
+ self.placeholder_bounds += other.placeholder_bounds
+ self.transforms += other.transforms
+
+ def as_dict(self) -> dict[str, int]:
+ return {
+ "native_frames": self.native_frames,
+ "placeholder_bounds": self.placeholder_bounds,
+ "transforms": self.transforms,
+ "changed_attributes": self.changed_attributes,
+ }
+
+
+def _number_tokens(value: str) -> list[str] | None:
+ stripped = value.strip()
+ if not stripped:
+ return None
+ tokens = re.split(r"[\s,]+", stripped)
+ if not tokens or any(_NUMBER_RE.fullmatch(token) is None for token in tokens):
+ return None
+ return tokens
+
+
+def format_coordinate(value: str | float) -> str:
+ """Format one finite page-space coordinate with at most two decimals."""
+ numeric = float(value)
+ if not math.isfinite(numeric):
+ raise ValueError(f"Coordinate is not finite: {value!r}")
+ compact = (
+ f"{numeric:.{COORDINATE_DECIMAL_PLACES}f}".rstrip("0").rstrip(".")
+ )
+ return "0" if compact in {"", "-0"} else compact
+
+
+def _compact_coordinate_quad(value: str) -> str:
+ tokens = _number_tokens(value)
+ if tokens is None or len(tokens) != 4:
+ return value
+ return " ".join(format_coordinate(token) for token in tokens)
+
+
+def _compact_transform(value: str) -> str:
+ def replace(match: re.Match[str]) -> str:
+ name, arguments = match.groups()
+ tokens = _number_tokens(arguments)
+ if tokens is None:
+ return match.group(0)
+
+ lowered = name.lower()
+ compacted: list[str]
+ if lowered == "translate" and len(tokens) in {1, 2}:
+ compacted = [format_coordinate(token) for token in tokens]
+ elif lowered == "rotate" and len(tokens) == 3:
+ compacted = [
+ tokens[0],
+ format_coordinate(tokens[1]),
+ format_coordinate(tokens[2]),
+ ]
+ elif lowered == "matrix" and len(tokens) == 6:
+ compacted = [
+ *tokens[:4],
+ format_coordinate(tokens[4]),
+ format_coordinate(tokens[5]),
+ ]
+ else:
+ return match.group(0)
+ return f"{name}({' '.join(compacted)})"
+
+ return _TRANSFORM_FUNCTION_RE.sub(replace, value)
+
+
+def _compact_attribute_value(
+ name: str,
+ value: str,
+ *,
+ compact_native_frames: bool,
+) -> str:
+ if name == "data-pptx-frame":
+ return _compact_coordinate_quad(value) if compact_native_frames else value
+ if name == "data-pptx-placeholder-bounds":
+ return _compact_coordinate_quad(value)
+ if name == "transform":
+ return _compact_transform(value)
+ return value
+
+
+def _record_change(stats: CoordinateCompactionStats, name: str) -> None:
+ if name == "data-pptx-frame":
+ stats.native_frames += 1
+ elif name == "data-pptx-placeholder-bounds":
+ stats.placeholder_bounds += 1
+ elif name == "transform":
+ stats.transforms += 1
+
+
+def compact_svg_tree(
+ root: ET.Element,
+ *,
+ compact_native_frames: bool = True,
+) -> CoordinateCompactionStats:
+ """Compact safe coordinate metadata in one parsed SVG tree."""
+ stats = CoordinateCompactionStats()
+ for element in root.iter():
+ for name in (
+ "data-pptx-frame",
+ "data-pptx-placeholder-bounds",
+ "transform",
+ ):
+ current = element.get(name)
+ if current is None:
+ continue
+ compacted = _compact_attribute_value(
+ name,
+ current,
+ compact_native_frames=compact_native_frames,
+ )
+ if compacted == current:
+ continue
+ element.set(name, compacted)
+ _record_change(stats, name)
+ return stats
+
+
+def compact_svg_text(
+ text: str,
+ *,
+ compact_native_frames: bool = True,
+) -> tuple[str, CoordinateCompactionStats]:
+ """Compact safe coordinates while preserving unrelated SVG formatting."""
+ stats = CoordinateCompactionStats()
+
+ def replace(match: re.Match[str]) -> str:
+ name = match.group("name")
+ current = match.group("value")
+ compacted = _compact_attribute_value(
+ name,
+ current,
+ compact_native_frames=compact_native_frames,
+ )
+ if compacted == current:
+ return match.group(0)
+ _record_change(stats, name)
+ return (
+ f"{name}{match.group('spacing')}{match.group('quote')}"
+ f"{compacted}{match.group('quote')}"
+ )
+
+ return _COMPACTABLE_ATTRIBUTE_RE.sub(replace, text), stats
+
+
+def _svg_files(input_path: Path) -> list[Path]:
+ if input_path.is_file():
+ return [input_path] if input_path.suffix.lower() == ".svg" else []
+ return sorted(path for path in input_path.rglob("*.svg") if path.is_file())
+
+
+def _write_atomic(path: Path, payload: str) -> None:
+ mode = stat.S_IMODE(path.stat().st_mode)
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ newline="\n",
+ prefix=f".{path.name}.",
+ suffix=".tmp",
+ dir=path.parent,
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ handle.write(payload)
+ try:
+ temporary_path.chmod(mode)
+ temporary_path.replace(path)
+ except OSError:
+ temporary_path.unlink(missing_ok=True)
+ raise
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Compact safe page-space SVG coordinates to at most two decimal "
+ "places. Runs as a dry-run unless --inplace is supplied."
+ ),
+ )
+ parser.add_argument("input", type=Path, help="SVG file or directory")
+ parser.add_argument(
+ "--inplace",
+ action="store_true",
+ help="Atomically replace changed SVG files",
+ )
+ parser.add_argument(
+ "--keep-native-frames",
+ action="store_true",
+ help=(
+ "Leave data-pptx-frame unchanged while compacting slot bounds and "
+ "transform translations"
+ ),
+ )
+ return parser
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ args = build_parser().parse_args(argv)
+ input_path = args.input.resolve()
+ if not input_path.exists():
+ print(
+ json.dumps(
+ {"error": f"Input does not exist: {input_path}"},
+ ensure_ascii=False,
+ ),
+ file=sys.stderr,
+ )
+ return 1
+
+ paths = _svg_files(input_path)
+ if not paths:
+ print(
+ json.dumps(
+ {"error": f"No SVG files found under {input_path}"},
+ ensure_ascii=False,
+ ),
+ file=sys.stderr,
+ )
+ return 1
+
+ staged: list[tuple[Path, str]] = []
+ totals = CoordinateCompactionStats()
+ bytes_before = 0
+ bytes_after = 0
+ try:
+ for path in paths:
+ original = path.read_text(encoding="utf-8")
+ ET.fromstring(original)
+ compacted, stats = compact_svg_text(
+ original,
+ compact_native_frames=not args.keep_native_frames,
+ )
+ totals.merge(stats)
+ before = len(original.encode("utf-8"))
+ after = len(compacted.encode("utf-8"))
+ bytes_before += before
+ bytes_after += after
+ if compacted != original:
+ staged.append((path, compacted))
+ except (OSError, UnicodeDecodeError, ET.ParseError, ValueError) as exc:
+ print(
+ json.dumps({"error": str(exc)}, ensure_ascii=False),
+ file=sys.stderr,
+ )
+ return 1
+
+ if args.inplace:
+ try:
+ for path, payload in staged:
+ _write_atomic(path, payload)
+ except OSError as exc:
+ print(
+ json.dumps({"error": str(exc)}, ensure_ascii=False),
+ file=sys.stderr,
+ )
+ return 1
+
+ print(json.dumps({
+ "input": str(input_path),
+ "inplace": args.inplace,
+ "files_scanned": len(paths),
+ "files_changed": len(staged),
+ "bytes_before": bytes_before,
+ "bytes_after": bytes_after,
+ "bytes_saved": bytes_before - bytes_after,
+ "coordinates": totals.as_dict(),
+ }, ensure_ascii=False, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 6fe29bff..f29b0763 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -34,7 +34,9 @@ The projected copy:
- keeps visible paths, text, images, stable ids, Master/Layout root markers,
selected native-shape intent, and a document-local `data-pptx-source-ref` on
each imported logical object;
-- rewrites relative local asset references for the projection's new location.
+- rewrites relative local asset references for the projection's new location;
+- compacts imported model-facing frames and safe transform page coordinates to
+ at most two decimals.
The summary stores the current SVG roster plus compact per-file canvas, size,
text, image, vector, placeholder, icon, and source-ref counts. Models read the
@@ -65,6 +67,31 @@ is owned by [`shared-standards.md`](../../references/shared-standards.md), with
authoring guidance in
[`native-shape-authoring.md`](../../references/native-shape-authoring.md).
+## `compact_svg_coordinates.py`
+
+Compact safe model-facing page-space coordinates without rewriting unrelated
+SVG formatting:
+
+```bash
+python3 scripts/compact_svg_coordinates.py <svg-file-or-directory>
+python3 scripts/compact_svg_coordinates.py <template-directory> \
+ --inplace --keep-native-frames
+```
+
+The default run is a dry-run JSON report. `--inplace` atomically replaces only
+changed SVG files. The shared create-template final pass uses
+`--keep-native-frames`: it compacts `data-pptx-placeholder-bounds`, translation
+values, rotation centers, and matrix `e/f`, while preserving canonical
+authored-preset or inline native frames. `svg_authoring_view.py` separately
+compacts imported model-facing frames because unchanged mirror refs can recover
+their exact coordinates from immutable lossless backing.
+
+The compactor never rounds path/points geometry, normalized crop or nested
+`viewBox` ratios, gradient offsets, opacity, scale arguments, rotation angles,
+or matrix `a/b/c/d` coefficients. Type A mirror materialization invokes the
+same compactor before native-record externalization; `standard` and `fidelity`
+use the shared final pass before template validation.
+
## `extract_svg_assets.py`
Factor large vector subtrees out of lightweight authoring IR documents and
@@ -118,19 +145,22 @@ Materialization preserves source page order and emits one definition-only
It mechanically expands fixed Master/Layout group wrappers into direct atoms,
rehydrates only unchanged converter-supported Slide-local/slot refs, keeps the
current SVG fallback for edited refs, preserves explicit text hard breaks, and
-removes every IR-only source ref. Supported opaque `p:txBody`,
+removes every IR-only source ref. Imported axis-flipped groups retain their
+geometry reflection while descendant SVG text receives a matching
+counter-reflection, preserving PowerPoint's upright glyph appearance in browser
+previews. Supported opaque `p:txBody`,
relationship-free `p:style`, and `a:custGeom` payloads are deduplicated into
`templates/native_payloads.json.gz`. Repeated native restoration attributes
are stored there as short `data-pptx-native-ref` records; page and
imported-vector SVGs retain only those record ids and content-hash payload
-references. Structural Master/Layout, placeholder, layer, and editable-object
+references. The native record referenced by an imported text placeholder
+carrier owns its authoritative source frame, so the Slide-local frame can
+differ from reusable Layout bounds without restoring long exact coordinates
+inline. Structural Master/Layout, placeholder, layer, and editable-object
fields remain inline. Source `p:sldLayout@showMasterSp` and
`p:sld@showMasterSp` facts become canonical root
`data-pptx-show-master-shapes` and
-`data-pptx-show-inherited-shapes` booleans. An imported text placeholder keeps
-its authoritative native frame on the `<text data-pptx-frame>` carrier so the
-Slide-local frame can differ from the reusable Layout bounds without collapsing
-to glyph bounds.
+`data-pptx-show-inherited-shapes` booleans.
Checker, template-structure validation, and export hydrate both store layers in
memory; legacy inline payload and v1 payload-only stores remain readable.
diff --git a/skills/ppt-master/scripts/extract_svg_assets.py b/skills/ppt-master/scripts/extract_svg_assets.py
index 8051f538..00221568 100644
--- a/skills/ppt-master/scripts/extract_svg_assets.py
+++ b/skills/ppt-master/scripts/extract_svg_assets.py
@@ -447,6 +447,9 @@ def _existing_placeholder_entries(
for asset, entry in sorted(by_asset.items()):
asset_path = icons_dir / asset
if asset_path.exists():
+ entry["asset_sha256"] = hashlib.sha256(
+ asset_path.read_bytes()
+ ).hexdigest()
try:
root = ET.parse(asset_path).getroot()
except ET.ParseError:
diff --git a/skills/ppt-master/scripts/mirror_template_materialize.py b/skills/ppt-master/scripts/mirror_template_materialize.py
index 33514a9b..7211a07c 100644
--- a/skills/ppt-master/scripts/mirror_template_materialize.py
+++ b/skills/ppt-master/scripts/mirror_template_materialize.py
@@ -33,6 +33,7 @@ from typing import Any, Iterable
from urllib.parse import unquote, urlsplit, urlunsplit
from xml.etree import ElementTree as ET
+from compact_svg_coordinates import compact_svg_tree, format_coordinate
from console_encoding import configure_utf8_stdio
from native_payloads import (
PAYLOAD_STORE_RELATIVE_PATH,
@@ -120,6 +121,15 @@ _AGGREGATE_GROUP_ATTRIBUTES = frozenset({
_URL_REFERENCE_RE = re.compile(r"url\(\s*(['\"]?)#([^)'\"\s]+)\1\s*\)")
_CSS_ID_RE = re.compile(r"#([A-Za-z_][A-Za-z0-9_.:-]*)")
_SAFE_KEY_RE = re.compile(r"[^A-Za-z0-9_.-]+")
+_TRANSFORM_NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
+_AXIS_REFLECTION_RE = re.compile(
+ rf"^\s*translate\(\s*({_TRANSFORM_NUMBER})[\s,]+"
+ rf"({_TRANSFORM_NUMBER})\s*\)\s*"
+ rf"scale\(\s*({_TRANSFORM_NUMBER})[\s,]+"
+ rf"({_TRANSFORM_NUMBER})\s*\)\s*"
+ rf"translate\(\s*({_TRANSFORM_NUMBER})[\s,]+"
+ rf"({_TRANSFORM_NUMBER})\s*\)\s*$"
+)
class MirrorMaterializationError(RuntimeError):
@@ -166,12 +176,14 @@ class RestorationStats:
fallback_refs: int = 0
structural_refs: int = 0
detached_connector_endpoints: int = 0
+ upright_text_compensations: int = 0
def merge(self, other: "RestorationStats") -> None:
self.rehydrated_refs += other.rehydrated_refs
self.fallback_refs += other.fallback_refs
self.structural_refs += other.structural_refs
self.detached_connector_endpoints += other.detached_connector_endpoints
+ self.upright_text_compensations += other.upright_text_compensations
def as_dict(self) -> dict[str, int]:
return {
@@ -179,6 +191,7 @@ class RestorationStats:
"fallback_refs": self.fallback_refs,
"structural_refs": self.structural_refs,
"detached_connector_endpoints": self.detached_connector_endpoints,
+ "upright_text_compensations": self.upright_text_compensations,
}
@@ -192,6 +205,80 @@ def _local_name(name: object) -> str:
return name.rsplit("}", 1)[-1] if isinstance(name, str) else ""
+def _axis_reflection_transform(value: str | None) -> str | None:
+ """Return one exact importer axis-reflection transform when valid."""
+ if not value:
+ return None
+ match = _AXIS_REFLECTION_RE.fullmatch(value)
+ if match is None:
+ return None
+ cx, cy, scale_x, scale_y, offset_x, offset_y = (
+ float(token) for token in match.groups()
+ )
+ if not (
+ math.isclose(abs(scale_x), 1.0, abs_tol=1e-9)
+ and math.isclose(abs(scale_y), 1.0, abs_tol=1e-9)
+ and (scale_x < 0 or scale_y < 0)
+ and math.isclose(offset_x, -cx, abs_tol=1e-7)
+ and math.isclose(offset_y, -cy, abs_tol=1e-7)
+ ):
+ return None
+ return value.strip()
+
+
+def _compensate_reflected_group_text(root: ET.Element) -> int:
+ """Keep browser-visible text upright inside imported flipped groups."""
+ parent_by_child = {
+ child: parent
+ for parent in root.iter()
+ for child in parent
+ }
+ reflected_groups: list[tuple[int, ET.Element, str]] = []
+ for element in root.iter():
+ if _local_name(element.tag) != "g":
+ continue
+ transform = _axis_reflection_transform(element.get("transform"))
+ if transform is None:
+ continue
+ depth = 0
+ current = element
+ while current in parent_by_child:
+ depth += 1
+ current = parent_by_child[current]
+ reflected_groups.append((depth, element, transform))
+
+ wrapped = 0
+ for _depth, group, transform in sorted(
+ reflected_groups,
+ key=lambda item: item[0],
+ reverse=True,
+ ):
+ text_elements = [
+ element
+ for element in group.iter()
+ if _local_name(element.tag) == "text"
+ ]
+ for text in text_elements:
+ current_parents = {
+ child: parent
+ for parent in group.iter()
+ for child in parent
+ }
+ parent = current_parents.get(text)
+ if parent is None:
+ continue
+ position = list(parent).index(text)
+ parent.remove(text)
+ wrapper = ET.Element(
+ f"{{{SVG_NS}}}g",
+ {"transform": transform},
+ )
+ wrapper.append(text)
+ parent.insert(position, wrapper)
+ wrapped += 1
+ return wrapped
+
+
def _sha256_bytes(payload: bytes) -> str:
return hashlib.sha256(payload).hexdigest()
@@ -1421,7 +1508,7 @@ def _copy_text_carrier(source: ET.Element | None) -> ET.Element | None:
tspan.attrib.pop("x", None)
elif child_index == 0 and text_y is not None and previous_y is not None:
tspan.set("x", text.get("x", texts[0].get("x", "0")))
- tspan.set("dy", _format_number(text_y - previous_y))
+ tspan.set("dy", format_coordinate(text_y - previous_y))
if text_index > 0 and child_index == 0:
tspan.set("data-paragraph-soft-break", "0")
carrier.append(tspan)
@@ -1430,7 +1517,7 @@ def _copy_text_carrier(source: ET.Element | None) -> ET.Element | None:
attrs: dict[str, str] = {}
if not first_output and text_y is not None and previous_y is not None:
attrs["x"] = text.get("x", texts[0].get("x", "0"))
- attrs["dy"] = _format_number(text_y - previous_y)
+ attrs["dy"] = format_coordinate(text_y - previous_y)
if text_index > 0:
attrs["data-paragraph-soft-break"] = "0"
tspan = ET.SubElement(carrier, f"{{{SVG_NS}}}tspan", attrs)
@@ -1444,7 +1531,7 @@ def _copy_text_carrier(source: ET.Element | None) -> ET.Element | None:
if source_frame is not None:
carrier.set(
"data-pptx-frame",
- " ".join(_format_number(value) for value in source_frame),
+ " ".join(format_coordinate(value) for value in source_frame),
)
carrier.set("data-pptx-placeholder-carrier", "true")
return carrier
@@ -1595,17 +1682,14 @@ def _remap_placeholder_decorations(
translate_x = to_x - from_x * scale_x
translate_y = to_y - from_y * scale_y
frame_transform = "matrix({})".format(
- " ".join(
- _format_number(value)
- for value in (
- scale_x,
- 0.0,
- 0.0,
- scale_y,
- translate_x,
- translate_y,
- )
- )
+ " ".join((
+ _format_number(scale_x),
+ "0",
+ "0",
+ _format_number(scale_y),
+ format_coordinate(translate_x),
+ format_coordinate(translate_y),
+ ))
)
for decoration in decorations:
existing = (decoration.get("transform") or "").strip()
@@ -1707,8 +1791,8 @@ def _blank_text_carrier(
carrier = ET.Element(
f"{{{SVG_NS}}}text",
{
- "x": _format_number(x),
- "y": _format_number(y + min(height, 24)),
+ "x": format_coordinate(x),
+ "y": format_coordinate(y + min(height, 24)),
"font-size": "18",
"fill": "#000000",
"data-pptx-placeholder-carrier": "true",
@@ -1720,7 +1804,7 @@ def _blank_text_carrier(
if carrier.get("data-pptx-frame") is None:
carrier.set(
"data-pptx-frame",
- " ".join(_format_number(value) for value in plan.bounds),
+ " ".join(format_coordinate(value) for value in plan.bounds),
)
carrier.set("data-pptx-placeholder-carrier", "true")
return carrier
@@ -1731,10 +1815,10 @@ def _blank_image_carrier(plan: SlotPlan) -> ET.Element:
return ET.Element(
f"{{{SVG_NS}}}image",
{
- "x": _format_number(x),
- "y": _format_number(y),
- "width": _format_number(width),
- "height": _format_number(height),
+ "x": format_coordinate(x),
+ "y": format_coordinate(y),
+ "width": format_coordinate(width),
+ "height": format_coordinate(height),
"href": TRANSPARENT_PIXEL_DATA_URI,
"preserveAspectRatio": "none",
"data-pptx-placeholder-carrier": "true",
@@ -1769,7 +1853,7 @@ def _slot_wrapper(
"id": plan.slot_id,
"data-pptx-placeholder": plan.semantic_role,
"data-pptx-placeholder-bounds": " ".join(
- _format_number(item) for item in plan.bounds
+ format_coordinate(item) for item in plan.bounds
),
},
)
@@ -1949,9 +2033,11 @@ def _compose_template(
f"{{{SVG_NS}}}svg",
{
"version": "1.1",
- "width": _format_number(width),
- "height": _format_number(height),
- "viewBox": f"0 0 {_format_number(width)} {_format_number(height)}",
+ "width": format_coordinate(width),
+ "height": format_coordinate(height),
+ "viewBox": (
+ f"0 0 {format_coordinate(width)} {format_coordinate(height)}"
+ ),
"data-pptx-master": str(master["key"]),
"data-pptx-master-name": str(master["name"]),
"data-pptx-layout": str(layout["key"]),
@@ -2507,6 +2593,10 @@ def materialize_mirror_template(
asset_sources=asset_sources,
)
total_stats.detached_connector_endpoints += _sanitize_connector_references(root)
+ total_stats.upright_text_compensations += (
+ _compensate_reflected_group_text(root)
+ )
+ compact_svg_tree(root, compact_native_frames=False)
_refresh_preset_preview_hashes(root)
try:
native_payload_stats.merge(
@@ -2537,6 +2627,7 @@ def materialize_mirror_template(
total_stats.detached_connector_endpoints += _sanitize_connector_references(
icon_root
)
+ compact_svg_tree(icon_root, compact_native_frames=False)
_refresh_preset_preview_hashes(icon_root)
try:
native_payload_stats.merge(
diff --git a/skills/ppt-master/scripts/svg_authoring_view.py b/skills/ppt-master/scripts/svg_authoring_view.py
index ca17af1b..6cb23164 100644
--- a/skills/ppt-master/scripts/svg_authoring_view.py
+++ b/skills/ppt-master/scripts/svg_authoring_view.py
@@ -44,6 +44,7 @@ from typing import Optional
from urllib.parse import urlsplit, urlunsplit
from xml.etree import ElementTree as ET
+from compact_svg_coordinates import compact_svg_tree
from console_encoding import configure_utf8_stdio
configure_utf8_stdio()
@@ -244,6 +245,7 @@ class ProjectionStats:
geometry_preview_wrappers: int = 0
geometry_detail_markers: int = 0
asset_references_rewritten: int = 0
+ coordinate_attributes_compacted: int = 0
source_attributes: Counter[str] = field(default_factory=Counter)
def as_dict(self) -> dict[str, object]:
@@ -254,6 +256,7 @@ class ProjectionStats:
"geometry_detail_markers": self.geometry_detail_markers,
"source_attributes": dict(sorted(self.source_attributes.items())),
"asset_references_rewritten": self.asset_references_rewritten,
+ "coordinate_attributes_compacted": self.coordinate_attributes_compacted,
}
def merge(self, other: "ProjectionStats") -> None:
@@ -262,6 +265,9 @@ class ProjectionStats:
self.geometry_preview_wrappers += other.geometry_preview_wrappers
self.geometry_detail_markers += other.geometry_detail_markers
self.asset_references_rewritten += other.asset_references_rewritten
+ self.coordinate_attributes_compacted += (
+ other.coordinate_attributes_compacted
+ )
self.source_attributes.update(other.source_attributes)
@@ -430,6 +436,9 @@ def _render_projection(source: Path, output: Path) -> tuple[ProjectionReport, by
_project_subtree(root, stats)
_strip_import_attributes(root, stats)
_rewrite_asset_references(root, source.parent, output.parent, stats)
+ stats.coordinate_attributes_compacted = compact_svg_tree(
+ root,
+ ).changed_attributes
_index_initial_authoring_references(root, source_references)
projected = ET.tostring(root, encoding="utf-8", xml_declaration=False)
diff --git a/skills/ppt-master/workflows/create-template.md b/skills/ppt-master/workflows/create-template.md
index 54a1c480..01c25e12 100644
--- a/skills/ppt-master/workflows/create-template.md
+++ b/skills/ppt-master/workflows/create-template.md
@@ -159,7 +159,7 @@ Only when the import explicitly used `--inheritance-mode both`, create the optio
python3 skills/ppt-master/scripts/svg_authoring_view.py "<import_workspace>/svg-flat" -o "<import_workspace>/authoring-svg-flat" --projection-kind flat
```
-Each bundle contains editable SVGs, a model-readable `authoring_summary.json`, and a tool-only `authoring_manifest.json`. The projection removes opaque text payload, duplicate hidden geometry carriers, and import-only identity attributes while keeping visible shape intent, compact preset/frame metadata, structure markers, logical ids, valid asset references, and a reserved `data-pptx-source-ref` on each imported logical object. The summary lists the current SVG roster plus per-file canvas, size, text, image, vector, placeholder, and source-ref counts. The machine manifest records relative source files, document hashes, source paths, and initial authoring-subtree hashes; it does not duplicate opaque payload and MUST NOT enter model context. Source refs are unique within one document and are interpreted by tools together with that document's manifest record.
+Each bundle contains editable SVGs, a model-readable `authoring_summary.json`, and a tool-only `authoring_manifest.json`. The projection removes opaque text payload, duplicate hidden geometry carriers, and import-only identity attributes while keeping visible shape intent, compact preset/frame metadata, structure markers, logical ids, valid asset references, and a reserved `data-pptx-source-ref` on each imported logical object. Model-facing `data-pptx-frame` values and safe transform page coordinates use at most two decimals; normalized crop ratios, path geometry, transform linear coefficients, and the immutable lossless source retain their required precision. The summary lists the current SVG roster plus per-file canvas, size, text, image, vector, placeholder, and source-ref counts. The machine manifest records relative source files, document hashes, source paths, and initial authoring-subtree hashes; it does not duplicate opaque payload and MUST NOT enter model context. Source refs are unique within one document and are interpreted by tools together with that document's manifest record.
In-place vector and picture normalization refreshes the summary automatically.
After any other direct IR edit, refresh it before the next analysis pass:
@@ -613,7 +613,7 @@ becomes the prototype Slide placeholder, while
| Centered exceptions | Center alignment is reserved for semantically short focal content such as KPI values, short process nodes, hero statements, and compact takeaways. Record a template-wide exception in `design_spec.md §IV` when it is part of the layout grammar. |
| Review Slide binding | `template_preview_pptx.py` sizes each authored Slide carrier to the same complete frame as its registered Layout placeholder. A review deck whose Slide carrier is only the prompt text's tight box fails Step 6. |
| Review prompt legibility | For `standard` / `fidelity`, the preview exporter substitutes concise sample text only in ephemeral review SVGs so long canonical markers such as `{{CHAPTER_NUM}}` or `{{PAGE_NUM}}` do not wrap. The source SVG markers, carrier font sizes, slot metadata, and Layout frames remain unchanged. |
-| Mirror boundary | `mirror` preserves source Slide carrier geometry exactly; the materializer places the authoritative source `data-pptx-frame` on its text carrier and keeps `data-pptx-placeholder-bounds` as the reusable Layout default. Do not normalize one to the other when the source intentionally overrides that frame. |
+| Mirror boundary | `mirror` preserves source Slide carrier geometry exactly in the tool-side native record referenced by its text carrier and keeps `data-pptx-placeholder-bounds` as the reusable Layout default. Do not normalize one to the other when the source intentionally overrides that frame. |
---
@@ -640,9 +640,12 @@ ls -la "<template_workspace>/templates"
ls -la "<template_workspace>/images" "<template_workspace>/icons"
```
-Run SVG validation on the template directory:
+Compact safe page-space metadata and transform coordinates, then run SVG
+validation on the template directory. Keep canonical authored-preset and native
+record frames unchanged:
```bash
+python3 skills/ppt-master/scripts/compact_svg_coordinates.py "<template_workspace>/templates" --inplace --keep-native-frames
python3 skills/ppt-master/scripts/svg_quality_checker.py "<template_workspace>/templates" --template-mode --format <canvas_format>
```
@@ -667,6 +670,7 @@ This checker validates the authoring contract, not the compiled OOXML package. T
- [ ] If TOC exists, placeholder pattern uses the canonical indexed form
- [ ] `design_spec.md` frontmatter declares `canvas_format`, `canvas_width`, `canvas_height`, and `canvas_viewbox`; PPTX/SVG-backed templates also declare `source_canvas_width`, `source_canvas_height`, and `source_viewbox`
- [ ] SVG `viewBox` matches the declared canvas dimensions, not just the aspect ratio (for `ppt169`: `0 0 1280 720`; for `banner`: `0 0 1920 1080`); `width` / `height`, if written, equal it
+- [ ] Model-facing placeholder bounds and transform page coordinates use at most two decimals; normalized crop/viewBox ratios, path geometry, transform scale/rotation coefficients, authored-preset frames, and tool-side native frames retain their required precision
- [ ] Placeholder names follow the canonical convention where applicable; templates with intentionally different vocabularies (e.g. `{{KEY_MESSAGE}}` instead of `{{PAGE_TITLE}}`) should declare a `placeholders:` frontmatter block to silence advisory warnings
- [ ] Asset files referenced by SVGs exist at their resolved paths. In both scopes, bitmap references resolve through `../images/`; no bitmap remains accidentally stranded in `templates/`
- [ ] `design_spec.md` frontmatter declares `native_structure_mode: structured`; no `native_structure.json` or `source_template.pptx` is packaged