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

refactor(image-gen): switch to explicit provider config and clarify env precedence

hugohe3092829b5ff22
diff --git a/.env.example b/.env.example
index d439b84d..ac3790b7 100644
--- a/.env.example
+++ b/.env.example
@@ -2,41 +2,102 @@
# Image Generation Configuration / 图片生成配置
# ─────────────────────────────────────────────────────────────
-# Backend: "gemini" or "openai" (default: auto-detect based on available keys)
-# 后端选择:"gemini" 或 "openai"(默认根据已配置的 key 自动检测)
-# IMAGE_BACKEND=gemini
+# This file is an optional fallback config source for image_gen.py.
+# Current process environment variables take precedence over this file.
+# 当前文件是 image_gen.py 的可选 fallback 配置来源。
+# 当前进程环境变量优先于这个文件。
-# API Key (required) / API 密钥(必需)
-# IMAGE_API_KEY=your-api-key
+# Active backend (required) / 当前启用后端(必需)
+# Recommended core backends: gemini / openai / qwen / zhipu / volcengine
+# 推荐核心后端:gemini / openai / qwen / zhipu / volcengine
+# IMAGE_BACKEND=gemini
-# Custom API endpoint (optional, for proxy or local models)
-# 自定义 API 端点(可选,用于代理服务或本地模型)
-# IMAGE_BASE_URL=https://your-proxy-url.com/v1beta
+# You may also provide the same variables directly via the current process environment.
+# 也可以不写 .env,而是直接通过当前运行进程的环境变量提供同样的配置。
-# Model override (optional, each backend has its own default)
-# 模型名称覆盖(可选,各后端有默认值)
-# IMAGE_MODEL=gemini-3.1-flash-image-preview
+# IMPORTANT:
+# - IMAGE_API_KEY / IMAGE_MODEL / IMAGE_BASE_URL are no longer supported.
+# - Use provider-specific keys only.
+# 重要:
+# - 不再支持 IMAGE_API_KEY / IMAGE_MODEL / IMAGE_BASE_URL。
+# - 请只使用各提供商自己的变量。
# ─────────────────────────────────────────────────────────────
-# Example: Gemini backend / Gemini 后端示例
+# Example: Gemini / Gemini 示例
# ─────────────────────────────────────────────────────────────
# IMAGE_BACKEND=gemini
-# IMAGE_API_KEY=your-gemini-api-key
-# IMAGE_BASE_URL=https://your-proxy-url.com/v1beta
+# GEMINI_API_KEY=your-gemini-api-key
+# GEMINI_MODEL=gemini-3.1-flash-image-preview
+# GEMINI_BASE_URL=https://your-proxy-url.com/v1beta
# ─────────────────────────────────────────────────────────────
-# Example: OpenAI backend / OpenAI 后端示例
+# Example: OpenAI / OpenAI 示例
# ─────────────────────────────────────────────────────────────
# IMAGE_BACKEND=openai
-# IMAGE_API_KEY=sk-xxx
-# IMAGE_BASE_URL=http://127.0.0.1:3000/v1
-# IMAGE_MODEL=gpt-image-1
+# OPENAI_API_KEY=sk-xxx
+# OPENAI_MODEL=gpt-image-1
+# OPENAI_BASE_URL=http://127.0.0.1:3000/v1
# ─────────────────────────────────────────────────────────────
-# Legacy variables (still work, no need to migrate)
-# 旧版变量(仍然有效,无需迁移)
+# Example: Qwen / 通义生图示例
# ─────────────────────────────────────────────────────────────
-# GEMINI_API_KEY=your-api-key
-# GEMINI_BASE_URL=https://your-proxy-url.com/v1beta
-# OPENAI_API_KEY=sk-xxx
-# OPENAI_BASE_URL=http://127.0.0.1:3000/v1
+# IMAGE_BACKEND=qwen
+# QWEN_API_KEY=your-dashscope-key
+# QWEN_MODEL=qwen-image-2.0-pro
+# QWEN_BASE_URL=https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
+
+# ─────────────────────────────────────────────────────────────
+# Example: Zhipu / 智谱生图示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=zhipu
+# ZHIPU_API_KEY=your-zhipu-key
+# ZHIPU_MODEL=glm-image
+# ZHIPU_BASE_URL=https://open.bigmodel.cn/api/paas/v4/images/generations
+
+# ─────────────────────────────────────────────────────────────
+# Example: Volcengine / 火山引擎示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=volcengine
+# VOLCENGINE_API_KEY=your-volcengine-key
+# VOLCENGINE_MODEL=doubao-seedream-4-5-251128
+# VOLCENGINE_BASE_URL=https://operator.las.cn-beijing.volces.com/api/v1/images/generations
+
+# ─────────────────────────────────────────────────────────────
+# Extended / Experimental backends
+# 扩展 / 实验后端
+# ─────────────────────────────────────────────────────────────
+# STABILITY_API_KEY=your-stability-key
+# STABILITY_MODEL=stable-image-core
+# STABILITY_BASE_URL=https://api.stability.ai
+#
+# BFL_API_KEY=your-bfl-key
+# BFL_MODEL=flux-pro-1.1-ultra
+# BFL_BASE_URL=https://api.bfl.ai
+#
+# IDEOGRAM_API_KEY=your-ideogram-key
+# IDEOGRAM_MODEL=ideogram-v3
+# IDEOGRAM_BASE_URL=https://api.ideogram.ai
+#
+# SILICONFLOW_API_KEY=your-siliconflow-key
+# SILICONFLOW_MODEL=Qwen/Qwen-Image
+# SILICONFLOW_BASE_URL=https://api.siliconflow.cn/v1/images/generations
+#
+# FAL_KEY=your-fal-key
+# FAL_MODEL=fal-ai/imagen3/fast
+# FAL_BASE_URL=https://fal.run
+#
+# REPLICATE_API_TOKEN=r8_xxx
+# REPLICATE_MODEL=black-forest-labs/flux-1.1-pro
+# REPLICATE_BASE_URL=https://api.replicate.com/v1/predictions
+
+# ─────────────────────────────────────────────────────────────
+# Multi-provider example / 多提供商共存示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=gemini
+# GEMINI_API_KEY=your-gemini-api-key
+# GEMINI_MODEL=gemini-3.1-flash-image-preview
+# ZHIPU_API_KEY=your-zhipu-key
+# ZHIPU_MODEL=glm-image
+#
+# Switch providers by changing IMAGE_BACKEND only.
+# 切换提供商时,只改 IMAGE_BACKEND 即可。
diff --git a/AGENTS.md b/AGENTS.md
index ac00fbed..4f5c1edc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -52,6 +52,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> -s final
- `skills/ppt-master/workflows/create-template.md` — Standalone template workflow
- `skills/ppt-master/references/` — Role definitions and technical specifications
- `skills/ppt-master/scripts/` — Tool scripts
+- `skills/ppt-master/scripts/docs/` — Topic-focused script docs (`conversion`, `project`, `svg-pipeline`, `image`, `troubleshooting`)
- `skills/ppt-master/templates/` — Layout templates, chart templates, icon library
- `examples/` — Example projects
- `projects/` — User project workspace
diff --git a/CLAUDE.md b/CLAUDE.md
index 5a2e5e0d..2b804ef4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -43,7 +43,8 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> -s final
## Architecture
- `skills/ppt-master/references/` — AI role definitions and technical specifications
-- `skills/ppt-master/scripts/` — 28 tool scripts
+- `skills/ppt-master/scripts/` — Runnable tool scripts
+- `skills/ppt-master/scripts/docs/` — Topic-focused script docs
- `skills/ppt-master/templates/` — Layout templates, chart templates, 640+ vector icons
- `examples/` — Example projects
- `projects/` — User project workspace
diff --git a/README.md b/README.md
index e9f4f68c..d0ec44cb 100644
--- a/README.md
+++ b/README.md
@@ -84,7 +84,12 @@ Output: Two files are generated automatically:
| 🖼️ [Image Embedding Guide](./skills/ppt-master/references/svg-image-embedding.md) | SVG image embedding best practices |
| 📊 [Chart Template Library](./skills/ppt-master/templates/charts/) | Standardized chart templates |
| 🔧 [Role Definitions](./skills/ppt-master/references/) | Role definitions and technical references |
-| 🛠️ [Toolset](./skills/ppt-master/scripts/README.md) | Usage instructions for all tools |
+| 🛠️ [Toolset](./skills/ppt-master/scripts/README.md) | Script index and high-frequency commands |
+| ↳ [Conversion Docs](./skills/ppt-master/scripts/docs/conversion.md) | PDF / DOCX / web conversion tools |
+| ↳ [Project Docs](./skills/ppt-master/scripts/docs/project.md) | Project init, validation, and indexing |
+| ↳ [SVG Pipeline Docs](./skills/ppt-master/scripts/docs/svg-pipeline.md) | Finalize, validate, notes, and PPTX export |
+| ↳ [Image Docs](./skills/ppt-master/scripts/docs/image.md) | Image generation and image analysis tools |
+| ↳ [Troubleshooting Docs](./skills/ppt-master/scripts/docs/troubleshooting.md) | Validation, preview, export, and dependency issues |
| 💼 [Examples Index](./examples/README.md) | 15 projects, 229 SVG pages of examples |
---
@@ -174,9 +179,33 @@ AI: Sure. First we'll confirm whether to use a template; after that Strategist w
### 5. AI Image Generation (Optional)
-The `image_gen.py` tool generates high-quality images via Gemini or OpenAI-compatible APIs directly within AI clients. Choose one of the following configuration methods:
+The `image_gen.py` tool supports multiple providers, but the recommended set is intentionally kept small.
-#### Option A: Using `.env` file (Recommended)
+- Core recommended: `gemini`, `openai`, `qwen`, `zhipu`, `volcengine`
+- Extended: `stability`, `bfl` (FLUX), `ideogram`
+- Experimental: `siliconflow`, `fal`, `replicate`
+
+To inspect the current support tiers in the CLI:
+
+```bash
+python3 skills/ppt-master/scripts/image_gen.py --list-backends
+```
+
+Image generation accepts configuration from either of these sources:
+
+1. Current process environment variables
+2. Project-root `.env` file as a fallback
+
+Precedence:
+- Current process environment wins
+- `.env` only fills values that are not already present
+
+One rule is mandatory:
+- `IMAGE_BACKEND` must be set explicitly
+
+The tool does **not** guess a provider from API keys, and it does **not** default to Gemini.
+
+#### Option A: Configure `.env`
```bash
cp .env.example .env
@@ -186,30 +215,49 @@ Edit the `.env` file with your configuration:
```env
IMAGE_BACKEND=gemini
-IMAGE_API_KEY=your-api-key
+GEMINI_API_KEY=your-api-key
+GEMINI_MODEL=gemini-3.1-flash-image-preview
```
> `.env` is already in `.gitignore` and will not be committed to the repository, so your keys stay safe.
-#### Option B: Using environment variables
+#### Option B: Use current process environment variables
```bash
-# Backend selection: "gemini" (default) or "openai"
-export IMAGE_BACKEND="gemini"
+export IMAGE_BACKEND=gemini
+export GEMINI_API_KEY=your-api-key
+export GEMINI_MODEL=gemini-3.1-flash-image-preview
+python3 skills/ppt-master/scripts/image_gen.py "abstract tech background"
+```
+
+This is useful for CI, containers, secret managers, and one-off local runs.
+
+Important:
+- The script reads the current process environment, not your shell startup files in the abstract
+- If a tool launches a non-interactive shell and your `~/.bashrc` or `~/.zshrc` is not sourced, those exports may not be visible
+- In that situation, `.env` is usually the more stable local choice
+
+> 💡 **Provider-specific config**: Put credentials and overrides in provider namespaces such as `GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_BASE_URL`, `OPENAI_API_KEY`, `QWEN_MODEL`, `ZHIPU_MODEL`, `VOLCENGINE_API_KEY`, and `REPLICATE_API_TOKEN`.
-# Required: API key for the selected backend
-export IMAGE_API_KEY="your-api-key"
+> 💡 **No global image credentials**: `IMAGE_API_KEY`, `IMAGE_MODEL`, and `IMAGE_BASE_URL` are intentionally not supported. Use provider-specific variables only.
+
+> 💡 **Multi-provider setup**: You can keep multiple providers in one `.env` or environment, but `IMAGE_BACKEND` must explicitly select the active one.
+
+Example:
+
+```env
+IMAGE_BACKEND=zhipu
-# Optional: Custom API endpoint (for proxy services or local models)
-export IMAGE_BASE_URL="https://your-proxy-url.com/v1beta"
+GEMINI_API_KEY=your-gemini-key
+GEMINI_MODEL=gemini-3.1-flash-image-preview
-# Optional: Model name override
-export IMAGE_MODEL="gemini-3.1-flash-image-preview"
+ZHIPU_API_KEY=your-zhipu-key
+ZHIPU_MODEL=glm-image
```
-> 💡 **Persist settings**: Add the `export` commands above to `~/.zshrc` (macOS/Linux zsh) or `~/.bashrc` (Linux bash), then restart your terminal.
+Switch providers by changing `IMAGE_BACKEND` only.
-> 💡 **Legacy support**: `GEMINI_API_KEY` / `GEMINI_BASE_URL` and `OPENAI_API_KEY` / `OPENAI_BASE_URL` still work for backward compatibility. If `IMAGE_BACKEND` is not set, the system auto-detects based on available keys.
+> 💡 **Recommendation**: Prefer the core backends unless you have a clear reason to use an extended or experimental provider.
> 💡 **AI Image Generation Tip**: For AI-generated images, we recommend generating them in [Gemini](https://gemini.google.com/) and selecting **Download full size** for higher resolution. Gemini images have a star watermark in the bottom right corner, which can be removed using [gemini-watermark-remover](https://github.com/journey-ad/gemini-watermark-remover) or this project's `skills/ppt-master/scripts/gemini_watermark_remover.py`.
@@ -261,7 +309,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <project_path> -s final
# Default transition: fade (0.5s). Disable with: -t none
```
-> 📖 For complete tool documentation, see [Tools Usage Guide](./skills/ppt-master/scripts/README.md)
+> 📖 For script docs, start with [Tools Usage Guide](./skills/ppt-master/scripts/README.md), then jump to [Conversion](./skills/ppt-master/scripts/docs/conversion.md), [Project](./skills/ppt-master/scripts/docs/project.md), [SVG Pipeline](./skills/ppt-master/scripts/docs/svg-pipeline.md), [Image](./skills/ppt-master/scripts/docs/image.md), or [Troubleshooting](./skills/ppt-master/scripts/docs/troubleshooting.md)
---
diff --git a/README_CN.md b/README_CN.md
index fbeeb558..82b88db1 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -83,7 +83,12 @@
| 📐 [画布格式](./skills/ppt-master/references/canvas-formats.md) | PPT、小红书、朋友圈等 10+ 种格式 |
| 🖼️ [图片嵌入指南](./skills/ppt-master/references/svg-image-embedding.md) | SVG 图片嵌入最佳实践 |
| 📊 [图表模板库](./skills/ppt-master/templates/charts/) | 13 种标准化图表模板 |
-| 🛠️ [工具集](./skills/ppt-master/scripts/README.md) | 所有工具的使用说明 |
+| 🛠️ [工具集](./skills/ppt-master/scripts/README.md) | 脚本索引与高频命令 |
+| ↳ [转换文档](./skills/ppt-master/scripts/docs/conversion.md) | PDF / DOCX / 网页转 Markdown |
+| ↳ [项目文档](./skills/ppt-master/scripts/docs/project.md) | 项目初始化、校验与索引 |
+| ↳ [SVG 流水线文档](./skills/ppt-master/scripts/docs/svg-pipeline.md) | 后处理、校验、备注与 PPTX 导出 |
+| ↳ [图片文档](./skills/ppt-master/scripts/docs/image.md) | 图片生成与图片分析工具 |
+| ↳ [排障文档](./skills/ppt-master/scripts/docs/troubleshooting.md) | 校验、预览、导出与依赖问题 |
| 💼 [示例索引](./examples/README.md) | 15 个项目、229 页 SVG 示例 |
---
@@ -172,9 +177,33 @@ AI:好的,先确认是否使用模板;确认后我会继续八项确认并
### 5. AI 生图配置(可选)
-本项目的 `image_gen.py` 可通过 Gemini 或 OpenAI 兼容 API 在 AI 客户端中直接生成高质量配图。配置方式二选一:
+本项目的 `image_gen.py` 支持多家图片模型提供商,但推荐默认只聚焦少数后端:
-#### 方式 A:使用 `.env` 文件(推荐)
+- 核心推荐:`gemini`、`openai`、`qwen`、`zhipu`、`volcengine`
+- 扩展支持:`stability`、`bfl`(FLUX)、`ideogram`
+- 实验支持:`siliconflow`、`fal`、`replicate`
+
+可用下面的命令直接查看 CLI 中的后端分级:
+
+```bash
+python3 skills/ppt-master/scripts/image_gen.py --list-backends
+```
+
+图片生成支持两种配置来源:
+
+1. 当前运行进程的环境变量
+2. 项目根目录 `.env` 文件作为补充 fallback
+
+优先级:
+- 当前进程环境变量优先
+- `.env` 只补充那些当前进程里还没有的值
+
+有一条规则是强制的:
+- 必须显式设置 `IMAGE_BACKEND`
+
+工具不会根据 API Key 自动猜后端,也不会在未配置时偷偷默认到 Gemini。
+
+#### 方式 A:配置 `.env`
```bash
cp .env.example .env
@@ -184,30 +213,49 @@ cp .env.example .env
```env
IMAGE_BACKEND=gemini
-IMAGE_API_KEY=your-api-key
+GEMINI_API_KEY=your-api-key
+GEMINI_MODEL=gemini-3.1-flash-image-preview
```
> `.env` 文件已在 `.gitignore` 中,不会被提交到仓库,无需担心密钥泄露。
-#### 方式 B:使用环境变量
+#### 方式 B:使用当前进程环境变量
```bash
-# 后端选择:"gemini"(默认)或 "openai"
-export IMAGE_BACKEND="gemini"
+export IMAGE_BACKEND=gemini
+export GEMINI_API_KEY=your-api-key
+export GEMINI_MODEL=gemini-3.1-flash-image-preview
+python3 skills/ppt-master/scripts/image_gen.py "abstract tech background"
+```
+
+这种方式适合 CI、容器、密钥管理平台,以及一次性的本地测试。
+
+注意:
+- 脚本读取的是“当前运行进程可见的环境变量”,不是抽象意义上的 shell 配置
+- 如果某个工具启动的是非交互 shell,而你的 `~/.bashrc` 或 `~/.zshrc` 没有被 source,那么里面的 export 可能根本不可见
+- 这种情况下,本地开发通常还是 `.env` 更稳定
+
+> 💡 **提供商命名空间**:请把密钥和模型覆盖写在各家自己的变量里,例如 `GEMINI_API_KEY`、`GEMINI_MODEL`、`GEMINI_BASE_URL`、`OPENAI_API_KEY`、`QWEN_MODEL`、`ZHIPU_MODEL`、`VOLCENGINE_API_KEY`、`REPLICATE_API_TOKEN`。
-# 必需:所选后端的 API Key
-export IMAGE_API_KEY="your-api-key"
+> 💡 **不支持全局图片密钥变量**:`IMAGE_API_KEY`、`IMAGE_MODEL`、`IMAGE_BASE_URL` 已明确废弃,请只使用 provider 自己的变量。
+
+> 💡 **多提供商共存**:同一个 `.env` 或同一组环境变量里可以保留多家配置,但必须用 `IMAGE_BACKEND` 明确指定当前启用的是哪一家。
+
+示例:
+
+```env
+IMAGE_BACKEND=zhipu
-# 可选:自定义 API 端点(用于代理服务或本地模型)
-export IMAGE_BASE_URL="https://your-proxy-url.com/v1beta"
+GEMINI_API_KEY=your-gemini-key
+GEMINI_MODEL=gemini-3.1-flash-image-preview
-# 可选:模型名称覆盖
-export IMAGE_MODEL="gemini-3.1-flash-image-preview"
+ZHIPU_API_KEY=your-zhipu-key
+ZHIPU_MODEL=glm-image
```
-> 💡 **持久化**:将上述 `export` 命令添加到 `~/.zshrc`(macOS/Linux zsh)或 `~/.bashrc`(Linux bash)中,重启终端即可永久生效。
+切换提供商时,只改 `IMAGE_BACKEND` 即可。
-> 💡 **向后兼容**:`GEMINI_API_KEY` / `GEMINI_BASE_URL` 以及 `OPENAI_API_KEY` / `OPENAI_BASE_URL` 仍然有效。未设置 `IMAGE_BACKEND` 时,系统会根据已配置的 key 自动检测后端。
+> 💡 **推荐原则**:没有特殊诉求时,优先使用“核心推荐”里的后端。
> 💡 **AI 生成图片建议**:如需 AI 生成配图,建议在 [Gemini](https://gemini.google.com/) 中生成后选择 **Download full size** 下载,分辨率比 Antigravity 直接生成的更高。Gemini 生成的图片右下角会有星星水印,可使用 [gemini-watermark-remover](https://github.com/journey-ad/gemini-watermark-remover) 或本项目的 `skills/ppt-master/scripts/gemini_watermark_remover.py` 去除。
@@ -257,7 +305,7 @@ python3 skills/ppt-master/scripts/svg_to_pptx.py <项目路径> -s final
```
-> 📖 完整工具说明请参阅 [脚本使用指南](./skills/ppt-master/scripts/README.md)
+> 📖 脚本文档建议先看 [脚本使用指南](./skills/ppt-master/scripts/README.md),再按主题进入 [转换](./skills/ppt-master/scripts/docs/conversion.md)、[项目](./skills/ppt-master/scripts/docs/project.md)、[SVG 流水线](./skills/ppt-master/scripts/docs/svg-pipeline.md)、[图片](./skills/ppt-master/scripts/docs/image.md)、[排障](./skills/ppt-master/scripts/docs/troubleshooting.md)
---
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index ef93c905..d0e67540 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -41,7 +41,7 @@ description: >
| `${SKILL_DIR}/scripts/web_to_md.cjs` | WeChat / high-security sites to Markdown |
| `${SKILL_DIR}/scripts/project_manager.py` | Project init / validate / manage |
| `${SKILL_DIR}/scripts/analyze_images.py` | Image analysis |
-| `${SKILL_DIR}/scripts/image_gen.py` | AI image generation (Gemini / OpenAI) |
+| `${SKILL_DIR}/scripts/image_gen.py` | AI image generation (multi-provider) |
| `${SKILL_DIR}/scripts/svg_quality_checker.py` | SVG quality check |
| `${SKILL_DIR}/scripts/total_md_split.py` | Speaker notes splitting |
| `${SKILL_DIR}/scripts/finalize_svg.py` | SVG post-processing (unified entry) |
diff --git a/skills/ppt-master/references/image-generator.md b/skills/ppt-master/references/image-generator.md
index bd1d56a8..a2659158 100644
--- a/skills/ppt-master/references/image-generator.md
+++ b/skills/ppt-master/references/image-generator.md
@@ -239,24 +239,40 @@ python3 scripts/image_gen.py "your prompt" \
| `--image_size` | - | Size (`1K`/`2K`/`4K`) | `1K` |
| `--output` | `-o` | Output directory | Current directory |
| `--filename` | `-f` | Output filename (no extension) | Auto-named |
-| `--backend` | `-b` | Override backend (`gemini`/`openai`) | Auto-detect |
+| `--backend` | `-b` | Override backend (`gemini`/`openai`/`stability`/`bfl`/`ideogram`/`qwen`/`zhipu`/`volcengine`/`siliconflow`/`fal`/`replicate`) | None |
| `--model` | `-m` | Model name | Backend default |
+| `--list-backends` | - | Print support tiers and exit | `false` |
-**Environment variables**:
+**Configuration sources**:
+- Current process environment variables
+- Project-root `.env` as fallback
+
+Precedence:
+- Current process environment wins
+- `.env` fills missing values only
| Variable | Required | Description |
|----------|----------|-------------|
-| `IMAGE_BACKEND` | Optional | `gemini` or `openai` (auto-detect if not set) |
-| `IMAGE_API_KEY` | Required | API key for the selected backend |
-| `IMAGE_BASE_URL` | Optional | Custom API endpoint (proxy / local models) |
-| `IMAGE_MODEL` | Optional | Model name override |
+| `IMAGE_BACKEND` | Required | `gemini` / `openai` / `stability` / `bfl` / `ideogram` / `qwen` / `zhipu` / `volcengine` / `siliconflow` / `fal` / `replicate` |
+| `{PROVIDER}_API_KEY` | Required | Provider-specific API key, e.g. `GEMINI_API_KEY`, `ZHIPU_API_KEY` |
+| `{PROVIDER}_BASE_URL` | Optional | Provider-specific custom endpoint |
+| `{PROVIDER}_MODEL` | Optional | Provider-specific model override |
+
+> Use provider-specific names only: `GEMINI_API_KEY`, `OPENAI_API_KEY`, `STABILITY_API_KEY`, `BFL_API_KEY`, `IDEOGRAM_API_KEY`, `QWEN_API_KEY` / `DASHSCOPE_API_KEY`, `ZHIPU_API_KEY` / `BIGMODEL_API_KEY`, `VOLCENGINE_API_KEY` / `ARK_API_KEY`, `SILICONFLOW_API_KEY`, `FAL_KEY`, and `REPLICATE_API_TOKEN`.
+
+> `IMAGE_API_KEY`, `IMAGE_MODEL`, and `IMAGE_BASE_URL` are intentionally unsupported.
+
+> If `.env` or the current environment contains multiple provider configs, `IMAGE_BACKEND` explicitly selects the active one.
-> Legacy: `GEMINI_API_KEY` / `GEMINI_BASE_URL` still work for backward compatibility.
+**Support tiers (recommended usage)**:
+- Core: `gemini`, `openai`, `qwen`, `zhipu`, `volcengine`
+- Extended: `stability`, `bfl`, `ideogram`
+- Experimental: `siliconflow`, `fal`, `replicate`
**Generation pacing (mandatory)**:
- Execute only one generation command at a time; wait for file confirmation before the next
- Recommend 2-5 second intervals between images to avoid concurrency failures
-- If failure/no output occurs, halt the queue, check environment variables and output directory, then resume
+- If failure/no output occurs, halt the queue, check `IMAGE_BACKEND`, provider-specific credentials, and the output directory, then resume
#### Method 2: Auto-generation
diff --git a/skills/ppt-master/references/svg-image-embedding.md b/skills/ppt-master/references/svg-image-embedding.md
index 4d11eb56..0ea0819f 100644
--- a/skills/ppt-master/references/svg-image-embedding.md
+++ b/skills/ppt-master/references/svg-image-embedding.md
@@ -126,9 +126,9 @@ python3 scripts/svg_to_pptx.py <project_path> -s final # Export PPTX from final
For processing specific SVGs without running the full pipeline:
```bash
-python3 scripts/embed_images.py <svg_file> # Single file
-python3 scripts/embed_images.py <project_path>/svg_output/*.svg # Batch
-python3 scripts/embed_images.py --dry-run <project_path>/svg_output/*.svg # Preview
+python3 scripts/svg_finalize/embed_images.py <svg_file> # Single file
+python3 scripts/svg_finalize/embed_images.py <project_path>/svg_output/*.svg # Batch
+python3 scripts/svg_finalize/embed_images.py --dry-run <project_path>/svg_output/*.svg # Preview
```
---
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index eee220f6..e1380b65 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -1,1430 +1,78 @@
# PPT Master Toolset
-This directory contains utility tools for project management, validation, and file processing.
+This directory contains user-facing scripts for conversion, project setup, SVG processing, export, and image generation.
-## Tool Architecture Overview
+## Directory Layout
-```mermaid
-graph TB
- subgraph Input["Input Conversion"]
- A1[pdf_to_md.py]
- A1b[doc_to_md.py]
- A2[web_to_md.py / .cjs]
- end
+- Top-level `scripts/`: runnable entry scripts
+- `scripts/image_backends/`: internal provider implementations used by `image_gen.py`
+- `scripts/svg_finalize/`: internal post-processing helpers used by `finalize_svg.py`
+- `scripts/docs/`: topic-focused script documentation
+- `scripts/assets/`: static assets consumed by scripts
- subgraph Project["Project Management"]
- B1[project_manager.py]
- B2[project_utils.py]
- B1 --> B2
- end
+## Quick Start
- subgraph Finalize["Post-processing (finalize_svg.py)"]
- direction TB
- C0[finalize_svg.py<br/>Unified Entry Point]
- C1[embed_icons.py]
- C2[crop_images.py]
- C3[fix_image_aspect.py]
- C4[embed_images.py]
- C5[flatten_tspan.py]
- C6[svg_rect_to_path.py]
-
- C0 --> C1
- C0 --> C2
- C0 --> C3
- C0 --> C4
- C0 --> C5
- C0 --> C6
- end
-
- subgraph Export["Export"]
- D1[svg_to_pptx.py]
- end
-
- subgraph Quality["Quality Check"]
- E1[svg_quality_checker.py]
- E2[batch_validate.py]
- end
-
- subgraph Utils["Utilities"]
- F1[rotate_images.py]
- F2[analyze_images.py]
- F3[svg_position_calculator.py]
- F4[config.py]
- F5[image_gen.py]
- end
-
- A1 --> B1
- A2 --> B1
- B1 -->|svg_output/| C0
- C0 -->|svg_final/| D1
- D1 -->|.pptx| Output[PowerPoint]
-```
-
-### Core Workflow
-
-```
-Source Document → [pdf_to_md / doc_to_md / web_to_md] → Markdown
- ↓
- [project_manager init]
- ↓
- AI generates SVG → svg_output/
- ↓
- [finalize_svg] ← Aggregates 6 sub-tools
- ↓
- svg_final/
- ↓
- [svg_to_pptx] → output.pptx
-```
-
-### Tool Category Quick Index
-
-| Category | Tool | Description |
-|----------|------|-------------|
-| **Input Conversion** | `pdf_to_md.py`, `doc_to_md.py`, `web_to_md.py/.cjs` | Convert PDF/DOCX/web pages to Markdown |
-| **Project Management** | `project_manager.py` | Create and validate projects |
-| **Post-processing** | `finalize_svg.py` ⭐ | Unified entry point, invokes the 6 tools below |
-| ↳ Sub-tool | `embed_icons.py` | Embed icon placeholders |
-| ↳ Sub-tool | `crop_images.py` | Smart image cropping |
-| ↳ Sub-tool | `fix_image_aspect.py` | Fix image aspect ratio |
-| ↳ Sub-tool | `embed_images.py` | Base64 image embedding |
-| ↳ Sub-tool | `flatten_tspan.py` | Text flattening |
-| ↳ Sub-tool | `svg_rect_to_path.py` | Rounded rect to Path |
-| **Export** | `svg_to_pptx.py` | SVG to PowerPoint |
-| **Speaker Notes** | `total_md_split.py` | Speaker notes splitter |
-| **Quality Check** | `svg_quality_checker.py`, `batch_validate.py` | Validate SVG compliance |
-| **Asset Generation** | `image_gen.py` | AI image generation (Gemini / OpenAI) |
-| **Utilities** | `config.py`, `analyze_images.py`, `rotate_images.py` | Configuration and image processing |
-
----
-
-## Tool List
-
-### 0. pdf_to_md.py — PDF to Markdown Tool (Recommended First Choice)
-
-Uses PyMuPDF to convert PDF documents to Markdown format. Runs locally, fast, and free.
-
-**Features**:
-
-- Extract PDF text content and convert to Markdown
-- Automatically extract tables and convert to Markdown tables
-- Automatically extract images and save to `images/` directory
-- Support batch processing of all PDFs in a directory
-
-**Usage**:
-
-```bash
-# Convert a single file
-python3 scripts/pdf_to_md.py book.pdf
-
-# Specify output file
-python3 scripts/pdf_to_md.py book.pdf -o output.md
-
-# Convert all PDFs in a directory
-python3 scripts/pdf_to_md.py ./pdfs
-
-# Specify output directory
-python3 scripts/pdf_to_md.py ./pdfs -o ./markdown
-```
-
-**When to use pdf_to_md.py vs MinerU**:
-
-| Scenario | Recommended Tool | Reason |
-|----------|------------------|--------|
-| **Native PDF** (exported from Word/LaTeX) | `pdf_to_md.py` | Local, instant, free |
-| **Simple tables** | `pdf_to_md.py` | Table extraction supported |
-| **Privacy-sensitive documents** | `pdf_to_md.py` | Data stays on your machine |
-| **Scanned/image PDFs** | MinerU | OCR required |
-| **Complex multi-column layouts** | MinerU | Better layout analysis |
-| **Math formulas** | MinerU | Stronger AI recognition |
-| **Garbled PDFs** (encoding lost) | MinerU | Visual recognition as fallback |
-
-> **Strategy**: PyMuPDF first, MinerU as fallback. Run `pdf_to_md.py` first; if the result is garbled/blank/misformatted, switch to MinerU.
-
-**Dependencies**:
-
-```bash
-pip install PyMuPDF
-```
-
----
-
-### 0.3. doc_to_md.py — Document to Markdown Tool (Pandoc-based)
-
-Uses Pandoc to convert various document formats to Markdown. Ideal for converting DOCX lecture notes, manuscripts, and other documents.
-
-**Supported formats**: `.docx`, `.doc`, `.odt`, `.rtf`, `.epub`, `.html`, `.tex`, `.rst`, `.org`, `.ipynb`, `.typ`
-
-**Usage**:
-
-```bash
-# Convert a Word document
-python3 scripts/doc_to_md.py lecture.docx
-
-# Specify output file
-python3 scripts/doc_to_md.py lecture.docx -o output.md
-
-# Convert other formats
-python3 scripts/doc_to_md.py notes.epub
-python3 scripts/doc_to_md.py paper.tex -o paper.md
-```
-
-**Dependencies**:
-
-```bash
-# Install pandoc (required)
-# macOS: brew install pandoc
-# Ubuntu: sudo apt install pandoc
-# Windows: https://pandoc.org/installing.html
-```
-
----
-
-### 0.5. web_to_md.py / web_to_md.cjs — Web Page to Markdown Tool
-
-Scrapes web page content and converts it to Markdown format, automatically downloading images locally.
-
-**Note**: Both Python and Node.js versions are provided. For sites with TLS fingerprint blocking such as WeChat Official Accounts, **the Node.js version is strongly recommended** (`web_to_md.cjs`).
-
-**Features**:
-
-- Scrape web page content and convert to Markdown
-- Automatically extract page metadata (title, date, author)
-- Automatically download images and save to `_files/` directory
-- **Automatic filename cleanup** (retains only alphanumeric characters, Chinese characters, and underscores for maximum compatibility)
-- Smart main content area detection (supports Chinese news/government websites)
-- Support batch processing of multiple URLs
-
-**Usage (Python)**:
-
-```bash
-# Convert a single web page
-python3 scripts/web_to_md.py https://example.com/article
-
-# Convert multiple web pages
-python3 scripts/web_to_md.py https://url1.com https://url2.com
-
-# Batch read URLs from file
-python3 scripts/web_to_md.py -f urls.txt
-
-# Specify output file
-python3 scripts/web_to_md.py https://example.com -o output.md
-```
-
-**Usage (Node.js) — Recommended for WeChat Official Accounts**:
-
-```bash
-# Convert a single web page
-node scripts/web_to_md.cjs https://mp.weixin.qq.com/s/xxxx
-
-# Convert multiple web pages
-node scripts/web_to_md.cjs https://url1.com https://url2.com
-
-# Batch read URLs from file
-node scripts/web_to_md.cjs -f urls.txt
-```
-
-**Output Structure**:
-
-```
-projects/
-├── article_title.md # Markdown content
-└── article_title_files/ # Image directory
- ├── image_1.jpg
- ├── image_2.png
- └── ...
-```
-
-**When to use web_to_md.py / .cjs**:
-
-| Scenario | Recommended Tool | Reason |
-|----------|------------------|--------|
-| **WeChat Official Accounts / heavily protected sites** | `web_to_md.cjs` | Node.js handles TLS fingerprint blocking better and significantly reduces the chance of 403 errors |
-| **Regular news/article pages** | Either one | Both can auto-extract body text and download images |
-| **Image-rich content** (travel logs, guides, etc.) | Either one | Preserves image assets |
-| **Government/institutional websites** | `web_to_md.py` | Python version may handle certain Chinese encodings slightly better |
-| **Pages requiring login** | Manual processing | Tools do not support authentication |
-| **Dynamically rendered pages (SPA)** | Manual processing | Requires a headless browser |
-
-> **Strategy**: If you encounter a 403 error or are scraping a WeChat article, switch directly to `web_to_md.cjs`.
-
-**Dependencies**:
-
-Python:
-```bash
-pip install requests beautifulsoup4
-```
-
-Node.js:
-(The script uses native modules; no extra npm install needed, but a Node.js environment is required)
-
----
-
-### 0.6. rotate_images.py — Image Orientation Correction Tool
-
-A dedicated tool for handling missing or incorrect EXIF orientation data in images downloaded from the web.
-
-**Features**:
-
-- **Auto EXIF correction**: Detect and fix images with EXIF Orientation tags
-- **Visual rotation**: Generate an HTML tool page for click-to-rotate functionality
-- **Natural sorting**: Ensure images are sorted by filename in natural order
-- **Standalone operation**: Independent of scraping scripts; can be used on any directory
-
-**Usage**:
-
-```bash
-# 1. Auto-correct (silent mode, EXIF fix only)
-python3 scripts/rotate_images.py auto projects/xxx_files
-
-# 2. Generate visual tool (fix EXIF first, then generate web page)
-python3 scripts/rotate_images.py gen projects/xxx_files
-# -> Generates projects/image_orientation_tool.html, open in browser to operate
-
-# 3. Apply corrections (from JSON generated by the web page)
-python3 scripts/rotate_images.py fix fixes.json
-```
-
----
-
-### 1. project_utils.py — Project Utilities Common Module
-
-Provides common functionality for project info parsing, validation, etc., reused by other tools.
-
-**Features**:
-
-- Canvas format definition and management
-- Project info parsing (extract format, date, etc. from directory name)
-- Project structure validation
-- SVG viewBox validation
-- Project discovery and statistics
-
-**Usage**:
-
-```bash
-# Imported as a module by other tools
-from project_utils import get_project_info, validate_project_structure
-
-# Can also be run directly for testing
-python3 scripts/project_utils.py <project_path>
-```
-
----
-
-### 2. project_manager.py — Project Management Tool
-
-An all-in-one tool for project initialization, validation, and management.
-
-**Features**:
-
-- Initialize new projects (create standard directory structure)
-- Validate project integrity
-- View project information
-
-**Usage**:
+Typical end-to-end workflow:
```bash
-# Initialize a new project
+python3 scripts/pdf_to_md.py <file.pdf>
python3 scripts/project_manager.py init <project_name> --format ppt169
-
-# Import raw materials and standardized Markdown into the project directory
-python3 scripts/project_manager.py import-sources <project_path> <source1> [<source2> ...]
-
-# Validate project structure
-python3 scripts/project_manager.py validate <project_path>
-
-# View project information
-python3 scripts/project_manager.py info <project_path>
-```
-
-Notes:
-- Files outside the workspace are copied to `sources/` by default
-- With `--move`, files outside the workspace are moved to `sources/` instead
-- If a file is already within the current workspace, it will be moved directly to `sources/`
-
-**Supported Canvas Formats**:
-
-- `ppt169` - PPT 16:9 (1280×720)
-- `ppt43` - PPT 4:3 (1024×768)
-- `wechat` - WeChat Official Account header image (900×383)
-- `xiaohongshu` - Xiaohongshu (RED) 3:4 (1242×1660)
-- `moments` - WeChat Moments / Instagram 1:1 (1080×1080)
-- `story` - Story / Vertical 9:16 (1080×1920)
-- `banner` - Horizontal Banner 16:9 (1920×1080)
-- `a4` - A4 Print (1240×1754)
-
-**Examples**:
-
-```bash
-# Create a new PPT 16:9 project
-python3 scripts/project_manager.py init my_presentation --format ppt169
-
-# Validate project
-python3 scripts/project_manager.py validate projects/my_presentation_ppt169_20251116
-
-# View project information
-python3 scripts/project_manager.py info projects/my_presentation_ppt169_20251116
-```
-
----
-
-### 3. flatten_tspan.py — Text Flattening (Remove `<tspan>`)
-
-> **Recommended**: Use `finalize_svg.py` as the unified entry point, which already includes text flattening. The following is advanced standalone usage.
-
-Flattens `<text>` structures containing multi-line `<tspan>` elements into multiple independent `<text>` elements, for compatibility with certain renderers or text extraction.
-
-**Note**: The generation side should still use `<tspan>` for manual line breaks (see banned features in `AGENTS.md`). This tool is for post-processing only.
-
-**Usage**:
-
-```bash
-# Flatten an entire output directory
-python3 scripts/flatten_tspan.py examples/<project>/svg_output
-
-# Process a single SVG
-python3 scripts/flatten_tspan.py path/to/input.svg path/to/output.svg
-```
-
-**Behavior**:
-
-- Computes absolute position for each `<tspan>` (combining `x`/`y` with `dx`/`dy`), merges parent/child styles, and outputs as independent `<text>` elements
-- Copies common text attributes and `style` from the parent `<text>`; child overrides take priority
-- Preserves or merges `transform`
-- Output uses UTF-8 encoding without XML declaration
-
-**Known Limitations**:
-
-- Only processes `<text>`/`<tspan>` structures; other child elements are not converted
-- For complex nesting or special layouts, simplify to standardized per-line `<tspan>` on the generation side first
-
----
-
-### 4. batch_validate.py — Batch Project Validation Tool
-
-Check the structural integrity and compliance of multiple projects at once.
-
-**Features**:
-
-- Batch project structure validation
-- Check required files (README, design spec, SVGs, etc.)
-- Validate SVG viewBox settings
-- Generate validation reports
-- Provide fix suggestions
-
-**Usage**:
-
-```bash
-# Validate a single directory
-python3 scripts/batch_validate.py examples
-
-# Validate multiple directories
-python3 scripts/batch_validate.py examples projects
-
-# Validate all
-python3 scripts/batch_validate.py --all
-
-# Export report
-python3 scripts/batch_validate.py examples --export
-```
-
-**Example Output**:
-
-```
-✅ google_annual_report_ppt169_20251116
- Path: examples/google_annual_report_ppt169_20251116
- Format: PPT 16:9 | SVGs: 10 | Date: 2025-11-16
-
-⚠️ some_project_name
- Path: examples/some_project_name
- Format: PPT 16:9 | SVGs: 8 | Date: 2025-10-15
- ⚠️ Warnings (1):
- - Non-standard SVG filename: old_name.svg
-```
-
----
-
-### 5. generate_examples_index.py — Examples Index Generator
-
-Automatically scans the examples directory and generates a README.md index file.
-
-**Features**:
-
-- Automatically discover all example projects
-- Organize by format category
-- Generate statistics
-- Create preview links
-- Update usage instructions
-
-**Usage**:
-
-```bash
-# Generate examples/README.md
-python3 scripts/generate_examples_index.py
-
-# Specify directory
-python3 scripts/generate_examples_index.py examples
-```
-
-**Characteristics**:
-
-- Auto-detect project info (name, format, date, SVG count)
-- Group by canvas format
-- Show recently updated projects
-- Include usage instructions and contribution guidelines
-
----
-
-### 6. error_helper.py — Error Message Helper
-
-Provides friendly error messages and specific fix suggestions.
-
-**Features**:
-
-- Standardized error type definitions
-- Provide specific solutions
-- Support context customization
-- Formatted output
-
-**Usage**:
-
-```bash
-# View all error types
-python3 scripts/error_helper.py
-
-# View solution for a specific error
-python3 scripts/error_helper.py missing_readme
-
-# With context
-python3 scripts/error_helper.py missing_readme project_path=my_project
-```
-
-**Supported Error Types**:
-
-- `missing_readme` - Missing README.md
-- `missing_spec` - Missing design specification
-- `missing_svg_output` - Missing svg_output directory
-- `viewbox_mismatch` - viewBox mismatch
-- `foreignobject_detected` - Banned element detected (see AGENTS.md blocklist)
-- etc.
-
----
-
-### 7. svg_quality_checker.py — SVG Quality Check Tool
-
-Checks whether SVG files comply with the project's technical specifications.
-
-**Features**:
-
-- Validate viewBox attribute
-- Detect banned elements (see AGENTS.md)
-- Check font usage
-- Validate width/height consistency with viewBox
-- Check text line-break methods
-
-**Usage**:
-
-```bash
-# Check a single file
-python3 scripts/svg_quality_checker.py examples/project/svg_output/01_cover.svg
-
-# Check an entire directory
-python3 scripts/svg_quality_checker.py examples/project/svg_output
-
-# Check a project (auto-finds svg_output)
-python3 scripts/svg_quality_checker.py examples/project
-
-# Specify expected format
-python3 scripts/svg_quality_checker.py examples/project --format ppt169
-
-# Check all projects
-python3 scripts/svg_quality_checker.py --all examples
-
-# Export report
-python3 scripts/svg_quality_checker.py examples/project --export
-```
-
-**Check Items**:
-
-- ✅ viewBox attribute exists and is correctly formatted
-- ✅ No banned elements (see AGENTS.md)
-- ✅ Uses fonts specified in the Design Specification & Content Outline (design_spec)
-- ✅ width/height consistent with viewBox
-- ✅ Text uses `<tspan>` for line breaks
-
----
-
-### PPT Compatibility Rules
-
-To ensure consistent appearance after exporting to PPT, **transparency must use standard syntax**:
-
-| ❌ Banned | ✅ Correct |
-|-----------|-----------|
-| `fill="rgba(255,255,255,0.1)"` | `fill="#FFFFFF" fill-opacity="0.1"` |
-| `<g opacity="0.2">...</g>` | Set opacity on each child element individually |
-| `<image opacity="0.3"/>` | Add a mask layer after the image: `<rect fill="background-color" opacity="0.7"/>` |
-
-> **Mnemonic**: PPT does not support rgba, group opacity, image opacity, or markers.
-
----
-
-### 8. svg_to_pptx.py — SVG to PPTX Tool
-
-Batch converts SVG files in a project to a PowerPoint presentation, preserving vector graphics editability.
-
-**Features**:
-
-- **Default: generates two files** — native shapes (.pptx) + SVG reference (_svg.pptx)
-- Native shapes version: directly editable DrawingML shapes in PowerPoint
-- SVG reference version: preserves SVG as image for archival and quality review
-- Each SVG corresponds to one slide
-- Auto-detect canvas format and set slide dimensions
-- Support using svg_output or svg_final directories
-- **Support slide transition and entrance animations**
-- **Auto-embed speaker notes** (read from notes/ directory)
-
-**Usage**:
-
-```bash
-# Default: generates native shapes + SVG reference (two files)
+python3 scripts/project_manager.py import-sources <project_path> <source_files...> --move
+python3 scripts/total_md_split.py <project_path>
+python3 scripts/finalize_svg.py <project_path>
python3 scripts/svg_to_pptx.py <project_path> -s final
-
-# Only native shapes version (skip SVG reference)
-python3 scripts/svg_to_pptx.py <project_path> -s final --only native
-
-# Only SVG image version
-python3 scripts/svg_to_pptx.py <project_path> -s final --only legacy
-
-# Specify output file (SVG ref → output_svg.pptx)
-python3 scripts/svg_to_pptx.py <project_path> -s final -o output.pptx
-
-# Disable speaker notes
-python3 scripts/svg_to_pptx.py <project_path> -s final --no-notes
-
-# Disable default fade transition
-python3 scripts/svg_to_pptx.py <project_path> -t none
-
-# Use a different transition effect
-python3 scripts/svg_to_pptx.py <project_path> -t push --transition-duration 1.0
-
-# Silent mode
-python3 scripts/svg_to_pptx.py <project_path> -s final -q
```
-**Speaker Notes**:
-
-The tool automatically reads Markdown note files from the `notes/` directory and embeds them into the PPTX speaker notes.
-
-**Two naming conventions are supported**:
-- **Recommended**: Same name as the SVG (e.g., `01_cover.svg` maps to `notes/01_cover.md`)
-- **Compatible**: `slide01.md` format (backward compatible)
-
-| Parameter | Description |
-|-----------|-------------|
-| Default | Auto-embed notes (empty if no note file found) |
-| `--no-notes` | Disable note embedding |
-
-**Transition Effect Parameters**:
+## Script Index
-| Parameter | Description | Options |
-|-----------|-------------|---------|
-| `-t`, `--transition` | Slide transition effect (default: fade) | none, fade, push, wipe, split, strips, cover, random |
-| `--transition-duration` | Transition duration in seconds (default: 0.5) | Any positive number |
-| `--auto-advance` | Auto-advance interval in seconds | Any positive number |
+| Area | Primary scripts | Documentation |
+|------|-----------------|---------------|
+| Conversion | `pdf_to_md.py`, `doc_to_md.py`, `web_to_md.py`, `web_to_md.cjs` | [docs/conversion.md](./docs/conversion.md) |
+| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py` | [docs/project.md](./docs/project.md) |
+| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
+| Image tools | `image_gen.py`, `analyze_images.py`, `gemini_watermark_remover.py` | [docs/image.md](./docs/image.md) |
+| Troubleshooting | validation, preview, export, dependency issues | [docs/troubleshooting.md](./docs/troubleshooting.md) |
-**Transition Effects**:
-
-| Effect | Description |
-|--------|-------------|
-| none | No transition |
-| fade | Fade in/out (default) |
-| push | Push |
-| wipe | Wipe |
-| split | Split |
-| strips | Strips (diagonal wipe) |
-| cover | Cover |
-| random | Random |
-
-**SVG Source Directory (`-s`)**:
-
-| Parameter | Directory | Description |
-|-----------|-----------|-------------|
-| `-s output` | `svg_output/` | Original version |
-| `-s final` | `svg_final/` | Post-processed (recommended) |
-| `-s <any_name>` | `<any_name>/` | Specify subdirectory directly |
-
-**Examples**:
-
-```bash
-# Recommended workflow: post-process first, then export (fade transition applied by default)
-python3 scripts/finalize_svg.py examples/ppt169_demo
-python3 scripts/svg_to_pptx.py examples/ppt169_demo -s final
-
-# Auto-play presentation (3-second auto-advance)
-python3 scripts/svg_to_pptx.py examples/ppt169_demo -s final --auto-advance 3
-```
+## High-Frequency Commands
-**Dependencies**:
+Project setup:
```bash
-pip install python-pptx
+python3 scripts/project_manager.py init <project_name> --format ppt169
+python3 scripts/project_manager.py import-sources <project_path> <source_files...> --move
+python3 scripts/project_manager.py validate <project_path>
```
-**Notes**:
-
-- Default generates two PPTX files: native shapes (editable) + SVG reference (archival)
-- Native shapes version is directly editable in PowerPoint without manual conversion
-- SVG reference version preserves original SVGs for quality review and version archival
-- Use `--only native` or `--only legacy` to generate just one version
-- Requires PowerPoint 2016+ for correct display
-- Transition effects are off by default; users must explicitly enable them
-- Speaker notes are on by default; use `--no-notes` to disable
-
----
-
-### 9. total_md_split.py — Speaker Notes Splitter
-
-Splits the `total.md` speaker notes file into multiple individual note files, each corresponding to one SVG page.
-
-**Features**:
-
-- Read the `total.md` file and parse its level-1 headings and note content
-- Check whether all SVG files in the `svg_output` folder have corresponding notes
-- If any SVG lacks a corresponding note, output an error prompting regeneration of the notes file
-- If all match, split the document by name into multiple files
-- Split files are named the same as their SVG counterparts with a `.md` extension
-- Split files **do not include** the level-1 heading
-
-**Usage**:
+Post-processing and export:
```bash
-# Basic usage
python3 scripts/total_md_split.py <project_path>
-
-# Specify output directory
-python3 scripts/total_md_split.py <project_path> -o <output_directory>
-
-# Silent mode
-python3 scripts/total_md_split.py <project_path> -q
+python3 scripts/finalize_svg.py <project_path>
+python3 scripts/svg_to_pptx.py <project_path> -s final
```
-**Examples**:
+Image generation:
```bash
-# Basic usage
-python3 scripts/total_md_split.py projects/<svg_title>_ppt169_YYYYMMDD
-
-# Specify output directory
-python3 scripts/total_md_split.py projects/<svg_title>_ppt169_YYYYMMDD -o notes
-
-# Silent mode
-python3 scripts/total_md_split.py projects/<svg_title>_ppt169_YYYYMMDD -q
-```
-
-**Notes Format Requirements**:
-
-The `total.md` file must use the following format:
-
-```markdown
-# 01_<page_title>
-
-Speaker notes content...
-
----
-
-# 02_<page_title>
-
-Speaker notes content...
-
----
-
-# 03_<page_title>
-
-Speaker notes content...
+python3 scripts/image_gen.py "A modern futuristic workspace"
+python3 scripts/image_gen.py --list-backends
+python3 scripts/analyze_images.py <project_path>/images
```
-- Each section begins with a level-1 heading starting with `# ` (**strictly required**)
-- The heading text must match the corresponding SVG filename (**strictly required**)
-- Sections must be separated by `---` (**strictly required**)
-- Note content follows the heading until the next heading or end of file
-
-**Fault Tolerance (Tool Side)**:
-Even if the format does not strictly conform, `total_md_split.py` will attempt to split based on heading/page number/name similarity, but results are not guaranteed. Please adhere to the strict format.
-
-**Error Handling**:
-
-If any SVG file lacks a corresponding note, the tool will output an error message:
-
-```
-Error: SVG files and speaker notes do not match
- Missing notes: <N>_<page_title>
-
-Please regenerate the notes file, ensuring every SVG has a corresponding note.
-```
-
-**Dependencies**:
-
-- Python 3.6+
-- No external dependencies (standard library only)
-
----
-
-### 10. svg_position_calculator.py — SVG Position Calculation & Validation Tool
-
-A tool for **pre-calculation** and **post-validation** of chart coordinates, helping ensure accurate SVG element positioning.
-
-#### Core Features
-
-| Feature | Description |
-|---------|-------------|
-| **analyze** | Analyze an SVG file and extract coordinate information for all graphical elements |
-| **calc** | Calculate expected chart coordinates based on data |
-| **interactive** | Interactive guided calculation (recommended for beginners) |
-| **from-json** | Batch calculation from a JSON configuration file |
-| **validate** | Validate SVG coordinates against expected values for deviation |
-
-#### Supported Chart Types
-
-| Type | Calculation | Output |
-|------|-------------|--------|
-| **Bar chart (bar)** | Bar X/Y/width/height, label positions | Coordinate table |
-| **Pie chart (pie)** | Sector angles, arc endpoints, label positions | Coordinate table + Path d attribute |
-| **Radar chart (radar)** | Polygon vertices, label positions | Coordinate table + polygon points |
-| **Line chart (line)** | Data point SVG coordinates | Coordinate table + Path d attribute |
-| **Grid layout (grid)** | Cell positions and dimensions | Coordinate table |
-| **Custom polyline** | Arbitrary formula calculation | Coordinate table + polyline points |
-
----
-
-#### Command Details
-
-##### 1. analyze — Analyze SVG File
-
-Extract position information for all graphical elements in an SVG, for validation or debugging.
-
-```bash
-python3 scripts/svg_position_calculator.py analyze <svg_file>
-```
-
-**Example Output**:
-
-```
-======================================================================
-SVG File Analysis: slide_03_chart.svg
-======================================================================
-Canvas viewBox: 0 0 1920 1200
-
-Element Statistics:
- - rect (rectangles): 18
- - circle: 7
- - polyline/polygon: 1
- - path: 2
-
-=== Rectangle Elements (rect) ===
-Index X Y Width Height
-1 0 0 1920 130
-2 190 285 200 530
-...
-
-=== Polylines/Polygons (polyline/polygon) ===
-Polyline 1 (39 points):
- Start: (210,431) → (250,425) → (290,433) → (330,377) → (370,517)
- ... 39 points total
-```
-
-##### 2. calc — Quick Coordinate Calculation
-
-Quickly calculate expected chart element coordinates based on data.
-
-**Bar Chart**:
-
-```bash
-python3 scripts/svg_position_calculator.py calc bar \
- --data "East:185,South:142,North:128" \
- --canvas ppt169 \
- --bar-width 50
-```
-
-Output:
-```
-=== Bar Chart Coordinate Calculation ===
-Canvas: 1280×720
-Chart Area: (140, 150) - (1160, 600)
-
-Index Label Value X Y Width Height
----- ---------- -------- ------- ------- ------- -------
- 1 East 185.0 560.0 190.9 50.0 409.1
- 2 South 142.0 625.0 286.0 50.0 314.0
- 3 North 128.0 690.0 317.0 50.0 283.0
-```
-
-**Pie Chart**:
-
-```bash
-python3 scripts/svg_position_calculator.py calc pie \
- --data "A:35,B:25,C:20,D:12,Other:8" \
- --center 420,400 \
- --radius 200 \
- --start-angle -90
-```
-
-Output:
-```
-=== Pie Chart Sector Calculation ===
-Center: (420, 400) | Radius: 200
-
-Index Label Percent Start End LabelX LabelY
----- ---------- -------- -------- -------- ------- -------
- 1 A 35.0% -90.0 36.0 476.0 296.2
- 2 B 25.0% 36.0 126.0 508.3 443.8
-...
-
-=== Path d Attributes ===
-1. A: M 0,0 L 0.00,-200.00 A 200,200 0 0,1 161.80,-117.56 Z
-2. B: M 0,0 L 161.80,-117.56 A 200,200 0 0,1 117.56,161.80 Z
-...
-```
-
-**Radar Chart**:
-
-```bash
-python3 scripts/svg_position_calculator.py calc radar \
- --data "Performance:90,Security:85,Usability:75,Price:70,Service:80" \
- --center 640,400 \
- --radius 200
-```
-
-**Line Chart**:
-
-```bash
-python3 scripts/svg_position_calculator.py calc line \
- --data "0:50,10:80,20:120,30:95" \
- --canvas ppt169 \
- --y-range "0,150"
-```
-
-**Grid Layout**:
-
-```bash
-python3 scripts/svg_position_calculator.py calc grid \
- --rows 2 --cols 3 \
- --canvas ppt169 \
- --padding 20 --gap 20
-```
-
-##### 3. interactive — Interactive Mode
-
-Suitable for users unfamiliar with command-line arguments; guides you through calculation via menus.
-
-```bash
-python3 scripts/svg_position_calculator.py interactive
-```
-
-Menu Options:
-```
-Select chart type:
- 1. Bar chart (bar)
- 2. Pie chart (pie)
- 3. Radar chart (radar)
- 4. Line chart (line)
- 5. Grid layout (grid)
- 6. Custom polyline (custom) ← Supports custom formulas
- 0. Exit
-```
-
-**Custom polyline (option 6)** is particularly useful for scenarios like price index charts that require custom coordinate formulas:
-
-```
-=== Custom Polyline Calculation ===
-X start value [170]: 210
-X step [40]: 40
-Y baseline [595]: 595
-Y scale factor [20]: 20
-Reference baseline [100]: 100
-
-Formula: X = 210 + index × 40
- Y = 595 - (value - 100) × 20
-
-Input data: 108.2,108.5,108.1,110.9,103.9,97.0
-
-Index Value X Y
----- ---------- -------- --------
-1 108.2 250 431
-2 108.5 290 425
-3 108.1 330 433
-4 110.9 370 377
-5 103.9 410 517
-6 97.0 450 655
-
-polyline points:
-250,431 290,425 330,433 370,377 410,517 450,655
-```
-
-##### 4. from-json — Batch Calculation from JSON Config
-
-Read configuration from a JSON file for calculation; suitable for batch processing or saving frequently used configurations.
-
-```bash
-python3 scripts/svg_position_calculator.py from-json config.json
-```
-
-**JSON Configuration Examples**:
-
-Bar chart config:
-```json
-{
- "type": "bar",
- "canvas": "ppt169",
- "data": {
- "East": 185,
- "South": 142,
- "North": 128
- }
-}
-```
-
-Custom polyline config:
-```json
-{
- "type": "custom_line",
- "base_x": 210,
- "step_x": 40,
- "base_y": 595,
- "scale_y": 20,
- "ref_value": 100,
- "values": [108.2, 108.5, 108.1, 110.9, 103.9, 97.0]
-}
-```
-
----
-
-#### Typical Validation Workflow
-
-After AI generates SVG charts, you can use this tool to verify coordinate accuracy:
-
-1. **Analyze the SVG file** to extract actual coordinates:
- ```bash
- python3 scripts/svg_position_calculator.py analyze slide.svg
- ```
-
-2. **Calculate expected coordinates from the raw data** (using calc or interactive)
-
-3. **Compare expected coordinates with actual coordinates** to check for deviations
-
-4. **If deviations exist, correct the SVG file**
-
-**Example: Validating a Price Index Line Chart**
-
-```bash
-# 1. Analyze the SVG to view polyline points
-python3 scripts/svg_position_calculator.py analyze slide_03_trend.svg
-
-# 2. Use interactive mode to calculate expected coordinates (select 6. Custom polyline)
-python3 scripts/svg_position_calculator.py interactive
-
-# 3. Compare the output polyline points with the actual values in the SVG
-```
-
----
-
-#### Coordinate Calculation Formula Reference
-
-**Bar Chart**:
-```
-bar_x = chart_area.x_min + (chart_area.width - total_bars_width) / 2 + i * (bar_width + gap)
-bar_y = chart_area.y_max - (value / max_value) * chart_area.height
-bar_height = (value / max_value) * chart_area.height
-```
-
-**Pie Chart Arc Endpoints**:
-```
-angle_rad = angle_degrees × π / 180
-end_x = radius × cos(angle_rad)
-end_y = radius × sin(angle_rad)
-```
-
-**Line Chart (Custom Formula)**:
-```
-X = base_x + index × step_x
-Y = base_y - (value - ref_value) × scale_y
-```
-
----
-
-#### FAQ
-
-**Q: What if the output shows garbled Chinese characters?**
-
-A: The tool automatically handles UTF-8 encoding issues on Windows. If problems persist, ensure your terminal is set to UTF-8:
-```bash
-chcp 65001
-```
-
-**Q: How to validate complex charts?**
-
-A: For complex charts (e.g., multi-series bar charts), it is recommended to:
-1. First use `analyze` to extract all elements
-2. Manually calculate expected values based on chart logic
-3. Compare and verify one by one
-
-**Q: Which canvas formats are supported?**
-
-A: Supports `ppt169`, `ppt43`, `xiaohongshu`, `moments`, etc. See `CANVAS_FORMATS` in `project_utils.py` for details.
-
----
-
-### 11. svg_rect_to_path.py — SVG Rounded Rect to Path Tool
-
-Solves the problem of rounded corners being lost when using "Convert to Shape" in PowerPoint.
-
-**Problem**: PowerPoint cannot correctly parse the `rx`/`ry` rounded corner attributes of `<rect>`
-
-**Solution**: Convert `<rect rx="12" ry="12">` to an equivalent `<path d="...arcs...">`
-
-**Usage**:
-
-```bash
-# Process SVGs in a project (defaults to svg_output)
-python3 scripts/svg_rect_to_path.py <project_path>
-
-# Specify SVG source directory
-python3 scripts/svg_rect_to_path.py <project_path> -s final
-
-# Specify output directory name
-python3 scripts/svg_rect_to_path.py <project_path> -o svg_for_ppt
-
-# Process a single file
-python3 scripts/svg_rect_to_path.py path/to/file.svg
-
-# Verbose output
-python3 scripts/svg_rect_to_path.py <project_path> -v
-```
-
-**Examples**:
-
-```bash
-# Process a project
-python3 scripts/svg_rect_to_path.py examples/ppt169_demo
-# Output to: examples/ppt169_demo/svg_rounded/
-
-# Process a single file
-python3 scripts/svg_rect_to_path.py examples/ppt169_demo/svg_output/01_cover.svg
-# Output to: examples/ppt169_demo/svg_output/01_cover_rounded.svg
-```
-
-**Use Cases**:
-
-When you need to "Convert to Shape" in PowerPoint for editing, pre-process the SVG with this tool to preserve rounded corner effects.
-
-**Notes**:
-
-- If you are only embedding the SVG without converting to shapes, this tool is not needed
-- Transparency will still be lost after "Convert to Shape" (PowerPoint limitation)
-
----
-
-### 12. fix_image_aspect.py — SVG Image Aspect Ratio Fix Tool
-
-Solves the problem of `<image>` elements in SVG being stretched when using "Convert to Shape" in PowerPoint.
-
-**Problem**: When PowerPoint converts SVG to editable shapes, it ignores the `preserveAspectRatio` attribute, causing images to be stretched to fill the specified width/height area.
-
-**Solution**:
-1. Read the image's original aspect ratio
-2. Calculate the correct x, y, width, height based on the `preserveAspectRatio` mode (meet/slice)
-3. Remove the `preserveAspectRatio` attribute, replacing it with precisely calculated dimensions
-
-**Usage**:
-
-```bash
-# Process a single SVG file
-python3 scripts/fix_image_aspect.py path/to/slide.svg
-
-# Process multiple files
-python3 scripts/fix_image_aspect.py 01_cover.svg 02_toc.svg 03_content.svg
-
-# Preview mode (does not modify files)
-python3 scripts/fix_image_aspect.py --dry-run path/to/slide.svg
-
-# Process automatically via finalize_svg.py (recommended)
-python3 scripts/finalize_svg.py <project_path>
-```
-
-**Dependencies**:
-
-```bash
-pip install Pillow # For reading image dimensions (recommended)
-```
-
-> **Note**: If Pillow is not installed, the tool will attempt to read PNG/JPEG header information using basic methods, but installing Pillow is recommended for better compatibility.
-
-**Use Cases**:
-
-When you need to "Convert to Shape" in PowerPoint for editing and the SVG contains images, use this tool to prevent image stretching.
-
-**Integrated into finalize_svg.py**:
-
-This tool is already included as one of the processing steps in `finalize_svg.py` (`fix-aspect`) and runs automatically by default.
-
----
-
-### 13. gemini_watermark_remover.py — Gemini Watermark Removal Tool
-
-Removes the watermark logo from the bottom-right corner of Gemini-generated images. Uses a reverse blending algorithm to restore original pixels.
-
-**Features**:
-
-- Auto-detect watermark size (96px for large images, 48px for small images)
-- Support PNG, JPG, JPEG formats
-- Use reverse blending algorithm for precise original pixel restoration
-- Output files default to adding an `_unwatermarked` suffix
-
-**Usage**:
-
-```bash
-# Process a single image
-python3 scripts/gemini_watermark_remover.py <image_path>
-
-# Specify output file
-python3 scripts/gemini_watermark_remover.py <image_path> -o output_path.png
-
-# Silent mode
-python3 scripts/gemini_watermark_remover.py <image_path> -q
-```
-
-**Examples**:
-
-```bash
-# Process a Gemini-generated image
-python3 scripts/gemini_watermark_remover.py projects/demo/images/bg_01.png
-
-# Specify output path
-python3 scripts/gemini_watermark_remover.py image.jpg -o image_clean.jpg
-```
-
-**Watermark Detection Rules**:
-
-| Image Size | Watermark Size | Margin |
-|------------|----------------|--------|
-| > 1024×1024 | 96×96 | 64px |
-| ≤ 1024×1024 | 48×48 | 32px |
-
-**Dependencies**:
-
-```bash
-pip install Pillow numpy
-```
-
-**Notes**:
-
-- This tool requires `bg_48.png` and `bg_96.png` watermark background images in the `scripts/assets/` directory
-- Processed images are generated at the original location with an `_unwatermarked` suffix
-
----
-
-### 14. image_gen.py — Unified AI Image Generation Tool
-
-Generates high-quality images via Gemini or OpenAI-compatible APIs, with automatic backend dispatch.
-
-**Features**:
-
-- **Multi-backend**: Supports Gemini and OpenAI-compatible APIs (including local models)
-- **Auto-detect**: Automatically selects backend based on configured environment variables
-- **High resolution**: Supports up to 4K resolution generation
-- **Custom aspect ratio**: Supports mainstream ratios including `16:9`, `4:3`, `1:1`, `9:16`, etc.
-- **Prompt engineering**: Built-in negative prompt support with automatic quality optimization
-
-**Usage**:
-
-```bash
-# Generate an image
-python3 scripts/image_gen.py "A modern futuristic workspace"
-
-# Specify aspect ratio and size
-python3 scripts/image_gen.py "Abstract tech background" --aspect_ratio 16:9 --image_size 4K
-
-# Specify output directory
-python3 scripts/image_gen.py "Concept car" -o projects/demo/images
-
-# Use negative prompt
-python3 scripts/image_gen.py "Beautiful landscape" -n "low quality, blurry, watermark"
-
-# Override backend
-python3 scripts/image_gen.py "A cat" --backend openai
-```
-
-**Parameter Reference**:
-
-| Parameter | Shorthand | Default | Options |
-|-----------|-----------|---------|---------|
-| `prompt` | - | - | Prompt string |
-| `--negative_prompt` | `-n` | None | Negative prompt |
-| `--aspect_ratio` | - | `1:1` | `1:1`, `16:9`, `4:3`, `3:2`, `9:16`, `21:9`, etc. |
-| `--image_size` | - | `1K` | `512px`, `1K`, `2K`, `4K` |
-| `--output` | `-o` | Current working directory | Image save directory |
-| `--filename` | `-f` | Auto-named | Output filename (without extension) |
-| `--backend` | `-b` | Auto-detect | `gemini` or `openai` |
-| `--model` | `-m` | Backend default | Model name override |
-
-**Environment Variable Configuration**:
-
-```bash
-# Backend selection (optional, auto-detects if not set)
-export IMAGE_BACKEND="gemini" # or "openai"
-
-# API Key (required)
-export IMAGE_API_KEY="your-api-key"
-
-# Custom API endpoint (optional, for proxy or local models)
-export IMAGE_BASE_URL="https://your-proxy-url.com/v1beta"
-
-# Model override (optional)
-export IMAGE_MODEL="gemini-3.1-flash-image-preview"
-```
-
-Or use a `.env` file: `cp .env.example .env` and edit.
-
-> **Legacy support**: `GEMINI_API_KEY` / `GEMINI_BASE_URL` and `OPENAI_API_KEY` / `OPENAI_BASE_URL` still work for backward compatibility.
-
-**Dependencies**:
-
-```bash
-pip install google-genai # Gemini backend
-pip install openai # OpenAI backend
-```
-
----
-
-### 15. embed_icons.py — SVG Icon Embedding Tool
-
-Replaces icon placeholders (`<use ...>`) in SVG files with actual icon path data, achieving "zero-dependency" icon embedding.
-
-**Features**:
-
-- Scan `<use data-icon="...">` placeholders
-- Read corresponding SVG icons from the icon library (default `templates/icons/`)
-- Embed as `<g>` groups with applied position, size, and color
-- Support batch processing
-
-**Usage**:
-
-```bash
-# Process a single file
-python3 scripts/embed_icons.py output.svg
-
-# Process an entire directory
-python3 scripts/embed_icons.py svg_output/*.svg
-
-# Preview mode
-python3 scripts/embed_icons.py --dry-run svg_output/*.svg
-```
-
----
-
-## Workflow Integration
-
-### Typical Workflow
-
-1. **Create a new project**
-
- ```bash
- python3 scripts/project_manager.py init my_project --format ppt169
- ```
-
-2. **Edit the Design Specification & Content Outline**
- Edit the generated `design_spec.md` file
-
-3. **Generate SVG files**
- Use AI roles (Strategist → Executor) to generate SVGs and save to `svg_output/`
-
-4. **Post-processing (runs all steps by default)**
-
- ```bash
- # Just run it, no extra parameters needed
- python3 scripts/finalize_svg.py projects/my_project_ppt169_20251116
- ```
-
-5. **Export to PPTX**
-
- ```bash
- python3 scripts/svg_to_pptx.py projects/my_project_ppt169_20251116 -s final
- ```
-
-6. **(Optional) Validate the project**
-
- ```bash
- python3 scripts/project_manager.py validate projects/my_project_ppt169_20251116
- ```
-
-### Batch Operations
-
-**Batch validate projects**:
-
-```bash
-# Validate all example projects
-python3 scripts/batch_validate.py examples
-
-# Validate and export report
-python3 scripts/batch_validate.py examples --export
-```
-
-**Batch check SVG quality**:
-
-```bash
-# Check SVGs in all example projects
-python3 scripts/svg_quality_checker.py --all examples
-
-# Export quality report
-python3 scripts/svg_quality_checker.py --all examples --export
-```
-
-## Dependency Requirements
-
-Most tools use the Python 3 standard library and require no additional dependencies.
-
-**Minimum Python Version**: Python 3.6+
-
-**Optional Dependencies**:
-
-- `python-pptx` — Required for SVG to PPTX conversion
-- `Pillow` — Required for image aspect ratio fixing and watermark removal
-- `numpy` — Required for watermark removal
-
-Install dependencies:
-
-```bash
-pip install -r requirements.txt
-# Or install individually
-pip install python-pptx
-```
-
-## Troubleshooting
-
-### Issue: Project Validation Failed
-
-**Solution**:
-
-1. Run `python3 scripts/project_manager.py validate <path>` to see detailed errors
-2. Fix missing files or directories based on the error messages
-3. Refer to `projects/README.md` for the standard structure
-
-### Issue: SVG Preview Not Displaying Correctly
-
-**Solution**:
-
-1. Ensure the SVG file path is correct
-2. Check that SVG filenames follow the naming convention (`slide_XX_name.svg`)
-3. Use a local server for preview: `python3 -m http.server --directory <svg_output_path> 8000`
-
-## Related Documentation
-
-- [Workflow Tutorial](../../AGENTS.md)
-- [Quick Reference](../../AGENTS.md)
-- [AGENTS Guide](../AGENTS.md)
+## Recommendations
----
+- Keep new runnable scripts at the top level of `scripts/`
+- Move provider-specific or helper internals into subdirectories
+- Prefer the unified entry points `project_manager.py`, `finalize_svg.py`, and `image_gen.py`
+- Prefer `svg_final/` over `svg_output/` when exporting
-_Last updated: 2026-02-03_
+## Related Docs
-_image_gen.py documentation updated: 2026-03-26_
+- [Conversion Tools](./docs/conversion.md)
+- [Project Tools](./docs/project.md)
+- [SVG Pipeline Tools](./docs/svg-pipeline.md)
+- [Image Tools](./docs/image.md)
+- [Troubleshooting](./docs/troubleshooting.md)
+- [AGENTS Guide](../../../AGENTS.md)
-_gemini_watermark_remover.py documentation updated: 2025-12-20_
+_Last updated: 2026-03-26_
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
new file mode 100644
index 00000000..a9ae4f83
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -0,0 +1,89 @@
+# Conversion Tools
+
+Source conversion tools turn PDFs, documents, and web pages into Markdown before project creation.
+
+## `pdf_to_md.py`
+
+Recommended first choice for native PDFs.
+
+```bash
+python3 scripts/pdf_to_md.py book.pdf
+python3 scripts/pdf_to_md.py book.pdf -o output.md
+python3 scripts/pdf_to_md.py ./pdfs
+python3 scripts/pdf_to_md.py ./pdfs -o ./markdown
+```
+
+Use cases:
+- Native PDFs exported from Word, PowerPoint, LaTeX, or similar tools
+- Privacy-sensitive documents that should stay local
+- Fast first-pass extraction before falling back to OCR-heavy tools
+
+Prefer MinerU or another OCR/layout tool when:
+- The PDF is scanned or image-based
+- Multi-column layout parsing is poor
+- Encoding is garbled
+
+Dependency:
+
+```bash
+pip install PyMuPDF
+```
+
+## `doc_to_md.py`
+
+Pandoc-based converter for office and markup formats.
+
+Supported formats include:
+- `.docx`, `.doc`, `.odt`, `.rtf`
+- `.epub`, `.html`, `.tex`, `.rst`, `.org`, `.ipynb`, `.typ`
+
+```bash
+python3 scripts/doc_to_md.py lecture.docx
+python3 scripts/doc_to_md.py lecture.docx -o output.md
+python3 scripts/doc_to_md.py notes.epub
+python3 scripts/doc_to_md.py paper.tex -o paper.md
+```
+
+Dependency:
+
+```bash
+# macOS
+brew install pandoc
+
+# Ubuntu
+sudo apt install pandoc
+```
+
+## `web_to_md.py` / `web_to_md.cjs`
+
+Convert web pages to Markdown and download images locally.
+
+Python version:
+
+```bash
+python3 scripts/web_to_md.py https://example.com/article
+python3 scripts/web_to_md.py https://url1.com https://url2.com
+python3 scripts/web_to_md.py -f urls.txt
+python3 scripts/web_to_md.py https://example.com -o output.md
+```
+
+Node.js version for WeChat or anti-bot pages:
+
+```bash
+node scripts/web_to_md.cjs https://mp.weixin.qq.com/s/xxxx
+node scripts/web_to_md.cjs https://url1.com https://url2.com
+```
+
+Use the Node.js version first for WeChat Official Accounts and similar high-security sites.
+
+## `rotate_images.py`
+
+Fix image EXIF orientation in downloaded or imported assets.
+
+```bash
+python3 scripts/rotate_images.py auto projects/xxx_files
+python3 scripts/rotate_images.py gen projects/xxx_files
+python3 scripts/rotate_images.py fix fixes.json
+```
+
+Use this when extracted photos appear sideways after conversion or import.
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
new file mode 100644
index 00000000..459bacf3
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -0,0 +1,96 @@
+# Image Tools
+
+Image tools cover prompt-based generation, image inspection, and Gemini watermark removal.
+
+## `image_gen.py`
+
+Unified image generation entry point.
+
+```bash
+python3 scripts/image_gen.py "A modern futuristic workspace"
+python3 scripts/image_gen.py "Abstract tech background" --aspect_ratio 16:9 --image_size 4K
+python3 scripts/image_gen.py "Concept car" -o projects/demo/images
+python3 scripts/image_gen.py "Beautiful landscape" -n "low quality, blurry, watermark"
+python3 scripts/image_gen.py --list-backends
+```
+
+Support tiers:
+- Core: `gemini`, `openai`, `qwen`, `zhipu`, `volcengine`
+- Extended: `stability`, `bfl`, `ideogram`
+- Experimental: `siliconflow`, `fal`, `replicate`
+
+Backend selection:
+
+```bash
+python3 scripts/image_gen.py "A cat" --backend openai
+python3 scripts/image_gen.py "A product launch hero image" --backend qwen
+python3 scripts/image_gen.py "科技感背景图" --backend zhipu
+python3 scripts/image_gen.py "A product KV in cinematic style" --backend volcengine
+```
+
+Configuration sources:
+
+1. Current process environment variables
+2. Repo-root `.env` as a fallback
+
+The active backend must always be selected explicitly via `IMAGE_BACKEND`.
+
+Example `.env`:
+
+```env
+IMAGE_BACKEND=gemini
+GEMINI_API_KEY=your-api-key
+GEMINI_BASE_URL=https://your-proxy-url.com/v1beta
+GEMINI_MODEL=gemini-3.1-flash-image-preview
+```
+
+Example process environment:
+
+```bash
+export IMAGE_BACKEND=gemini
+export GEMINI_API_KEY=your-api-key
+export GEMINI_MODEL=gemini-3.1-flash-image-preview
+```
+
+Current process environment wins over `.env`.
+
+Use provider-specific keys only, such as `GEMINI_API_KEY`, `OPENAI_API_KEY`, `QWEN_API_KEY`, `ZHIPU_API_KEY`, `VOLCENGINE_API_KEY`, `FAL_KEY`, or `REPLICATE_API_TOKEN`.
+
+`IMAGE_API_KEY`, `IMAGE_MODEL`, and `IMAGE_BASE_URL` are intentionally unsupported.
+
+If you keep multiple providers in one `.env` or environment, `IMAGE_BACKEND` must explicitly select the active provider.
+
+Recommendation:
+- Default to the Core tier for routine PPT work
+- Use Extended only when you need a specific model style
+- Treat Experimental backends as opt-in
+
+## `analyze_images.py`
+
+Analyze images in a project directory before writing the design spec or composing slide layouts.
+
+```bash
+python3 scripts/analyze_images.py <project_path>/images
+```
+
+Use this instead of opening image files directly when following the project workflow.
+
+## `gemini_watermark_remover.py`
+
+Remove Gemini watermark assets after manual download.
+
+```bash
+python3 scripts/gemini_watermark_remover.py <image_path>
+python3 scripts/gemini_watermark_remover.py <image_path> -o output_path.png
+python3 scripts/gemini_watermark_remover.py <image_path> -q
+```
+
+Notes:
+- Requires `scripts/assets/bg_48.png` and `scripts/assets/bg_96.png`
+- Best used after downloading “full size” Gemini images
+
+Dependencies:
+
+```bash
+pip install Pillow numpy
+```
diff --git a/skills/ppt-master/scripts/docs/project.md b/skills/ppt-master/scripts/docs/project.md
new file mode 100644
index 00000000..06d82142
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/project.md
@@ -0,0 +1,84 @@
+# Project Tools
+
+Project tools create, validate, and inspect the standard PPT Master workspace.
+
+## `project_manager.py`
+
+Main entry point for project setup and validation.
+
+```bash
+python3 scripts/project_manager.py init <project_name> --format ppt169
+python3 scripts/project_manager.py import-sources <project_path> <source1> [<source2> ...]
+python3 scripts/project_manager.py validate <project_path>
+python3 scripts/project_manager.py info <project_path>
+```
+
+Notes:
+- Files outside the workspace are copied into `sources/` by default
+- With `--move`, files outside the workspace are moved into `sources/`
+- Files already inside the workspace are moved directly
+
+Common formats:
+- `ppt169`
+- `ppt43`
+- `xiaohongshu`
+- `moments`
+- `story`
+- `banner`
+- `a4`
+
+Examples:
+
+```bash
+python3 scripts/project_manager.py init my_presentation --format ppt169
+python3 scripts/project_manager.py validate projects/my_presentation_ppt169_20251116
+python3 scripts/project_manager.py info projects/my_presentation_ppt169_20251116
+```
+
+## `project_utils.py`
+
+Shared helper module used by other scripts.
+
+Typical use:
+
+```python
+from project_utils import get_project_info, validate_project_structure
+```
+
+You can also run it directly for quick checks:
+
+```bash
+python3 scripts/project_utils.py <project_path>
+```
+
+## `batch_validate.py`
+
+Batch-check project structure and compliance.
+
+```bash
+python3 scripts/batch_validate.py examples
+python3 scripts/batch_validate.py examples projects
+python3 scripts/batch_validate.py --all
+python3 scripts/batch_validate.py examples --export
+```
+
+Use this for repository-wide health checks before release or cleanup.
+
+## `generate_examples_index.py`
+
+Rebuild `examples/README.md` automatically.
+
+```bash
+python3 scripts/generate_examples_index.py
+python3 scripts/generate_examples_index.py examples
+```
+
+## `error_helper.py`
+
+Show standardized fixes for common project errors.
+
+```bash
+python3 scripts/error_helper.py
+python3 scripts/error_helper.py missing_readme
+python3 scripts/error_helper.py missing_readme project_path=my_project
+```
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
new file mode 100644
index 00000000..eb070a3d
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -0,0 +1,161 @@
+# SVG Pipeline Tools
+
+These tools cover post-processing, SVG validation, speaker notes, and PPTX export.
+
+## Recommended Pipeline
+
+Run these steps in order:
+
+```bash
+python3 scripts/total_md_split.py <project_path>
+python3 scripts/finalize_svg.py <project_path>
+python3 scripts/svg_to_pptx.py <project_path> -s final
+```
+
+## `finalize_svg.py`
+
+Unified post-processing entry point. This is the preferred way to run SVG cleanup.
+
+It aggregates:
+- `embed_icons.py`
+- `crop_images.py`
+- `fix_image_aspect.py`
+- `embed_images.py`
+- `flatten_tspan.py`
+- `svg_rect_to_path.py`
+
+Typical usage:
+
+```bash
+python3 scripts/finalize_svg.py <project_path>
+```
+
+Use standalone sub-tools only when you need advanced debugging or one-off fixes.
+
+## `svg_to_pptx.py`
+
+Convert project SVGs into PPTX.
+
+```bash
+python3 scripts/svg_to_pptx.py <project_path> -s final
+python3 scripts/svg_to_pptx.py <project_path> -s final --only native
+python3 scripts/svg_to_pptx.py <project_path> -s final --only legacy
+python3 scripts/svg_to_pptx.py <project_path> -s final --no-notes
+python3 scripts/svg_to_pptx.py <project_path> -t none
+python3 scripts/svg_to_pptx.py <project_path> -s final --auto-advance 3
+```
+
+Behavior:
+- Default output: native editable PPTX + SVG reference PPTX
+- Recommended source directory: `svg_final/`
+- Speaker notes are embedded automatically unless `--no-notes` is used
+
+Dependency:
+
+```bash
+pip install python-pptx
+```
+
+## `total_md_split.py`
+
+Split `total.md` into per-slide note files.
+
+```bash
+python3 scripts/total_md_split.py <project_path>
+python3 scripts/total_md_split.py <project_path> -o <output_directory>
+python3 scripts/total_md_split.py <project_path> -q
+```
+
+Requirements:
+- Each section begins with `# `
+- Heading text matches the SVG filename
+- Sections are separated by `---`
+
+## `svg_quality_checker.py`
+
+Validate SVG technical compliance.
+
+```bash
+python3 scripts/svg_quality_checker.py examples/project/svg_output/01_cover.svg
+python3 scripts/svg_quality_checker.py examples/project/svg_output
+python3 scripts/svg_quality_checker.py examples/project
+python3 scripts/svg_quality_checker.py examples/project --format ppt169
+python3 scripts/svg_quality_checker.py --all examples
+python3 scripts/svg_quality_checker.py examples/project --export
+```
+
+Checks include:
+- `viewBox`
+- banned elements
+- width/height consistency
+- line-break structure
+
+## `svg_position_calculator.py`
+
+Analyze or pre-calculate chart coordinates.
+
+Common commands:
+
+```bash
+python3 scripts/svg_position_calculator.py analyze <svg_file>
+python3 scripts/svg_position_calculator.py interactive
+python3 scripts/svg_position_calculator.py calc bar --data "East:185,South:142"
+python3 scripts/svg_position_calculator.py calc pie --data "A:35,B:25,C:20"
+python3 scripts/svg_position_calculator.py from-json config.json
+```
+
+Use this when chart geometry needs to be verified before or after AI generation.
+
+## Advanced Standalone Tools
+
+### `flatten_tspan.py`
+
+```bash
+python3 scripts/svg_finalize/flatten_tspan.py examples/<project>/svg_output
+python3 scripts/svg_finalize/flatten_tspan.py path/to/input.svg path/to/output.svg
+```
+
+### `svg_rect_to_path.py`
+
+```bash
+python3 scripts/svg_finalize/svg_rect_to_path.py <project_path>
+python3 scripts/svg_finalize/svg_rect_to_path.py <project_path> -s final
+python3 scripts/svg_finalize/svg_rect_to_path.py path/to/file.svg
+```
+
+Use when rounded corners must survive PowerPoint shape conversion.
+
+### `fix_image_aspect.py`
+
+```bash
+python3 scripts/svg_finalize/fix_image_aspect.py path/to/slide.svg
+python3 scripts/svg_finalize/fix_image_aspect.py 01_cover.svg 02_toc.svg
+python3 scripts/svg_finalize/fix_image_aspect.py --dry-run path/to/slide.svg
+```
+
+Use when embedded images stretch after PowerPoint shape conversion.
+
+### `embed_icons.py`
+
+```bash
+python3 scripts/svg_finalize/embed_icons.py output.svg
+python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
+python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
+```
+
+Use for manual icon embedding checks outside `finalize_svg.py`.
+
+## PPT Compatibility Rules
+
+Use PowerPoint-safe transparency syntax:
+
+| Avoid | Use instead |
+|------|-------------|
+| `fill=\"rgba(...)\"` | `fill=\"#hex\"` + `fill-opacity` |
+| `<g opacity=\"...\">` | Set opacity on each child |
+| `<image opacity=\"...\">` | Overlay with a mask layer |
+
+PowerPoint also has trouble with:
+- marker-based arrows
+- unsupported filters
+- direct SVG features not mapped to DrawingML
diff --git a/skills/ppt-master/scripts/docs/troubleshooting.md b/skills/ppt-master/scripts/docs/troubleshooting.md
new file mode 100644
index 00000000..125cba96
--- /dev/null
+++ b/skills/ppt-master/scripts/docs/troubleshooting.md
@@ -0,0 +1,62 @@
+# Troubleshooting
+
+## Validation Failed
+
+1. Run:
+
+```bash
+python3 scripts/project_manager.py validate <project_path>
+```
+
+2. Fix missing files or invalid directories reported by the validator.
+3. Re-run validation before post-processing or export.
+
+## SVG Preview Looks Wrong
+
+1. Check the file path and filename.
+2. Confirm naming conventions are consistent.
+3. Preview via a local server if browser file loading is inconsistent:
+
+```bash
+python3 -m http.server --directory <svg_output_path> 8000
+```
+
+## Speaker Notes Do Not Split
+
+Check `total.md`:
+- headings must start with `# `
+- heading text must match SVG filenames
+- sections must be separated by `---`
+
+Then rerun:
+
+```bash
+python3 scripts/total_md_split.py <project_path>
+```
+
+## PPT Export Quality Issues
+
+Preferred sequence:
+
+```bash
+python3 scripts/total_md_split.py <project_path>
+python3 scripts/finalize_svg.py <project_path>
+python3 scripts/svg_to_pptx.py <project_path> -s final
+```
+
+Do not export directly from `svg_output/` when `svg_final/` exists.
+
+## Dependency Checklist
+
+Most tools use the standard library. Install extra dependencies only when needed:
+
+```bash
+pip install -r requirements.txt
+```
+
+Important optional packages:
+- `python-pptx` for PPTX export
+- `Pillow` for image utilities
+- `numpy` for watermark removal
+- `PyMuPDF` for PDF conversion
+- `google-genai` / `openai` for image generation backends
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index 64d2ccfc..021b3f89 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -32,12 +32,12 @@ import shutil
import argparse
from pathlib import Path
-# Import utility modules from the same directory
+# Import finalize helpers from the internal package.
sys.path.insert(0, str(Path(__file__).parent))
-from embed_icons import process_svg_file as embed_icons_in_file
-from embed_images import embed_images_in_svg
-from fix_image_aspect import fix_image_aspect_in_svg
-from crop_images import process_svg_images as crop_images_in_svg
+from svg_finalize.crop_images import process_svg_images as crop_images_in_svg
+from svg_finalize.embed_icons import process_svg_file as embed_icons_in_file
+from svg_finalize.embed_images import embed_images_in_svg
+from svg_finalize.fix_image_aspect import fix_image_aspect_in_svg
def safe_print(text):
@@ -53,7 +53,7 @@ def safe_print(text):
def process_flatten_text(svg_file: Path, verbose: bool = False) -> bool:
"""Flatten text in a single SVG file (in-place modification)"""
try:
- from flatten_tspan import flatten_text_with_tspans
+ from svg_finalize.flatten_tspan import flatten_text_with_tspans
from xml.etree import ElementTree as ET
tree = ET.parse(str(svg_file))
@@ -73,7 +73,7 @@ def process_flatten_text(svg_file: Path, verbose: bool = False) -> bool:
def process_rounded_rect(svg_file: Path, verbose: bool = False) -> int:
"""Convert rounded rectangles in a single SVG file (in-place modification)"""
try:
- from svg_rect_to_path import process_svg
+ from svg_finalize.svg_rect_to_path import process_svg
with open(svg_file, 'r', encoding='utf-8') as f:
content = f.read()
diff --git a/skills/ppt-master/scripts/image_backends/__init__.py b/skills/ppt-master/scripts/image_backends/__init__.py
new file mode 100644
index 00000000..11f791ba
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/__init__.py
@@ -0,0 +1 @@
+"""Internal backend implementations for image_gen.py."""
diff --git a/skills/ppt-master/scripts/image_backends/backend_bfl.py b/skills/ppt-master/scripts/image_backends/backend_bfl.py
new file mode 100644
index 00000000..e36362df
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_bfl.py
@@ -0,0 +1,174 @@
+#!/usr/bin/env python3
+"""
+Black Forest Labs FLUX image generation backend.
+
+Configuration keys:
+ BFL_API_KEY (required)
+ BFL_BASE_URL (optional)
+ BFL_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ poll_json,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+VALID_ASPECT_RATIOS = [
+ "1:1", "2:3", "3:2", "3:4", "4:3",
+ "4:5", "5:4", "9:16", "16:9", "21:9",
+]
+
+DEFAULT_BASE_URL = "https://api.bfl.ai"
+DEFAULT_MODEL = "flux-pro-1.1-ultra"
+
+MODEL_ENDPOINTS = {
+ "flux-pro-1.1": "/v1/flux-pro-1.1",
+ "flux-pro-1.1-ultra": "/v1/flux-pro-1.1-ultra",
+ "flux-dev": "/v1/flux-dev",
+}
+
+ASPECT_RATIO_TO_DIMENSIONS = {
+ "1:1": (1024, 1024),
+ "2:3": (1024, 1536),
+ "3:2": (1536, 1024),
+ "3:4": (1024, 1365),
+ "4:3": (1365, 1024),
+ "4:5": (1024, 1280),
+ "5:4": (1280, 1024),
+ "9:16": (1024, 1820),
+ "16:9": (1820, 1024),
+ "21:9": (2048, 878),
+}
+
+
+def _submit_request(url: str, headers: dict, payload: dict) -> dict:
+ response = requests.post(url, headers=headers, json=payload, timeout=180)
+ if response.status_code != 200:
+ raise http_error(response, "BFL generation request")
+ return response.json()
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
+ del image_size # BFL quality is primarily controlled by model choice.
+
+ if aspect_ratio not in VALID_ASPECT_RATIOS:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for BFL backend. "
+ f"Supported: {VALID_ASPECT_RATIOS}"
+ )
+
+ normalized_model = model.strip().lower()
+ endpoint = MODEL_ENDPOINTS.get(normalized_model)
+ if not endpoint:
+ supported = sorted(MODEL_ENDPOINTS)
+ raise ValueError(f"Unsupported BFL model '{model}'. Supported: {supported}")
+
+ headers = {
+ "x-key": api_key,
+ "accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+ final_prompt = prompt
+ if negative_prompt:
+ final_prompt += f"\n\nAvoid the following: {negative_prompt}"
+
+ payload = {
+ "prompt": final_prompt,
+ "prompt_upsampling": False,
+ "output_format": "png",
+ }
+
+ if normalized_model.endswith("-ultra"):
+ payload["aspect_ratio"] = aspect_ratio
+ payload["raw"] = False
+ else:
+ width, height = ASPECT_RATIO_TO_DIMENSIONS[aspect_ratio]
+ payload["width"] = width
+ payload["height"] = height
+
+ url = base_url.rstrip("/") + endpoint
+
+ print("[Black Forest Labs]")
+ print(f" Model: {normalized_model}")
+ print(f" Prompt: {final_prompt[:120]}{'...' if len(final_prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print()
+ print(" ⏳ Submitting request...", end="", flush=True)
+ start = time.time()
+ request_payload = _submit_request(url, headers, payload)
+ elapsed = time.time() - start
+ print(f"\n ✅ Request accepted ({elapsed:.1f}s)")
+
+ polling_url = request_payload.get("polling_url")
+ if not polling_url:
+ raise RuntimeError(f"BFL response missing polling_url: {request_payload}")
+
+ print(" ⏳ Polling result...")
+ result_payload = poll_json(
+ polling_url,
+ {"x-key": api_key, "accept": "application/json"},
+ status_label="status",
+ ready_values=["Ready"],
+ failed_values=["Error", "Failed", "Request Moderated", "Content Moderated"],
+ )
+
+ image_url = ((result_payload.get("result") or {}).get("sample"))
+ if not image_url:
+ raise RuntimeError(f"BFL result missing sample URL: {result_payload}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "BFL_API_KEY",
+ message="No API key found. Set BFL_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("BFL_BASE_URL") or DEFAULT_BASE_URL
+ resolved_model = model or os.environ.get("BFL_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_common.py b/skills/ppt-master/scripts/image_backends/backend_common.py
new file mode 100644
index 00000000..f3ba4f2a
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_common.py
@@ -0,0 +1,139 @@
+#!/usr/bin/env python3
+"""
+Shared helpers for image generation backends.
+"""
+
+import os
+import time
+
+import requests
+
+try:
+ from PIL import Image as PILImage
+ HAS_PIL = True
+except ImportError:
+ HAS_PIL = False
+
+
+MAX_RETRIES = 3
+RETRY_BASE_DELAY = 10
+RETRY_BACKOFF = 2
+
+
+def resolve_output_path(prompt: str, output_dir: str = None,
+ filename: str = None, ext: str = ".png") -> str:
+ """Compute the final output file path based on parameters."""
+ if filename:
+ file_name = os.path.splitext(filename)[0]
+ else:
+ safe = "".join(c for c in prompt if c.isalnum() or c in (" ", "_")).rstrip()
+ safe = safe.replace(" ", "_").lower()[:30]
+ file_name = safe or "generated_image"
+
+ full_name = f"{file_name}{ext}"
+ if output_dir:
+ os.makedirs(output_dir, exist_ok=True)
+ return os.path.join(output_dir, full_name)
+ return full_name
+
+
+def report_resolution(path: str):
+ """Try to report image resolution using PIL."""
+ if HAS_PIL:
+ try:
+ img = PILImage.open(path)
+ print(f" Resolution: {img.size[0]}x{img.size[1]}")
+ except Exception:
+ pass
+
+
+def normalize_image_size(image_size: str) -> str:
+ """Normalize image size input to standard format."""
+ s = image_size.strip()
+ upper = s.upper()
+ if upper in ("1K", "2K", "4K"):
+ return upper
+ if upper in ("512PX", "512"):
+ return "512px"
+ return s
+
+
+def is_rate_limit_error(exc: Exception) -> bool:
+ """Check whether the exception appears to be rate limiting."""
+ err_str = str(exc).lower()
+ return (
+ "429" in err_str
+ or "rate" in err_str
+ or "quota" in err_str
+ or "resource_exhausted" in err_str
+ )
+
+
+def retry_delay(attempt: int, rate_limited: bool) -> int:
+ """Return the retry delay for a given attempt."""
+ if rate_limited:
+ return RETRY_BASE_DELAY * (RETRY_BACKOFF ** attempt)
+ return 5
+
+
+def download_image(url: str, path: str, headers: dict = None, timeout: int = 180) -> str:
+ """Download an image URL and save it to disk."""
+ response = requests.get(url, headers=headers or {}, timeout=timeout)
+ response.raise_for_status()
+ with open(path, "wb") as f:
+ f.write(response.content)
+ print(f" File saved to: {path}")
+ report_resolution(path)
+ return path
+
+
+def require_api_key(*candidates: str, message: str):
+ """Return the first non-empty env var from candidates or raise."""
+ for name in candidates:
+ value = os.environ.get(name)
+ if value:
+ return value
+ raise ValueError(message)
+
+
+def http_error(response: requests.Response, label: str) -> RuntimeError:
+ """Convert an HTTP response into a readable RuntimeError."""
+ body = response.text.strip()
+ if len(body) > 500:
+ body = body[:500] + "..."
+ return RuntimeError(f"{label} failed ({response.status_code}): {body}")
+
+
+def poll_json(url: str, headers: dict, *,
+ interval_seconds: float = 2.0,
+ timeout_seconds: int = 300,
+ status_label: str = "status",
+ ready_values=None,
+ failed_values=None) -> dict:
+ """Poll a JSON endpoint until it reports a ready or failed status."""
+ ready = {value.lower() for value in (ready_values or ["ready", "success", "succeeded"])}
+ failed = {value.lower() for value in (failed_values or ["error", "failed", "fail"])}
+
+ start = time.time()
+ while True:
+ response = requests.get(url, headers=headers, timeout=180)
+ response.raise_for_status()
+ payload = response.json()
+ raw_status = str(payload.get(status_label, "")).strip()
+ status = raw_status.lower()
+
+ if raw_status:
+ print(f" Status: {raw_status}")
+
+ if status in ready:
+ return payload
+
+ if status in failed:
+ raise RuntimeError(f"Remote generation failed: {payload}")
+
+ if time.time() - start > timeout_seconds:
+ raise RuntimeError(
+ f"Timed out after {timeout_seconds}s while polling {url}"
+ )
+
+ time.sleep(interval_seconds)
diff --git a/skills/ppt-master/scripts/image_backends/backend_fal.py b/skills/ppt-master/scripts/image_backends/backend_fal.py
new file mode 100644
index 00000000..ab05082e
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_fal.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+"""
+fal.ai image generation backend.
+
+Configuration keys:
+ FAL_KEY / FAL_API_KEY (required)
+ FAL_BASE_URL (optional)
+ FAL_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+VALID_ASPECT_RATIOS = ["1:1", "16:9", "9:16", "3:4", "4:3"]
+DEFAULT_ENDPOINT = "https://fal.run"
+DEFAULT_MODEL = "fal-ai/imagen3/fast"
+
+
+def _resolve_url(base_url: str, model: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith(model):
+ return base
+ return f"{base}/{model}"
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ del image_size
+
+ if aspect_ratio not in VALID_ASPECT_RATIOS:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for fal backend. "
+ f"Supported: {VALID_ASPECT_RATIOS}"
+ )
+
+ url = _resolve_url(base_url, model)
+ headers = {
+ "Authorization": f"Key {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "prompt": prompt,
+ "aspect_ratio": aspect_ratio,
+ "num_images": 1,
+ }
+ if negative_prompt:
+ payload["negative_prompt"] = negative_prompt
+
+ print("[fal.ai]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "fal image generation")
+
+ data = response.json()
+ images = data.get("images") or []
+ image_url = images[0].get("url") if images else None
+ if not image_url:
+ raise RuntimeError(f"fal response missing image URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "FAL_KEY",
+ "FAL_API_KEY",
+ message="No API key found. Set FAL_KEY or FAL_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("FAL_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("FAL_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/backend_gemini.py b/skills/ppt-master/scripts/image_backends/backend_gemini.py
similarity index 68%
rename from skills/ppt-master/scripts/backend_gemini.py
rename to skills/ppt-master/scripts/image_backends/backend_gemini.py
index 0c0c0c96..055082fc 100644
--- a/skills/ppt-master/scripts/backend_gemini.py
+++ b/skills/ppt-master/scripts/image_backends/backend_gemini.py
@@ -5,28 +5,28 @@ Gemini Image Generation Backend
Generates images via the Google GenAI API (Gemini).
Used by image_gen.py as a backend module.
-Environment variables (checked in order):
- IMAGE_API_KEY / GEMINI_API_KEY (required)
- IMAGE_BASE_URL / GEMINI_BASE_URL (optional) Custom API endpoint for proxy services
- IMAGE_MODEL (optional) Override default model
+Configuration keys:
+ GEMINI_API_KEY (required)
+ GEMINI_BASE_URL (optional) Custom API endpoint for proxy services
+ GEMINI_MODEL (optional) Override default model
Dependencies:
pip install google-genai Pillow
"""
import os
-import sys
import time
import threading
from google import genai
from google.genai import types
-
-# Optional dependency: PIL (used to report image resolution)
-try:
- from PIL import Image as PILImage
- HAS_PIL = True
-except ImportError:
- HAS_PIL = False
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ is_rate_limit_error,
+ normalize_image_size,
+ report_resolution,
+ resolve_output_path,
+ retry_delay,
+)
# ╔══════════════════════════════���═══════════════════════════════════╗
@@ -43,68 +43,6 @@ VALID_IMAGE_SIZES = ["512px", "1K", "2K", "4K"]
DEFAULT_MODEL = "gemini-3.1-flash-image-preview"
-MAX_RETRIES = 3
-RETRY_BASE_DELAY = 10
-RETRY_BACKOFF = 2
-
-
-# ╔═════════════════��════════════════════════════════════════════════╗
-# ║ Utilities ║
-# ╚═══════════════���══════════════════════���═══════════════════════════╝
-
-def save_binary_file(file_name: str, data: bytes):
- """Save binary data to a file"""
- with open(file_name, "wb") as f:
- f.write(data)
- print(f"File saved to: {file_name}")
-
-
-def _resolve_output_path(prompt: str, output_dir: str = None,
- filename: str = None, ext: str = ".png") -> str:
- """Compute the final output file path based on parameters"""
- if filename:
- file_name = os.path.splitext(filename)[0]
- else:
- safe = "".join(c for c in prompt if c.isalnum() or c in (' ', '_')).rstrip()
- safe = safe.replace(" ", "_").lower()[:30]
- file_name = safe or "generated_image"
-
- full_name = f"{file_name}{ext}"
- if output_dir:
- os.makedirs(output_dir, exist_ok=True)
- return os.path.join(output_dir, full_name)
- return full_name
-
-
-def _normalize_image_size(image_size: str) -> str:
- """
- Case-insensitive normalization: normalize user input to API-accepted format.
- e.g.: "2k" -> "2K", "4k" -> "4K", "512PX" -> "512px"
- """
- s = image_size.strip()
- upper = s.upper()
- if upper in ("1K", "2K", "4K"):
- return upper
- if upper in ("512PX", "512"):
- return "512px"
- return s
-
-
-def _report_resolution(path: str):
- """Try to report image resolution using PIL"""
- if HAS_PIL:
- try:
- img = PILImage.open(path)
- print(f" Resolution: {img.size[0]}x{img.size[1]}")
- except Exception:
- pass
-
-
-def _is_rate_limit_error(e: Exception) -> bool:
- """Check whether the exception is a rate limit (429) error"""
- err_str = str(e).lower()
- return "429" in err_str or "rate" in err_str or "quota" in err_str or "resource_exhausted" in err_str
-
# ╔══════���═══════════════════════════════════════════════��═══════════╗
# ║ Image Generation ║
@@ -205,10 +143,10 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
if chunk_count > 1:
print(f" Keeping the final chunk (highest quality).")
image = last_image_data.as_image()
- path = _resolve_output_path(prompt, output_dir, filename, ".png")
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
image.save(path)
print(f"File saved to: {path}")
- _report_resolution(path)
+ report_resolution(path)
return path
raise RuntimeError("No image was generated. The server may have refused the request.")
@@ -225,10 +163,10 @@ def generate(prompt: str, negative_prompt: str = None,
"""
Gemini image generation with automatic retry.
- Reads credentials from environment variables:
- IMAGE_API_KEY / GEMINI_API_KEY (fallback)
- IMAGE_BASE_URL / GEMINI_BASE_URL (fallback)
- IMAGE_MODEL (optional override)
+ Reads credentials from the current process environment or the project-root `.env`:
+ GEMINI_API_KEY
+ GEMINI_BASE_URL
+ GEMINI_MODEL (optional override)
Args:
prompt: Positive prompt text
@@ -243,18 +181,18 @@ def generate(prompt: str, negative_prompt: str = None,
Returns:
Path of the saved image file
"""
- api_key = os.environ.get("IMAGE_API_KEY") or os.environ.get("GEMINI_API_KEY")
- base_url = os.environ.get("IMAGE_BASE_URL") or os.environ.get("GEMINI_BASE_URL")
+ api_key = os.environ.get("GEMINI_API_KEY")
+ base_url = os.environ.get("GEMINI_BASE_URL")
if not api_key:
raise ValueError(
- "No API key found. Set IMAGE_API_KEY or GEMINI_API_KEY environment variable."
+ "No API key found. Set GEMINI_API_KEY in the current environment or the project-root .env."
)
if model is None:
- model = os.environ.get("IMAGE_MODEL") or DEFAULT_MODEL
+ model = os.environ.get("GEMINI_MODEL") or DEFAULT_MODEL
- image_size = _normalize_image_size(image_size)
+ image_size = normalize_image_size(image_size)
if aspect_ratio not in VALID_ASPECT_RATIOS:
raise ValueError(f"Invalid aspect ratio '{aspect_ratio}'. Valid: {VALID_ASPECT_RATIOS}")
@@ -270,13 +208,13 @@ def generate(prompt: str, negative_prompt: str = None,
filename, model, base_url)
except Exception as e:
last_error = e
- if attempt < max_retries and _is_rate_limit_error(e):
- delay = RETRY_BASE_DELAY * (RETRY_BACKOFF ** attempt)
+ if attempt < max_retries and is_rate_limit_error(e):
+ delay = retry_delay(attempt, rate_limited=True)
print(f"\n ⚠️ Rate limit hit (attempt {attempt + 1}/{max_retries + 1}). "
f"Waiting {delay}s before retry...")
time.sleep(delay)
elif attempt < max_retries:
- delay = 5
+ delay = retry_delay(attempt, rate_limited=False)
print(f"\n ⚠️ Error (attempt {attempt + 1}/{max_retries + 1}): {e}. "
f"Retrying in {delay}s...")
time.sleep(delay)
diff --git a/skills/ppt-master/scripts/image_backends/backend_ideogram.py b/skills/ppt-master/scripts/image_backends/backend_ideogram.py
new file mode 100644
index 00000000..bdecd190
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_ideogram.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""
+Ideogram image generation backend.
+
+Configuration keys:
+ IDEOGRAM_API_KEY (required)
+ IDEOGRAM_BASE_URL (optional)
+ IDEOGRAM_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+ASPECT_RATIO_MAP = {
+ "1:1": "1x1",
+ "1:4": "1x4",
+ "2:3": "2x3",
+ "3:2": "3x2",
+ "3:4": "3x4",
+ "4:1": "4x1",
+ "4:3": "4x3",
+ "4:5": "4x5",
+ "5:4": "5x4",
+ "9:16": "9x16",
+ "16:9": "16x9",
+ "21:9": "21x9",
+}
+
+DEFAULT_BASE_URL = "https://api.ideogram.ai"
+DEFAULT_MODEL = "ideogram-v3"
+MODEL_ALIASES = {"ideogram-v3", "v3"}
+
+IMAGE_SIZE_TO_SPEED = {
+ "512px": "TURBO",
+ "1K": "DEFAULT",
+ "2K": "QUALITY",
+ "4K": "QUALITY",
+}
+
+
+def _resolve_url(base_url: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith("/generate"):
+ return base
+ return base + "/v1/ideogram-v3/generate"
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
+ normalized_model = model.strip().lower()
+ if normalized_model not in MODEL_ALIASES:
+ raise ValueError(
+ f"Unsupported Ideogram model '{model}'. Supported: {sorted(MODEL_ALIASES)}"
+ )
+
+ mapped_ratio = ASPECT_RATIO_MAP.get(aspect_ratio)
+ if not mapped_ratio:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Ideogram backend. "
+ f"Supported: {sorted(ASPECT_RATIO_MAP)}"
+ )
+
+ rendering_speed = IMAGE_SIZE_TO_SPEED.get(image_size, "DEFAULT")
+ url = _resolve_url(base_url)
+ headers = {"Api-Key": api_key}
+ files = {
+ "prompt": (None, prompt),
+ "aspect_ratio": (None, mapped_ratio),
+ "rendering_speed": (None, rendering_speed),
+ }
+ if negative_prompt:
+ files["negative_prompt"] = (None, negative_prompt)
+
+ print("[Ideogram]")
+ print(f" Model: {normalized_model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio} -> {mapped_ratio}")
+ print(f" Render Speed: {rendering_speed}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, files=files, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Ideogram generation")
+
+ payload = response.json()
+ data = payload.get("data") or []
+ image_url = data[0].get("url") if data else None
+ if not image_url:
+ raise RuntimeError(f"Ideogram response missing image URL: {payload}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "IDEOGRAM_API_KEY",
+ message="No API key found. Set IDEOGRAM_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("IDEOGRAM_BASE_URL") or DEFAULT_BASE_URL
+ resolved_model = model or os.environ.get("IDEOGRAM_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/backend_openai.py b/skills/ppt-master/scripts/image_backends/backend_openai.py
similarity index 70%
rename from skills/ppt-master/scripts/backend_openai.py
rename to skills/ppt-master/scripts/image_backends/backend_openai.py
index 5a7a1cf4..9d5f80f9 100644
--- a/skills/ppt-master/scripts/backend_openai.py
+++ b/skills/ppt-master/scripts/image_backends/backend_openai.py
@@ -5,30 +5,34 @@ OpenAI Compatible Image Generation Backend
Generates images via OpenAI-compatible APIs (OpenAI, local models like Qwen-Image, etc.).
Used by image_gen.py as a backend module.
-Environment variables:
- IMAGE_API_KEY (required) API key
- IMAGE_BASE_URL (optional) Custom API endpoint (e.g. http://127.0.0.1:3000/v1)
- IMAGE_MODEL (optional) Model name (default: gpt-image-1)
+Configuration keys:
+ OPENAI_API_KEY (required) API key
+ OPENAI_BASE_URL (optional) Custom API endpoint (e.g. http://127.0.0.1:3000/v1)
+ OPENAI_MODEL (optional) Model name (default: gpt-image-1)
Dependencies:
pip install openai Pillow
"""
import base64
-import io
import os
-import sys
import time
import threading
from openai import OpenAI
-
-# Optional dependency: PIL (used to report image resolution)
-try:
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ HAS_PIL,
+ is_rate_limit_error,
+ normalize_image_size,
+ report_resolution,
+ resolve_output_path,
+ retry_delay,
+)
+
+if HAS_PIL:
+ import io
from PIL import Image as PILImage
- HAS_PIL = True
-except ImportError:
- HAS_PIL = False
# ╔══════════════════════════════════════════════════════════════════╗
@@ -62,58 +66,6 @@ IMAGE_SIZE_TO_QUALITY = {
DEFAULT_MODEL = "gpt-image-1"
-MAX_RETRIES = 3
-RETRY_BASE_DELAY = 10
-RETRY_BACKOFF = 2
-
-
-# ╔══════════════════════════════════════════════════════════════════╗
-# ║ Utilities ║
-# ╚══════════════════════════════════════════════════════════════════╝
-
-def _resolve_output_path(prompt: str, output_dir: str = None,
- filename: str = None, ext: str = ".png") -> str:
- """Compute the final output file path based on parameters"""
- if filename:
- file_name = os.path.splitext(filename)[0]
- else:
- safe = "".join(c for c in prompt if c.isalnum() or c in (' ', '_')).rstrip()
- safe = safe.replace(" ", "_").lower()[:30]
- file_name = safe or "generated_image"
-
- full_name = f"{file_name}{ext}"
- if output_dir:
- os.makedirs(output_dir, exist_ok=True)
- return os.path.join(output_dir, full_name)
- return full_name
-
-
-def _report_resolution(path: str):
- """Try to report image resolution using PIL"""
- if HAS_PIL:
- try:
- img = PILImage.open(path)
- print(f" Resolution: {img.size[0]}x{img.size[1]}")
- except Exception:
- pass
-
-
-def _is_rate_limit_error(e: Exception) -> bool:
- """Check whether the exception is a rate limit (429) error"""
- err_str = str(e).lower()
- return "429" in err_str or "rate" in err_str or "quota" in err_str
-
-
-def _normalize_image_size(image_size: str) -> str:
- """Normalize image size input to standard format."""
- s = image_size.strip()
- upper = s.upper()
- if upper in ("1K", "2K", "4K"):
- return upper
- if upper in ("512PX", "512"):
- return "512px"
- return s
-
# ╔══════════════════════════════════════════════════════════════════╗
# ║ Image Generation ║
@@ -186,7 +138,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
print(f"\n ✅ Image generated ({elapsed:.1f}s)")
if resp is not None and resp.data:
- path = _resolve_output_path(prompt, output_dir, filename, ".png")
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
image_data = base64.b64decode(resp.data[0].b64_json)
if HAS_PIL:
@@ -197,7 +149,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
f.write(image_data)
print(f" File saved to: {path}")
- _report_resolution(path)
+ report_resolution(path)
return path
raise RuntimeError("No image was generated. The server may have refused the request.")
@@ -214,10 +166,10 @@ def generate(prompt: str, negative_prompt: str = None,
"""
OpenAI-compatible image generation with automatic retry.
- Reads credentials from environment variables:
- IMAGE_API_KEY / OPENAI_API_KEY (fallback)
- IMAGE_BASE_URL / OPENAI_BASE_URL (fallback)
- IMAGE_MODEL (optional override)
+ Reads credentials from the current process environment or the project-root `.env`:
+ OPENAI_API_KEY
+ OPENAI_BASE_URL
+ OPENAI_MODEL (optional override)
Args:
prompt: Positive prompt text
@@ -232,18 +184,18 @@ def generate(prompt: str, negative_prompt: str = None,
Returns:
Path of the saved image file
"""
- api_key = os.environ.get("IMAGE_API_KEY") or os.environ.get("OPENAI_API_KEY")
- base_url = os.environ.get("IMAGE_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
+ api_key = os.environ.get("OPENAI_API_KEY")
+ base_url = os.environ.get("OPENAI_BASE_URL")
if not api_key:
raise ValueError(
- "No API key found. Set IMAGE_API_KEY or OPENAI_API_KEY environment variable."
+ "No API key found. Set OPENAI_API_KEY in the current environment or the project-root .env."
)
if model is None:
- model = os.environ.get("IMAGE_MODEL") or DEFAULT_MODEL
+ model = os.environ.get("OPENAI_MODEL") or DEFAULT_MODEL
- image_size = _normalize_image_size(image_size)
+ image_size = normalize_image_size(image_size)
if aspect_ratio not in ASPECT_RATIO_TO_SIZE:
supported = list(ASPECT_RATIO_TO_SIZE.keys())
@@ -260,13 +212,13 @@ def generate(prompt: str, negative_prompt: str = None,
filename, model, base_url)
except Exception as e:
last_error = e
- if attempt < max_retries and _is_rate_limit_error(e):
- delay = RETRY_BASE_DELAY * (RETRY_BACKOFF ** attempt)
+ if attempt < max_retries and is_rate_limit_error(e):
+ delay = retry_delay(attempt, rate_limited=True)
print(f"\n ⚠️ Rate limit hit (attempt {attempt + 1}/{max_retries + 1}). "
f"Waiting {delay}s before retry...")
time.sleep(delay)
elif attempt < max_retries:
- delay = 5
+ delay = retry_delay(attempt, rate_limited=False)
print(f"\n ⚠️ Error (attempt {attempt + 1}/{max_retries + 1}): {e}. "
f"Retrying in {delay}s...")
time.sleep(delay)
diff --git a/skills/ppt-master/scripts/image_backends/backend_qwen.py b/skills/ppt-master/scripts/image_backends/backend_qwen.py
new file mode 100644
index 00000000..67d25264
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_qwen.py
@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+"""
+Alibaba Cloud Qwen image generation backend.
+
+Configuration keys:
+ QWEN_API_KEY / DASHSCOPE_API_KEY (required)
+ QWEN_BASE_URL (optional)
+ QWEN_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+DEFAULT_ENDPOINT = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
+DEFAULT_MODEL = "qwen-image-2.0-pro"
+
+ASPECT_RATIO_SIZE_MAP = {
+ "512px": {
+ "1:1": "1024*1024",
+ "2:3": "768*1152",
+ "3:2": "1152*768",
+ "3:4": "864*1152",
+ "4:3": "1152*864",
+ "4:5": "896*1120",
+ "5:4": "1120*896",
+ "9:16": "720*1280",
+ "16:9": "1280*720",
+ "21:9": "1344*576",
+ },
+ "1K": {
+ "1:1": "1536*1536",
+ "2:3": "1024*1536",
+ "3:2": "1536*1024",
+ "3:4": "1152*1536",
+ "4:3": "1536*1152",
+ "4:5": "1216*1536",
+ "5:4": "1536*1216",
+ "9:16": "896*1600",
+ "16:9": "1600*896",
+ "21:9": "1792*768",
+ },
+ "2K": {
+ "1:1": "2048*2048",
+ "2:3": "1536*2048",
+ "3:2": "2048*1536",
+ "3:4": "1728*2368",
+ "4:3": "2368*1728",
+ "4:5": "1792*2240",
+ "5:4": "2240*1792",
+ "9:16": "1536*2688",
+ "16:9": "2688*1536",
+ "21:9": "2688*1152",
+ },
+ "4K": {
+ "1:1": "2048*2048",
+ "2:3": "1536*2048",
+ "3:2": "2048*1536",
+ "3:4": "1728*2368",
+ "4:3": "2368*1728",
+ "4:5": "1792*2240",
+ "5:4": "2240*1792",
+ "9:16": "1536*2688",
+ "16:9": "2688*1536",
+ "21:9": "2688*1152",
+ },
+}
+
+
+def _resolve_url(base_url: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith("/generation"):
+ return base
+ return base + "/api/v1/services/aigc/multimodal-generation/generation"
+
+
+def _resolve_size(aspect_ratio: str, image_size: str) -> str:
+ normalized = normalize_image_size(image_size)
+ size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
+ if not size:
+ supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Qwen backend. "
+ f"Supported: {supported}"
+ )
+ return size
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ size = _resolve_size(aspect_ratio, image_size)
+ url = _resolve_url(base_url)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": model,
+ "input": {
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"text": prompt}],
+ }
+ ]
+ },
+ "parameters": {
+ "size": size,
+ "prompt_extend": True,
+ "watermark": False,
+ },
+ }
+ if negative_prompt:
+ payload["parameters"]["negative_prompt"] = negative_prompt
+
+ print("[Alibaba Qwen Image]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Resolution: {size}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Qwen image generation")
+
+ data = response.json()
+ choices = ((data.get("output") or {}).get("choices") or [])
+ contents = (((choices[0] if choices else {}).get("message") or {}).get("content") or [])
+ image_url = contents[0].get("image") if contents else None
+ if not image_url:
+ raise RuntimeError(f"Qwen response missing image URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "QWEN_API_KEY",
+ "DASHSCOPE_API_KEY",
+ message="No API key found. Set QWEN_API_KEY or DASHSCOPE_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("QWEN_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("QWEN_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_replicate.py b/skills/ppt-master/scripts/image_backends/backend_replicate.py
new file mode 100644
index 00000000..7db92b5d
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_replicate.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python3
+"""
+Replicate image generation backend.
+
+Configuration keys:
+ REPLICATE_API_KEY / REPLICATE_API_TOKEN (required)
+ REPLICATE_BASE_URL (optional)
+ REPLICATE_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ poll_json,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+VALID_ASPECT_RATIOS = ["1:1", "16:9", "9:16", "3:4", "4:3", "3:2", "2:3", "4:5", "5:4", "21:9"]
+DEFAULT_BASE_URL = "https://api.replicate.com/v1"
+DEFAULT_MODEL = "black-forest-labs/flux-1.1-pro"
+
+
+def _split_model(model: str) -> tuple[str, str]:
+ parts = [part for part in model.strip().split("/") if part]
+ if len(parts) != 2:
+ raise ValueError(
+ f"Replicate model must be in 'owner/name' format, got '{model}'."
+ )
+ return parts[0], parts[1]
+
+
+def _extract_output_url(payload: dict) -> str | None:
+ output = payload.get("output")
+ if isinstance(output, str):
+ return output
+ if isinstance(output, list) and output:
+ first = output[0]
+ if isinstance(first, str):
+ return first
+ if isinstance(first, dict):
+ return first.get("url")
+ if isinstance(output, dict):
+ return output.get("url")
+ return None
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
+ del image_size
+
+ if aspect_ratio not in VALID_ASPECT_RATIOS:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Replicate backend. "
+ f"Supported: {VALID_ASPECT_RATIOS}"
+ )
+
+ owner, name = _split_model(model)
+ url = f"{base_url.rstrip('/')}/models/{owner}/{name}/predictions"
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ "Prefer": "wait=60",
+ }
+
+ final_prompt = prompt
+ if negative_prompt:
+ final_prompt += f"\n\nAvoid the following: {negative_prompt}"
+
+ payload = {
+ "input": {
+ "prompt": final_prompt,
+ "aspect_ratio": aspect_ratio,
+ "output_format": "png",
+ }
+ }
+
+ print("[Replicate]")
+ print(f" Model: {model}")
+ print(f" Prompt: {final_prompt[:120]}{'...' if len(final_prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=180)
+ elapsed = time.time() - start
+ print(f"\n ✅ Initial response received ({elapsed:.1f}s)")
+
+ if response.status_code not in (200, 201):
+ raise http_error(response, "Replicate generation request")
+
+ data = response.json()
+ status = str(data.get("status", "")).lower()
+ if status != "succeeded":
+ poll_url = ((data.get("urls") or {}).get("get"))
+ if not poll_url:
+ prediction_id = data.get("id")
+ if prediction_id:
+ poll_url = f"{base_url.rstrip('/')}/predictions/{prediction_id}"
+ if not poll_url:
+ raise RuntimeError(f"Replicate response missing poll URL: {data}")
+
+ print(" ⏳ Polling result...")
+ data = poll_json(
+ poll_url,
+ {"Authorization": f"Bearer {api_key}"},
+ status_label="status",
+ ready_values=["succeeded"],
+ failed_values=["failed", "canceled"],
+ )
+
+ image_url = _extract_output_url(data)
+ if not image_url:
+ raise RuntimeError(f"Replicate response missing output URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "REPLICATE_API_KEY",
+ "REPLICATE_API_TOKEN",
+ message="No API key found. Set REPLICATE_API_KEY or REPLICATE_API_TOKEN in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("REPLICATE_BASE_URL") or DEFAULT_BASE_URL
+ resolved_model = model or os.environ.get("REPLICATE_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_siliconflow.py b/skills/ppt-master/scripts/image_backends/backend_siliconflow.py
new file mode 100644
index 00000000..fa4f6ee3
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_siliconflow.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""
+SiliconFlow image generation backend.
+
+Configuration keys:
+ SILICONFLOW_API_KEY (required)
+ SILICONFLOW_BASE_URL (optional)
+ SILICONFLOW_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+DEFAULT_ENDPOINT = "https://api.siliconflow.cn/v1/images/generations"
+DEFAULT_MODEL = "Qwen/Qwen-Image"
+
+ASPECT_RATIO_SIZE_MAP = {
+ "512px": {
+ "1:1": "1024x1024",
+ "2:3": "1056x1584",
+ "3:2": "1584x1056",
+ "3:4": "1140x1472",
+ "4:3": "1472x1140",
+ "4:5": "1140x1425",
+ "5:4": "1425x1140",
+ "9:16": "928x1664",
+ "16:9": "1664x928",
+ },
+ "1K": {
+ "1:1": "1328x1328",
+ "2:3": "1056x1584",
+ "3:2": "1584x1056",
+ "3:4": "1140x1472",
+ "4:3": "1472x1140",
+ "4:5": "1140x1425",
+ "5:4": "1425x1140",
+ "9:16": "928x1664",
+ "16:9": "1664x928",
+ },
+ "2K": {
+ "1:1": "2048x2048",
+ "2:3": "1536x2048",
+ "3:2": "2048x1536",
+ "3:4": "1536x2048",
+ "4:3": "2048x1536",
+ "4:5": "1638x2048",
+ "5:4": "2048x1638",
+ "9:16": "1152x2048",
+ "16:9": "2048x1152",
+ },
+ "4K": {
+ "1:1": "2048x2048",
+ "2:3": "1536x2048",
+ "3:2": "2048x1536",
+ "3:4": "1536x2048",
+ "4:3": "2048x1536",
+ "4:5": "1638x2048",
+ "5:4": "2048x1638",
+ "9:16": "1152x2048",
+ "16:9": "2048x1152",
+ },
+}
+
+
+def _resolve_url(base_url: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith("/images/generations"):
+ return base
+ return base + "/v1/images/generations"
+
+
+def _resolve_size(aspect_ratio: str, image_size: str) -> str:
+ normalized = normalize_image_size(image_size)
+ size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
+ if not size:
+ supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for SiliconFlow backend. "
+ f"Supported: {supported}"
+ )
+ return size
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ size = _resolve_size(aspect_ratio, image_size)
+ url = _resolve_url(base_url)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "image_size": size,
+ }
+ if negative_prompt:
+ payload["negative_prompt"] = negative_prompt
+
+ print("[SiliconFlow]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Resolution: {size}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "SiliconFlow image generation")
+
+ data = response.json()
+ images = data.get("images") or []
+ image_url = images[0].get("url") if images else None
+ if not image_url:
+ raise RuntimeError(f"SiliconFlow response missing image URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "SILICONFLOW_API_KEY",
+ message="No API key found. Set SILICONFLOW_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("SILICONFLOW_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("SILICONFLOW_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_stability.py b/skills/ppt-master/scripts/image_backends/backend_stability.py
new file mode 100644
index 00000000..f528ec05
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_stability.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""
+Stability AI image generation backend.
+
+Configuration keys:
+ STABILITY_API_KEY (required)
+ STABILITY_BASE_URL (optional)
+ STABILITY_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ http_error,
+ is_rate_limit_error,
+ report_resolution,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+VALID_ASPECT_RATIOS = [
+ "1:1", "2:3", "3:2", "3:4", "4:3",
+ "4:5", "5:4", "9:16", "16:9", "21:9",
+]
+
+DEFAULT_BASE_URL = "https://api.stability.ai"
+DEFAULT_MODEL = "stable-image-core"
+
+MODEL_ENDPOINTS = {
+ "core": "/v2beta/stable-image/generate/core",
+ "stable-image-core": "/v2beta/stable-image/generate/core",
+ "ultra": "/v2beta/stable-image/generate/ultra",
+ "stable-image-ultra": "/v2beta/stable-image/generate/ultra",
+}
+
+
+def _resolve_endpoint(model: str, image_size: str, base_url: str) -> tuple[str, str]:
+ resolved_model = model or DEFAULT_MODEL
+ if not model and image_size.upper() in ("2K", "4K"):
+ resolved_model = "stable-image-ultra"
+
+ normalized_model = resolved_model.lower()
+ endpoint = MODEL_ENDPOINTS.get(normalized_model)
+ if not endpoint:
+ supported = sorted(MODEL_ENDPOINTS)
+ raise ValueError(
+ f"Unsupported Stability model '{resolved_model}'. Supported aliases: {supported}"
+ )
+ return normalized_model, base_url.rstrip("/") + endpoint
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
+ if aspect_ratio not in VALID_ASPECT_RATIOS:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Stability backend. "
+ f"Supported: {VALID_ASPECT_RATIOS}"
+ )
+
+ resolved_model, url = _resolve_endpoint(model, image_size, base_url)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "image/*",
+ }
+ data = {
+ "prompt": prompt,
+ "aspect_ratio": aspect_ratio,
+ "output_format": "png",
+ }
+ if negative_prompt:
+ data["negative_prompt"] = negative_prompt
+
+ print("[Stability AI]")
+ print(f" Model: {resolved_model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Preset Size: {image_size}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+
+ response = requests.post(url, headers=headers, data=data, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Stability generation")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ with open(path, "wb") as f:
+ f.write(response.content)
+ print(f" File saved to: {path}")
+ report_resolution(path)
+ return path
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "STABILITY_API_KEY",
+ message="No API key found. Set STABILITY_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("STABILITY_BASE_URL") or DEFAULT_BASE_URL
+ resolved_model = model or os.environ.get("STABILITY_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_volcengine.py b/skills/ppt-master/scripts/image_backends/backend_volcengine.py
new file mode 100644
index 00000000..0e7c702c
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_volcengine.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python3
+"""
+Volcengine Seedream image generation backend.
+
+Configuration keys:
+ VOLCENGINE_API_KEY / ARK_API_KEY (required)
+ VOLCENGINE_BASE_URL (optional)
+ VOLCENGINE_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+DEFAULT_ENDPOINT = "https://operator.las.cn-beijing.volces.com/api/v1/images/generations"
+DEFAULT_MODEL = "doubao-seedream-4-5-251128"
+
+ASPECT_RATIO_SIZE_MAP = {
+ "512px": {
+ "1:1": "1024x1024",
+ "2:3": "1024x1536",
+ "3:2": "1536x1024",
+ "3:4": "1024x1365",
+ "4:3": "1365x1024",
+ "4:5": "1024x1280",
+ "5:4": "1280x1024",
+ "9:16": "1024x1820",
+ "16:9": "1820x1024",
+ "21:9": "2048x878",
+ },
+ "1K": {
+ "1:1": "1536x1536",
+ "2:3": "1344x2016",
+ "3:2": "2016x1344",
+ "3:4": "1440x1920",
+ "4:3": "1920x1440",
+ "4:5": "1536x1920",
+ "5:4": "1920x1536",
+ "9:16": "1152x2048",
+ "16:9": "2048x1152",
+ "21:9": "2048x878",
+ },
+ "2K": {
+ "1:1": "2048x2048",
+ "2:3": "1536x2048",
+ "3:2": "2048x1536",
+ "3:4": "1536x2048",
+ "4:3": "2048x1536",
+ "4:5": "1638x2048",
+ "5:4": "2048x1638",
+ "9:16": "1152x2048",
+ "16:9": "2048x1152",
+ "21:9": "2048x878",
+ },
+ "4K": {
+ "1:1": "2048x2048",
+ "2:3": "1536x2048",
+ "3:2": "2048x1536",
+ "3:4": "1536x2048",
+ "4:3": "2048x1536",
+ "4:5": "1638x2048",
+ "5:4": "2048x1638",
+ "9:16": "1152x2048",
+ "16:9": "2048x1152",
+ "21:9": "2048x878",
+ },
+}
+
+
+def _resolve_url(base_url: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith("/images/generations"):
+ return base
+ return base + "/api/v1/images/generations"
+
+
+def _resolve_size(aspect_ratio: str, image_size: str) -> str:
+ normalized = normalize_image_size(image_size)
+ size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
+ if not size:
+ supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Volcengine backend. "
+ f"Supported: {supported}"
+ )
+ return size
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ size = _resolve_size(aspect_ratio, image_size)
+ url = _resolve_url(base_url)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "size": size,
+ "response_format": "url",
+ "watermark": False,
+ }
+ if negative_prompt:
+ payload["negative_prompt"] = negative_prompt
+
+ print("[Volcengine Seedream]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Resolution: {size}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Volcengine image generation")
+
+ data = response.json()
+ items = data.get("data") or []
+ image_url = items[0].get("url") if items else None
+ if not image_url:
+ raise RuntimeError(f"Volcengine response missing image URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".jpeg")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "VOLCENGINE_API_KEY",
+ "ARK_API_KEY",
+ message="No API key found. Set VOLCENGINE_API_KEY or ARK_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("VOLCENGINE_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("VOLCENGINE_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_backends/backend_zhipu.py b/skills/ppt-master/scripts/image_backends/backend_zhipu.py
new file mode 100644
index 00000000..6516da34
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_zhipu.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python3
+"""
+Zhipu GLM-Image generation backend.
+
+Configuration keys:
+ ZHIPU_API_KEY / BIGMODEL_API_KEY (required)
+ ZHIPU_BASE_URL (optional)
+ ZHIPU_MODEL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+)
+
+
+DEFAULT_ENDPOINT = "https://open.bigmodel.cn/api/paas/v4/images/generations"
+DEFAULT_MODEL = "glm-image"
+
+ASPECT_RATIO_SIZE_MAP = {
+ "512px": {
+ "1:1": "1024x1024",
+ "2:3": "768x1152",
+ "3:2": "1152x768",
+ "3:4": "864x1152",
+ "4:3": "1152x864",
+ "4:5": "1024x1280",
+ "5:4": "1280x1024",
+ "9:16": "720x1440",
+ "16:9": "1440x720",
+ "21:9": "1536x640",
+ },
+ "1K": {
+ "1:1": "1280x1280",
+ "2:3": "960x1440",
+ "3:2": "1440x960",
+ "3:4": "1024x1365",
+ "4:3": "1365x1024",
+ "4:5": "1024x1280",
+ "5:4": "1280x1024",
+ "9:16": "768x1344",
+ "16:9": "1344x768",
+ "21:9": "1536x640",
+ },
+ "2K": {
+ "1:1": "1440x1440",
+ "2:3": "1152x1728",
+ "3:2": "1728x1152",
+ "3:4": "1152x1536",
+ "4:3": "1536x1152",
+ "4:5": "1280x1600",
+ "5:4": "1600x1280",
+ "9:16": "720x1440",
+ "16:9": "1440x720",
+ "21:9": "1792x768",
+ },
+ "4K": {
+ "1:1": "1440x1440",
+ "2:3": "1152x1728",
+ "3:2": "1728x1152",
+ "3:4": "1152x1536",
+ "4:3": "1536x1152",
+ "4:5": "1280x1600",
+ "5:4": "1600x1280",
+ "9:16": "720x1440",
+ "16:9": "1440x720",
+ "21:9": "1792x768",
+ },
+}
+
+
+def _resolve_url(base_url: str) -> str:
+ base = base_url.rstrip("/")
+ if base.endswith("/images/generations"):
+ return base
+ return base + "/api/paas/v4/images/generations"
+
+
+def _resolve_size(aspect_ratio: str, image_size: str) -> str:
+ normalized = normalize_image_size(image_size)
+ size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
+ if not size:
+ supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Zhipu backend. "
+ f"Supported: {supported}"
+ )
+ return size
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ size = _resolve_size(aspect_ratio, image_size)
+ url = _resolve_url(base_url)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+
+ final_prompt = prompt
+ if negative_prompt:
+ final_prompt += f"\n\nAvoid the following: {negative_prompt}"
+
+ payload = {
+ "model": model,
+ "prompt": final_prompt,
+ "size": size,
+ }
+
+ print("[Zhipu GLM-Image]")
+ print(f" Model: {model}")
+ print(f" Prompt: {final_prompt[:120]}{'...' if len(final_prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Resolution: {size}")
+ print()
+ print(" ⏳ Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n ✅ Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Zhipu image generation")
+
+ data = response.json()
+ items = data.get("data") or []
+ image_url = items[0].get("url") if items else None
+ if not image_url:
+ raise RuntimeError(f"Zhipu response missing image URL: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(image_url, path)
+
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ api_key = require_api_key(
+ "ZHIPU_API_KEY",
+ "BIGMODEL_API_KEY",
+ message="No API key found. Set ZHIPU_API_KEY or BIGMODEL_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("ZHIPU_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("ZHIPU_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n ⚠️ {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
diff --git a/skills/ppt-master/scripts/image_gen.py b/skills/ppt-master/scripts/image_gen.py
index b5fbd224..7c266233 100644
--- a/skills/ppt-master/scripts/image_gen.py
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -2,24 +2,37 @@
"""
Unified Image Generation Tool
-Dispatches to the appropriate backend (Gemini or OpenAI) based on configuration.
+Dispatches to the appropriate backend based on explicit provider configuration.
-Backend selection (IMAGE_BACKEND env var):
- IMAGE_BACKEND=gemini -> Gemini backend (google-genai SDK)
- IMAGE_BACKEND=openai -> OpenAI-compatible backend (openai SDK)
- (not set) -> Auto-detect: use Gemini if GEMINI_API_KEY is present
+Backend selection (`IMAGE_BACKEND` in `.env` or the current process environment):
+ IMAGE_BACKEND=gemini -> Gemini backend (google-genai SDK)
+ IMAGE_BACKEND=openai -> OpenAI-compatible backend (openai SDK)
+ IMAGE_BACKEND=stability -> Stability AI backend
+ IMAGE_BACKEND=bfl -> Black Forest Labs FLUX backend
+ IMAGE_BACKEND=ideogram -> Ideogram backend
+ IMAGE_BACKEND=qwen -> Alibaba Qwen image backend
+ IMAGE_BACKEND=zhipu -> Zhipu GLM-Image backend
+ IMAGE_BACKEND=volcengine -> Volcengine Seedream backend
+ IMAGE_BACKEND=siliconflow -> SiliconFlow backend
+ IMAGE_BACKEND=fal -> fal.ai backend
+ IMAGE_BACKEND=replicate -> Replicate backend
-Environment variables:
- IMAGE_BACKEND (optional) "gemini" or "openai"
- IMAGE_API_KEY (required) API key for the selected backend
- IMAGE_BASE_URL (optional) Custom API endpoint
- IMAGE_MODEL (optional) Model name override
+Configuration source:
+ 1. Current process environment variables
+ 2. Project-root `.env` as a fallback layer
- Legacy support (Gemini only):
- GEMINI_API_KEY / GEMINI_BASE_URL still work when IMAGE_BACKEND is not set.
+Supported keys:
+ IMAGE_BACKEND (required) backend name
+
+ Provider-specific keys are used for credentials and overrides, for example:
+ GEMINI_API_KEY / GEMINI_MODEL / GEMINI_BASE_URL
+ OPENAI_API_KEY / OPENAI_MODEL / OPENAI_BASE_URL
+ QWEN_API_KEY / QWEN_MODEL / QWEN_BASE_URL
+ ZHIPU_API_KEY / ZHIPU_MODEL / ZHIPU_BASE_URL
Usage:
python3 image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o images/
+ python3 image_gen.py --list-backends
"""
import os
@@ -27,13 +40,29 @@ import sys
import argparse
from pathlib import Path
-# Load .env from project root (if python-dotenv is installed)
-try:
- from dotenv import load_dotenv
- _env_path = Path(__file__).resolve().parents[3] / ".env"
- load_dotenv(_env_path)
-except ImportError:
- pass
+ENV_PATH = Path(__file__).resolve().parents[3] / ".env"
+IMAGE_ENV_PREFIXES = (
+ "IMAGE_",
+ "GEMINI_",
+ "OPENAI_",
+ "STABILITY_",
+ "BFL_",
+ "IDEOGRAM_",
+ "QWEN_",
+ "DASHSCOPE_",
+ "ZHIPU_",
+ "BIGMODEL_",
+ "VOLCENGINE_",
+ "ARK_",
+ "SILICONFLOW_",
+ "FAL_",
+ "REPLICATE_",
+)
+DEPRECATED_IMAGE_KEYS = {
+ "IMAGE_API_KEY",
+ "IMAGE_MODEL",
+ "IMAGE_BASE_URL",
+}
# All aspect ratios accepted by the unified CLI
# (each backend validates its own subset internally)
@@ -45,46 +74,240 @@ ALL_ASPECT_RATIOS = [
ALL_IMAGE_SIZES = ["512px", "1K", "2K", "4K"]
+BACKEND_REGISTRY = {
+ "gemini": {
+ "module": "backend_gemini",
+ "tier": "core",
+ "label": "Google Gemini",
+ "default_model": "gemini-3.1-flash-image-preview",
+ "key_hint": "GEMINI_API_KEY",
+ "aliases": ["google"],
+ },
+ "openai": {
+ "module": "backend_openai",
+ "tier": "core",
+ "label": "OpenAI / OpenAI-compatible",
+ "default_model": "gpt-image-1",
+ "key_hint": "OPENAI_API_KEY",
+ "aliases": ["openai-compatible", "openai_compatible"],
+ },
+ "qwen": {
+ "module": "backend_qwen",
+ "tier": "core",
+ "label": "Alibaba Qwen Image",
+ "default_model": "qwen-image-2.0-pro",
+ "key_hint": "QWEN_API_KEY / DASHSCOPE_API_KEY",
+ "aliases": ["alibaba", "dashscope"],
+ },
+ "zhipu": {
+ "module": "backend_zhipu",
+ "tier": "core",
+ "label": "Zhipu GLM-Image",
+ "default_model": "glm-image",
+ "key_hint": "ZHIPU_API_KEY / BIGMODEL_API_KEY",
+ "aliases": ["bigmodel", "glm", "glm-image"],
+ },
+ "volcengine": {
+ "module": "backend_volcengine",
+ "tier": "core",
+ "label": "Volcengine Seedream",
+ "default_model": "doubao-seedream-4-5-251128",
+ "key_hint": "VOLCENGINE_API_KEY / ARK_API_KEY",
+ "aliases": ["ark", "doubao", "seedream"],
+ },
+ "stability": {
+ "module": "backend_stability",
+ "tier": "extended",
+ "label": "Stability AI",
+ "default_model": "stable-image-core",
+ "key_hint": "STABILITY_API_KEY",
+ "aliases": ["stabilityai", "stability-ai"],
+ },
+ "bfl": {
+ "module": "backend_bfl",
+ "tier": "extended",
+ "label": "Black Forest Labs FLUX",
+ "default_model": "flux-pro-1.1-ultra",
+ "key_hint": "BFL_API_KEY",
+ "aliases": ["flux", "black-forest-labs", "black_forest_labs"],
+ },
+ "ideogram": {
+ "module": "backend_ideogram",
+ "tier": "extended",
+ "label": "Ideogram",
+ "default_model": "ideogram-v3",
+ "key_hint": "IDEOGRAM_API_KEY",
+ },
+ "siliconflow": {
+ "module": "backend_siliconflow",
+ "tier": "experimental",
+ "label": "SiliconFlow",
+ "default_model": "Qwen/Qwen-Image",
+ "key_hint": "SILICONFLOW_API_KEY",
+ "aliases": ["silicon"],
+ },
+ "fal": {
+ "module": "backend_fal",
+ "tier": "experimental",
+ "label": "fal.ai",
+ "default_model": "fal-ai/imagen3/fast",
+ "key_hint": "FAL_KEY / FAL_API_KEY",
+ "aliases": ["fal-ai"],
+ },
+ "replicate": {
+ "module": "backend_replicate",
+ "tier": "experimental",
+ "label": "Replicate",
+ "default_model": "black-forest-labs/flux-1.1-pro",
+ "key_hint": "REPLICATE_API_TOKEN / REPLICATE_API_KEY",
+ },
+}
-def _resolve_backend():
+TIER_ORDER = {"core": 0, "extended": 1, "experimental": 2}
+SUPPORTED_BACKENDS = tuple(sorted(BACKEND_REGISTRY))
+
+
+def _is_image_env_key(name: str) -> bool:
+ return name.startswith(IMAGE_ENV_PREFIXES)
+
+
+def _strip_env_quotes(value: str) -> str:
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
+ return value[1:-1]
+ return value
+
+
+def _load_image_env_file():
"""
- Determine which backend to use based on environment variables.
+ Load image generation config from the project-root `.env` as a fallback layer.
- Returns:
- A backend module with a generate() function.
+ Existing process environment variables win over `.env`.
"""
- backend_name = os.environ.get("IMAGE_BACKEND", "").strip().lower()
+ if not ENV_PATH.exists():
+ return
- if backend_name == "gemini":
- import backend_gemini
- return backend_gemini, "gemini"
+ with ENV_PATH.open("r", encoding="utf-8") as fh:
+ for lineno, raw_line in enumerate(fh, start=1):
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
- if backend_name == "openai":
- import backend_openai
- return backend_openai, "openai"
+ if line.startswith("export "):
+ line = line[7:].lstrip()
- if backend_name and backend_name not in ("gemini", "openai"):
- print(f"Error: Unknown IMAGE_BACKEND='{backend_name}'. Supported: gemini, openai")
- sys.exit(1)
+ if "=" not in line:
+ raise ValueError(
+ f"Invalid line in {ENV_PATH}:{lineno}. Expected KEY=VALUE."
+ )
+
+ key, value = line.split("=", 1)
+ key = key.strip()
+ if not key:
+ raise ValueError(
+ f"Invalid line in {ENV_PATH}:{lineno}. Missing variable name."
+ )
+
+ if not _is_image_env_key(key):
+ continue
+
+ if key in DEPRECATED_IMAGE_KEYS:
+ replacement = {
+ "IMAGE_API_KEY": "GEMINI_API_KEY / OPENAI_API_KEY / QWEN_API_KEY / ZHIPU_API_KEY / ...",
+ "IMAGE_MODEL": "GEMINI_MODEL / OPENAI_MODEL / QWEN_MODEL / ZHIPU_MODEL / ...",
+ "IMAGE_BASE_URL": "GEMINI_BASE_URL / OPENAI_BASE_URL / QWEN_BASE_URL / ZHIPU_BASE_URL / ...",
+ }[key]
+ raise ValueError(
+ f"Unsupported key in {ENV_PATH}:{lineno}: {key}\n"
+ "Global image config keys have been removed.\n"
+ f"Use IMAGE_BACKEND plus provider-specific keys instead, such as {replacement}."
+ )
+
+ os.environ.setdefault(key, _strip_env_quotes(value.strip()))
+
+
+def _validate_runtime_config():
+ """Reject deprecated global image variables from any configuration source."""
+ for key in DEPRECATED_IMAGE_KEYS:
+ if key not in os.environ:
+ continue
+ replacement = {
+ "IMAGE_API_KEY": "GEMINI_API_KEY / OPENAI_API_KEY / QWEN_API_KEY / ZHIPU_API_KEY / ...",
+ "IMAGE_MODEL": "GEMINI_MODEL / OPENAI_MODEL / QWEN_MODEL / ZHIPU_MODEL / ...",
+ "IMAGE_BASE_URL": "GEMINI_BASE_URL / OPENAI_BASE_URL / QWEN_BASE_URL / ZHIPU_BASE_URL / ...",
+ }[key]
+ raise ValueError(
+ f"Unsupported image config key: {key}\n"
+ "Global image config keys have been removed.\n"
+ f"Use IMAGE_BACKEND plus provider-specific keys instead, such as {replacement}."
+ )
+
+
+def _build_backend_aliases():
+ aliases = {}
+ for canonical_name, config in BACKEND_REGISTRY.items():
+ aliases[canonical_name] = canonical_name
+ for alias in config.get("aliases", []):
+ aliases[alias] = canonical_name
+ return aliases
- # Auto-detect: IMAGE_BACKEND not set
- # Check for IMAGE_API_KEY first, then legacy keys
- if os.environ.get("IMAGE_API_KEY") or os.environ.get("GEMINI_API_KEY"):
- import backend_gemini
- return backend_gemini, "gemini"
- if os.environ.get("OPENAI_API_KEY"):
- import backend_openai
- return backend_openai, "openai"
+BACKEND_ALIASES = _build_backend_aliases()
+
+def _load_backend(canonical_name: str):
+ module_name = f"image_backends.{BACKEND_REGISTRY[canonical_name]['module']}"
+ module = __import__(module_name, fromlist=["*"])
+ return module, canonical_name
+
+
+def _print_backend_list():
+ """Print supported backends grouped by support tier."""
+ print("Supported image backends:\n")
+ tiers = ("core", "extended", "experimental")
+ for tier in tiers:
+ print(f"{tier.upper()}:")
+ for name, info in sorted(
+ BACKEND_REGISTRY.items(),
+ key=lambda item: (TIER_ORDER[item[1]["tier"]], item[0]),
+ ):
+ if info["tier"] != tier:
+ continue
+ print(
+ f" {name:<12} {info['label']} | default={info['default_model']} | keys={info['key_hint']}"
+ )
+ print()
+ print("Recommendation: prefer CORE backends for everyday PPT generation.")
+ print(f"Config fallback file: {ENV_PATH}")
+
+
+def _resolve_backend():
+ """
+ Determine which backend to use from explicit configuration.
+
+ Returns:
+ A backend module with a generate() function.
+ """
+ backend_name = os.environ.get("IMAGE_BACKEND", "").strip().lower()
+ if backend_name:
+ canonical = BACKEND_ALIASES.get(backend_name)
+ if not canonical:
+ supported = ", ".join(SUPPORTED_BACKENDS)
+ print(f"Error: Unknown IMAGE_BACKEND='{backend_name}'. Supported: {supported}")
+ sys.exit(1)
+ return _load_backend(canonical)
+
+ supported = ", ".join(SUPPORTED_BACKENDS)
print(
"Error: No image backend configured.\n"
"\n"
- "Set environment variables:\n"
- " IMAGE_BACKEND=gemini # or openai\n"
- " IMAGE_API_KEY=your-key\n"
+ "Set IMAGE_BACKEND explicitly in one of these places:\n"
+ f" 1. Current process environment\n"
+ f" 2. {ENV_PATH}\n"
+ "\n"
+ f"Supported backends: {supported}\n"
"\n"
- "Or for legacy Gemini usage:\n"
+ "Example:\n"
+ " IMAGE_BACKEND=gemini\n"
" GEMINI_API_KEY=your-key\n"
)
sys.exit(1)
@@ -92,7 +315,7 @@ def _resolve_backend():
def main():
parser = argparse.ArgumentParser(
- description="Generate images using AI (Gemini or OpenAI backend)."
+ description="Generate images using AI image model providers."
)
parser.add_argument(
"prompt", nargs="?", default="a beautiful landscape",
@@ -123,13 +346,28 @@ def main():
help="Model name. Default depends on backend."
)
parser.add_argument(
- "--backend", "-b", default=None, choices=["gemini", "openai"],
+ "--backend", "-b", default=None, choices=SUPPORTED_BACKENDS,
help="Override IMAGE_BACKEND env var."
)
+ parser.add_argument(
+ "--list-backends", action="store_true",
+ help="List available backends grouped by support tier and exit."
+ )
args = parser.parse_args()
- # CLI --backend overrides env var
+ if args.list_backends:
+ _print_backend_list()
+ return
+
+ try:
+ _load_image_env_file()
+ _validate_runtime_config()
+ except ValueError as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+
+ # CLI --backend overrides the value loaded from .env
if args.backend:
os.environ["IMAGE_BACKEND"] = args.backend
diff --git a/skills/ppt-master/scripts/svg_finalize/__init__.py b/skills/ppt-master/scripts/svg_finalize/__init__.py
new file mode 100644
index 00000000..8327387b
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_finalize/__init__.py
@@ -0,0 +1 @@
+"""Internal SVG finalize helpers used by finalize_svg.py and compatibility wrappers."""
diff --git a/skills/ppt-master/scripts/crop_images.py b/skills/ppt-master/scripts/svg_finalize/crop_images.py
similarity index 99%
rename from skills/ppt-master/scripts/crop_images.py
rename to skills/ppt-master/scripts/svg_finalize/crop_images.py
index 67c41c5e..d5a500df 100644
--- a/skills/ppt-master/scripts/crop_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/crop_images.py
@@ -12,7 +12,7 @@ Supports 9 alignment modes:
- xMinYMax / xMidYMax / xMaxYMax (bottom alignment)
Usage:
- python scripts/crop_images.py <SVG file or directory> [--dry-run]
+ python3 scripts/svg_finalize/crop_images.py <SVG file or directory> [--dry-run]
"""
import os
diff --git a/skills/ppt-master/scripts/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
similarity index 93%
rename from skills/ppt-master/scripts/embed_icons.py
rename to skills/ppt-master/scripts/svg_finalize/embed_icons.py
index 4ced7da5..dd23cca7 100644
--- a/skills/ppt-master/scripts/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -13,8 +13,8 @@ After replacement:
</g>
Usage:
- python3 scripts/embed_icons.py <svg_file> [svg_file2] ...
- python3 scripts/embed_icons.py svg_output/*.svg
+ python3 scripts/svg_finalize/embed_icons.py <svg_file> [svg_file2] ...
+ python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
Options:
--icons-dir <path> Icon directory path (default: templates/icons/)
@@ -30,7 +30,7 @@ from pathlib import Path
# Default icon directory
-DEFAULT_ICONS_DIR = Path(__file__).parent.parent / 'templates' / 'icons'
+DEFAULT_ICONS_DIR = Path(__file__).parent.parent.parent / 'templates' / 'icons'
# Icon base size
ICON_BASE_SIZE = 16
@@ -202,10 +202,10 @@ def main():
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
- python3 scripts/embed_icons.py svg_output/01_cover.svg
- python3 scripts/embed_icons.py svg_output/*.svg
- python3 scripts/embed_icons.py --dry-run svg_output/*.svg
- python3 scripts/embed_icons.py --icons-dir my_icons/ output.svg
+ python3 scripts/svg_finalize/embed_icons.py svg_output/01_cover.svg
+ python3 scripts/svg_finalize/embed_icons.py svg_output/*.svg
+ python3 scripts/svg_finalize/embed_icons.py --dry-run svg_output/*.svg
+ python3 scripts/svg_finalize/embed_icons.py --icons-dir my_icons/ output.svg
'''
)
@@ -247,4 +247,3 @@ Examples:
if __name__ == '__main__':
main()
-
diff --git a/skills/ppt-master/scripts/embed_images.py b/skills/ppt-master/scripts/svg_finalize/embed_images.py
similarity index 94%
rename from skills/ppt-master/scripts/embed_images.py
rename to skills/ppt-master/scripts/svg_finalize/embed_images.py
index 59df0f5a..e07270bd 100644
--- a/skills/ppt-master/scripts/embed_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_images.py
@@ -4,12 +4,12 @@ SVG Image Embedding Tool
Converts externally referenced images in SVG files to Base64 inline format.
Usage:
- python3 embed_images.py <svg_file> [svg_file2] ...
- python3 embed_images.py *.svg
+ python3 scripts/svg_finalize/embed_images.py <svg_file> [svg_file2] ...
+ python3 scripts/svg_finalize/embed_images.py *.svg
Examples:
- python3 embed_images.py examples/ppt169_demo/svg_output/01_cover.svg
- python3 embed_images.py examples/ppt169_demo/svg_output/*.svg
+ python3 scripts/svg_finalize/embed_images.py examples/ppt169_demo/svg_output/01_cover.svg
+ python3 scripts/svg_finalize/embed_images.py examples/ppt169_demo/svg_output/*.svg
"""
import os
diff --git a/skills/ppt-master/scripts/fix_image_aspect.py b/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
similarity index 97%
rename from skills/ppt-master/scripts/fix_image_aspect.py
rename to skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
index 7dffb297..ffe5ff22 100644
--- a/skills/ppt-master/scripts/fix_image_aspect.py
+++ b/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
@@ -13,14 +13,14 @@ Principle:
<image> elements so that images are centered and maintain their original aspect ratio.
Usage:
- python3 scripts/fix_image_aspect.py <svg_file> [svg_file2] ...
- python3 scripts/fix_image_aspect.py projects/xxx/svg_output/*.svg
+ python3 scripts/svg_finalize/fix_image_aspect.py <svg_file> [svg_file2] ...
+ python3 scripts/svg_finalize/fix_image_aspect.py projects/xxx/svg_output/*.svg
# Preview mode
- python3 scripts/fix_image_aspect.py --dry-run projects/xxx/svg_output/*.svg
+ python3 scripts/svg_finalize/fix_image_aspect.py --dry-run projects/xxx/svg_output/*.svg
Examples:
- python3 scripts/fix_image_aspect.py projects/demo/svg_output/slide_06_current_overview.svg
+ python3 scripts/svg_finalize/fix_image_aspect.py projects/demo/svg_output/slide_06_current_overview.svg
"""
import os
diff --git a/skills/ppt-master/scripts/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
similarity index 99%
rename from skills/ppt-master/scripts/flatten_tspan.py
rename to skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 66be6196..25f86799 100644
--- a/skills/ppt-master/scripts/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -425,7 +425,7 @@ def main():
if args.interactive or not args.input:
inp, out_base = _interactive_get_paths()
if not inp:
- print("Cancelled. Usage: python scripts/flatten_tspan.py <input_dir_or_svg> [output_dir]")
+ print("Cancelled. Usage: python3 scripts/svg_finalize/flatten_tspan.py <input_dir_or_svg> [output_dir]")
sys.exit(0)
else:
inp = args.input
diff --git a/skills/ppt-master/scripts/svg_rect_to_path.py b/skills/ppt-master/scripts/svg_finalize/svg_rect_to_path.py
similarity index 96%
rename from skills/ppt-master/scripts/svg_rect_to_path.py
rename to skills/ppt-master/scripts/svg_finalize/svg_rect_to_path.py
index d0ee3e55..ea93337a 100644
--- a/skills/ppt-master/scripts/svg_rect_to_path.py
+++ b/skills/ppt-master/scripts/svg_finalize/svg_rect_to_path.py
@@ -6,13 +6,13 @@ Solves the issue of rounded corners being lost when using "Convert to Shape" in
Converts <rect> elements with rx/ry to equivalent <path> elements.
Usage:
- python3 scripts/svg_rect_to_path.py <SVG file or directory>
- python3 scripts/svg_rect_to_path.py <project_path> -s output
- python3 scripts/svg_rect_to_path.py <project_path> -s final -o svg_rounded
+ python3 scripts/svg_finalize/svg_rect_to_path.py <SVG file or directory>
+ python3 scripts/svg_finalize/svg_rect_to_path.py <project_path> -s output
+ python3 scripts/svg_finalize/svg_rect_to_path.py <project_path> -s final -o svg_rounded
Examples:
- python3 scripts/svg_rect_to_path.py examples/ppt169_demo
- python3 scripts/svg_rect_to_path.py examples/ppt169_demo/svg_output/01_cover.svg
+ python3 scripts/svg_finalize/svg_rect_to_path.py examples/ppt169_demo
+ python3 scripts/svg_finalize/svg_rect_to_path.py examples/ppt169_demo/svg_output/01_cover.svg
Output:
- Directory mode: outputs to svg_rounded/ subdirectory
@@ -328,4 +328,3 @@ What it does:
if __name__ == '__main__':
main()
-