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

fix(checker): close text-bounds blind spots and fail overlapping root modules

hugohe3fb538778633a
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index c3ae96db..fb141989 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -156,7 +156,7 @@ Before drawing each page, look up its entry in `page_rhythm` (key format `P<NN>`
## 3. Execution Guidelines
-- **Element grouping (Mandatory)**: wrap each logical Slide-local body unit in a descriptive, page-unique top-level `<g id>`. Every visible direct root `<g>` except a compact helper-authored preset atom declares root-coordinate `data-pptx-bounds="x y width height"`; that text-free atom stays top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native coordinates do not replace bounds on any other group, and placeholder bounds also supply the slot frame. Nested groups need no bounds and any such values are ignored. Checker compares root bounds with the `viewBox`, recursively checks estimable text against its root module with DrawingML wrapping headroom, and independently checks every estimable visible text carrier against the page without that headroom: through `1px` is ignored; module overflow warns through `5%` and fails above it, while larger page overflow always fails. Unestimable visible text receives an advisory warning. Only a wholly off-canvas direct-root Morph endpoint may set `data-pptx-morph-staging="true"`; keep its text inside its own module bounds, use an explicit pair when Morph remains enabled, and never use the marker for partial overflow. Images, shapes, paths, `<use>`, effects, and object frames remain geometrically free. Flat pages use ordinary groups; structured slots already qualify, while titles, direct Master/Layout atoms, and canvas-level static framing may remain root primitives. On flat pages, give a root background image or full-canvas scrim/decoration rectangle a stable `id` plus `data-pptx-role="background"` / `"decoration"`; never wrap it only to silence the advisory.
+- **Element grouping (Mandatory)**: wrap each logical Slide-local body unit in a descriptive, page-unique top-level `<g id>`. Every visible direct root `<g>` except a compact helper-authored preset atom declares root-coordinate `data-pptx-bounds="x y width height"`; that text-free atom stays top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native coordinates do not replace bounds on any other group, and placeholder bounds also supply the slot frame. Nested groups need no bounds and any such values are ignored. Checker fails ordinary root-group overlap exceeding `1px` on both axes; structured slots, structural-role groups, and off-canvas Morph staging groups are exempt, but structured Slide-local groups are not. Checker compares root bounds with the `viewBox`, recursively checks estimable text—including both shared multiline forms—against its root module with DrawingML wrapping headroom, and independently checks every estimable visible text carrier against the page without that headroom: through `1px` is ignored; module overflow warns through `5%` and fails above it, while larger page overflow always fails. Unestimable visible text receives an advisory warning. Only a wholly off-canvas direct-root Morph endpoint may set `data-pptx-morph-staging="true"`; keep its text inside its own module bounds, use an explicit pair when Morph remains enabled, and never use the marker for partial overflow. Images, shapes, paths, `<use>`, effects, and object frames remain geometrically free. Flat pages use ordinary groups; structured slots already qualify, while titles, direct Master/Layout atoms, and canvas-level static framing may remain root primitives. On flat pages, give a root background image or full-canvas scrim/decoration rectangle a stable `id` plus `data-pptx-role="background"` / `"decoration"`; never wrap it only to silence the advisory.
- **Reference — not a constraint**: top-level groups set semantic and automatic-animation granularity, but they may contain descriptive nested `<g>` edit groups when the page has meaningful internal subunits. Nested groups need no bounds and create no automatic animation step; use or omit them from the page's actual editing semantics, with no default pattern, depth, or quota.
- **Default — size `data-pptx-bounds` as the intended module zone, not a glyph box (may skip when no text is estimable)**: make the zone as generous as the canvas and sibling layout allow, without overlapping another module zone. An untransformed line spans `y - 0.85 × font_size` to `y + 0.35 × font_size`; width uses the shared SVG-to-PPTX per-run estimate and safety headroom. If text does not fit, first expand a zone that has unused non-overlapping space; otherwise reflow or adapt. Larger bounds do not repair off-canvas text.
- **Spec adherence**: follow binding color, canvas, typography, identity, resource, and template anchors; apply layout and other Reference directions under §2.1 without turning them into locks
diff --git a/skills/ppt-master/references/shared-standards-core.md b/skills/ppt-master/references/shared-standards-core.md
index 2c4bee85..22ed7edc 100644
--- a/skills/ppt-master/references/shared-standards-core.md
+++ b/skills/ppt-master/references/shared-standards-core.md
@@ -645,7 +645,7 @@ These forms are needed only when the stated PPT behavior matters:
| Desired behavior | Required form |
|---|---|
-| One editable PPT text frame with mixed formatting or multiline prose | Use one `<text>` per logical paragraph and non-positional `<tspan>` children for inline runs. Keep the first authored line as direct text; later lines use direct positioned `<tspan>` children that repeat parent `x` with positive relative `dy`; an all-`<tspan>` form may start at `dy="0"`. Default retains these breaks without PowerPoint wrapping; `--reflow-text` may join eligible lines. A font-size change, list marker, or larger accepted gap starts another paragraph. Sibling `<text>` elements are forbidden as one paragraph's line breaks; they remain valid for independent frames. |
+| One editable PPT text frame with mixed formatting or multiline prose | Use one `<text>` per logical paragraph and non-positional `<tspan>` children for inline runs. Keep the first line as direct text; later lines use direct positioned `<tspan>` children that repeat parent `x` with positive relative `dy`; an all-`<tspan>` form may start at `dy="0"`. Default retains these breaks without PowerPoint wrapping; `--reflow-text` may join eligible lines. A font-size change, list marker, or larger accepted gap starts another paragraph. Sibling `<text>` elements are forbidden as one paragraph's line breaks; they remain valid for independent frames. |
| Stable object grouping or object-level animation anchor | Wrap the intended object in `<g id="...">`. Content grouping is **mandatory** per §4.3 — a top-level `<g id>` is also the animation anchor; it is not an optional convenience. |
| Native PowerPoint background promotion | Outside structured mode, the first eligible visual layer may be a direct full-canvas `<rect>` or one inside a simple single-child group. Its fill must have a registered native mapping (solid, linear/radial gradient, or preset pattern), and it must have no transform, filter, clip, rounding, or visible stroke. Export writes the fill as Slide `p:bg`; image elements remain pictures. Structured routes use the narrower explicit solid-background ownership contract in [`pptx-structure-interface.md`](./pptx-structure-interface.md). |
| Free-design / brand-only PowerPoint structure | Use `pptx_structure.mode: flat`. Keep represented objects Slide-local; export emits one clean Master plus Blank Layout, removes stock content placeholders/Layout inventory, and retains the standard date/footer/slide-number hooks. Do not author Master/Layout identities, layers, or slots. Without a Layout/Deck owner, Quick uses the same ownership with converter-default theme scaffolding. |
@@ -657,7 +657,7 @@ These forms are needed only when the stated PPT behavior matters:
### 4.3 Element Grouping (Mandatory)
-**Hard rule — root groups protect body-text layout**: Every visible direct root `<g>` except a compact helper-authored preset atom declares positive root-coordinate `data-pptx-bounds="x y width height"`. That text-free atom stays top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native coordinates do not replace bounds on any other group; placeholder bounds also supply the slot frame. On flat pages, make each module zone as generous as the canvas and sibling layout allow without overlapping another module zone. Checker validates this subcanvas against the root `viewBox`, then recursively validates only estimable `<text>` descendants against it using the shared SVG-to-PPTX per-run width estimate, inline-formula native-height envelope, and DrawingML wrapping headroom. It validates every estimable visible text carrier directly against the root `viewBox` with the same per-run estimate before that headroom. Nested groups and all shapes, images, paths, `<use>` instances, effects, and object frames are not module-boundary inputs. Per side, Checker ignores overflow through `1px`; module-boundary overflow warns through `5%` and fails above `5%`, while any larger root-`viewBox` text overflow fails. Bounds do not clip or reflow; unestimable visible text receives an advisory warning. The only page-boundary exception is a wholly off-canvas direct-root Morph endpoint marked `data-pptx-morph-staging="true"`; its own module bounds still apply, retained Morph uses an explicit pair, and the marker never excuses partial page overflow.
+**Hard rule — root groups protect body-text layout**: Every visible direct root `<g>` except a compact helper-authored preset atom declares positive root-coordinate `data-pptx-bounds="x y width height"`. That text-free atom stays top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native coordinates do not replace bounds on any other group; placeholder bounds also supply the slot frame. On flat pages, maximize ordinary zones within canvas/sibling space without overlap; Checker fails overlap exceeding `1px` on both axes. Structured slots, structural-role groups, and off-canvas Morph staging groups are exempt; structured Slide-local groups are not. Checker compares each subcanvas with the root `viewBox`, and estimable descendant text—including both §4.2 multiline forms—with the subcanvas using the shared per-run width estimate, inline-formula height envelope, and DrawingML wrapping headroom. It separately compares estimable visible text with the root `viewBox` before that headroom. Nested groups and all shapes, images, paths, `<use>` instances, effects, and object frames are not module-boundary inputs. Per side, Checker ignores overflow through `1px`; module-boundary overflow warns through `5%` and fails above `5%`, while any larger root-`viewBox` text overflow fails. Bounds do not clip or reflow; unestimable visible text receives an advisory warning. The only page-boundary exception is a wholly off-canvas direct-root Morph endpoint marked `data-pptx-morph-staging="true"`; its own module bounds still apply, retained Morph uses an explicit pair, and the marker never excuses partial page overflow.
Wrap each logical Slide-local body unit in one descriptive top-level `<g id>`; group count follows the page's semantic units, and each group becomes one stable animation target when animation is enabled. Generic deck-wide animation gives that target one step; an explicit animation sidecar may assign it several ordered effects. Nested implementation groups may remain anonymous and need no bounds; any nested bounds are ignored. Flat pages use ordinary groups; structured slots already qualify, while titles, direct atomic Master/Layout elements, and canvas-level static framing—including background images and full-canvas scrim/decoration rectangles—may remain root primitives. On flat pages, give such static framing a stable `id` plus `data-pptx-role="background"` / `"decoration"`; never add a `<g>` solely to silence an ungrouped-element advisory.
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 193f7681..48e6a2ec 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -837,7 +837,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. Dangerous compatibility export first applies the registry in `svg_compatibility.py`; it currently lowers a filter on an otherwise attribute-free one-child group whose child is a supported native filter target. The complete strict preflight then runs normally; every remaining contract, resource, conversion, relationship, or package error still blocks export.
- Default export 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 direct root `<g>` except a compact helper-authored preset atom requires root-coordinate `data-pptx-bounds`; nested bounds are ignored. The text-free preset atom remains top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native metadata never replaces bounds on any other group; placeholder bounds also define the slot frame. Checker compares root bounds with `viewBox`, descendant text with its module using DrawingML wrapping headroom, and every estimable visible text carrier directly with the root `viewBox` before that headroom. Images, shapes, paths, `<use>`, effects, and object frames are excluded from module containment. Per side, ≤`1px` is ignored; module overflow ≤`5%` warns and >`5%` fails, while larger page text overflow always fails. Bounds never clip/reflow; unestimable visible text warns. A wholly off-canvas direct-root Morph endpoint may opt out of page containment with `data-pptx-morph-staging="true"`; it still needs valid module bounds, retained Morph uses an explicit pair, and partial overflow remains blocking.
+- Every visible direct root `<g>` except a compact helper-authored preset atom requires root-coordinate `data-pptx-bounds`; nested bounds are ignored. The text-free preset atom remains top-level when standalone, uses `data-pptx-frame`, and never carries bounds. Frame/native metadata never replaces bounds on any other group; placeholder bounds also define the slot frame. Checker fails ordinary direct-root module pairs whose intersection exceeds `1px` on both axes; complete structured slots, registered structural-role groups, and wholly off-canvas Morph staging groups are excluded, while ordinary Slide-local groups remain checked on structured pages. Checker compares root bounds with `viewBox`, estimable descendant text—including the canonical direct first line plus later positioned tspan form—with its module using DrawingML wrapping headroom, and every estimable visible text carrier directly with the root `viewBox` before that headroom. Images, shapes, paths, `<use>`, effects, and object frames are excluded from module containment. Per side, ≤`1px` is ignored; module overflow ≤`5%` warns and >`5%` fails, while larger page text overflow always fails. Bounds never clip/reflow; unestimable visible text warns. A wholly off-canvas direct-root Morph endpoint may opt out of page containment with `data-pptx-morph-staging="true"`; it still needs valid module bounds, retained Morph uses an explicit pair, and partial overflow remains blocking.
- Missing required root bounds fails on final pages/templates and under `--template-mode`; references warn until adapted.
- 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.
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 71bcb031..95d87d75 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -278,6 +278,24 @@ def _build_paragraph_child_view(
return view, synthetic_first
+def _is_svg_tag(el: ET.Element, name: str) -> bool:
+ """Return whether one element has the requested SVG namespace tag."""
+ return el.tag == f"{{{SVG_NS}}}{name}"
+
+
+def _is_new_line_tspan(tspan: ET.Element) -> bool:
+ """Return whether one direct tspan starts a positioned visual line."""
+ t_dy_attr = get_attr(tspan, "dy")
+ t_y_attr = get_attr(tspan, "y")
+ t_x_attr = get_attr(tspan, "x")
+ dy_val = parse_first_number(t_dy_attr) if t_dy_attr is not None else None
+ return (
+ t_y_attr is not None
+ or (dy_val is not None and dy_val != 0)
+ or t_x_attr is not None
+ )
+
+
def _get_font_size_px(elem: ET.Element) -> float | None:
"""Read font-size from an attribute or inline style."""
size = parse_first_number(get_attr(elem, "font-size"))
@@ -437,6 +455,19 @@ def _classify_paragraph_block(
return base, extras, break_kinds, line_groups, synthetic_first
+def classify_paragraph_block(
+ text_el: ET.Element,
+ preserve_line_breaks: bool = False,
+) -> tuple[float, list[float], list[str], list[list[ET.Element]], ET.Element | None] | None:
+ """Classify one paragraph block with the shared synthetic-first logic."""
+ return _classify_paragraph_block(
+ text_el,
+ _is_svg_tag,
+ _is_new_line_tspan,
+ preserve_line_breaks,
+ )
+
+
def _emit_mergeable_paragraph(
text_el: ET.Element,
base_dy: float,
@@ -540,30 +571,11 @@ def flatten_text_with_tspans(
parent_map = {c: p for p in root.iter() for c in p}
changed = False
- def is_svg_tag(el: ET.Element, name: str) -> bool:
- return el.tag == f"{{{SVG_NS}}}{name}"
-
- def is_new_line_tspan(tspan: ET.Element) -> bool:
- """Determine whether a tspan represents a new line (has its own y or non-zero dy)."""
- t_dy_attr = get_attr(tspan, "dy")
- t_y_attr = get_attr(tspan, "y")
- t_x_attr = get_attr(tspan, "x")
- dy_val = parse_first_number(t_dy_attr) if t_dy_attr is not None else None
- # Has its own y attribute, or has non-zero dy, or has its own x attribute (indicating a new line)
- if t_y_attr is not None:
- return True
- if dy_val is not None and dy_val != 0:
- return True
- # If tspan has an x attribute and there are preceding sibling tspans, treat it as a new line
- if t_x_attr is not None:
- return True
- return False
-
# Collect candidates first to avoid modifying while iterating
candidates = []
for el in root.iter():
- if is_svg_tag(el, "text"):
- has_tspan_child = any(is_svg_tag(c, "tspan") for c in list(el))
+ if _is_svg_tag(el, "text"):
+ has_tspan_child = any(_is_svg_tag(c, "tspan") for c in list(el))
if has_tspan_child:
candidates.append(el)
@@ -575,9 +587,9 @@ def flatten_text_with_tspans(
# First check whether any tspan needs flattening (dy != 0 or has its own y attribute)
needs_flatten = False
for child in list(text_el):
- if not is_svg_tag(child, "tspan"):
+ if not _is_svg_tag(child, "tspan"):
continue
- if is_new_line_tspan(child):
+ if _is_new_line_tspan(child):
needs_flatten = True
break
@@ -589,11 +601,9 @@ def flatten_text_with_tspans(
# <text>. The downstream converter either preserves visual breaks or
# reflows them. Split mode promotes each positioned line to <text>.
if merge_paragraphs:
- paragraph = _classify_paragraph_block(
+ paragraph = classify_paragraph_block(
text_el,
- is_svg_tag,
- is_new_line_tspan,
- preserve_line_breaks,
+ preserve_line_breaks=preserve_line_breaks,
)
if paragraph is not None:
base_dy, extras, break_kinds, line_groups, synthetic_first = paragraph
@@ -619,13 +629,13 @@ def flatten_text_with_tspans(
current_line_lead_text = text_el.text or None
for idx, child in enumerate(list(text_el)):
- if not is_svg_tag(child, "tspan"):
+ if not _is_svg_tag(child, "tspan"):
continue
content = collect_text_content(child)
# Check whether this tspan starts a new line
- if is_new_line_tspan(child):
+ if _is_new_line_tspan(child):
# Save previously accumulated same-line tspans first
if current_line_tspans or _has_non_xml_whitespace(
current_line_lead_text
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 8733c5e1..090edec7 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -254,6 +254,7 @@ except ImportError:
try:
from svg_to_pptx.semantic_markers import (
SEMANTIC_ATTRS as _SEMANTIC_ATTRS,
+ STRUCTURAL_ROLES as _STRUCTURAL_ROLES,
is_static_page_frame as _is_static_page_frame,
validate_semantic_markers as _validate_semantic_markers,
)
@@ -262,6 +263,16 @@ except ImportError:
'data-pptx-page-role',
'data-pptx-role',
})
+ _STRUCTURAL_ROLES = frozenset({
+ 'background',
+ 'chrome',
+ 'decoration',
+ 'footer',
+ 'header',
+ 'logo',
+ 'page-number',
+ 'watermark',
+ })
_is_static_page_frame = None
_validate_semantic_markers = None
@@ -276,10 +287,12 @@ except ImportError:
try:
from svg_to_pptx.tspan_flattener import (
+ classify_paragraph_block as _classify_paragraph_block,
flatten_positional_tspans as _flatten_positional_tspans,
nested_positional_tspan_errors as _nested_positional_tspan_errors,
)
except ImportError:
+ _classify_paragraph_block = None
_flatten_positional_tspans = None
_nested_positional_tspan_errors = None
@@ -1881,6 +1894,18 @@ class SVGQualityChecker:
text_el: ET.Element,
) -> List[Tuple[ET.Element, str]] | None:
"""Return normalized inline runs, or ``None`` for positioned text."""
+ raw_runs = cls._inline_text_segments(text_el, 'default')
+ if raw_runs is None:
+ return None
+ return cls._normalize_source_text_runs(raw_runs)
+
+ @classmethod
+ def _inline_text_segments(
+ cls,
+ container: ET.Element,
+ inherited_xml_space: str,
+ ) -> List[Tuple[ET.Element, str, str]] | None:
+ """Collect inline text while rejecting descendant positioning."""
if (
_normalize_project_text_segments is None
or _resolve_project_xml_space is None
@@ -1892,17 +1917,17 @@ class SVGQualityChecker:
if raw:
raw_runs.append((owner, xml_space, raw))
- def collect(container: ET.Element, inherited_xml_space: str) -> bool:
+ def collect(element: ET.Element, inherited: str) -> bool:
try:
xml_space = _resolve_project_xml_space(
- container,
- inherited_xml_space,
+ element,
+ inherited,
)
except ValueError:
return False
- if container.text:
- append_run(container, container.text, xml_space)
- for child in list(container):
+ if element.text:
+ append_run(element, element.text, xml_space)
+ for child in list(element):
if not cls._is_tspan(child):
return False
if any(child.get(name) is not None for name in ('x', 'y', 'dx', 'dy')):
@@ -1915,11 +1940,18 @@ class SVGQualityChecker:
if not collect(child, xml_space):
return False
if child.tail:
- append_run(container, child.tail, xml_space)
+ append_run(element, child.tail, xml_space)
return True
- if not collect(text_el, 'default'):
+ if not collect(container, inherited_xml_space):
return None
+ return raw_runs
+
+ @staticmethod
+ def _normalize_source_text_runs(
+ raw_runs: List[Tuple[ET.Element, str, str]],
+ ) -> List[Tuple[ET.Element, str]]:
+ """Normalize collected segments while retaining their style owner."""
normalized = _normalize_project_text_segments([
(xml_space, raw)
for _owner, xml_space, raw in raw_runs
@@ -1929,6 +1961,38 @@ class SVGQualityChecker:
for index, text in normalized
]
+ @classmethod
+ def _paragraph_line_text_runs(
+ cls,
+ text_el: ET.Element,
+ line_group: List[ET.Element],
+ synthetic_first: ET.Element | None,
+ ) -> List[Tuple[ET.Element, str]] | None:
+ """Return one classified visual line's normalized source runs."""
+ if (
+ _normalize_project_text_segments is None
+ or _resolve_project_xml_space is None
+ ):
+ return None
+ try:
+ parent_xml_space = _resolve_project_xml_space(text_el, 'default')
+ except ValueError:
+ return None
+
+ raw_runs: List[Tuple[ET.Element, str, str]] = []
+ for member in line_group:
+ if member is synthetic_first:
+ if member.text:
+ raw_runs.append((text_el, parent_xml_space, member.text))
+ continue
+ member_runs = cls._inline_text_segments(member, parent_xml_space)
+ if member_runs is None:
+ return None
+ raw_runs.extend(member_runs)
+ if member.tail:
+ raw_runs.append((text_el, parent_xml_space, member.tail))
+ return cls._normalize_source_text_runs(raw_runs)
+
@staticmethod
def _unchanged_txbody_group_ids(
root: ET.Element,
@@ -1996,6 +2060,22 @@ class SVGQualityChecker:
source_runs = cls._single_line_text_runs(text_el)
if source_runs is None:
return None
+ return cls._resolved_text_runs(
+ source_runs,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+
+ @classmethod
+ def _resolved_text_runs(
+ cls,
+ source_runs: List[Tuple[ET.Element, str]],
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ ) -> List[Dict]:
+ """Resolve run metrics shared by single and classified text lines."""
resolved: List[Dict] = []
for owner, text in source_runs:
raw_weight = (
@@ -2234,8 +2314,101 @@ class SVGQualityChecker:
if _parse_project_geometry_length is None:
return None
children = list(text_el)
- if not children or (text_el.text or '').strip():
+ if not children:
return None
+ if (text_el.text or '').strip():
+ if _classify_paragraph_block is None:
+ return None
+ paragraph = _classify_paragraph_block(
+ text_el,
+ preserve_line_breaks=True,
+ )
+ if paragraph is None:
+ return None
+ _base, _extras, _breaks, line_groups, synthetic_first = paragraph
+ try:
+ current_y = _parse_project_geometry_length(
+ text_el.get('y') or '0',
+ 'y',
+ )
+ parent_x = _parse_project_geometry_length(
+ text_el.get('x') or '0',
+ 'x',
+ )
+ except ValueError:
+ return None
+
+ lines: List[
+ Tuple[ET.Element, float, float, List[Dict], float]
+ ] = []
+ for line_group in line_groups:
+ starter = line_group[0]
+ if starter is synthetic_first:
+ line_element = text_el
+ line_x = parent_x
+ line_y = current_y
+ else:
+ if starter.get('x') is None:
+ return None
+ line_element = starter
+ try:
+ line_x = _parse_project_geometry_length(
+ starter.get('x'),
+ 'x',
+ )
+ line_y = (
+ _parse_project_geometry_length(
+ starter.get('y'),
+ 'y',
+ )
+ if starter.get('y') is not None
+ else current_y
+ )
+ if starter.get('dx') is not None:
+ line_x += _parse_project_geometry_length(
+ starter.get('dx'),
+ 'dx',
+ )
+ if starter.get('dy') is not None:
+ line_y += _parse_project_geometry_length(
+ starter.get('dy'),
+ 'dy',
+ )
+ except ValueError:
+ return None
+
+ current_y = line_y
+ source_runs = cls._paragraph_line_text_runs(
+ text_el,
+ line_group,
+ synthetic_first,
+ )
+ if source_runs is None:
+ return None
+ try:
+ runs = cls._resolved_text_runs(
+ source_runs,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ except (KeyError, TypeError, ValueError):
+ return None
+ if not runs:
+ continue
+ try:
+ font_size = max(float(run['font_size']) for run in runs)
+ except (KeyError, TypeError, ValueError):
+ return None
+ lines.append((
+ line_element,
+ line_x,
+ line_y,
+ runs,
+ font_size,
+ ))
+ return lines or None
+
if any(
not cls._is_tspan(child)
or not cls._is_line_tspan(child)
@@ -2584,6 +2757,19 @@ class SVGQualityChecker:
or top >= other_bottom
)
+ @staticmethod
+ def _bounds_overlap_dimensions(
+ first: Tuple[float, float, float, float],
+ second: Tuple[float, float, float, float],
+ ) -> Tuple[float, float]:
+ """Return positive intersection width and height for two bounds."""
+ left, top, right, bottom = first
+ other_left, other_top, other_right, other_bottom = second
+ return (
+ max(min(right, other_right) - max(left, other_left), 0.0),
+ max(min(bottom, other_bottom) - max(top, other_top), 0.0),
+ )
+
@classmethod
def _is_off_canvas_morph_group(
cls,
@@ -2599,6 +2785,25 @@ class SVGQualityChecker:
and cls._bounds_are_disjoint(resolved[1], canvas)
)
+ @classmethod
+ def _root_module_overlap_exempt(
+ cls,
+ group: ET.Element,
+ *,
+ structured_page: bool,
+ canvas: Tuple[float, float, float, float] | None,
+ ) -> bool:
+ """Return whether one root group is not an ordinary module zone."""
+ role = (group.get('data-pptx-role') or '').strip().lower()
+ if role in _STRUCTURAL_ROLES:
+ return True
+ if structured_page and group.get('data-pptx-placeholder') is not None:
+ return True
+ return (
+ canvas is not None
+ and cls._is_off_canvas_morph_group(group, canvas)
+ )
+
@classmethod
def _record_bounds_overflow(
cls,
@@ -2890,6 +3095,9 @@ class SVGQualityChecker:
)
missing: List[str] = []
+ bounded_root_groups: List[
+ Tuple[ET.Element, Tuple[float, float, float, float]]
+ ] = []
root_groups = [
child
for child in list(root)
@@ -2924,7 +3132,10 @@ class SVGQualityChecker:
continue
resolved = self._resolved_root_module_bounds(group)
- if resolved is None or canvas is None:
+ if resolved is None:
+ continue
+ bounded_root_groups.append((group, resolved[1]))
+ if canvas is None:
continue
if self._is_off_canvas_morph_group(group, canvas):
continue
@@ -2940,6 +3151,43 @@ class SVGQualityChecker:
),
)
+ structured_page = all(
+ (root.get(attribute) or '').strip()
+ for attribute in _PPTX_ROOT_STRUCTURE_ATTRS
+ )
+ for index, (first_group, first_bounds) in enumerate(
+ bounded_root_groups,
+ ):
+ if self._root_module_overlap_exempt(
+ first_group,
+ structured_page=structured_page,
+ canvas=canvas,
+ ):
+ continue
+ for second_group, second_bounds in bounded_root_groups[index + 1:]:
+ if self._root_module_overlap_exempt(
+ second_group,
+ structured_page=structured_page,
+ canvas=canvas,
+ ):
+ continue
+ overlap_width, overlap_height = self._bounds_overlap_dimensions(
+ first_bounds,
+ second_bounds,
+ )
+ if (
+ overlap_width <= _BOUNDS_OVERFLOW_TOLERANCE
+ or overlap_height <= _BOUNDS_OVERFLOW_TOLERANCE
+ ):
+ continue
+ result['errors'].append(
+ f'{_element_label(first_group)} {_BOUNDS_ATTR} overlaps '
+ f'{_element_label(second_group)} {_BOUNDS_ATTR} by '
+ f'{overlap_width:.1f}px x {overlap_height:.1f}px; keep '
+ 'ordinary direct-root module zones disjoint beyond the '
+ f'{_BOUNDS_OVERFLOW_TOLERANCE:.0f}px tolerance'
+ )
+
if missing:
sample = '; '.join(missing[:3])
suffix = '' if len(missing) <= 3 else f'; +{len(missing) - 3} more'
@@ -3022,7 +3270,7 @@ class SVGQualityChecker:
parent_by_id,
font_sizes,
letter_spacings,
- include_headroom=False,
+ include_headroom=True,
)
if estimated is not None:
estimated_by_id[id(text_element)] = estimated
diff --git a/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py b/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
index ce4b93b7..21ab6241 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
@@ -12,6 +12,9 @@ performs the same transformation in memory so ``svg_to_pptx`` can consume
``svg_output/`` directly without that disk step.
Public API:
+ classify_paragraph_block(text_el, preserve_line_breaks=False)
+ Classify compatible positioned paragraphs without mutating the SVG.
+
flatten_positional_tspans(tree) -> bool
Walk the SVG element tree, replace every positional ``<tspan>``
with an independent ``<text>``, and return whether anything
@@ -59,6 +62,23 @@ def flatten_positional_tspans(
)
+def classify_paragraph_block(
+ text_el: ET.Element,
+ preserve_line_breaks: bool = False,
+) -> tuple[
+ float,
+ list[float],
+ list[str],
+ list[list[ET.Element]],
+ ET.Element | None,
+] | None:
+ """Return shared positioned-paragraph classification without mutation."""
+ return _flatten_module().classify_paragraph_block(
+ text_el,
+ preserve_line_breaks=preserve_line_breaks,
+ )
+
+
def nested_positional_tspan_errors(root: ET.Element) -> list[str]:
"""Return shared diagnostics for unsupported nested baseline jumps."""
return _flatten_module().nested_positional_tspan_errors(root)
diff --git a/skills/ppt-master/scripts/tests/test_svg_quality_checker.py b/skills/ppt-master/scripts/tests/test_svg_quality_checker.py
new file mode 100644
index 00000000..7e2f34be
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_svg_quality_checker.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python3
+"""Focused regression tests for SVG text and module-bound checks."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from xml.etree import ElementTree as ET
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from svg_quality import checker as checker_module # noqa: E402
+from svg_quality.checker import SVGQualityChecker # noqa: E402
+
+
+SVG_NS = 'http://www.w3.org/2000/svg'
+
+
+def _parse_svg(body: str, root_attributes: str = '') -> ET.Element:
+ return ET.fromstring(
+ f'<svg xmlns="{SVG_NS}" viewBox="0 0 1000 1000" '
+ f'{root_attributes}>{body}</svg>'
+ )
+
+
+def _empty_result() -> dict:
+ return {'errors': [], 'warnings': []}
+
+
+class SVGQualityCheckerBoundsTests(unittest.TestCase):
+ def test_leading_direct_text_and_positioned_tspans_are_estimable(self) -> None:
+ root = _parse_svg(
+ '<g id="module" data-pptx-bounds="0 0 1000 1000">'
+ '<text id="mixed" x="10" y="30" font-size="20">'
+ 'Leading <tspan font-weight="700">bold</tspan>'
+ '<tspan x="10" dy="28">Second line</tspan>'
+ '</text></g>'
+ )
+ text_element = root.find(f'.//{{{SVG_NS}}}text')
+ self.assertIsNotNone(text_element)
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ font_sizes = checker_module._resolve_project_font_sizes(root)
+ letter_spacings = checker_module._resolve_project_letter_spacings(
+ root,
+ font_sizes,
+ )
+
+ lines = SVGQualityChecker._positioned_text_lines(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+
+ self.assertIsNotNone(lines)
+ self.assertEqual(len(lines), 2)
+ self.assertEqual(
+ [''.join(run['text'] for run in line[3]) for line in lines],
+ ['Leading bold', 'Second line'],
+ )
+ result = _empty_result()
+ SVGQualityChecker()._check_text_bounds(root, result)
+ self.assertFalse(
+ any('Cannot verify' in warning for warning in result['warnings'])
+ )
+
+ def test_existing_all_tspan_and_inline_single_line_forms_still_resolve(self) -> None:
+ cases = {
+ 'all_tspan': (
+ '<text x="10" y="30" font-size="20">'
+ '<tspan x="10">First</tspan>'
+ '<tspan x="10" dy="28">Second</tspan>'
+ '</text>',
+ 2,
+ ),
+ 'single_inline': (
+ '<text x="10" y="30" font-size="20">'
+ 'First <tspan font-weight="700">line</tspan>'
+ '</text>',
+ 1,
+ ),
+ }
+ for name, (text_svg, expected_lines) in cases.items():
+ with self.subTest(name=name):
+ root = _parse_svg(
+ '<g id="module" data-pptx-bounds="0 0 1000 1000">'
+ f'{text_svg}</g>'
+ )
+ text_element = root.find(f'.//{{{SVG_NS}}}text')
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+ font_sizes = checker_module._resolve_project_font_sizes(root)
+ letter_spacings = checker_module._resolve_project_letter_spacings(
+ root,
+ font_sizes,
+ )
+ bounds = SVGQualityChecker._estimated_text_bounds(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ self.assertIsNotNone(bounds)
+ if expected_lines == 2:
+ lines = SVGQualityChecker._positioned_text_lines(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ self.assertEqual(len(lines), expected_lines)
+ else:
+ runs = SVGQualityChecker._resolved_single_line_text_runs(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ self.assertIsNotNone(runs)
+
+ def test_module_bounds_use_headroom_but_page_bounds_do_not(self) -> None:
+ root = _parse_svg(
+ '<g id="module" data-pptx-bounds="0 0 100 100">'
+ '<text id="text" x="0" y="20" font-size="12">Text</text>'
+ '</g>'
+ )
+ include_headroom_calls = []
+
+ def estimated_bounds(*_args, include_headroom=True, **_kwargs):
+ include_headroom_calls.append(include_headroom)
+ right = 106.0 if include_headroom else 100.0
+ return (0.0, 0.0, right, 20.0)
+
+ result = _empty_result()
+ checker = SVGQualityChecker()
+ with patch.object(
+ checker,
+ '_estimated_text_bounds',
+ side_effect=estimated_bounds,
+ ):
+ checker._check_text_bounds(root, result)
+
+ self.assertEqual(include_headroom_calls, [True, False])
+ self.assertTrue(
+ any('data-pptx-bounds' in error for error in result['errors'])
+ )
+ self.assertFalse(
+ any('root viewBox' in error for error in result['errors'])
+ )
+
+ def test_root_module_overlap_is_error_with_minimal_exemptions(self) -> None:
+ cases = (
+ (
+ 'overlap_above_tolerance',
+ _parse_svg(
+ '<g id="first" data-pptx-bounds="0 0 100 100"/>'
+ '<g id="second" data-pptx-bounds="98.9 0 100 100"/>'
+ ),
+ True,
+ ),
+ (
+ 'overlap_at_tolerance',
+ _parse_svg(
+ '<g id="first" data-pptx-bounds="0 0 100 100"/>'
+ '<g id="second" data-pptx-bounds="99 0 100 100"/>'
+ ),
+ False,
+ ),
+ (
+ 'static_page_frame',
+ _parse_svg(
+ '<g id="background" data-pptx-role="background" '
+ 'data-pptx-bounds="0 0 1000 1000"/>'
+ '<g id="content" data-pptx-bounds="100 100 200 200"/>'
+ ),
+ False,
+ ),
+ (
+ 'structured_slots',
+ _parse_svg(
+ '<g id="picture" data-pptx-placeholder="picture" '
+ 'data-pptx-bounds="0 0 500 500"/>'
+ '<g id="title" data-pptx-placeholder="title" '
+ 'data-pptx-bounds="100 100 300 100"/>',
+ 'data-pptx-master="master" '
+ 'data-pptx-master-name="Master" '
+ 'data-pptx-layout="layout" '
+ 'data-pptx-layout-name="Layout"',
+ ),
+ False,
+ ),
+ (
+ 'structured_ordinary_modules',
+ _parse_svg(
+ '<g id="first" data-pptx-bounds="0 0 100 100"/>'
+ '<g id="second" data-pptx-bounds="50 0 100 100"/>',
+ 'data-pptx-master="master" '
+ 'data-pptx-master-name="Master" '
+ 'data-pptx-layout="layout" '
+ 'data-pptx-layout-name="Layout"',
+ ),
+ True,
+ ),
+ (
+ 'off_canvas_morph_staging',
+ _parse_svg(
+ '<g id="morph-a" data-pptx-morph-staging="true" '
+ 'data-pptx-bounds="1100 0 100 100"/>'
+ '<g id="morph-b" data-pptx-morph-staging="true" '
+ 'data-pptx-bounds="1100 0 100 100"/>'
+ ),
+ False,
+ ),
+ )
+ checker = SVGQualityChecker()
+ for name, root, expects_overlap_error in cases:
+ with self.subTest(name=name):
+ result = _empty_result()
+ checker._check_module_bounds_contract(root, result)
+ overlap_errors = [
+ error
+ for error in result['errors']
+ if 'data-pptx-bounds overlaps' in error
+ ]
+ self.assertEqual(bool(overlap_errors), expects_overlap_error)
+
+
+if __name__ == '__main__':
+ unittest.main()