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(svg-editor): browser preview, revised-project derivation, opt-in workflow

hugohe3af3453fef4c7
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 88c78b60..08b0ce28 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -336,38 +336,40 @@ Full effect list, anchor logic, and limits: [`references/animations.md`](referen
> ❌ **NEVER** export from `svg_output/` — MUST use `-s final` (exports from `svg_final/`)
> ❌ **NEVER** use `--only` (it suppresses one of the two output files)
-**Step 7.4: SVG Editor — MUST execute**
+**Step 7.4: SVG Editor — opt-in only**
-After PPTX export, **MUST** start the SVG editor for the user:
+This step is **OPTIONAL**. Do **NOT** run it as part of the default flow. Run it **only** when the user explicitly asks for fine-grained visual edits (any wording — recognize intent, don't match keywords).
+
+When such an intent is detected, ask the user (in their language) whether they want to launch the visual editor.
+
+If the user confirms, start the editor. The server will automatically derive a `<project>_revised_<timestamp>/` copy beside the original project, so the original is preserved untouched:
```bash
python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --no-browser
```
-Then tell the user:
-> SVG 编辑器已启动,请在浏览器打开: http://localhost:5000
-> 在浏览器中选择元素并添加批注,完成后在编辑器中点击"保存",然后回来告诉我。
-
-**❌ NEVER skip Step 7.4.** After PPTX export, always start the editor. Do not ask the user whether they want it — just start it. The user decides whether to use it or ignore it.
+Read the printed `Derived revised project: <revised_path>` line, then inform the user (in their language) that:
+- the editor is running at `http://localhost:5050`
+- they should click an element in the browser, add an annotation, and save when done
+- changes will be written to the derived copy `<revised_path>`, not the original
-**Edit Loop (When User Requests Annotation-Based Editing):**
+**Edit Loop (Triggered After User Submits Annotations):**
-When the user indicates they have submitted annotations (e.g. "已提交标注", "标注好了", "继续修改", "根据标注改", "帮我改", "改好了", or any similar intent — do NOT require exact wording, recognize the user's intent to have AI read and apply the saved annotations):
+When the user indicates (in any wording) that they have submitted annotations and want the AI to apply them:
1. The server will have auto-shut down after the user saved (port is released). If it's still running, kill it.
-2. Run `python3 ${SKILL_DIR}/scripts/check_annotations.py <project_path>` to discover annotations
+2. Run `python3 ${SKILL_DIR}/scripts/check_annotations.py <revised_project_path>` to discover annotations
3. If no annotations found, inform the user and stop
-4. Read each annotated SVG file from `svg_output/`
+4. Read each annotated SVG file from `<revised_project_path>/svg_output/`
5. For each annotation: modify the target SVG element per the user's instruction
6. Remove `data-edit-target` and `data-edit-annotation` attributes from modified elements
-7. Remove temporary `_edit_N` id attributes from elements that did not have a user-assigned id originally
-8. Re-run Step 7 post-processing: `finalize_svg.py` → `svg_to_pptx.py`
-9. Re-start the SVG editor server:
+7. Re-run Step 7 post-processing on the revised project: `finalize_svg.py` → `svg_to_pptx.py`
+8. Re-start the SVG editor server pointing at the **same** revised project (it already contains `_revised_` in the name, so no further derivation happens):
```bash
- python3 ${SKILL_DIR}/scripts/svg_editor/server.py <project_path> --no-browser
+ python3 ${SKILL_DIR}/scripts/svg_editor/server.py <revised_project_path> --no-browser
```
-10. Tell the user: "标注已处理,PPT 已更新。编辑器已重启: http://localhost:5000 。无需标注时告诉我即可。"
-11. Wait for the user's next message. If they indicate they are done (e.g. "好了", "可以了", "不需要了", "结束"), the editing loop ends. If they submit more annotations, return to step 1.
+9. Inform the user (in their language) that annotations have been applied, the PPT has been updated, and the editor is running again at `http://localhost:5050`.
+10. Wait for the user's next message. If they indicate they are done, the editing loop ends. If they submit more annotations, return to step 1.
---
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index 35f0d7c5..be654415 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -18,11 +18,14 @@ Dependencies:
import argparse
import os
+import re
+import shutil
import sys
import threading
import time
import webbrowser
import xml.etree.ElementTree as ET
+from datetime import datetime
from pathlib import Path
from typing import Optional
@@ -33,18 +36,89 @@ _SCRIPTS_DIR = Path(__file__).resolve().parent
if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
+_FINALIZE_DIR = _SCRIPTS_DIR.parent / 'svg_finalize'
+if str(_FINALIZE_DIR) not in sys.path:
+ sys.path.insert(0, str(_FINALIZE_DIR))
+
from annotations import ( # noqa: E402
assign_temp_ids,
parse_annotations,
set_annotation,
remove_annotation,
)
+from embed_icons import ( # noqa: E402
+ parse_use_element,
+ resolve_icon_path,
+ extract_paths_from_icon,
+ generate_icon_group,
+)
+
+_ICONS_DIR = _SCRIPTS_DIR.parent.parent / 'templates' / 'icons'
+_USE_ICON_PATTERN = re.compile(r'<use\s+[^>]*data-icon="[^"]*"[^>]*/>')
+
+
+def _inline_icons(content: str) -> str:
+ """Replace <use data-icon="..."/> with rendered <g> for browser preview.
+
+ Preserves the original <use>'s id on the produced <g> so editor element
+ targeting (and AI-side annotation lookups against svg_output) stays consistent.
+ """
+ matches = list(_USE_ICON_PATTERN.finditer(content))
+ if not matches:
+ return content
+ new_content = content
+ for match in reversed(matches):
+ use_str = match.group(0)
+ try:
+ attrs = parse_use_element(use_str)
+ icon_name = attrs.get('icon')
+ if not icon_name:
+ continue
+ icon_path, _ = resolve_icon_path(str(icon_name), _ICONS_DIR)
+ color = str(attrs.get('fill', '#000000'))
+ elements, style, base_size = extract_paths_from_icon(icon_path, color)
+ except Exception:
+ continue
+ if not elements:
+ continue
+ replacement = generate_icon_group(attrs, elements, style, base_size)
+ id_match = re.search(r'\bid="([^"]+)"', use_str)
+ if id_match:
+ replacement = replacement.replace(
+ '<g ', f'<g id="{id_match.group(1)}" data-icon="{icon_name}" ', 1,
+ )
+ new_content = new_content[:match.start()] + replacement + new_content[match.end():]
+ return new_content
+
+
+def derive_revised_project(source: Path) -> Path:
+ """Create a `<name>_revised_<timestamp>/` sibling and copy required subdirs.
+
+ Idempotent: if `source` already looks like a revised copy, returns it as-is.
+ Copies svg_output/ (required) and images/, sources/, metadata.json if present.
+ """
+ if '_revised_' in source.name:
+ return source
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
+ target = source.parent / f'{source.name}_revised_{timestamp}'
+ target.mkdir(parents=True, exist_ok=False)
+ shutil.copytree(source / 'svg_output', target / 'svg_output')
+ for sub in ('images', 'sources'):
+ sub_path = source / sub
+ if sub_path.exists():
+ shutil.copytree(sub_path, target / sub)
+ for f in ('metadata.json', 'README.md'):
+ fp = source / f
+ if fp.exists():
+ shutil.copy2(fp, target / f)
+ return target
def create_app(project_dir: str, idle_timeout: int = 900) -> Flask:
"""Create and configure the Flask app for a given project directory."""
project_path = Path(project_dir).resolve()
svg_dir = project_path / 'svg_output'
+ images_dir = project_path / 'images'
app = Flask(__name__, static_folder='static', static_url_path='/static')
app.config['PROJECT_PATH'] = project_path
@@ -87,6 +161,24 @@ def create_app(project_dir: str, idle_timeout: int = 900) -> Flask:
def index():
return send_from_directory(app.static_folder, 'index.html')
+ @app.route('/images/<path:filename>')
+ def serve_image(filename: str):
+ """Serve images referenced by SVGs as `../images/*.png`.
+
+ Resolution against an absolute images_dir + relative_to() check is the
+ authoritative path-traversal guard.
+ """
+ if not images_dir.exists():
+ return jsonify({'error': 'images directory not found'}), 404
+ target = (images_dir / filename).resolve()
+ try:
+ target.relative_to(images_dir.resolve())
+ except ValueError:
+ return jsonify({'error': 'invalid path'}), 400
+ if not target.exists() or not target.is_file():
+ return jsonify({'error': 'not found'}), 404
+ return send_from_directory(str(images_dir), filename)
+
@app.route('/api/slides')
def get_slides():
svg_dir = app.config['SVG_DIR']
@@ -167,6 +259,8 @@ def create_app(project_dir: str, idle_timeout: int = 900) -> Flask:
})
content = ET.tostring(root, encoding='unicode', xml_declaration=False)
+ # Inline <use data-icon> placeholders so the browser can render icons.
+ content = _inline_icons(content)
return jsonify({
'name': name,
@@ -243,6 +337,15 @@ def create_app(project_dir: str, idle_timeout: int = 900) -> Flask:
for element_id, annotation_text in anns.items():
set_annotation(root, element_id, annotation_text)
+ # Strip transient _edit_N ids from elements that are NOT user-annotated.
+ # Only annotated elements need to keep their id so the AI can locate them
+ # via check_annotations.py; the rest are pollution.
+ annotated_ids = set(anns.keys())
+ for elem in root.iter():
+ eid = elem.get('id', '')
+ if eid.startswith('_edit_') and eid not in annotated_ids:
+ elem.attrib.pop('id', None)
+
tree.write(str(svg_file), encoding='UTF-8', xml_declaration=True)
modified.append(filename)
@@ -259,9 +362,14 @@ def build_parser() -> argparse.ArgumentParser:
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('project_dir', help='Path to project directory (contains svg_output/)')
- parser.add_argument('--port', type=int, default=5000, help='Port to listen on (default: 5000)')
+ parser.add_argument('--port', type=int, default=5050, help='Port to listen on (default: 5050)')
parser.add_argument('--no-browser', action='store_true', help='Do not auto-open browser')
parser.add_argument('--timeout', type=int, default=900, help='Idle timeout in seconds (default: 900 = 15min)')
+ parser.add_argument(
+ '--no-derive',
+ action='store_true',
+ help='Edit svg_output in place instead of deriving a `<name>_revised_<timestamp>/` copy',
+ )
return parser
@@ -274,6 +382,12 @@ def main(argv: Optional[list[str]] = None) -> int:
print(f"Error: {project_path / 'svg_output'} does not exist", file=sys.stderr)
return 1
+ if not args.no_derive:
+ derived = derive_revised_project(project_path)
+ if derived != project_path:
+ print(f"Derived revised project: {derived}")
+ project_path = derived
+
app = create_app(str(project_path), idle_timeout=args.timeout)
url = f'http://localhost:{args.port}'