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(svg): validate bounded content modules

hugohe34a5fbedc83f8
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 1e08e32c..83306a5d 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -37,7 +37,7 @@ Before the first SVG page, output a confirmation listing: the compact communicat
python3 skills/ppt-master/scripts/project_manager.py page-context <project_path> P<NN> --bundle --record-usage
```
-Use the bundle's communication contract, canvas, mode/style, colors, typography, icons, current `design_spec.md §IX` brief, and current-page lock assignments. The bundle is a read-only projection of `design_spec.md` and `spec_lock.md`; it does not replace either required gate artifact or authorize values absent from the lock. After an approved upstream lock change, rerun the command before drawing the affected page.
+Use the bundle's communication, canvas, mode/style, colors, typography, icons, current §IX brief/locks, and optional `global.template_application`. The latter governs which template content stays, changes, or moves; reuse/adherence select exporter mechanics only. This projection overrides neither facts, locks, nor technical constraints. After an approved lock change, rerun it before drawing the affected page.
**Source facts**: The bundle carries page intent and locked execution values, not the complete source corpus. Read the relevant `sources/` content and resolve listed `Fact IDs` from `sources/*.facts.json` when the page needs concrete claims, quotes, names, or data.
@@ -101,7 +101,7 @@ Before drawing each page, look up its entry in `page_rhythm` (key format `P<NN>`
## 3. Execution Guidelines
- **Proximity**: group related elements with tight spacing; separate unrelated groups
-- **Element grouping (Mandatory)**: wrap every logical Slide-local content unit — title, core-message line, each content block, card, list item, and diagram — in a top-level `<g id="...">` with a descriptive, page-unique id. Nested implementation groups within that unit may remain anonymous; they are not independent animation targets. Flat free-design/brand-only pages use ordinary semantic groups for every logical unit. On structured template pages, slot `<g>` elements are already semantic groups and direct Master/Layout atoms are the required exception to grouping. Authored native preset fragments (`preset_shape_svg.py`) already are one atomic `<g id>` each and count as one ordinary content group. When a preset needs labels or decorations, put the preset and those siblings inside a separate parent content group; never put them inside the preset group itself.
+- **Element grouping (Mandatory)**: wrap every logical Slide-local content unit — title, core-message line, each content block, card, list item, and diagram — in a top-level `<g id="...">` with a descriptive, page-unique id. Treat every visible `<g>` as one module and declare exactly one boundary: ordinary groups use `data-pptx-module-bounds="x y width height"`; slots and native/preset groups reuse their existing specialized bounds. Nested groups also declare bounds and stay inside their nearest parent module; text stays inside its nearest module. Nested implementation groups may remain anonymous, but never unbounded. Flat pages use ordinary semantic groups; structured pages already count slot groups, while direct Master/Layout atoms remain the grouping exception. When a preset needs labels or decorations, put it and those siblings inside a separately bounded parent group; never put them inside the preset group itself.
- **Spec adherence**: follow color, layout, canvas format, and typography in the spec
- **Template structure**: inherit the native visual framework only for `template_reuse_scope: mirror|layout`; `style` uses the flat route
- **Main-agent ownership**: SVG generation must run in the main agent (not sub-agents) — pages share upstream context for cross-page visual continuity
diff --git a/skills/ppt-master/references/executor-structured.md b/skills/ppt-master/references/executor-structured.md
index fb745718..fe86aa95 100644
--- a/skills/ppt-master/references/executor-structured.md
+++ b/skills/ppt-master/references/executor-structured.md
@@ -32,7 +32,7 @@ Resolve the per-page template SVG from `page_context.template.prototype`; the ow
> Note: `page_layouts` disambiguates the multiple content variants a template may ship; missing mappings are contract errors.
-**Templates supply structure, not skin (`layout` scope)**: a chart or layout template's gradients, drop-shadows, palette, **and font sizes** are placeholder. Inherit its geometry, label / legend placement, and series-encoding logic; re-skin every fill / stroke to the deck's `visual_style` + `spec_lock.colors` — flat styles strip the gradients and shadows, gradient / glass styles repaint their own. Forbidden — shipping a template's default `<linearGradient>` / `cardShadow` / Tailwind fills unchanged. `mirror` scope is the exception: §1.1 preserves visuals verbatim.
+**Default — re-skin `layout` (may override when the application plan keeps template visuals and the lock reflects them)**: inherit geometry, label/legend placement, and series encoding; otherwise repaint template gradients, shadows, fills, and strokes from the current style/lock. Template font sizes remain placeholders. `mirror` preserves visuals under §1.1.
**Font size is skin, not geometry (non-mirror).** A chart / layout template's hardcoded `font-size` values (often 11–16px, sized for the template's own dense placeholder text) are NOT inherited — classify each text into its `spec_lock.md` role and use that role's locked size, exactly as you re-skin color. **Structural roles (page title / body / subtitle / annotation / footnote) hold their one deck-wide size on every page** — the template's placeholder px never overrides it; same-role text drifting page to page is what makes a deck look unprofessional.
@@ -88,7 +88,7 @@ This section applies only when a deck/layout template's AI-derived lock records
**Hard rule — PowerPoint paint order**: Direct children appear in this order: Master background atoms, Layout background atoms, optional Slide background, remaining Master atoms, remaining Layout atoms, then slot groups and Slide-local content groups. Backgrounds are the inheritance plane beneath all shapes.
-**Mandatory — slot authoring**: A reusable content slot is one direct root `<g id>` carrying `data-pptx-placeholder` and positive `data-pptx-placeholder-bounds`. A normal slot contains exactly one compatible direct drawable child marked `data-pptx-placeholder-carrier="true"`. Export unwraps that child into the real Slide placeholder binding. Decorations do not belong in the slot; move reusable decoration to a root Layout atom and keep page-specific labels/captions in another slot or Slide-local group.
+**Mandatory — slot authoring**: A reusable content slot is one direct root `<g id>` carrying `data-pptx-placeholder` and positive `data-pptx-placeholder-bounds`; that design zone is also the slot module's boundary, so do not duplicate it with `data-pptx-module-bounds`. A normal slot contains exactly one compatible direct drawable child marked `data-pptx-placeholder-carrier="true"`. Export unwraps that child into the real Slide placeholder binding. Decorations do not belong in the slot; move reusable decoration to a root Layout atom and keep page-specific labels/captions in another bounded slot or Slide-local group.
**Mandatory — slot identity**: Preserve imported `data-pptx-placeholder-idx` values where available; otherwise omit the title index and assign unique indices only where repeated roles need disambiguation. Pages sharing one Layout key repeat the same slot ids/types/effective indices/default bounds/binding modes. Current text, crop, and Slide-local carrier geometry may differ.
@@ -106,7 +106,7 @@ This section applies only when a deck/layout template's AI-derived lock records
**Layout identity**: Different keys differ in fixed Layout atoms or slot topology/default bounds/binding modes. Identical contracts should share one key. Current wording, imagery, crop, and Slide-local geometry never define identity.
-**Template adherence**: Strict copies the prototype Master/Layout/slot contract exactly. Adaptive keeps the prototype Master and may change reusable Layout atoms or slots only under a new explicit Layout key/name. When the completed composition genuinely needs that change, update `spec_lock.md pptx_layouts` immediately while authoring the first affected page; later pages may reuse the new key only by repeating its exact contract. Changing only a label is not a new Layout.
+**Template adherence**: Strict preserves reusable Master/Layout atoms and slot ids/types/indices/default bounds/bindings. Under `layout`, the application plan may still change current text/tspans, line height, crop, and carrier-local geometry inside those bounds; `mirror` remains topology-frozen. Adaptive keeps the prototype Master and changes reusable atoms or slots only under a new explicit Layout key/name, written to `spec_lock.md pptx_layouts` while authoring the first affected page. Changing only content is not a new Layout.
**Layout-content boundary**: Mark only genuinely reusable fixed framing as a Master/Layout atom. Concrete titles, body copy, metrics, chart marks, images, and page-specific groups remain inside slot groups or ordinary Slide-local content groups. The exporter never infers or clusters structure.
diff --git a/skills/ppt-master/references/shared-standards-core.md b/skills/ppt-master/references/shared-standards-core.md
index 4f4aa86e..0d57f353 100644
--- a/skills/ppt-master/references/shared-standards-core.md
+++ b/skills/ppt-master/references/shared-standards-core.md
@@ -301,6 +301,7 @@ one. This array is still diagnostic metadata, not an authoring surface.
| 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-module-bounds` in generated SVG | At most two decimals. |
| `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. |
@@ -581,9 +582,9 @@ These forms are needed only when the stated PPT behavior matters:
### 4.3 Element Grouping (Mandatory)
-Wrap logically related Slide-local elements in top-level `<g id="...">` groups. This is **required on every generated page**, not an optional convenience: it produces real PowerPoint groups in the exported PPTX and gives each content unit a stable animation anchor. Plain `<g>` is the grouping primitive; keep alpha on individual descendants per §2.2. Flat free-design/brand-only pages use only ordinary semantic groups. On structured template pages, direct atomic Master/Layout elements are the required exception and a top-level slot `<g>` is already a semantic group. Nested implementation groups inside one named content unit may remain anonymous unless another specialized contract requires an id; they are not independent animation targets.
+**Hard rule — every visible `<g>` is a bounded module**: Declare exactly one positive local-coordinate `x y width height` boundary. Ordinary groups use `data-pptx-module-bounds`; slots use `data-pptx-placeholder-bounds`; imported/native and preset groups use `data-pptx-frame`; native chart/table groups may use complete explicit metadata bounds. Never duplicate sources. Keep nested modules inside their nearest parent and text inside its nearest module. Missing bounds and estimable overflow warn; fix `<tspan>` lines or module geometry because export never auto-wraps/resizes SVG text.
-**Semantic-group rule**: direct Slide content uses semantic groups. Aim for **3–8 ordinary top-level content `<g id>` groups per slide**; on structured template pages, slot groups and atomic Master/Layout objects are excluded. Each ordinary group becomes one entrance step under the chosen animation trigger. Leaving Slide-local titles, body lines, list items, cards, or decorative clusters as ungrouped top-level atoms is an authoring-contract violation reported as an aggregate Checker warning.
+Wrap each logical Slide-local unit in a descriptive top-level `<g id>`; aim for **3–8 ordinary groups**, each becoming one animation step. Nested implementation groups may be anonymous but remain bounded. Flat pages use ordinary groups; structured slots already qualify, while direct atomic Master/Layout elements are the exception. Ungrouped Slide-local content produces an aggregate Checker warning.
**Structural atoms and slots are excluded automatically.** `data-pptx-layer` and `data-pptx-placeholder` semantics are read first; otherwise explicit `data-pptx-role` values (`background`, `decoration`, `header`, `footer`, `chrome`, `watermark`, `page-number`, `logo`) mark Slide-local static framing (§4.1, [`semantic-svg.md`](semantic-svg.md)). A normal slot group has exactly one direct compatible carrier; several drawing atoms require the explicit composite `object` proxy fallback. Native chart/table carrier groups retain their specialized [`native-data-interface.md`](./native-data-interface.md) contract.
@@ -614,7 +615,7 @@ separate parent content group; never put them inside the preset group itself.
**Naming — required.** A descriptive, page-unique `id` on every top-level content `<g>` (`card-1`, `step-discover`, `header`, `footer`) is mandatory; it is the stable SVG-side animation and trace anchor. An anonymous top-level group still converts, but `animations.json` cannot reference it; an anonymous one-child implementation wrapper may also flatten. Primitive fallback is unrelated and applies only to roots with no top-level groups.
```xml
-<g id="card-benefits-1">
+<g id="card-benefits-1" data-pptx-module-bounds="60 115 565 260">
<!-- Shadow only if the card floats over a colored panel; on flat white, omit it. -->
<rect x="60" y="115" width="565" height="260" rx="20" fill="#FFFFFF" filter="url(#shadow)"/>
<use data-icon="chunk-filled/bolt" x="108" y="163" width="44" height="44" fill="#0071E3"/>
diff --git a/skills/ppt-master/scripts/compact_svg_coordinates.py b/skills/ppt-master/scripts/compact_svg_coordinates.py
index 858ccfed..6ab0d705 100644
--- a/skills/ppt-master/scripts/compact_svg_coordinates.py
+++ b/skills/ppt-master/scripts/compact_svg_coordinates.py
@@ -40,7 +40,8 @@ _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<name>data-pptx-frame|data-pptx-module-bounds|"
+ r"data-pptx-placeholder-bounds|transform)"
r"(?P<spacing>\s*=\s*)"
r"(?P<quote>[\"'])"
r"(?P<value>.*?)"
@@ -54,21 +55,29 @@ class CoordinateCompactionStats:
"""Count safely compacted coordinate-bearing SVG attributes."""
native_frames: int = 0
+ module_bounds: int = 0
placeholder_bounds: int = 0
transforms: int = 0
@property
def changed_attributes(self) -> int:
- return self.native_frames + self.placeholder_bounds + self.transforms
+ return (
+ self.native_frames
+ + self.module_bounds
+ + self.placeholder_bounds
+ + self.transforms
+ )
def merge(self, other: "CoordinateCompactionStats") -> None:
self.native_frames += other.native_frames
+ self.module_bounds += other.module_bounds
self.placeholder_bounds += other.placeholder_bounds
self.transforms += other.transforms
def as_dict(self) -> dict[str, int]:
return {
"native_frames": self.native_frames,
+ "module_bounds": self.module_bounds,
"placeholder_bounds": self.placeholder_bounds,
"transforms": self.transforms,
"changed_attributes": self.changed_attributes,
@@ -141,7 +150,10 @@ def _compact_attribute_value(
) -> str:
if name == "data-pptx-frame":
return _compact_coordinate_quad(value) if compact_native_frames else value
- if name == "data-pptx-placeholder-bounds":
+ if name in {
+ "data-pptx-module-bounds",
+ "data-pptx-placeholder-bounds",
+ }:
return _compact_coordinate_quad(value)
if name == "transform":
return _compact_transform(value)
@@ -151,6 +163,8 @@ def _compact_attribute_value(
def _record_change(stats: CoordinateCompactionStats, name: str) -> None:
if name == "data-pptx-frame":
stats.native_frames += 1
+ elif name == "data-pptx-module-bounds":
+ stats.module_bounds += 1
elif name == "data-pptx-placeholder-bounds":
stats.placeholder_bounds += 1
elif name == "transform":
@@ -167,6 +181,7 @@ def compact_svg_tree(
for element in root.iter():
for name in (
"data-pptx-frame",
+ "data-pptx-module-bounds",
"data-pptx-placeholder-bounds",
"transform",
):
@@ -256,8 +271,8 @@ def build_parser() -> argparse.ArgumentParser:
"--keep-native-frames",
action="store_true",
help=(
- "Leave data-pptx-frame unchanged while compacting slot bounds and "
- "transform translations"
+ "Leave data-pptx-frame unchanged while compacting module/slot "
+ "bounds and transform translations"
),
)
return parser
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 707dc007..fc3ce061 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -80,8 +80,9 @@ python3 scripts/compact_svg_coordinates.py <template-directory> \
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
+`--keep-native-frames`: it compacts `data-pptx-module-bounds`,
+`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.
@@ -331,6 +332,7 @@ Behavior:
- Native mode is strict about unsupported visual SVG elements: if a visual element cannot be represented or safely preserved, export fails with the SVG file, element tag, and position instead of silently dropping content.
- Omitting `--pptx-structure` reads `spec_lock.md`. Free-design, brand-only, and `template_reuse_scope: style` releases declare `mode: flat`, omit Master/Layout mappings and SVG structure metadata, and materialize one clean project-owned Master plus one Blank Layout from the current lock. Deck/layout templates use `mode: structured` only for `template_reuse_scope: mirror|layout`, with complete unique `pptx_masters` / `pptx_layouts` rosters and one `page_pptx_layouts` assignment per page. A template-backed Layout definition may remain unused by pages and still register in the final package.
- On structured template routes, every page root repeats Master/Layout keys and picker names. Master/Layout fixed visuals are direct semantic atoms. Ordinary layer `<g>` elements are invalid; one validated compact authored-preset `<g>` emitted by `preset_shape_svg.py` is the sole group exception because it compiles to one native shape.
+- Every visible authored `<g>` is a module with one explicit boundary. Ordinary groups use `data-pptx-module-bounds`; placeholder/native groups reuse their specialized boundary. The checker aggregates missing boundaries, warns when a module exceeds its parent/canvas, and warns when estimable text exceeds its nearest module. It never auto-wraps or resizes text.
- On structured template routes, each normal slot is a direct root `<g id>` with semantic type, positive design-zone bounds, and exactly one compatible carrier. Composite `object` slots use explicit proxy binding; zero-slot Layouts are valid. Flat pages keep all SVG objects Slide-local.
- Flat export maps locked typography/colors into a clean project-owned theme/Master, removes stock content placeholders and unused built-in Layouts, retains only the standard date/footer/slide-number capability hooks, and keeps one Blank Layout without promoting Slide content. Structured export additionally creates one reusable Layout per declared key and reopens the package to verify the full Presentation → Master → Layout → Slide graph, fixed-object order, placeholder identities/bounds, carrier bindings, hidden proxies, and zero-slot Layouts.
- Template `page_layouts` remains input provenance. Strict preserves the prototype contract; adaptive retains its Master and may use a new Layout identity only when fixed Layout atoms or slot topology/bounds change.
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index be958e14..132ff7ff 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -443,6 +443,8 @@ _NON_VISUAL_SVG_TAGS = frozenset({
'style',
'title',
})
+_MODULE_BOUNDS_ATTR = 'data-pptx-module-bounds'
+_NATIVE_OBJECT_BOUNDS_LABEL = 'native chart/table bounds'
_PPTX_ROOT_STRUCTURE_ATTRS = (
'data-pptx-master',
'data-pptx-master-name',
@@ -607,19 +609,30 @@ def _generated_theme_contract_errors(project_path: Path) -> List[str]:
]
-def _placeholder_bounds_error(value: str) -> str | None:
- """Return a concise error for invalid design-zone bounds."""
+def _parse_positive_bounds(
+ value: str,
+) -> Tuple[float, float, float, float]:
+ """Parse one positive x/y/width/height boundary."""
raw_values = [item for item in re.split(r"[\s,]+", value.strip()) if item]
if len(raw_values) != 4:
- return "must contain exactly four numbers: x y width height"
+ raise ValueError("must contain exactly four numbers: x y width height")
try:
values = tuple(float(item) for item in raw_values)
- except ValueError:
- return "must contain only numeric values"
+ except ValueError as exc:
+ raise ValueError("must contain only numeric values") from exc
if not all(math.isfinite(item) for item in values):
- return "must contain only finite values"
+ raise ValueError("must contain only finite values")
if values[2] <= 0 or values[3] <= 0:
- return "must use positive width and height"
+ raise ValueError("must use positive width and height")
+ return values
+
+
+def _placeholder_bounds_error(value: str) -> str | None:
+ """Return a concise error for invalid design-zone bounds."""
+ try:
+ _parse_positive_bounds(value)
+ except ValueError as exc:
+ return str(exc)
return None
@@ -2492,8 +2505,10 @@ class SVGQualityChecker:
result['info']['text_elements'] = text_count
result['info']['tspan_elements'] = tspan_count
+ self._check_module_bounds_contract(root, result)
self._check_text_output_geometry(root, result)
self._check_single_line_text_bounds(root, result)
+ self._check_module_text_bounds(root, result)
self._check_unmergeable_leading_text(root, result)
@classmethod
@@ -2868,6 +2883,19 @@ class SVGQualityChecker:
for current in chain
):
continue
+ if any(
+ _local_name(current) == 'g'
+ and (
+ any(current.get(attr) is not None for attr in (
+ _MODULE_BOUNDS_ATTR,
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-frame',
+ ))
+ or self._explicit_native_object_bounds(current) is not None
+ )
+ for current in chain
+ ):
+ continue
if text_el.get('data-paragraph-line-height') is not None:
continue
if self._has_ancestor_id(text_el, parent_by_id, unchanged_groups):
@@ -2989,6 +3017,542 @@ class SVGQualityChecker:
'positioned <tspan> lines'
)
+ @classmethod
+ def _positioned_text_lines(
+ cls,
+ text_el: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ ) -> List[Tuple[ET.Element, float, float, List[Dict], float]] | None:
+ """Resolve direct positioned tspans into estimable visual lines."""
+ if _parse_project_geometry_length is None:
+ return None
+ children = list(text_el)
+ if not children or (text_el.text or '').strip():
+ return None
+ if any(
+ not cls._is_tspan(child)
+ or not cls._is_line_tspan(child)
+ or child.get('x') is None
+ or (child.tail or '').strip()
+ for child in children
+ ):
+ return None
+
+ try:
+ current_y = _parse_project_geometry_length(
+ text_el.get('y') or '0',
+ 'y',
+ )
+ except ValueError:
+ return None
+
+ lines: List[Tuple[ET.Element, float, float, List[Dict], float]] = []
+ for child in children:
+ try:
+ line_x = _parse_project_geometry_length(child.get('x'), 'x')
+ line_y = (
+ _parse_project_geometry_length(child.get('y'), 'y')
+ if child.get('y') is not None
+ else current_y
+ )
+ if child.get('dx') is not None:
+ line_x += _parse_project_geometry_length(
+ child.get('dx'),
+ 'dx',
+ )
+ if child.get('dy') is not None:
+ line_y += _parse_project_geometry_length(
+ child.get('dy'),
+ 'dy',
+ )
+ runs = cls._resolved_single_line_text_runs(
+ child,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ except (KeyError, TypeError, ValueError):
+ return None
+ current_y = line_y
+ if not runs:
+ continue
+ try:
+ font_size = max(float(run['font_size']) for run in runs)
+ except (KeyError, TypeError, ValueError):
+ return None
+ lines.append((child, line_x, line_y, runs, font_size))
+ return lines or None
+
+ @classmethod
+ def _estimated_text_line_bounds(
+ cls,
+ line_el: ET.Element,
+ x: float,
+ y: float,
+ runs: List[Dict],
+ font_size: float,
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[float, float, float, float] | None:
+ """Estimate one line's transformed visible bounds in SVG coordinates."""
+ if any(helper is None for helper in (
+ _estimate_single_line_text_frame_width,
+ _IDENTITY_MATRIX,
+ _matrix_multiply,
+ _parse_project_text_anchor,
+ _parse_transform_matrix,
+ _transform_point,
+ )):
+ return None
+ try:
+ width = float(_estimate_single_line_text_frame_width(runs))
+ raw_anchor = (
+ _effective_presentation_value(
+ line_el,
+ 'text-anchor',
+ parent_by_id,
+ )
+ or 'start'
+ ).strip().lower()
+ anchor = _parse_project_text_anchor(raw_anchor).value
+ except (TypeError, ValueError):
+ return None
+ if not all(math.isfinite(value) for value in (x, y, width, font_size)):
+ return None
+ if width <= 0 or font_size <= 0:
+ return None
+
+ if anchor == 'middle':
+ left = x - width / 2
+ right = x + width / 2
+ elif anchor == 'end':
+ left = x - width
+ right = x
+ elif anchor == 'start':
+ left = x
+ right = x + width
+ else:
+ return None
+ top = y - font_size * 0.85
+ bottom = y + font_size * 0.35
+
+ return cls._transformed_rect_bounds(
+ line_el,
+ (left, top, right - left, bottom - top),
+ parent_by_id,
+ )
+
+ @classmethod
+ def _estimated_text_bounds(
+ cls,
+ text_el: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ ) -> Tuple[float, float, float, float] | None:
+ """Estimate one single- or multi-line text carrier's visual bounds."""
+ lines: List[Tuple[ET.Element, float, float, List[Dict], float]] | None
+ try:
+ runs = cls._resolved_single_line_text_runs(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ except (KeyError, TypeError, ValueError):
+ return None
+ if runs:
+ try:
+ lines = [(
+ text_el,
+ _parse_project_geometry_length(text_el.get('x') or '0', 'x'),
+ _parse_project_geometry_length(text_el.get('y') or '0', 'y'),
+ runs,
+ max(float(run['font_size']) for run in runs),
+ )]
+ except (KeyError, TypeError, ValueError):
+ return None
+ else:
+ lines = cls._positioned_text_lines(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ if not lines:
+ return None
+
+ bounds = [
+ cls._estimated_text_line_bounds(
+ line_el,
+ x,
+ y,
+ line_runs,
+ font_size,
+ parent_by_id,
+ )
+ for line_el, x, y, line_runs, font_size in lines
+ ]
+ resolved = [item for item in bounds if item is not None]
+ if not resolved:
+ return None
+ return (
+ min(item[0] for item in resolved),
+ min(item[1] for item in resolved),
+ max(item[2] for item in resolved),
+ max(item[3] for item in resolved),
+ )
+
+ @staticmethod
+ def _transformed_rect_bounds(
+ element: ET.Element,
+ bounds: Tuple[float, float, float, float],
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[float, float, float, float] | None:
+ """Transform one local rectangle into root SVG coordinates."""
+ if any(helper is None for helper in (
+ _IDENTITY_MATRIX,
+ _matrix_multiply,
+ _parse_transform_matrix,
+ _transform_point,
+ )):
+ return None
+ x, y, width, height = bounds
+ chain: List[ET.Element] = []
+ current: ET.Element | None = element
+ while current is not None:
+ chain.append(current)
+ current = parent_by_id.get(id(current))
+ matrix = _IDENTITY_MATRIX
+ try:
+ for current in reversed(chain):
+ raw_transform = current.get('transform')
+ if raw_transform:
+ matrix = _matrix_multiply(
+ matrix,
+ _parse_transform_matrix(raw_transform),
+ )
+ corners = [
+ _transform_point(matrix, corner_x, corner_y)
+ for corner_x, corner_y in (
+ (x, y),
+ (x + width, y),
+ (x + width, y + height),
+ (x, y + height),
+ )
+ ]
+ except (TypeError, ValueError):
+ return None
+ xs = [point[0] for point in corners]
+ ys = [point[1] for point in corners]
+ return min(xs), min(ys), max(xs), max(ys)
+
+ @classmethod
+ def _resolved_group_bounds(
+ cls,
+ group: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[str, Tuple[float, float, float, float]] | None:
+ """Return one group's nearest explicit boundary in root coordinates."""
+ for attribute in (
+ _MODULE_BOUNDS_ATTR,
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-frame',
+ ):
+ raw = group.get(attribute)
+ if raw is None:
+ continue
+ try:
+ local_bounds = _parse_positive_bounds(raw)
+ except ValueError:
+ return None
+ transformed = cls._transformed_rect_bounds(
+ group,
+ local_bounds,
+ parent_by_id,
+ )
+ if transformed is None:
+ return None
+ return attribute, transformed
+ native_bounds = cls._explicit_native_object_bounds(group)
+ if native_bounds is not None:
+ return _NATIVE_OBJECT_BOUNDS_LABEL, native_bounds
+ return None
+
+ @staticmethod
+ def _explicit_native_object_bounds(
+ group: ET.Element,
+ ) -> Tuple[float, float, float, float] | None:
+ """Return complete explicit native chart/table bounds in root space."""
+ if group.get('data-pptx-replace-with') not in {'chart', 'table'}:
+ return None
+ payload: Dict = {}
+ raw_payload = group.get('data-pptx-json')
+ if raw_payload:
+ try:
+ loaded = json.loads(raw_payload)
+ except json.JSONDecodeError:
+ loaded = None
+ if isinstance(loaded, dict):
+ payload = loaded
+ else:
+ for child in group:
+ if (
+ _local_name(child) != 'metadata'
+ or child.get('type') != 'application/json'
+ ):
+ continue
+ try:
+ loaded = json.loads(''.join(child.itertext()))
+ except json.JSONDecodeError:
+ loaded = None
+ if isinstance(loaded, dict):
+ payload = loaded
+ break
+
+ raw_values = (
+ payload.get('x', group.get('data-pptx-x')),
+ payload.get('y', group.get('data-pptx-y')),
+ payload.get('width', group.get('data-pptx-width')),
+ payload.get('height', group.get('data-pptx-height')),
+ )
+ if any(value is None for value in raw_values):
+ return None
+ try:
+ x, y, width, height = (float(value) for value in raw_values)
+ except (TypeError, ValueError):
+ return None
+ if (
+ not all(math.isfinite(value) for value in (x, y, width, height))
+ or width <= 0
+ or height <= 0
+ ):
+ return None
+ return x, y, x + width, y + height
+
+ @classmethod
+ def _nearest_group_bounds(
+ cls,
+ element: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[ET.Element, str, Tuple[float, float, float, float]] | None:
+ """Resolve the nearest ancestor module with an explicit boundary."""
+ current = parent_by_id.get(id(element))
+ while current is not None:
+ if _local_name(current) == 'g':
+ resolved = cls._resolved_group_bounds(current, parent_by_id)
+ if resolved is not None:
+ attribute, bounds = resolved
+ return current, attribute, bounds
+ current = parent_by_id.get(id(current))
+ return None
+
+ @staticmethod
+ def _bounds_overflow_axes(
+ inner: Tuple[float, float, float, float],
+ outer: Tuple[float, float, float, float],
+ *,
+ tolerance: float = 1.0,
+ ) -> str | None:
+ """Return the axes on which one root-coordinate box exceeds another."""
+ left, top, right, bottom = inner
+ outer_left, outer_top, outer_right, outer_bottom = outer
+ horizontal = (
+ left < outer_left - tolerance
+ or right > outer_right + tolerance
+ )
+ vertical = (
+ top < outer_top - tolerance
+ or bottom > outer_bottom + tolerance
+ )
+ if horizontal and vertical:
+ return 'horizontal and vertical'
+ if horizontal:
+ return 'horizontal'
+ if vertical:
+ return 'vertical'
+ return None
+
+ def _check_module_bounds_contract(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Validate explicit boundaries on visible authored SVG groups."""
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ viewbox = _parse_viewbox_values(root.get('viewBox') or '')
+ canvas = None
+ if viewbox is not None:
+ x, y, width, height = viewbox
+ canvas = (x, y, x + width, y + height)
+
+ for element in root.iter():
+ if (
+ element.get(_MODULE_BOUNDS_ATTR) is not None
+ and _local_name(element) != 'g'
+ ):
+ result['errors'].append(
+ f'{_element_label(element)} {_MODULE_BOUNDS_ATTR} is valid '
+ 'only on a visible <g> module'
+ )
+
+ missing: List[str] = []
+ for group in root.iter(f'{{{SVG_NS}}}g'):
+ chain: List[ET.Element] = []
+ current: ET.Element | None = group
+ while current is not None:
+ chain.append(current)
+ current = parent_by_id.get(id(current))
+ if any(
+ _local_name(current) in _NON_VISUAL_SVG_TAGS
+ for current in chain
+ ):
+ continue
+
+ raw_module_bounds = group.get(_MODULE_BOUNDS_ATTR)
+ if raw_module_bounds is not None:
+ try:
+ _parse_positive_bounds(raw_module_bounds)
+ except ValueError as exc:
+ result['errors'].append(
+ f'{_element_label(group)} {_MODULE_BOUNDS_ATTR} {exc}'
+ )
+
+ explicit_attributes = [
+ attribute
+ for attribute in (
+ _MODULE_BOUNDS_ATTR,
+ 'data-pptx-placeholder-bounds',
+ 'data-pptx-frame',
+ )
+ if group.get(attribute) is not None
+ ]
+ native_bounds = self._explicit_native_object_bounds(group)
+ boundary_sources = [*explicit_attributes]
+ if native_bounds is not None:
+ boundary_sources.append(_NATIVE_OBJECT_BOUNDS_LABEL)
+ if not boundary_sources:
+ missing.append(_element_label(group))
+ continue
+ if len(boundary_sources) > 1:
+ result['errors'].append(
+ f'{_element_label(group)} declares multiple module '
+ f'boundaries ({", ".join(boundary_sources)}); keep the '
+ 'specialized placeholder/native boundary or one ordinary '
+ f'{_MODULE_BOUNDS_ATTR}, not both'
+ )
+ continue
+
+ resolved = self._resolved_group_bounds(group, parent_by_id)
+ if resolved is None:
+ continue
+ attribute, bounds = resolved
+ if attribute != _MODULE_BOUNDS_ATTR:
+ continue
+ parent_bounds = self._nearest_group_bounds(group, parent_by_id)
+ if parent_bounds is None:
+ if canvas is None:
+ continue
+ outer_label = 'canvas viewBox'
+ outer = canvas
+ else:
+ parent_group, parent_attribute, outer = parent_bounds
+ outer_label = (
+ f'{_element_label(parent_group)} {parent_attribute}'
+ )
+ axes = self._bounds_overflow_axes(bounds, outer)
+ if axes is None:
+ continue
+ left, top, right, bottom = bounds
+ outer_left, outer_top, outer_right, outer_bottom = outer
+ result['warnings'].append(
+ f'{_element_label(group)} {_MODULE_BOUNDS_ATTR} exceeds '
+ f'{outer_label} on the {axes} axis: module '
+ f'({left:.1f}, {top:.1f})-({right:.1f}, {bottom:.1f}), '
+ f'container ({outer_left:.1f}, {outer_top:.1f})-'
+ f'({outer_right:.1f}, {outer_bottom:.1f})'
+ )
+
+ if missing and not self.template_mode:
+ sample = '; '.join(missing[:3])
+ suffix = '' if len(missing) <= 3 else f'; +{len(missing) - 3} more'
+ result['warnings'].append(
+ f'Detected {len(missing)} visible <g> module(s) without an '
+ f'explicit boundary ({sample}{suffix}); generated ordinary '
+ f'groups add {_MODULE_BOUNDS_ATTR}="x y width height", while '
+ 'placeholder/native groups reuse their existing specialized '
+ 'boundary'
+ )
+
+ def _check_module_text_bounds(
+ self,
+ root: ET.Element,
+ result: Dict,
+ ) -> None:
+ """Warn when estimable text exceeds its nearest module boundary."""
+ helpers = (
+ _estimate_single_line_text_frame_width,
+ _parse_project_font_weight,
+ _parse_project_geometry_length,
+ _parse_project_text_anchor,
+ _resolve_project_font_sizes,
+ _resolve_project_letter_spacings,
+ )
+ if any(helper is None for helper in helpers):
+ return
+ try:
+ font_sizes = _resolve_project_font_sizes(root)
+ letter_spacings = _resolve_project_letter_spacings(root, font_sizes)
+ except ValueError:
+ return
+
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ unchanged_groups = self._unchanged_txbody_group_ids(root)
+ for text_el in root.iter(f'{{{SVG_NS}}}text'):
+ if self._has_ancestor_id(text_el, parent_by_id, unchanged_groups):
+ continue
+ visible_text = ''.join(text_el.itertext())
+ if not visible_text.strip() or ('{{' in visible_text and '}}' in visible_text):
+ continue
+
+ resolved_group = self._nearest_group_bounds(text_el, parent_by_id)
+ if resolved_group is None:
+ continue
+ group, boundary_attribute, boundary = resolved_group
+
+ estimated = self._estimated_text_bounds(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ if estimated is None:
+ continue
+ left, top, right, bottom = estimated
+ axes = self._bounds_overflow_axes(estimated, boundary)
+ if axes is None:
+ continue
+
+ bound_left, bound_top, bound_right, bound_bottom = boundary
+ result['warnings'].append(
+ f'{_element_label(text_el)} exceeds '
+ f'{_element_label(group)} {boundary_attribute} on the '
+ f'{axes} axis: estimated ({left:.1f}, {top:.1f})-'
+ f'({right:.1f}, {bottom:.1f}), module ({bound_left:.1f}, '
+ f'{bound_top:.1f})-({bound_right:.1f}, {bound_bottom:.1f}); '
+ 'reflow with positioned <tspan> lines or revise the module '
+ 'layout within the applicable design/template contract'
+ )
+
def _check_unmergeable_leading_text(self, root: ET.Element, result: Dict) -> None:
"""Warn when leading text cannot be normalized for paragraph merging."""
risky = []