Skip to content

Agent-driven creation of editable, tastefully crafted visual artifacts.

Python

Update HTML to PPTX page detection

Junyanye5e657d7588a4
diff --git a/README.md b/README.md
index 4fc05f6..8897dd1 100644
--- a/README.md
+++ b/README.md
@@ -58,7 +58,7 @@ This repository now ships the code behind the workflow as two independent Codex
| Skill | Purpose | Main outputs |
| --- | --- | --- |
| [`editable-design`](./skills/editable-design/) | Create polished fixed-canvas visual designs from a brief | HTML, PNG, mouse editor, animated layer breakdown, and Agent Design Replay |
-| [`html-to-pptx`](./skills/html-to-pptx/) | Optionally convert compatible HTML into editable PowerPoint | Editable `.pptx` with independently selectable elements where the source structure permits |
+| [`html-to-pptx`](./skills/html-to-pptx/) | Convert clean designs, editor pages, or exploded-layer HTML into editable PowerPoint | Editable `.pptx` with independently selectable elements where the source structure permits |
`editable-design` is the complete core workflow and does not require PowerPoint support. `html-to-pptx` is a sibling tool that runs only when a PPTX is requested. Installation is covered in [Quick Start](#quick-start); the standalone [Toolkit guide](./TOOLKIT.md) and each skill's README contain the detailed requirements and direct commands.
diff --git a/TOOLKIT.md b/TOOLKIT.md
index d366b55..6b8762c 100644
--- a/TOOLKIT.md
+++ b/TOOLKIT.md
@@ -11,9 +11,9 @@ See the public [Editable Visual Design Gallery](https://github.com/yejy53/Editab
| Skill | Purpose | Main outputs |
| --- | --- | --- |
| [`editable-design`](skills/editable-design/) | Create polished posters, covers, campaign graphics, information designs, menus, banners, and social cards | `index.html`, rendered PNG, `editor.html`, `layers.html`, and `replay/index.html` |
-| [`html-to-pptx`](skills/html-to-pptx/) | Convert compatible fixed-canvas HTML into an editable PowerPoint file | Editable `.pptx` with independently selectable elements where the source structure permits |
+| [`html-to-pptx`](skills/html-to-pptx/) | Convert clean fixed-canvas HTML, Editable Design editor pages, or exploded-layer boards | Editable `.pptx` with independently selectable elements where the source structure permits |
-The skills are siblings, not nested dependencies. `editable-design` completes its normal HTML and PNG delivery without PowerPoint support. `html-to-pptx` runs only when the user asks for a PPTX and can also convert compatible HTML produced elsewhere.
+The skills are siblings, not nested dependencies. `editable-design` completes its normal HTML and PNG delivery without PowerPoint support. `html-to-pptx` runs only when the user asks for a PPTX and automatically recognizes clean design HTML, `editor.html`, and `layers.html`; it can also convert compatible HTML produced elsewhere.
## Install
diff --git a/skills/html-to-pptx/README.md b/skills/html-to-pptx/README.md
index 09d6d7c..7d81618 100644
--- a/skills/html-to-pptx/README.md
+++ b/skills/html-to-pptx/README.md
@@ -1,6 +1,6 @@
# HTML to Editable PPTX
-`html-to-pptx` is an independent Codex skill that deterministically converts compatible slide, poster, and fixed-canvas HTML into an editable PowerPoint file. It also supports `layers.html` exploded-layer boards and an optional visual comparison workflow.
+`html-to-pptx` is an independent Codex skill that deterministically converts compatible slide, poster, and fixed-canvas HTML into an editable PowerPoint file. One entry point automatically handles clean design HTML, Editable Design's `editor.html`, and `layers.html` exploded-layer boards.
## Requirements
@@ -26,11 +26,14 @@ python3 -m pip install -r requirements-check.txt
```bash
python3 scripts/to_pptx.py /path/to/index.html -o /path/to/design.pptx
-python3 scripts/exploded_to_pptx.py /path/to/layers.html
+python3 scripts/to_pptx.py /path/to/editor.html
+python3 scripts/to_pptx.py /path/to/layers.html --keep-overview
python3 scripts/render_check.py /path/to/index.html /path/to/design.pptx
```
-Use the original `index.html` or an editor-downloaded `*.edited.html` beside its assets. Do not pass an editor shell such as `editor.html`.
+The default `--mode auto` recognizes `plain`, `editor`, and `exploded` pages. For `editor.html`, it calls the editor's own `fullHTML()` export to remove the toolbar, panels, and scaled stage before conversion. For `layers.html`, it waits for the animation to settle and removes the overview by default. Use `--mode` only when automatic detection needs to be overridden.
+
+Keep the HTML beside its assets so relative image, CSS, and font paths resolve correctly.
Editable Design is a supported source of HTML, but it is not required. This skill runs only when PPTX conversion is requested.
diff --git a/skills/html-to-pptx/SKILL.md b/skills/html-to-pptx/SKILL.md
index 7badb0a..00f9e27 100644
--- a/skills/html-to-pptx/SKILL.md
+++ b/skills/html-to-pptx/SKILL.md
@@ -1,6 +1,6 @@
---
name: html-to-pptx
-description: 把 slide/poster 的 HTML 确定性地转成可编辑 PPTX——每个视觉元素(插画、图标、箭头、装饰线、文字)都是能单独选中拖动的对象,而不是压成一张背景图;也能把 case 的图层展开图 layers.html 转成一页可编辑 PPTX;并可把产物渲回图片做保真度比对。当用户要导出 pptx/ppt、问「HTML 怎么转 PowerPoint」、想让生成的海报或幻灯片能在 PowerPoint 里继续改、要把图层展开图/拆解图变成 ppt、或需要检查转换后元素是否独立可编辑时使用。
+description: 把 slide/poster 的 HTML 确定性地转成可编辑 PPTX——每个视觉元素(插画、图标、箭头、装饰线、文字)都是能单独选中拖动的对象,而不是压成一张背景图;也能自动识别并转换 Editable Design 的 editor.html 和 case 的图层展开图 layers.html;并可把产物渲回图片做保真度比对。当用户要导出 pptx/ppt、问「HTML 怎么转 PowerPoint」、想让生成的海报或幻灯片能在 PowerPoint 里继续改、要把图层展开图/拆解图变成 ppt、或需要检查转换后元素是否独立可编辑时使用。
---
# HTML → 可编辑 PPTX
@@ -27,15 +27,33 @@ python3 -m playwright install chromium
## 转换
+一个入口支持三类页面并自动识别:
+
```bash
-python3 scripts/to_pptx.py <index.html> # → 同目录同名 .pptx
-python3 scripts/to_pptx.py <index.html> -o deck.pptx
-python3 scripts/to_pptx.py <index.html> --selector '#hero' # 画布识别失败时手动指定
+python3 scripts/to_pptx.py <任意 HTML> # → 同目录同名 .pptx
+python3 scripts/to_pptx.py <HTML> -o deck.pptx
+python3 scripts/to_pptx.py <HTML> --selector '#hero' # 画布识别失败时手动指定
+python3 scripts/to_pptx.py <HTML> --mode exploded # 自动识别出错时手动指定
```
-输出示例,**先看这行确认画布和元素分布是否合理**:
+| 输入页面 | 自动模式 | 转换前处理 |
+| --- | --- | --- |
+| `index.html`、`*.edited.html` | `plain` | 直接测量固定画布 |
+| `editor.html` | `editor` | 调用编辑器的 `fullHTML()`,剥掉工具栏、面板和缩放舞台 |
+| `layers.html` | `exploded` | 等动画落位、去除 overview、关闭响应式缩放 |
+
+判别信号来自页面本身:编辑器暴露 `__layerEditor`/`__freeEditor.fullHTML()`,展开图包含
+`.hf-exploded-board`。如果页面像编辑器但 API 没有成功加载,转换会停止并报错,不会把
+编辑器 UI 悄悄写进 PPTX。
+
+`editor.html` 使用的 `fullHTML()` 与编辑器的 “Download HTML” 按钮是同一条官方导出路径。
+临时 HTML 写在原文件旁边以保留相对图片和字体路径,转换完成后立即删除。
+
+输出示例,**先确认页面类型、画布和元素分布是否合理**:
```
+页面类型:editor(自动识别)
+ 编辑器 fullHTML() 导出 15 KB,已剥掉编辑器外壳
✅ /path/dragon_poster.pptx
画布 1067x1600 ([data-canvas-width]) · 形状 4 · 文本框 10 · 独立图片 13 · 元素 28
```
@@ -47,7 +65,9 @@ python3 scripts/to_pptx.py <index.html> --selector '#hero' # 画布识别失败
PPTX,默认丢掉 overview 那一项:
```bash
-python3 scripts/exploded_to_pptx.py <case>/layers.html # → 同目录 layers.pptx
+python3 scripts/to_pptx.py <case>/layers.html # → 同目录 layers.pptx
+python3 scripts/to_pptx.py <case>/layers.html --keep-overview
+python3 scripts/exploded_to_pptx.py <case>/layers.html # 等价的专用入口
python3 scripts/exploded_to_pptx.py <case>/layers.html --keep-overview
```
@@ -59,8 +79,8 @@ board 3060x2400 · 分块 26 (跳过 overview 1)· {'layer': 12, 'group': 13
粒度是**元素级**而非分块级:每块内部的每行字、每张照片、每张卡片都是独立对象。
-这类页面有三个特性会干扰通用转换,`exploded_to_pptx.py` 在量画布之前一次性抹平,
-所以**不要直接用 `to_pptx.py` 指向 board**:
+这类页面有三个特性会干扰通用转换,`to_pptx.py` 识别后会转入
+`exploded_to_pptx.py`,在量画布之前一次性抹平:
1. board 会按窗口自适应缩放,而转换器又要把视口调成画布大小,两者互相触发、越缩越小。
用 `!important` 规则钉死 `transform`,压过页面脚本写的 inline style。
@@ -190,9 +210,10 @@ z-index:1` 的卡片会排到自己子元素后面,用底色盖住自己的图
源 HTML 整页画在**一个大 `<svg>`** 里。SVG 内部节点不拆——这类页面没有可分的顶层结构,
是转换器的已知限制,不是 bug。要拆得改 HTML 生成侧,让结构落在 DOM 元素上。
-**传错文件**
-别传编辑器外壳 `editor.html`(编辑器 UI 会被一起拍进去)。传原始 `index.html`,
-或 Editable Design 编辑器「下载 HTML」导出的 `*.edited.html`。
+**编辑器 UI 被拍进了 PPTX**
+说明页面被当作 `plain` 转换了。正常的 Editable Design `editor.html` 会被自动识别并调用
+`fullHTML()`;如果编辑器 API 没有成功加载,改传原始 `index.html` 或编辑器下载的
+`*.edited.html`。
**相对资源(css/字体/图片)丢失**
按 HTML 所在目录解析,所以在原目录里跑最稳。
@@ -217,4 +238,5 @@ HTML、PNG、浏览器编辑器和设计回放;本 Skill 只负责把用户指
当 Editable Design 已完成核心设计,如果本 Skill 可用,可以向用户简短说明“还可以导出为
可编辑 PPTX”。**只有用户明确说需要时才运行转换**,不能让 PPTX 导出阻塞或延迟核心设计交付。
-转换时使用原始 `index.html` 或编辑器下载的 `*.edited.html`,绝不使用 `editor.html`。
+转换时可使用原始 `index.html`、编辑器下载的 `*.edited.html`、正常加载的 `editor.html`
+或 `layers.html`;入口会自动选择对应的预处理路径。
diff --git a/skills/html-to-pptx/scripts/exploded_to_pptx.py b/skills/html-to-pptx/scripts/exploded_to_pptx.py
index 64b0fc2..4d160d1 100755
--- a/skills/html-to-pptx/scripts/exploded_to_pptx.py
+++ b/skills/html-to-pptx/scripts/exploded_to_pptx.py
@@ -7,6 +7,8 @@
用法:
python3 exploded_to_pptx.py <layers.html> [-o out.pptx] [--keep-overview]
+通常不必直接调它 —— ``to_pptx.py`` 会自动认出展开图并转到这里。
+
页面自身的三个特性会干扰通用转换器,这里在量画布之前一次性抹平:
1. board 会按窗口大小自适应缩放,而转换器又要把视口调成画布大小 —— 两者互相触发,
越缩越小。用 !important 规则钉死 transform,压过页面脚本写的 inline style。
@@ -91,8 +93,8 @@ PROBE_JS = r"""
"""
-def _locate_converter():
- """从本 Skill 自带的确定性转换核心加载模块。"""
+def locate_converter():
+ """Load the deterministic conversion core vendored with this Skill."""
vendored = Path(__file__).resolve().with_name("_html_to_pptx.py")
if vendored.is_file():
spec = importlib.util.spec_from_file_location("_wca_html_to_pptx", vendored)
@@ -105,11 +107,16 @@ def _locate_converter():
raise ModuleNotFoundError("缺少本 Skill 的 scripts/_html_to_pptx.py")
+# 老名字,外部可能还在用
+_locate_converter = locate_converter
+
+
def _browser_args() -> list[str]:
+ """Keep Chromium sandboxing on unless the host explicitly opts out."""
return ["--no-sandbox"] if os.environ.get("HTML_TO_PPTX_NO_SANDBOX") == "1" else []
-def _probe(src: Path) -> dict:
+def probe(src: Path) -> dict:
"""先量一遍 board:拿自然尺寸定视口,顺便报告分块构成。"""
from playwright.sync_api import sync_playwright
@@ -127,6 +134,43 @@ def _probe(src: Path) -> dict:
browser.close()
+_probe = probe
+
+
+def convert(src: Path, out: Path, *, keep_overview: bool = False, quiet: bool = False) -> dict:
+ """layers.html → 一页 pptx。返回 build_editable_pptx 的 manifest。"""
+ converter = locate_converter()
+ info = probe(src)
+ if not info:
+ raise RuntimeError(f"页面里没有 {BOARD},这不是一张图层展开图")
+
+ kept = [i for i in info["items"] if keep_overview or not i["overview"]]
+ if not quiet:
+ units: dict[str, int] = {}
+ for item in kept:
+ units[item["unit"]] = units.get(item["unit"], 0) + 1
+ print(
+ f"board {info['width']:.0f}x{info['height']:.0f} · 分块 {len(kept)} "
+ f"(跳过 overview {len(info['items']) - len(kept)})· {units}"
+ )
+
+ prepare = f"() => ({PREPARE_JS})({json.dumps({'keepOverview': keep_overview})})"
+ work = Path(tempfile.mkdtemp(prefix="exploded_pptx_"))
+ manifest = converter.build_editable_pptx(
+ src,
+ work,
+ out_name=out.name,
+ canvas_selector=BOARD,
+ use_llm=False,
+ ready_selector=READY,
+ prepare_js=prepare,
+ viewport=(int(info["width"]), int(info["height"])),
+ )
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(Path(manifest["pptx_path"]).read_bytes())
+ return manifest
+
+
def main() -> None:
ap = argparse.ArgumentParser(description="layers.html 图层展开图 -> 一页可编辑 PPTX")
ap.add_argument("html", help="case 的 layers.html")
@@ -141,41 +185,11 @@ def main() -> None:
out = Path(args.out).resolve() if args.out else src.with_suffix(".pptx")
try:
- converter = _locate_converter()
+ manifest = convert(src, out, keep_overview=args.keep_overview)
except Exception as exc: # noqa: BLE001
- sys.stderr.write(f"无法加载转换器: {exc}\n")
- sys.exit(1)
-
- info = _probe(src)
- if not info:
- sys.stderr.write(f"页面里没有 {BOARD},这不是一张图层展开图。\n")
+ sys.stderr.write(f"{exc}\n")
sys.exit(2)
- kept = [i for i in info["items"] if args.keep_overview or not i["overview"]]
- dropped = len(info["items"]) - len(kept)
- units: dict[str, int] = {}
- for item in kept:
- units[item["unit"]] = units.get(item["unit"], 0) + 1
- print(
- f"board {info['width']:.0f}x{info['height']:.0f} · 分块 {len(kept)} "
- f"(跳过 overview {dropped})· {units}"
- )
-
- prepare = f"() => ({PREPARE_JS})({json.dumps({'keepOverview': args.keep_overview})})"
- work = Path(tempfile.mkdtemp(prefix="exploded_pptx_"))
- manifest = converter.build_editable_pptx(
- src,
- work,
- out_name=out.name,
- canvas_selector=BOARD,
- use_llm=False,
- ready_selector=READY,
- prepare_js=prepare,
- viewport=(int(info["width"]), int(info["height"])),
- )
- produced = Path(manifest["pptx_path"])
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_bytes(produced.read_bytes())
print(
f"✅ {out}\n 形状 {manifest['shape_count']} · 文本框 {manifest['text_count']} · "
f"独立图片 {manifest['picture_count']} · 元素 {manifest['element_count']}"
diff --git a/skills/html-to-pptx/scripts/to_pptx.py b/skills/html-to-pptx/scripts/to_pptx.py
index 9f453b0..fa9d430 100755
--- a/skills/html-to-pptx/scripts/to_pptx.py
+++ b/skills/html-to-pptx/scripts/to_pptx.py
@@ -1,84 +1,234 @@
#!/usr/bin/env python3
"""to_pptx —— slide / poster HTML → 可编辑 PPTX(离线、纯确定性、无服务、无 LLM)。
-复用仓库现成的 ``build_editable_pptx(use_llm=False)``:自动识别画布(``.slide-canvas``
-/ ``.poster-canvas`` / ``[data-canvas-width]`` / ``#poster``)、按真实宽高比定幻灯片
-尺寸 → 量每个元素盒子/样式 → 四分类(text/shape/picture/image) → python-pptx 生成。
-每个视觉元素(图标、箭头、插画)都是独立可拖动对象,而不是压成一张背景图。
+一个入口吃三种页面,自己认,不用你分:
+
+ · 普通 slide / poster(``index.html``、编辑器导出的 ``*.edited.html``)
+ · 编辑器页面 ``editor.html`` —— 海报外面套着工具栏/图层面板/缩放舞台
+ · 图层展开图 ``layers.html`` —— 一块板上摊开各图层,还带 overview 和入场动画
+
+三条路最终都调同一个 ``build_editable_pptx(use_llm=False)``:识别画布 → 按真实宽高比
+定幻灯片尺寸 → 量每个元素的盒子和样式 → 四分类(text/shape/picture/image) → 生成 pptx。
+每个视觉元素(图标、箭头、插画)都是独立可拖对象,而不是压成一张背景图。
+
+差别只在**量画布之前怎么把页面弄成可测量的状态**,转换器为此留了
+``prepare_js`` / ``ready_selector`` / ``viewport`` 三个钩子:
+
+ · 普通页面:什么都不用做。
+ · editor.html:调编辑器自己暴露的 ``fullHTML()``(即「Download HTML」按钮的输出)
+ 拿到剥掉外壳的干净 HTML。用它的官方导出路径,就不会和编辑器实现漂移。
+ · layers.html:转给 ``exploded_to_pptx``,那里有等动画落位、去 overview、
+ 关响应式缩放的整套预处理。
用法:
- python3 to_pptx.py <slide-or-poster.html> [-o out.pptx] [--selector .slide-canvas]
+ python3 to_pptx.py <html> [-o out.pptx] [--selector .slide-canvas]
+ [--mode auto|plain|editor|exploded] [--keep-overview]
-约定:
- · 传编辑器「下载 HTML」导出的 slide.edited.html,或原始 index.html。
- **不要**传 editor.html(那里含编辑器外壳,会被一起拍进去)。
- · 相对资源(css/字体/图片)按 HTML 所在目录解析,所以在原目录里跑最稳。
+相对资源(css/字体/图片)按 HTML 所在目录解析,所以在原目录里跑最稳。
-依赖(与 harness 一致):playwright(Python) + python-pptx + Pillow。
+依赖:playwright(Python) + python-pptx + Pillow + numpy。
"""
from __future__ import annotations
import argparse
-import importlib.util
+import os
import sys
import tempfile
from pathlib import Path
+EDITOR_READY = "html[data-hf-ready='1']"
-def _locate_converter():
- """从本 Skill 自带的确定性转换核心加载 ``build_editable_pptx``。"""
- vendored = Path(__file__).resolve().with_name("_html_to_pptx.py")
- if vendored.is_file():
- spec = importlib.util.spec_from_file_location("_wca_html_to_pptx", vendored)
- if spec is None or spec.loader is None:
- raise ImportError(f"无法创建转换器加载器: {vendored}")
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module.build_editable_pptx
+# 三种页面的判别信号都很硬,不靠猜:编辑器会把 API 挂到 window 上,展开图有 board 容器。
+CLASSIFY_JS = """() => {
+ const api = window.__layerEditor || window.__freeEditor || null;
+ return {
+ editor: !!(api && typeof api.fullHTML === 'function'),
+ editorChrome: !!(document.querySelector('.hf-stage-wrap') && document.querySelector('.hf-bar')),
+ exploded: !!document.querySelector('.hf-exploded-board'),
+ };
+}"""
+
+SETTLED_JS = """() => !!(window.__layerEditor || window.__freeEditor)
+ || !!document.querySelector('.hf-exploded-board')"""
+
+GRAB_HTML_JS = """() => {
+ const api = window.__layerEditor || window.__freeEditor;
+ return (api && typeof api.fullHTML === 'function') ? api.fullHTML() : null;
+}"""
+
+
+def _browser_args() -> list[str]:
+ """Keep Chromium sandboxing on unless the host explicitly opts out."""
+ return ["--no-sandbox"] if os.environ.get("HTML_TO_PPTX_NO_SANDBOX") == "1" else []
+
+
+def _exploded_module():
+ """同目录的 exploded_to_pptx,用文件路径加载,免得依赖包结构。"""
+ import importlib.util
+
+ path = Path(__file__).resolve().parent / "exploded_to_pptx.py"
+ spec = importlib.util.spec_from_file_location("_wca_exploded", path)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"无法创建展开图转换器加载器: {path}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
- raise ModuleNotFoundError("缺少本 Skill 的 scripts/_html_to_pptx.py")
+
+def _locate_converter():
+ """Load the deterministic conversion core bundled with this Skill."""
+ return _exploded_module().locate_converter()
+
+
+def classify(src: Path) -> str:
+ """开一次页面,认出它是 plain / editor / exploded。"""
+ from playwright.sync_api import sync_playwright
+
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(args=_browser_args())
+ try:
+ page = browser.new_page(viewport={"width": 1600, "height": 1000})
+ page.goto(src.as_uri(), wait_until="load", timeout=30000)
+ # 编辑器和展开图都在 load 之后才装配,给它们一点时间;普通页面会等满后放行
+ try:
+ page.wait_for_function(SETTLED_JS, timeout=5000)
+ except Exception: # noqa: BLE001
+ pass
+ flags = page.evaluate(CLASSIFY_JS)
+ finally:
+ browser.close()
+
+ if flags["editor"]:
+ return "editor"
+ if flags["exploded"]:
+ return "exploded"
+ if flags["editorChrome"]:
+ # 有外壳却没 API:多半是编辑器脚本没跑起来,硬转会把工具栏拍进去
+ raise RuntimeError(
+ "看着像 editor.html,但页面没有暴露 __layerEditor/__freeEditor.fullHTML,"
+ "无法安全地剥掉编辑器外壳。请改传 index.html 或编辑器导出的 *.edited.html。"
+ )
+ return "plain"
+
+
+def editor_clean_html(src: Path) -> str:
+ """调编辑器自己的 fullHTML(),拿它「Download HTML」会给出的那份 HTML。"""
+ from playwright.sync_api import sync_playwright
+
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch(args=_browser_args())
+ try:
+ page = browser.new_page(viewport={"width": 1600, "height": 1000})
+ page.goto(src.as_uri(), wait_until="load", timeout=30000)
+ # <html> 永远不算 "visible",只能等它挂上
+ page.wait_for_selector(EDITOR_READY, state="attached", timeout=30000)
+ page.wait_for_timeout(300)
+ html = page.evaluate(GRAB_HTML_JS)
+ finally:
+ browser.close()
+ if not html:
+ raise RuntimeError("编辑器没有返回 fullHTML()")
+ return html
+
+
+def _report(out: Path, manifest: dict) -> None:
+ canvas = manifest.get("canvas") or {}
+ print(
+ f"✅ {out}\n 画布 {canvas.get('width', 0):.0f}x{canvas.get('height', 0):.0f}"
+ f" ({manifest.get('selector')}) · 形状 {manifest.get('shape_count')} · "
+ f"文本框 {manifest.get('text_count')} · 独立图片 {manifest.get('picture_count')} · "
+ f"元素 {manifest.get('element_count')}"
+ )
+ if not manifest.get("shape_count") and not manifest.get("text_count"):
+ print(" ⚠️ 未重建出可编辑形状/文本(多为纯 SVG slide,整页折成背景图,仍是合法 pptx)")
def main() -> None:
- ap = argparse.ArgumentParser(description="slide / poster HTML -> 可编辑 PPTX(离线确定性)")
- ap.add_argument("html", help="slide/poster HTML(*.edited.html 或 index.html,勿传 editor.html)")
+ ap = argparse.ArgumentParser(
+ description="slide / poster / editor / 图层展开图 HTML -> 可编辑 PPTX(离线确定性)"
+ )
+ ap.add_argument("html", help="index.html / *.edited.html / editor.html / layers.html")
ap.add_argument("-o", "--out", help="输出 .pptx(默认与输入同目录同名)")
ap.add_argument("--selector", default=None, help="画布选择器(默认自动识别)")
+ ap.add_argument(
+ "--mode",
+ default="auto",
+ choices=["auto", "plain", "editor", "exploded"],
+ help="页面类型,默认自动识别",
+ )
+ ap.add_argument("--keep-overview", action="store_true",
+ help="展开图专用:保留 Full overview 缩略图")
args = ap.parse_args()
src = Path(args.html).resolve()
if not src.is_file():
sys.stderr.write(f"找不到文件: {src}\n")
sys.exit(2)
-
out = Path(args.out).resolve() if args.out else src.with_suffix(".pptx")
try:
- build_editable_pptx = _locate_converter()
+ mode = args.mode if args.mode != "auto" else classify(src)
+ except Exception as exc: # noqa: BLE001
+ sys.stderr.write(f"{exc}\n")
+ sys.exit(2)
+ print(f"页面类型:{mode}" + ("(自动识别)" if args.mode == "auto" else "(手动指定)"))
+
+ if mode == "exploded":
+ try:
+ manifest = _exploded_module().convert(
+ src, out, keep_overview=args.keep_overview
+ )
+ except Exception as exc: # noqa: BLE001
+ sys.stderr.write(f"{exc}\n")
+ sys.exit(2)
+ _report(out, manifest)
+ return
+
+ try:
+ converter = _locate_converter()
except Exception as exc: # noqa: BLE001
sys.stderr.write(
"无法加载转换器 build_editable_pptx。\n"
f" 原因: {exc}\n"
- " 请确认 Skill 文件完整,并安装 requirements.txt。\n"
+ " 请在仓库环境(含 playwright / python-pptx / Pillow)里运行。\n"
)
sys.exit(1)
- work = Path(tempfile.mkdtemp(prefix="to_pptx_"))
- manifest = build_editable_pptx(
- src, work, out_name=out.name, canvas_selector=args.selector, use_llm=False
- )
- produced = Path(manifest["pptx_path"])
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_bytes(produced.read_bytes())
- canvas = manifest.get("canvas") or {}
- print(
- f"✅ {out}\n 画布 {canvas.get('width', 0):.0f}x{canvas.get('height', 0):.0f}"
- f" ({manifest.get('selector')}) · 形状 {manifest.get('shape_count')} · "
- f"文本框 {manifest.get('text_count')} · 独立图片 {manifest.get('picture_count')} · "
- f"元素 {manifest.get('element_count')}"
- )
- if not manifest.get("shape_count") and not manifest.get("text_count"):
- print(" ⚠️ 未重建出可编辑形状/文本(多为纯 SVG slide,整页折成背景图,仍是合法 pptx)")
+ staged: Path | None = None
+ source = src
+ if mode == "editor":
+ try:
+ html = editor_clean_html(src)
+ except Exception as exc: # noqa: BLE001
+ sys.stderr.write(f"无法从编辑器导出干净 HTML: {exc}\n")
+ sys.exit(2)
+ # 必须和 editor.html 同目录,否则 assets/ 里的字体和图片解析不到
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ encoding="utf-8",
+ dir=src.parent,
+ prefix=f".{src.stem}.wca-export-",
+ suffix=".html",
+ delete=False,
+ ) as handle:
+ handle.write(html)
+ staged = Path(handle.name)
+ source = staged
+ print(f" 编辑器 fullHTML() 导出 {len(html) / 1024:.0f} KB,已剥掉编辑器外壳")
+
+ try:
+ work = Path(tempfile.mkdtemp(prefix="to_pptx_"))
+ manifest = converter.build_editable_pptx(
+ source, work, out_name=out.name,
+ canvas_selector=args.selector, use_llm=False,
+ )
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_bytes(Path(manifest["pptx_path"]).read_bytes())
+ finally:
+ if staged is not None:
+ staged.unlink(missing_ok=True)
+
+ _report(out, manifest)
if __name__ == "__main__":