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(scripts): keep single-child group rotation, carry inline tspan dx, and apply root and native-gradient opacity on export
hugohe3397c5d92b1cf
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex e1771c71..b0defbe6 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -1180,6 +1180,23 @@ python3 scripts/svg_position_calculator.py calc line --data "68:0.5,71:1.5,49:2.### `flatten_tspan.py`+Positioned `x`/`y`/nonzero `dy` rows keep the existing split/preserve/reflow+behavior. A row starter's `dx` is consumed by its resolved line position;+later inline scalar `dx` stays with its run through flattening.++Native export represents inline `dx` with a separate NBSP run before the+affected text. Its `a:rPr@spc`, in hundredths of a point, is+`round(75 * (dx_px - estimated_space_width_px))`. The space estimate uses the+current run's font and size. This keeps both positive and negative movement+local to the boundary, including the first run, without changing tracking+inside a label. Font substitution and estimated space metrics can introduce+a small width difference. Spacing runs stay separate; positioned bullet+markers remain literal text so bullet extraction cannot remove the offset.++A small nonzero `dy` still starts a positioned row; it is not an inline+superscript/subscript displacement. Use the supported `baseline-shift` form+for inline vertical shifts.+```bashpython3 scripts/svg_finalize/flatten_tspan.py projects/<project>/svg_outputpython3 scripts/svg_finalize/flatten_tspan.py path/to/input.svg path/to/output.svgdiff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.pyindex a2c5c5e1..a48d1b89 100644--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py@@ -663,7 +663,7 @@ def flatten_text_with_tspans(# Keep raw XML whitespace and tails until the shared downstream# text normalizer sees the whole line. A whitespace-only run can# still be the visible boundary between two formatted runs.- if content or child.tail:+ if content or child.tail or child.get("dx") is not None:current_line_tspans.append(child)# Process the last line@@ -790,6 +790,7 @@ def _create_text_element_from_line(and not tspans[0].tailand tspans[0].get(INLINE_FORMULA_ATTR) is Noneand not _declares_baseline_shift(tspans[0])+ and (tspans[0].get("dx") is None or _is_new_line_tspan(tspans[0]))):tspan = tspans[0]content = collect_text_content(tspan)diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 00d346ad..56a34aea 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -1347,6 +1347,9 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:explicit_native_group = elem.get('data-pptx-object') == 'group'if (len(child_results) == 1+ # A fallback rotation still belongs to this group. Keep its container+ # so the pivot compensation below runs even for a single text child.+ and (matrix_supported or not angle_deg)and not explicit_native_groupand (not should_animate_group@@ -2324,6 +2327,7 @@ def convert_svg_to_slide_shapes(defs = collect_defs(root)source_shape_id_map = _build_source_shape_id_map(root)+ root_opacity = get_element_opacity(root)ctx = ConvertContext(defs=defs,reserved_shape_ids=frozenset(source_shape_id_map.values()),@@ -2347,6 +2351,7 @@ def convert_svg_to_slide_shapes(theme_color_spec=theme_color_spec,primary_language=primary_language,inherited_styles=_extract_inheritable_styles(root),+ opacity_multiplier=1.0 if root_opacity is None else root_opacity,parent_by_id={id(child): parent for parent in root.iter() for child in parent},text_font_sizes=text_font_sizes,text_letter_spacings=text_letter_spacings,diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex 2d4b6e17..94a236dc 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -2099,7 +2099,21 @@ def _normalize_text_run_whitespace((str(run.get('_xml_space', 'default')), str(run.get('text', '')))for run in runs]- for index, text in normalize_project_text_segments(segments):+ text_by_index = dict(normalize_project_text_segments(segments))+ for index, source_run in enumerate(runs):+ if '_inline_dx' in source_run:+ # Insert after whitespace normalization so dx neither preserves+ # indentation nor disappears with an empty/whitespace-only tspan.+ run = {**source_run, 'text': ' ', 'letter_spacing': 0.0, 'text_decoration': 'none'}+ dx = run.pop('_inline_dx')+ run['letter_spacing'] = dx - _estimate_run_text_width(run)+ run.update(text='\u00a0', _inline_dx=dx)+ run.pop('_xml_space', None)+ normalized.append(run)+ continue+ text = text_by_index.get(index)+ if text is None:+ continuerun = {**runs[index], 'text': text}run.pop('_xml_space', None)normalized.append(run)@@ -2208,6 +2222,8 @@ def _family_width_factor(run: dict[str, Any]) -> float:def _estimate_run_text_width(run: dict[str, Any]) -> float:"""Estimate one run using the metrics actually emitted to DrawingML."""+ if '_inline_dx' in run:+ return float(run['_inline_dx'])text = str(run.get('text', ''))font_size_px = (font_px_to_hpt(float(run.get('font_size', 16)))@@ -2293,6 +2309,17 @@ def _estimate_text_runs_width(so adding headroom there stretches the merged text frame beyond theauthor's source line width."""+ if any('_inline_dx' in run for run in runs):+ # A negative dx moves the cursor back; it must not subtract space+ # already occupied by earlier glyphs or make the frame extent negative.+ advance = right = 0.0+ for run in runs:+ if '_inline_dx' in run:+ advance += float(run['_inline_dx'])+ continue+ advance += _estimate_text_runs_width([run], include_headroom=include_headroom)+ right = max(right, advance)+ return rightif not include_headroom:return sum(_estimate_run_text_width(run) for run in runs)@@ -2394,6 +2421,10 @@ def _extract_text_bullet(runs: list[dict[str, Any]],) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:"""Convert a leading text bullet marker into paragraph metadata."""+ if any('_inline_dx' in run for run in runs):+ # Keep positioned markers literal so bullet normalization cannot+ # discard or relocate an authored displacement.+ return runs, Nonefirst_nonspace = _first_nonspace_run(runs)if first_nonspace and (first_nonspace.get(_INLINE_FORMULA_KEY) is not None@@ -2646,6 +2677,15 @@ def _collect_inline_runs(svg_hyperlink_href(container),)+ if container_tag == 'tspan' and container.get('dx') is not None:+ dx = parse_svg_length(+ container.get('dx'),+ percent_base=ctx.viewport_width,+ font_size=float(own_attrs.get('font_size', 16)) / (ctx.scale_y or 1.0),+ ) * ctx.scale_x+ if dx:+ runs.append({**own_attrs, 'text': '', '_inline_dx': dx})+if container.text:run = {**own_attrs,@@ -2910,7 +2950,7 @@ def _coalesce_text_runs(text = str(run.get('text', ''))if not text:continue- if run.get(_INLINE_FORMULA_KEY) is not None:+ if run.get(_INLINE_FORMULA_KEY) is not None or '_inline_dx' in run:merged.append({**run, 'text': text})previous_properties = Nonecontinuediff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.pyindex adc833a2..a427e516 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py@@ -50,7 +50,19 @@ def build_gradient_fill("""Build <a:gradFill> from SVG linearGradient or radialGradient element."""native = preserved_native_gradient_xml(grad_elem)if native is not None:- return native+ if opacity is None or opacity == 1.0:+ return native+ # Parse a fresh copy; other shapes may reuse the same gradient payload.+ gradient = ET.fromstring(native)+ namespace = '{http://schemas.openxmlformats.org/drawingml/2006/main}'+ for stop in gradient.findall(f'{namespace}gsLst/{namespace}gs'):+ for color in stop:+ alpha = color.find(f'{namespace}alpha')+ existing = 1.0 if alpha is None else int(alpha.get('val')) / 100000+ if alpha is None:+ alpha = ET.SubElement(color, f'{namespace}alpha')+ alpha.set('val', str(quantize_ooxml_alpha(existing * opacity)))+ return ET.tostring(gradient, encoding='unicode')tag = grad_elem.tag.replace(f'{{{SVG_NS}}}', '')stops_xml = []diff --git a/skills/ppt-master/scripts/tests/test_native_export_guards.py b/skills/ppt-master/scripts/tests/test_native_export_guards.pyindex b4536059..1d15340f 100644--- a/skills/ppt-master/scripts/tests/test_native_export_guards.py+++ b/skills/ppt-master/scripts/tests/test_native_export_guards.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Regression tests for coordinate, visibility, and pattern export guards."""+"""Regression tests for native export guards and SVG fidelity."""from __future__ import annotations@@ -15,11 +15,14 @@ if str(SCRIPTS_DIR) not in sys.path:sys.path.insert(0, str(SCRIPTS_DIR))from pptx_shapes.formula import OOXML_COORDINATE_MAX # noqa: E402+from pptx_gradients import native_gradient_metadata, preserved_native_gradient_xml # noqa: E402+from svg_finalize.flatten_tspan import flatten_text_with_tspans # noqa: E402from svg_quality.checker import SVGQualityChecker # noqa: E402from svg_to_pptx.drawingml.converter import ( # noqa: E402SvgNativeConversionError,convert_svg_to_slide_shapes,)+from svg_to_pptx.drawingml.styles import build_gradient_fill # noqa: E402NS = {@@ -214,6 +217,212 @@ class NativeExportGuardTests(unittest.TestCase):self.assertIsNone(slide.find('.//a:pattFill', NS))self.assertIsNotNone(slide.find('.//p:sp/p:spPr/a:noFill', NS))+ def test_single_child_rotation_matches_direct_transform(self) -> None:+ for child in (+ '<text x="100" y="120" {transform}>ABC</text>',+ '<rect x="100" y="120" width="80" height="30" {transform}/>',+ ):+ with self.subTest(child=child):+ transform = 'transform="rotate(90 100 120)"'+ self._svg(child.format(transform=transform), 'font-family="Arial" font-size="20"')+ direct = self._export().find('.//p:sp/p:spPr/a:xfrm', NS)+ self._svg(+ f'<g {transform}>{child.format(transform="")}</g>',+ 'font-family="Arial" font-size="20"',+ )+ grouped = self._export()+ rotated = grouped.find('.//a:xfrm[@rot]', NS)+ self.assertIsNotNone(rotated)+ self.assertEqual(rotated.get('rot'), direct.get('rot'))+ self.assertEqual(rotated.find('a:off', NS).attrib, direct.find('a:off', NS).attrib)+ self.assertEqual(rotated.find('a:ext', NS).attrib, direct.find('a:ext', NS).attrib)++ def test_multiple_child_rotation_keeps_group_frame(self) -> None:+ self._svg(+ '<g transform="rotate(90 100 120)"><text x="100" y="120">ABC</text>'+ '<rect x="160" y="110" width="40" height="20"/></g>',+ 'font-family="Arial" font-size="20"',+ )+ group = self._export().find('.//p:grpSp', NS)+ self.assertEqual(len(group.findall('p:sp', NS)), 2)+ frame = group.find('p:grpSpPr/a:xfrm', NS)+ self.assertEqual(frame.get('rot'), '5400000')+ self.assertEqual(frame.find('a:off', NS).attrib, {'x': '487680', 'y': '1468755'})+ self.assertEqual(frame.find('a:chOff', NS).attrib, {'x': '944880', 'y': '981075'})+ self.assertFalse(group.findall('p:sp/p:spPr/a:xfrm[@rot]', NS))++ def test_single_rect_matrix_matches_direct_geometry_and_skew_stays_rejected(self) -> None:+ for transform in ('matrix(0 1 -1 0 220 20)', 'matrix(2 0 0 3 10 20)'):+ with self.subTest(transform=transform):+ rect = '<rect x="100" y="120" width="80" height="30" {transform}/>'+ self._svg(rect.format(transform=f'transform="{transform}"'))+ direct = self._export().find('.//p:sp/p:spPr', NS)+ self._svg(f'<g transform="{transform}">{rect.format(transform="")}</g>')+ grouped = self._export().find('.//p:sp/p:spPr', NS)+ self.assertEqual(ET.tostring(grouped), ET.tostring(direct))+ for transform in ('matrix(1 0 0.36 1 0 0)', 'skewX(20)'):+ for body in (+ '<rect x="100" y="120" width="80" height="30" transform="{transform}"/>',+ '<g transform="{transform}"><rect x="100" y="120" width="80" height="30"/></g>',+ ):+ with self.subTest(transform=transform, body=body):+ self._svg(body.format(transform=transform))+ with self.assertRaisesRegex(SvgNativeConversionError, 'skew|skewX'):+ self._export()++ def test_root_opacity_multiplies_group_and_fill_opacity(self) -> None:+ for attributes in ('opacity="0.5"', 'style="opacity:0.5"', 'opacity="0.8" style="opacity:0.5"'):+ for group_opacity, expected in (('1', '50000'), ('0.5', '25000')):+ with self.subTest(attributes=attributes, group_opacity=group_opacity):+ self._svg(+ f'<g opacity="{group_opacity}" data-pptx-bounds="50 50 500 300">'+ '<rect x="100" y="100" width="200" height="100" fill="#FF0000"/></g>',+ attributes,+ )+ self.assertFalse(self._check()['errors'])+ alpha = self._export().find('.//p:sp/p:spPr/a:solidFill/a:srgbClr/a:alpha', NS)+ self.assertIsNotNone(alpha)+ self.assertEqual(alpha.get('val'), expected)+ self._svg('<rect width="1280" height="720" fill="#FF0000"/>', 'opacity="0"')+ self.assertEqual(self._export().find('.//a:alpha', NS).get('val'), '0')+ self._svg(+ '<rect x="100" y="100" width="200" height="100" fill="#FF0000"/>',+ 'opacity="0.5" fill-opacity="0.5"',+ )+ self.assertEqual(self._export().find('.//a:alpha', NS).get('val'), '25000')++ def _native_gradient(self, alpha: str = '') -> ET.Element:+ gradient = ET.fromstring(+ '<linearGradient xmlns="http://www.w3.org/2000/svg" id="g" x1="0" y1="0" x2="1" y2="0">'+ '<stop offset="0" stop-color="#FF0000"/><stop offset="1" stop-color="#0000FF"/>'+ '</linearGradient>'+ )+ native = ET.fromstring(+ f'<a:gradFill xmlns:a="{NS["a"]}"><a:gsLst>'+ f'<a:gs pos="0"><a:srgbClr val="FF0000">{alpha}</a:srgbClr></a:gs>'+ '<a:gs pos="100000"><a:schemeClr val="accent1"/></a:gs>'+ '</a:gsLst><a:lin ang="0" scaled="1"/></a:gradFill>'+ )+ gradient.attrib.update(native_gradient_metadata(native, gradient))+ return gradient++ def test_native_gradient_opacity_uses_copy_and_preserves_identity(self) -> None:+ for source_alpha, expected in (('', '50000'), ('<a:alpha val="33333"/>', '16667')):+ with self.subTest(source_alpha=source_alpha):+ gradient = self._native_gradient(source_alpha)+ original = preserved_native_gradient_xml(gradient)+ attributes = dict(gradient.attrib)+ tinted = ET.fromstring(build_gradient_fill(gradient, opacity=0.5))+ self.assertEqual([n.get('val') for n in tinted.findall('.//a:alpha', NS)], [expected, '50000'])+ self.assertEqual(gradient.attrib, attributes)+ self.assertEqual(build_gradient_fill(gradient, opacity=None), original)+ self.assertEqual(build_gradient_fill(gradient, opacity=1.0), original)+ self.assertEqual(build_gradient_fill(gradient, opacity=0.5), ET.tostring(tinted, encoding='unicode'))+ transparent = ET.fromstring(build_gradient_fill(gradient, opacity=0.0))+ self.assertEqual([n.get('val') for n in transparent.findall('.//a:alpha', NS)], ['0', '0'])++ def test_native_gradient_shape_opacity_exports_each_stop(self) -> None:+ gradient = self._native_gradient()+ self._svg(+ f'<defs>{ET.tostring(gradient, encoding="unicode")}</defs>'+ '<rect x="100" y="100" width="200" height="100" fill="url(#g)" opacity="0.5"/>'+ '<rect x="400" y="100" width="200" height="100" fill="url(#g)"/>',+ )+ self.assertFalse(self._check()['errors'])+ gradients = self._export().findall('.//a:gradFill', NS)+ self.assertEqual([n.get('val') for n in gradients[0].findall('.//a:alpha', NS)], ['50000', '50000'])+ self.assertFalse(gradients[1].findall('.//a:alpha', NS))++ def test_inline_dx_adds_only_spacing_runs_to_text_body(self) -> None:+ for dx in ('10', '-10', '-200', '0'):+ with self.subTest(dx=dx):+ body = (+ '<text x="100" y="120"><tspan {dx}>Alpha</tspan>'+ '<tspan fill="#123456" dx="20">Beta</tspan></text>'+ )+ attributes = 'font-family="Arial" font-size="20"'+ self._svg(body.format(dx=f'dx="{dx}"'), attributes)+ self.assertFalse(self._check()['errors'])+ shifted = self._export().find('.//p:txBody', NS)+ self._svg(body.format(dx='').replace(' dx="20"', ''), attributes)+ unshifted = self._export().find('.//p:txBody', NS)+ paragraph = shifted.find('a:p', NS)+ spacers = [r for r in paragraph.findall('a:r', NS) if r.find('a:t', NS).text == '\u00a0']+ self.assertEqual(len(spacers), 1 if dx == '0' else 2)+ if dx != '0':+ spacing = int(spacers[0].find('a:rPr', NS).get('spc'))+ self.assertGreater(spacing, 0) if dx == '10' else self.assertLess(spacing, 0)+ for spacer in spacers:+ paragraph.remove(spacer)+ self.assertEqual(ET.tostring(shifted), ET.tostring(unshifted))++ def test_inline_dx_keeps_nested_and_tail_runs(self) -> None:+ self._svg(+ '<text x="100" y="120"><tspan dx="10">A<tspan dx="-4" fill="#123456">B</tspan>C</tspan>'+ 'D<tspan dx="5">E</tspan></text>',+ 'font-family="Arial" font-size="20"',+ )+ self.assertFalse(self._check()['errors'])+ texts = [n.text for n in self._export().findall('.//a:t', NS)]+ self.assertEqual(texts, ['\u00a0', 'A', '\u00a0', 'B', 'CD', '\u00a0', 'E'])++ def test_inline_dx_does_not_coalesce_into_plain_ab(self) -> None:+ self._svg(+ '<text x="100" y="120"><tspan dx="10">A</tspan><tspan dx="20">B</tspan></text>',+ 'font-family="Arial" font-size="20"',+ )+ shifted = self._export()+ runs = shifted.findall('.//a:r', NS)+ self.assertEqual([r.find('a:t', NS).text for r in runs], ['\u00a0', 'A', '\u00a0', 'B'])+ self.assertEqual([r.find('a:rPr', NS).get('spc') for r in runs], ['300', None, '1050', None])+ self._svg('<text x="100" y="120"><tspan>A</tspan><tspan>B</tspan></text>',+ 'font-family="Arial" font-size="20"')+ self.assertEqual([t.text for t in self._export().findall('.//a:t', NS)], ['AB'])++ def test_inline_dx_survives_empty_span_and_first_line_compaction(self) -> None:+ for first in ('<tspan dx="10">A</tspan>', '<tspan dx="10"/><tspan>A</tspan>'):+ with self.subTest(first=first):+ self._svg(+ f'<text x="100" y="120">{first}<tspan x="100" dy="30">B</tspan></text>',+ 'font-family="Arial" font-size="20"',+ )+ texts = [t.text for t in self._export().findall('.//a:t', NS)]+ self.assertEqual(texts, ['\u00a0', 'A', 'B'])++ def test_inline_dx_survives_split_and_preserved_lines(self) -> None:+ for text_flow in ('split', 'preserve', 'reflow'):+ with self.subTest(text_flow=text_flow):+ self._svg(+ '<text x="100" y="120"><tspan x="100">Alpha</tspan><tspan dx="10">Beta</tspan>'+ '<tspan x="100" dy="30">Gamma</tspan><tspan dx="-5">Delta</tspan></text>',+ 'font-family="Arial" font-size="20"',+ )+ xml, *_ = convert_svg_to_slide_shapes(self.svg_path, resource_root=self.root, text_flow=text_flow)+ slide = ET.fromstring(xml)+ self.assertEqual(sum(n.text == '\u00a0' for n in slide.findall('.//a:t', NS)), 2)+ self.assertEqual(len(slide.findall('.//p:sp', NS)), 2 if text_flow == 'split' else 1)+ if text_flow == 'preserve':+ self.assertEqual(len(slide.findall('.//a:br', NS)), 1)++ def test_line_starter_dx_is_consumed_once_and_small_dy_still_splits(self) -> None:+ self._svg(+ '<text x="100" y="120"><tspan x="100" dx="10">A</tspan>'+ '<tspan x="100" dx="-5" dy="30">B</tspan></text>',+ 'font-family="Arial" font-size="20"',+ )+ positioned = ET.tostring(self._export())+ self._svg(+ '<text x="110" y="120">A</text><text x="95" y="150">B</text>',+ 'font-family="Arial" font-size="20"',+ )+ self.assertEqual(positioned, ET.tostring(self._export()))+ tree = ET.ElementTree(ET.fromstring(+ '<svg xmlns="http://www.w3.org/2000/svg"><text x="100" y="120">A<tspan dy="-4">B</tspan>'+ '</text></svg>'+ ))+ self.assertTrue(flatten_text_with_tspans(tree))+ self.assertEqual([n.get('y') for n in tree.getroot()], ['120', '116'])+if __name__ == '__main__':unittest.main()