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(scripts): add text_measure.py so authors can measure and wrap text before writing SVG

hugohe34f8cf09b75c1
diff --git a/skills/ppt-master/references/executor-base.md b/skills/ppt-master/references/executor-base.md
index 96407865..ce839f8b 100644
--- a/skills/ppt-master/references/executor-base.md
+++ b/skills/ppt-master/references/executor-base.md
@@ -158,7 +158,7 @@ Before drawing each page, look up its entry in `page_rhythm` (key format `P<NN>`
- **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.
+- **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. The same estimator is callable before writing: `python3 ${SKILL_DIR}/scripts/text_measure.py measure|wrap|box ...` measures lines, wraps one paragraph to a max width as ready `<tspan>` rows, and computes a text block's module zone. 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
- **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/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 3324d94f..76499c78 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -954,6 +954,24 @@ Requirements:
- Heading text matches the SVG filename
- Sections are separated by `---`
+## Measuring and wrapping text before authoring
+
+`text_measure.py` imports the same single-line DrawingML width estimator used by
+the SVG quality checker.
+
+- `measure` prints one `width<TAB>text` line per input, or a JSON array with
+ `--json`.
+- `wrap` prints greedy word- or CJK-cluster-wrapped SVG text content; `--y`
+ includes the outer `<text>` element, and `--json` prints line metrics.
+- `box` prints a `data-pptx-bounds` attribute plus numeric `top` and `bottom`, or
+ a JSON bounds object with `--json`.
+
+```bash
+python3 scripts/text_measure.py measure "Editable DrawingML text" --size 22
+python3 scripts/text_measure.py wrap "Editable DrawingML text stays measurable" --size 22 --max-width 240 --x 96 --dy 30 --y 140
+python3 scripts/text_measure.py box "First line" "Second line" --x 96 --y 140 --size 22 --lines 2 --dy 30
+```
+
## `svg_quality_checker.py`
Validate SVG technical compliance.
diff --git a/skills/ppt-master/scripts/tests/test_text_measure.py b/skills/ppt-master/scripts/tests/test_text_measure.py
new file mode 100644
index 00000000..233e815d
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_text_measure.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""Focused tests for the authoring-time text measurement CLI."""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from svg_to_pptx.drawingml.elements import ( # noqa: E402
+ estimate_single_line_text_frame_width,
+)
+from text_measure import ( # noqa: E402
+ _render_wrapped_svg,
+ measure_text,
+ text_box,
+ wrap_text,
+)
+
+
+SCRIPT = SCRIPTS_DIR / 'text_measure.py'
+SAMPLE = 'Current macro-free package; the main editable format in modern PowerPoint'
+
+
+def _run_cli(*args: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, str(SCRIPT), *args],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+
+class TextMeasureTests(unittest.TestCase):
+ def test_measure_matches_checker_estimator(self) -> None:
+ run = {
+ 'text': SAMPLE,
+ 'font_size': 22.0,
+ 'font_family': 'Calibri',
+ 'font_weight': 'normal',
+ 'letter_spacing': 0.0,
+ }
+ expected = estimate_single_line_text_frame_width([run])
+
+ self.assertAlmostEqual(measure_text(SAMPLE, size=22), expected)
+ result = _run_cli('measure', SAMPLE, '--size', '22')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, f'880.4\t{SAMPLE}\n')
+
+ def test_wrap_lines_never_exceed_max_width(self) -> None:
+ max_width = 180.0
+ lines, widths, oversized = wrap_text(
+ 'Editable DrawingML text stays measurable',
+ size=22,
+ max_width=max_width,
+ )
+
+ self.assertGreater(len(lines), 1)
+ self.assertEqual(oversized, [])
+ for line, width in zip(lines, widths):
+ direct = measure_text(line, size=22)
+ self.assertAlmostEqual(width, direct)
+ self.assertLessEqual(direct, max_width)
+
+ def test_oversized_token_is_emitted_alone_with_warning(self) -> None:
+ token = 'UnbreakableToken'
+ lines, widths, oversized = wrap_text(token, size=22, max_width=20)
+
+ self.assertEqual(lines, [token])
+ self.assertGreater(widths[0], 20)
+ self.assertEqual(oversized, [(token, widths[0])])
+ result = _run_cli(
+ 'wrap', token, '--size', '22', '--max-width', '20',
+ '--x', '96', '--dy', '30',
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, f'{token}\n')
+ self.assertIn('Warning: token exceeds max width', result.stderr)
+
+ def test_cjk_wrap_keeps_closing_punctuation_with_previous_cluster(self) -> None:
+ lines, widths, oversized = wrap_text('甲乙,丙丁', size=20, max_width=45)
+
+ self.assertEqual(lines, ['甲', '乙,', '丙丁'])
+ self.assertEqual(oversized, [])
+ self.assertTrue(all(width <= 45 for width in widths))
+
+ def test_box_arithmetic_and_anchor_adjustment(self) -> None:
+ expected_x = {'start': 100.0, 'middle': 60.0, 'end': 20.0}
+ for anchor, left in expected_x.items():
+ with self.subTest(anchor=anchor):
+ bounds = text_box(
+ x=100,
+ baseline_y=50,
+ size=20,
+ lines=2,
+ dy=24,
+ width=80,
+ anchor=anchor,
+ )
+ self.assertEqual(bounds['x'], left)
+ self.assertEqual(bounds['y'], 33.0)
+ self.assertEqual(bounds['width'], 80.0)
+ self.assertEqual(bounds['height'], 48.0)
+ self.assertEqual(bounds['top'], 33.0)
+ self.assertEqual(bounds['bottom'], 81.0)
+
+ result = _run_cli(
+ 'box', '--x', '100', '--y', '50', '--size', '20',
+ '--lines', '2', '--dy', '24', '--width', '80', '--anchor', 'middle',
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(
+ result.stdout,
+ 'data-pptx-bounds="60 33 80 48"\ttop=33\tbottom=81\n',
+ )
+
+ def test_wrapped_svg_escapes_xml_text(self) -> None:
+ rendered = _render_wrapped_svg(
+ ['A & B', '<C>'],
+ x=1.234,
+ dy=20,
+ y=10,
+ )
+
+ self.assertEqual(
+ rendered,
+ '<text x="1.23" y="10">A &amp; B'
+ '<tspan x="1.23" dy="20">&lt;C&gt;</tspan></text>',
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/skills/ppt-master/scripts/text_measure.py b/skills/ppt-master/scripts/text_measure.py
new file mode 100644
index 00000000..da12dc9a
--- /dev/null
+++ b/skills/ppt-master/scripts/text_measure.py
@@ -0,0 +1,249 @@
+#!/usr/bin/env python3
+"""PPT Master - Text Measurement
+
+Measure, wrap, or calculate bounds with the SVG checker's width estimator.
+
+Usage:
+ python3 scripts/text_measure.py <measure|wrap|box> [options]
+Examples:
+ python3 scripts/text_measure.py measure "Editable text" --size 22
+Dependencies:
+ Standard library and PPT Master sibling modules
+"""
+
+from __future__ import annotations
+
+import argparse
+import html
+import json
+import math
+import sys
+from functools import partial
+from pathlib import Path
+
+
+_SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+from svg_to_pptx.drawingml.elements import estimate_single_line_text_frame_width # noqa: E402
+from svg_to_pptx.drawingml.utils import is_cjk_char, split_project_text_clusters # noqa: E402
+
+
+_CLOSING_PUNCTUATION = frozenset(',.;:!?)]」』】》,。;:!?')
+_OPENING_PUNCTUATION = frozenset('([「『【《(')
+_WEIGHTS = ('normal', 'bold', '100', '200', '300', '400', '500', '600', '700', '800', '900')
+
+
+def _bounded_float(value: str, *, minimum: float | None = None, strict: bool = False) -> float:
+ number = float(value)
+ if not math.isfinite(number):
+ raise argparse.ArgumentTypeError('must be a finite number')
+ if minimum is not None and (number < minimum or strict and number == minimum):
+ relation = 'greater than' if strict else 'at least'
+ raise argparse.ArgumentTypeError(f'must be {relation} {minimum:g}')
+ return number
+
+
+_positive_float = partial(_bounded_float, minimum=0.0, strict=True)
+_nonnegative_float = partial(_bounded_float, minimum=0.0)
+
+
+def _positive_int(value: str) -> int:
+ number = int(value)
+ if number < 1:
+ raise argparse.ArgumentTypeError('must be at least 1')
+ return number
+
+
+def _format_number(value: float) -> str:
+ rounded = round(value, 2)
+ return '0' if rounded == 0 else f'{rounded:.2f}'.rstrip('0').rstrip('.')
+
+
+def measure_text(
+ text: str, *, size: float, family: str = 'Calibri',
+ weight: str = 'normal', letter_spacing: float = 0.0,
+) -> float:
+ """Measure one line with the checker-owned DrawingML estimator."""
+ run = dict(
+ text=text, font_size=size, font_family=family,
+ font_weight=weight, letter_spacing=letter_spacing,
+ )
+ return estimate_single_line_text_frame_width([run])
+
+
+def _protected_units(text: str) -> tuple[list[str], str]:
+ cjk_clusters = ' ' not in text and any(is_cjk_char(ch) for ch in text)
+ separator = '' if cjk_clusters else ' '
+ units = split_project_text_clusters(text) if cjk_clusters else [token for token in text.split(' ') if token]
+ protected: list[str] = []
+ for unit in units:
+ if protected and (unit[0] in _CLOSING_PUNCTUATION or protected[-1][-1] in _OPENING_PUNCTUATION):
+ protected[-1] += separator + unit
+ else:
+ protected.append(unit)
+ return protected, separator
+
+
+def wrap_text(
+ text: str, *, size: float, max_width: float, family: str = 'Calibri',
+ weight: str = 'normal', letter_spacing: float = 0.0,
+) -> tuple[list[str], list[float], list[tuple[str, float]]]:
+ """Greedily wrap text and return lines, widths, and oversized units."""
+ style = dict(size=size, family=family, weight=weight, letter_spacing=letter_spacing)
+ units, separator = _protected_units(text)
+ if not units:
+ return [''], [0.0], []
+
+ lines: list[str] = []
+ widths: list[float] = []
+ oversized: list[tuple[str, float]] = []
+ current, current_width = '', 0.0
+ for unit in units:
+ unit_width = measure_text(unit, **style)
+ if unit_width > max_width:
+ if current:
+ lines.append(current)
+ widths.append(current_width)
+ current = ''
+ lines.append(unit)
+ widths.append(unit_width)
+ oversized.append((unit, unit_width))
+ continue
+ candidate = unit if not current else current + separator + unit
+ candidate_width = measure_text(candidate, **style)
+ if current and candidate_width > max_width:
+ lines.append(current)
+ widths.append(current_width)
+ current = unit
+ current_width = unit_width
+ else:
+ current = candidate
+ current_width = candidate_width
+ if current:
+ lines.append(current)
+ widths.append(current_width)
+ return lines, widths, oversized
+
+
+def _render_wrapped_svg(lines: list[str], *, x: float, dy: float, y: float | None) -> str:
+ escaped = [html.escape(line, quote=False) for line in lines]
+ tspan = f'<tspan x="{_format_number(x)}" dy="{_format_number(dy)}">'
+ inner = escaped[0] + ''.join(f'{tspan}{line}</tspan>' for line in escaped[1:])
+ return inner if y is None else (
+ f'<text x="{_format_number(x)}" y="{_format_number(y)}">{inner}</text>'
+ )
+
+
+def text_box(
+ *, x: float, baseline_y: float, size: float, lines: int, dy: float,
+ width: float, anchor: str,
+) -> dict[str, float]:
+ """Calculate the module bounds for a positioned text block."""
+ left = x - width / 2 if anchor == 'middle' else x - width if anchor == 'end' else x
+ top = baseline_y - 0.85 * size
+ bottom = baseline_y + (lines - 1) * dy + 0.35 * size
+ return dict(x=left, y=top, width=width, height=bottom - top, top=top, bottom=bottom)
+
+
+def _add_style_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument('--size', type=_positive_float, required=True)
+ parser.add_argument('--family', default='Calibri')
+ parser.add_argument('--weight', choices=_WEIGHTS, default='normal')
+ parser.add_argument('--letter-spacing', type=_bounded_float, default=0.0)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description='Measure and wrap SVG authoring text.')
+ subparsers = parser.add_subparsers(dest='command', required=True)
+
+ measure = subparsers.add_parser('measure', help='Measure single-line text.')
+ measure.add_argument('text', metavar='TEXT', nargs='*')
+ measure.add_argument('--stdin', action='store_true')
+
+ wrap = subparsers.add_parser('wrap', help='Wrap one paragraph.')
+ wrap.add_argument('text', metavar='TEXT', nargs='?')
+ wrap.add_argument('--stdin', action='store_true')
+ wrap.add_argument('--max-width', type=_positive_float, required=True)
+ wrap.add_argument('--x', type=_bounded_float, required=True)
+ wrap.add_argument('--dy', type=_positive_float, required=True)
+ wrap.add_argument('--y', type=_bounded_float)
+
+ box = subparsers.add_parser('box', help='Calculate text-block bounds.')
+ box.add_argument('text', metavar='TEXT', nargs='*')
+ box.add_argument('--x', type=_bounded_float, required=True)
+ box.add_argument('--y', type=_bounded_float, required=True)
+ box.add_argument('--lines', type=_positive_int, required=True)
+ box.add_argument('--dy', type=_positive_float)
+ box.add_argument('--width', type=_nonnegative_float)
+ box.add_argument('--anchor', choices=('start', 'middle', 'end'), default='start')
+ for command in (measure, wrap, box):
+ command.add_argument('--json', action='store_true')
+ _add_style_arguments(command)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ configure_utf8_stdio()
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ style = dict(size=args.size, family=args.family, weight=args.weight, letter_spacing=args.letter_spacing)
+
+ if args.command == 'measure':
+ if args.stdin and args.text:
+ parser.error('measure accepts positional TEXT or --stdin, not both')
+ if not args.stdin and not args.text:
+ parser.error('measure requires positional TEXT or --stdin')
+ texts = sys.stdin.read().splitlines() if args.stdin else args.text
+ results = [{'text': text, 'width': measure_text(text, **style)} for text in texts]
+ if args.json:
+ print(json.dumps(results, ensure_ascii=False))
+ else:
+ sys.stdout.write(''.join(f'{item["width"]:.1f}\t{item["text"]}\n' for item in results))
+ return 0
+
+ if args.command == 'wrap':
+ if args.stdin and args.text is not None:
+ parser.error('wrap accepts positional TEXT or --stdin, not both')
+ if not args.stdin and args.text is None:
+ parser.error('wrap requires positional TEXT or --stdin')
+ text = sys.stdin.read().rstrip('\r\n') if args.stdin else args.text
+ lines, widths, oversized = wrap_text(text, max_width=args.max_width, **style)
+ for token, width in oversized:
+ warning = f'Warning: token exceeds max width ({width:.1f} > {args.max_width:.1f}): {token}'
+ print(warning, file=sys.stderr)
+ if args.json:
+ height = (len(lines) - 1) * args.dy + 1.2 * args.size
+ payload = dict(lines=lines, widths=widths, max_width=args.max_width, height=height)
+ print(json.dumps(payload, ensure_ascii=False))
+ else:
+ print(_render_wrapped_svg(lines, x=args.x, dy=args.dy, y=args.y))
+ return 0
+
+ if args.lines > 1 and args.dy is None:
+ parser.error('box requires --dy when --lines is greater than 1')
+ if args.width is None and len(args.text) != args.lines:
+ parser.error('box without --width requires one positional TEXT per line')
+ if args.width is not None and args.text:
+ parser.error('box accepts positional TEXT only when --width is omitted')
+ width = args.width
+ if width is None:
+ width = max(measure_text(text, **style) for text in args.text)
+ bounds = text_box(
+ x=args.x, baseline_y=args.y, size=args.size, lines=args.lines, dy=args.dy or 0.0,
+ width=width, anchor=args.anchor,
+ )
+ rounded = {key: round(value, 2) for key, value in bounds.items()}
+ if args.json:
+ print(json.dumps(rounded, ensure_ascii=False))
+ else:
+ values = ' '.join(_format_number(bounds[key]) for key in ('x', 'y', 'width', 'height'))
+ top, bottom = _format_number(bounds['top']), _format_number(bounds['bottom'])
+ print(f'data-pptx-bounds="{values}"\ttop={top}\tbottom={bottom}')
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/skills/ppt-master/workflows/generate-pptx.md b/skills/ppt-master/workflows/generate-pptx.md
index f0ca5115..04b7adf1 100644
--- a/skills/ppt-master/workflows/generate-pptx.md
+++ b/skills/ppt-master/workflows/generate-pptx.md
@@ -726,7 +726,7 @@ Run the command unfiltered (no `tail`/`head`/`grep`). Review the complete P01 is
| Signal | Reading |
|---|---|
-| Two or more issues share a category and direction | Method-level bias — resolve it to the authoritative rule before P02; a correction fitted to the observed offset only patches this sample. For text extents that rule is `svg_to_pptx.drawingml.elements.estimate_single_line_text_frame_width(runs)`, with `${SKILL_DIR}/scripts` on `sys.path` and every run key present — `text`, `font_size`, `font_family`, `font_weight`, `letter_spacing` — since omissions under-measure |
+| Two or more issues share a category and direction | Method-level bias — resolve it to the authoritative rule before P02; a correction fitted to the observed offset only patches this sample. For text extents that rule is the shared estimator, exposed as `python3 ${SKILL_DIR}/scripts/text_measure.py measure|wrap|box` — measure or wrap lines before writing them instead of estimating by hand |
| One isolated issue tied to this page's structure | Page-local — fix and continue |
| A recurring element appears for the first time (page furniture, caption format, section numbering, accent discipline) | It will be copied to every later page — confirm its semantics now |