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(finalize,svg-editor): keep identity, visibility and references through rewrites
hugohe306f0d1123cfc
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex 0d3adcb4..0adb9ed7 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -1350,6 +1350,11 @@ Positioned `x`/`y`/nonzero `dy` rows keep the existing split/preserve/reflowbehavior. A row starter's `dx` is consumed by its resolved line position;later inline scalar `dx` stays with its run through flattening.+Split rows retain text names, roles, classes and visibility. The first row+keeps the original text id; later rows use collision-free `-line-N` ids.+Inline anchors and id-bearing tspans survive splitting. These preservation+rules do not broaden the native Generate authoring gate.+Native export represents inline `dx` with a separate NBSP run before theaffected text. Its `a:rPr@spc`, in hundredths of a point, is`round(75 * (dx_px - estimated_space_width_px))`. The space estimate uses the@@ -1397,6 +1402,10 @@ SVG paths. The exact case-sensitive file must exist under the workspace`icons/`; bare, aliased, template-source, and unsynced references fail. Usethis only for manual checks outside `finalize_svg.py`.+The replacement group retains the placeholder's id, class, style, opacity,+visibility, clipping/filter context, and `data-pptx-*` / `data-edit-*`+attributes. Hidden icon placeholders therefore remain hidden after embedding.+## SVG Compatibility ContractThe always-on SVG authoring contract lives indiff --git a/skills/ppt-master/scripts/docs/svg_editor.md b/skills/ppt-master/scripts/docs/svg_editor.mdindex cc0d42e3..79f749f7 100644--- a/skills/ppt-master/scripts/docs/svg_editor.md+++ b/skills/ppt-master/scripts/docs/svg_editor.md@@ -20,7 +20,7 @@ The launcher starts the server in the background, waits for `GET /api/health`, r- **Single instance per project**: `live_preview/lock.json` is the discovery source for project-local consumers (including `visual_review.py`). A second launch reuses the live instance unless a different explicit `--port N` was requested — that mismatch fails and needs `--shutdown` first. Stale locks (dead pid) are overwritten; legacy `<project_path>/.live_preview.lock` root locks are still detected when live.- **Stop conditions**: **Exit preview** in the browser (the only UI action that stops Flask), a chat request to stop, the idle timeout, or an external kill. None of them discards unapplied work; see **Draft**.- **Draft**: every staging change (annotation add/remove, direct edit, undo) rewrites `live_preview/draft.json` before it is acknowledged; the file is removed once nothing is left unapplied. The next start restores each page whose SVG still matches the digest recorded when staging began, and the UI reports the restored pages. A page whose SVG changed meanwhile is not replayed — its draft moves to `live_preview/draft_conflict_<timestamp>.json`, as does an unreadable draft. A failed draft write is reported in the UI; the change then lives in memory only.-- **Transient ids**: each element gets a temporary `_edit_N` id while running; on save only annotated elements keep their id.+- **Transient ids**: each element gets a temporary `_edit_N` id while running; on save annotated elements and local fragment targets keep their id. Existing gradient, clip, and `<use>` references remain valid even when their target ids match `_edit_N`.- **Browser preview**: the server inlines `<use data-icon>` placeholders and serves `images/*`; the on-disk SVG is unchanged by preview.- **Re-export is chat-driven**: applying changes updates `svg_output/` only; refreshing the PPTX (`finalize_svg.py` + `svg_to_pptx.py`) is a chat step — the editor never runs the export pipeline.diff --git a/skills/ppt-master/scripts/svg_editor/annotations.py b/skills/ppt-master/scripts/svg_editor/annotations.pyindex 8d20ff86..b5ee74e7 100644--- a/skills/ppt-master/scripts/svg_editor/annotations.py+++ b/skills/ppt-master/scripts/svg_editor/annotations.py@@ -28,6 +28,21 @@ ET.register_namespace('xlink', XLINK_NS)# Only ids this tool generates; a user id like "_edit_gradient" is not transient._TEMP_ID_RE = re.compile(r'_edit_\d+')+_LOCAL_URL_RE = re.compile(r'''url\(\s*(['"]?)#([^)'"\s]+)\1\s*\)''', re.IGNORECASE)+++def _referenced_ids(root: ET.Element) -> set[str]:+ """Keep fragment targets even when their authored ids look transient."""+ referenced = set()+ for elem in root.iter():+ for name, value in elem.attrib.items():+ referenced.update(match.group(2) for match in _LOCAL_URL_RE.finditer(value))+ if name.rsplit('}', 1)[-1] == 'href' and value.startswith('#'):+ referenced.add(value[1:])+ if elem.tag.rsplit('}', 1)[-1] == 'style' and elem.text:+ referenced.update(match.group(2) for match in _LOCAL_URL_RE.finditer(elem.text))+ referenced.update(re.findall(r'#(_edit_\d+)\b', elem.text))+ return referenceddef assign_temp_ids(root: ET.Element) -> None:@@ -36,16 +51,20 @@ def assign_temp_ids(root: ET.Element) -> None:Clears any leftover _edit_N ids from previous sessions first, to avoidshifted numbering when elements are added/removed between sessions."""+ referenced = _referenced_ids(root)for elem in root.iter():eid = elem.get('id', '')- if _TEMP_ID_RE.fullmatch(eid):+ if _TEMP_ID_RE.fullmatch(eid) and eid not in referenced:elem.attrib.pop('id', None)+ retained_ids = {elem.get('id') for elem in root.iter() if elem.get('id')}counter = 0for elem in root.iter():if elem is root:continueif elem.get('id') is None:+ while f'_edit_{counter}' in retained_ids:+ counter += 1elem.set('id', f'_edit_{counter}')counter += 1@@ -332,7 +351,7 @@ def strip_unused_temp_ids(root: ET.Element, keep_ids: set) -> None:Mirrors the cleanup in server.py's save-all so a direct edit neverstrips the id an unsaved/saved annotation depends on."""- protected = set(keep_ids)+ protected = set(keep_ids) | _referenced_ids(root)for elem in root.iter():if elem.get('data-edit-target') == 'true':eid = elem.get('id')diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.pyindex 2ab08ac7..19faad7a 100644--- a/skills/ppt-master/scripts/svg_editor/server.py+++ b/skills/ppt-master/scripts/svg_editor/server.py@@ -212,10 +212,8 @@ def _inline_icons(warnings.append({'icon': icon_name, 'reason': 'no renderable paths in icon'})continuereplacement = generate_icon_group(attrs, elements, style, base_size)- id_match = re.search(r'\bid="([^"]+)"', use_str)- if id_match:+ if attrs.get('id'):preview_attrs = [- f'id="{_xml_attr(id_match.group(1))}"',f'data-icon="{_xml_attr(icon_name)}"',]for key in ('x', 'y', 'width', 'height'):diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.pyindex aed2c62b..b879ab62 100644--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py@@ -396,6 +396,16 @@ def parse_use_element(use_match: str) -> dict[str, str | float]:if stroke_width_value is not None:attrs['stroke-width'] = _validate_icon_attr(stroke_width_value, 'stroke-width', _ICON_STROKE_WIDTH_RE)+ # These belong to the authored object, rather than the icon's local+ # geometry. Keep them on the replacement group, including visibility.+ for match in re.finditer(+ r'''(?<!\S)(id|class|style|opacity|display|visibility|fill-opacity|stroke-opacity|'''+ r'''clip-path|filter|data-pptx-[\w.-]+|data-edit-[\w.-]+)\s*=\s*(["'])(.*?)\2''',+ use_match,+ re.DOTALL,+ ):+ attrs[match.group(1)] = html.unescape(match.group(3))+return attrs@@ -464,13 +474,21 @@ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], styl)elements_str = '\n '.join(elements)+ context_attrs = ''.join(+ f' {key}="{_xml_attr(value)}"'+ for key, value in attrs.items()+ if key in {+ 'id', 'class', 'style', 'opacity', 'display', 'visibility',+ 'fill-opacity', 'stroke-opacity', 'clip-path', 'filter',+ } or key.startswith(('data-pptx-', 'data-edit-'))+ )if style == 'preserve':if min_x or min_y:inner_transform = f'translate({_format_number(-min_x)}, {_format_number(-min_y)})'elements_str = f'<g transform="{_xml_attr(inner_transform)}">\n {elements_str}\n </g>'return f'''<!-- icon: {_xml_attr(icon_name)} -->- <g transform="{_xml_attr(transform)}">+ <g transform="{_xml_attr(transform)}"{context_attrs}>{elements_str}</g>'''@@ -484,7 +502,7 @@ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], stylcolor_attrs = f'fill="{_xml_attr(color)}"'return f'''<!-- icon: {_xml_attr(icon_name)} -->- <g transform="{_xml_attr(transform)}" {color_attrs}>+ <g transform="{_xml_attr(transform)}" {color_attrs}{context_attrs}>{elements_str}</g>'''diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.pyindex 5d0b6cdd..76c0fcdb 100644--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py@@ -45,6 +45,8 @@ TEXT_STYLE_ATTRS = {"stroke-width","stroke-opacity","opacity",+ "display",+ "visibility","paint-order",# transforms/filters"transform",@@ -52,6 +54,8 @@ TEXT_STYLE_ATTRS = {"filter",}+TEXT_IDENTITY_ATTRS = {"id", "class", "data-name", "data-pptx-shape-name", "data-pptx-role"}+num_re = re.compile(r"^[\s,]*([+-]?(?:\d+\.?\d*|\d*\.\d+))")@@ -169,7 +173,7 @@ def copy_text_attrs(# Copy style string firstif "style" in src_el.attrib and "style" not in exclude:dst_el.set("style", src_el.attrib["style"])- for k in TEXT_STYLE_ATTRS:+ for k in TEXT_STYLE_ATTRS | TEXT_IDENTITY_ATTRS:if k in exclude:continuev = src_el.get(k)@@ -586,6 +590,7 @@ def flatten_text_with_tspans()raise ValueError(f"Unsupported nested positional <tspan>: {preview}{suffix}")parent_map = {c: p for p in root.iter() for c in p}+ used_ids = {el.get("id") for el in root.iter() if el.get("id")}changed = False# Collect candidates first to avoid modifying while iterating@@ -646,7 +651,7 @@ def flatten_text_with_tspans(current_line_lead_text = text_el.text or Nonefor idx, child in enumerate(list(text_el)):- if not _is_svg_tag(child, "tspan"):+ if not (_is_svg_tag(child, "tspan") or _is_svg_tag(child, "a")):continuecontent = collect_text_content(child)@@ -684,6 +689,16 @@ def flatten_text_with_tspans(new_texts.append(ne)if new_texts:+ # Split rows remain distinct objects, but the first row retains+ # the authored locator and later rows get collision-free ids.+ original_id = text_el.get("id")+ if original_id:+ for line_number, ne in enumerate(new_texts[1:], start=2):+ candidate = f"{original_id}-line-{line_number}"+ while candidate in used_ids:+ candidate += "-line"+ ne.set("id", candidate)+ used_ids.add(candidate)# Replace original <text> with the list of new <text> nodestry:idx = list(parent).index(text_el)@@ -794,6 +809,8 @@ def _create_text_element_from_line(if (not lead_textand len(tspans) == 1+ and _is_svg_tag(tspans[0], "tspan")+ and not any(key in tspans[0].attrib for key in TEXT_IDENTITY_ATTRS)and not _has_tspan_children(tspans[0])and not tspans[0].tailand tspans[0].get(INLINE_FORMULA_ATTR) is Nonediff --git a/skills/ppt-master/scripts/tests/test_embed_icon_content_survival.py b/skills/ppt-master/scripts/tests/test_embed_icon_content_survival.pynew file mode 100644index 00000000..c54c8304--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_embed_icon_content_survival.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Verify icon replacement retains authored identity and visibility."""++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+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))+++class IconContentSurvivalTests(unittest.TestCase):+ def test_finalize_keeps_hidden_icons_hidden_and_preserves_context(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ project = Path(temporary)+ (project / 'svg_output').mkdir()+ icon_dir = project / 'icons' / 'imported'+ icon_dir.mkdir(parents=True)+ (icon_dir / 'marker.svg').write_text(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">'+ '<path d="M2 2H22V22H2Z"/></svg>', encoding='utf-8',+ )+ (project / 'svg_output' / '01.svg').write_text(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">'+ '<use id="VISIBLE_MARK" data-icon="imported/marker" '+ 'data-pptx-role="decoration" data-edit-annotation="A & B" '+ 'x="20" y="20" width="40" height="40" fill="#123456"/>'+ '<use id="DISPLAY_MARK" data-icon="imported/marker" '+ 'x="100" y="20" width="40" height="40" display="none"/>'+ '<use id="STYLE_MARK" data-icon="imported/marker" '+ 'x="200" y="20" width="40" height="40" style="display:none"/>'+ '<use id="OPACITY_MARK" data-icon="imported/marker" '+ 'x="300" y="20" width="40" height="40" opacity="0"/>'+ '</svg>', encoding='utf-8',+ )+ result = subprocess.run(+ [sys.executable, str(SCRIPTS_DIR / 'finalize_svg.py'), str(project)],+ capture_output=True, text=True,+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ root = ET.parse(project / 'svg_final' / '01.svg').getroot()+ elements = {elem.get('id'): elem for elem in root.iter() if elem.get('id')}+ self.assertEqual(elements['VISIBLE_MARK'].get('data-pptx-role'), 'decoration')+ self.assertEqual(elements['VISIBLE_MARK'].get('data-edit-annotation'), 'A & B')+ self.assertEqual(elements['DISPLAY_MARK'].get('display'), 'none')+ self.assertEqual(elements['STYLE_MARK'].get('style'), 'display:none')+ self.assertEqual(elements['OPACITY_MARK'].get('opacity'), '0')++ from svg_editor.server import create_app++ client = create_app(str(project), idle_timeout=0).test_client()+ preview = ET.fromstring(client.get('/api/slide/01.svg').get_json()['content'])+ icon = next(elem for elem in preview.iter() if elem.get('id') == 'VISIBLE_MARK')+ self.assertEqual(icon.get('data-icon'), 'imported/marker')diff --git a/skills/ppt-master/scripts/tests/test_finalize_content_survival.py b/skills/ppt-master/scripts/tests/test_finalize_content_survival.pynew file mode 100644index 00000000..635d94bf--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_finalize_content_survival.py@@ -0,0 +1,73 @@+#!/usr/bin/env python3+"""Verify text visibility, links, and identity through finalization's public CLI."""++import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+from xml.etree import ElementTree as ET+++SCRIPTS_DIR = Path(__file__).resolve().parents[1]+SVG_NS = 'http://www.w3.org/2000/svg'+++class FinalizeContentSurvivalTests(unittest.TestCase):+ def _finalize(self, content: str) -> ET.Element:+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ project = Path(temporary.name)+ (project / 'svg_output').mkdir()+ (project / 'svg_output' / '01.svg').write_text(+ f'<svg xmlns="{SVG_NS}" viewBox="0 0 1280 720">{content}</svg>',+ encoding='utf-8',+ )+ result = subprocess.run(+ [sys.executable, str(SCRIPTS_DIR / 'finalize_svg.py'), str(project)],+ capture_output=True, text=True,+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ return ET.parse(project / 'svg_final' / '01.svg').getroot()++ def test_split_rows_retain_identity_without_duplicate_ids(self) -> None:+ root = self._finalize(+ '<text id="name" data-pptx-shape-name="SELECTION_MARK" '+ 'data-pptx-role="decoration" x="10" y="20" font-size="24">'+ '<tspan id="RUN_ID_MARK" x="10" dy="20">ONE_MARK</tspan>'+ '<tspan x="10" dy="30">TWO_MARK</tspan></text>'+ '<rect id="name-line-2" width="20" height="20"/>',+ )+ ids = [elem.get('id') for elem in root.iter() if elem.get('id')]+ self.assertEqual(len(ids), len(set(ids)))+ self.assertIn('name', ids)+ self.assertIn('RUN_ID_MARK', ids)+ rows = root.findall(f'{{{SVG_NS}}}text')+ self.assertEqual(len(rows), 2)+ self.assertEqual(rows[0].get('data-pptx-shape-name'), 'SELECTION_MARK')+ self.assertEqual(rows[1].get('data-pptx-role'), 'decoration')+ self.assertEqual(''.join(root.itertext()), 'ONE_MARKTWO_MARK')++ def test_direct_inline_anchor_and_tail_survive_split(self) -> None:+ root = self._finalize(+ '<text x="10" y="20" font-size="24">LEAD_MARK'+ '<a href="https://example.com/LINK_MARK">ANCHOR_MARK</a>TAIL_MARK'+ '<tspan x="10" dy="30">NEXT_MARK</tspan></text>',+ )+ self.assertEqual(''.join(root.itertext()), 'LEAD_MARKANCHOR_MARKTAIL_MARKNEXT_MARK')+ anchor = root.find(f'.//{{{SVG_NS}}}a')+ self.assertIsNotNone(anchor)+ self.assertEqual(anchor.get('href'), 'https://example.com/LINK_MARK')++ def test_parent_and_row_visibility_survive_split(self) -> None:+ root = self._finalize(+ '<text display="none" x="10" y="20" font-size="24">'+ '<tspan x="10" dy="20">HIDDEN_PARENT_MARK</tspan></text>'+ '<text x="10" y="80" font-size="24">'+ '<tspan visibility="hidden" x="10" dy="20">HIDDEN_ROW_MARK</tspan>'+ '<tspan x="10" dy="30">VISIBLE_MARK</tspan></text>',+ )+ rows = {''.join(elem.itertext()): elem for elem in root.findall(f'{{{SVG_NS}}}text')}+ self.assertEqual(rows['HIDDEN_PARENT_MARK'].get('display'), 'none')+ self.assertEqual(rows['HIDDEN_ROW_MARK'].get('visibility'), 'hidden')+ self.assertIsNone(rows['VISIBLE_MARK'].get('visibility'))diff --git a/skills/ppt-master/scripts/tests/test_svg_editor_content_survival.py b/skills/ppt-master/scripts/tests/test_svg_editor_content_survival.pynew file mode 100644index 00000000..838113cc--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_svg_editor_content_survival.py@@ -0,0 +1,64 @@+#!/usr/bin/env python3+"""Exercise untouched local references through the live-preview save routes."""++import sys+import tempfile+import unittest+from pathlib import Path+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_editor.server import create_app # noqa: E402+++class EditorContentSurvivalTests(unittest.TestCase):+ def test_save_preserves_referenced_ids_and_untouched_content(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ project = Path(temporary)+ (project / 'svg_output').mkdir()+ path = project / 'svg_output' / '01.svg'+ path.write_text(+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1280 720">'+ '<defs><linearGradient id="_edit_0"><stop offset="0" stop-color="#123456"/>'+ '<stop offset="1" stop-color="#ABCDEF"/></linearGradient>'+ '<clipPath id="_edit_2"><rect width="60" height="40"/></clipPath>'+ '<g id="_edit_3"><text x="10" y="30">USE_MARK</text></g></defs>'+ '<style>#_edit_4 { visibility:hidden }</style>'+ '<rect id="box" x="10" width="100" height="80" fill="url(#_edit_0)" '+ 'style="clip-path:url(\'#_edit_2\')" data-pptx-role="decoration"/>'+ '<use xlink:href="#_edit_3"/>'+ '<text id="text" x="10" y="200">TEXT_MARK<tspan>RUN_MARK</tspan></text>'+ '<a href="https://example.com/LINK_MARK"><text>LINK_TEXT_MARK</text></a>'+ '<text id="_edit_4" style="display:none">HIDDEN_MARK</text></svg>',+ encoding='utf-8',+ )+ client = create_app(str(project), idle_timeout=0).test_client()+ preview = ET.fromstring(client.get('/api/slide/01.svg').get_json()['content'])+ preview_ids = [elem.get('id') for elem in preview.iter() if elem.get('id')]+ self.assertEqual(len(preview_ids), len(set(preview_ids)))+ for marker in ('_edit_0', '_edit_2', '_edit_3', '_edit_4'):+ self.assertIn(marker, preview_ids)+ response = client.post('/api/slide/01.svg/edit', json={+ 'element_id': 'box', 'attrs': {'x': '15'},+ })+ self.assertEqual(response.status_code, 200)+ client.post('/api/slide/01.svg/annotate', json={+ 'element_id': 'text', 'annotation': 'ANNOTATION_MARK',+ })+ saved = client.post('/api/save-all').get_json()+ self.assertEqual(saved['files_modified'], ['01.svg'])+ root = ET.parse(path).getroot()+ ids = {elem.get('id') for elem in root.iter()}+ for marker in ('_edit_0', '_edit_2', '_edit_3', '_edit_4'):+ self.assertIn(marker, ids)+ text = path.read_text(encoding='utf-8')+ for marker in ('USE_MARK', 'TEXT_MARK', 'RUN_MARK', 'LINK_MARK',+ 'LINK_TEXT_MARK', 'HIDDEN_MARK', 'ANNOTATION_MARK'):+ self.assertIn(marker, text)+ hidden = next(elem for elem in root.iter() if elem.text == 'HIDDEN_MARK')+ self.assertEqual(hidden.get('style'), 'display:none')