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: unified image generation with multi-backend support (Gemini/OpenAI)

hugohe386bb4ee519d6
diff --git a/.env.example b/.env.example
new file mode 100644
index 00000000..d439b84d
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,42 @@
+# ─────────────────────────────────────────────────────────────
+# Image Generation Configuration / 图片生成配置
+# ─────────────────────────────────────────────────────────────
+
+# Backend: "gemini" or "openai" (default: auto-detect based on available keys)
+# 后端选择:"gemini" 或 "openai"(默认根据已配置的 key 自动检测)
+# IMAGE_BACKEND=gemini
+
+# API Key (required) / API 密钥(必需)
+# IMAGE_API_KEY=your-api-key
+
+# Custom API endpoint (optional, for proxy or local models)
+# 自定义 API 端点(可选,用于代理服务或本地模型)
+# IMAGE_BASE_URL=https://your-proxy-url.com/v1beta
+
+# Model override (optional, each backend has its own default)
+# 模型名称覆盖(可选,各后端有默认值)
+# IMAGE_MODEL=gemini-3.1-flash-image-preview
+
+# ─────────────────────────────────────────────────────────────
+# Example: Gemini backend / Gemini 后端示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=gemini
+# IMAGE_API_KEY=your-gemini-api-key
+# IMAGE_BASE_URL=https://your-proxy-url.com/v1beta
+
+# ─────────────────────────────────────────────────────────────
+# Example: OpenAI backend / OpenAI 后端示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=openai
+# IMAGE_API_KEY=sk-xxx
+# IMAGE_BASE_URL=http://127.0.0.1:3000/v1
+# IMAGE_MODEL=gpt-image-1
+
+# ─────────────────────────────────────────────────────────────
+# Legacy variables (still work, no need to migrate)
+# 旧版变量(仍然有效,无需迁移)
+# ─────────────────────────────────────────────────────────────
+# 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
diff --git a/AGENTS.md b/AGENTS.md
index 84a387f8..ac00fbed 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,7 +31,7 @@ python3 skills/ppt-master/scripts/project_manager.py validate <project_path>
# Image tools
python3 skills/ppt-master/scripts/analyze_images.py <project_path>/images
-python3 skills/ppt-master/scripts/nano_banana_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
+python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
# SVG quality check
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
diff --git a/CLAUDE.md b/CLAUDE.md
index 21133fc1..5a2e5e0d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -24,7 +24,7 @@ python3 skills/ppt-master/scripts/project_manager.py validate <project_path>
# Image tools
python3 skills/ppt-master/scripts/analyze_images.py <project_path>/images
-python3 skills/ppt-master/scripts/nano_banana_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
+python3 skills/ppt-master/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
# SVG quality check
python3 skills/ppt-master/scripts/svg_quality_checker.py <project_path>
diff --git a/README.md b/README.md
index 0318d6a4..e9f4f68c 100644
--- a/README.md
+++ b/README.md
@@ -172,21 +172,44 @@ AI: Sure. First we'll confirm whether to use a template; after that Strategist w
> 💡 **AI Lost Context?** Ask the AI to read `skills/ppt-master/SKILL.md` first; use `AGENTS.md` as the repository-level entry overview.
-### 5. Gemini Image Generation (Optional)
+### 5. AI Image Generation (Optional)
-The `nano_banana_gen.py` tool can generate high-quality images via the Gemini API directly within AI clients. Configure the following environment variables before use:
+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:
+
+#### Option A: Using `.env` file (Recommended)
```bash
-# Required: Gemini API Key (obtain from https://aistudio.google.com/apikey)
-export GEMINI_API_KEY="your-api-key"
+cp .env.example .env
+```
+
+Edit the `.env` file with your configuration:
+
+```env
+IMAGE_BACKEND=gemini
+IMAGE_API_KEY=your-api-key
+```
+
+> `.env` is already in `.gitignore` and will not be committed to the repository, so your keys stay safe.
+
+#### Option B: Using environment variables
+
+```bash
+# Backend selection: "gemini" (default) or "openai"
+export IMAGE_BACKEND="gemini"
+
+# Required: API key for the selected backend
+export IMAGE_API_KEY="your-api-key"
+
+# Optional: Custom API endpoint (for proxy services or local models)
+export IMAGE_BASE_URL="https://your-proxy-url.com/v1beta"
-# Optional: Custom API endpoint (for proxy services)
-export GEMINI_BASE_URL="https://your-proxy-url.com/v1beta"
+# Optional: Model name override
+export IMAGE_MODEL="gemini-3.1-flash-image-preview"
```
> 💡 **Persist settings**: Add the `export` commands above to `~/.zshrc` (macOS/Linux zsh) or `~/.bashrc` (Linux bash), then restart your terminal.
-> 💡 If using the Antigravity proxy, pass the model parameter (`-m gemini-3.1-flash-image`).
+> 💡 **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.
> 💡 **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`.
diff --git a/README_CN.md b/README_CN.md
index 651c89ac..fbeeb558 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -170,21 +170,44 @@ AI:好的,先确认是否使用模板;确认后我会继续八项确认并
> 💡 **AI 迷失上下文?** 可提示 AI 优先阅读 `skills/ppt-master/SKILL.md`;如需一个仓库级入口概览,再参考 `AGENTS.md`
-### 5. Gemini 生图配置(可选)
+### 5. AI 生图配置(可选)
-本项目的 `nano_banana_gen.py` 可通过 Gemini API 在 AI 客户端中直接生成高质量配图。使用前需配置环境变量:
+本项目的 `image_gen.py` 可通过 Gemini 或 OpenAI 兼容 API 在 AI 客户端中直接生成高质量配图。配置方式二选一:
+
+#### 方式 A:使用 `.env` 文件(推荐)
```bash
-# 必需:Gemini API Key(从 https://aistudio.google.com/apikey 获取)
-export GEMINI_API_KEY="your-api-key"
+cp .env.example .env
+```
+
+编辑 `.env` 文件,填入你的配置:
+
+```env
+IMAGE_BACKEND=gemini
+IMAGE_API_KEY=your-api-key
+```
+
+> `.env` 文件已在 `.gitignore` 中,不会被提交到仓库,无需担心密钥泄露。
+
+#### 方式 B:使用环境变量
+
+```bash
+# 后端选择:"gemini"(默认)或 "openai"
+export IMAGE_BACKEND="gemini"
+
+# 必需:所选后端的 API Key
+export IMAGE_API_KEY="your-api-key"
+
+# 可选:自定义 API 端点(用于代理服务或本地模型)
+export IMAGE_BASE_URL="https://your-proxy-url.com/v1beta"
-# 可选:自定义 API 端点(用于代理服务)
-export GEMINI_BASE_URL="https://your-proxy-url.com/v1beta"
+# 可选:模型名称覆盖
+export IMAGE_MODEL="gemini-3.1-flash-image-preview"
```
> 💡 **持久化**:将上述 `export` 命令添加到 `~/.zshrc`(macOS/Linux zsh)或 `~/.bashrc`(Linux bash)中,重启终端即可永久生效。
-> 💡 若使用 Antigravity 代理,调用时需传入模型参数(`-m gemini-3.1-flash-image`)。
+> 💡 **向后兼容**:`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` 去除。
diff --git a/requirements.txt b/requirements.txt
index 9b8f8664..53ed0fc2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,60 +1,72 @@
-# PPT Master 依赖
-# ================
+# PPT Master Dependencies / PPT Master 依赖
+# =============================================
#
+# Most tools use only the Python standard library. Below are optional dependencies.
# 大部分工具仅使用 Python 标准库,以下为可选依赖。
#
-# 安装方式:
+# Install / 安装方式:
# pip install -r requirements.txt
# ─────────────────────────────────────────────────────────────
-# SVG 转 PPTX 工具 (skills/ppt-master/scripts/svg_to_pptx.py)
+# SVG to PPTX tool / SVG 转 PPTX 工具 (skills/ppt-master/scripts/svg_to_pptx.py)
# ─────────────────────────────────────────────────────────────
+# Batch-convert SVG files to PowerPoint presentations.
# 用于将 SVG 文件批量转换为 PowerPoint 演示文稿
+# Uses Office-compatible mode (PNG + SVG dual format) by default, supports all Office versions.
# 默认使用 Office 兼容模式(PNG + SVG 双格式),支持所有 Office 版本
python-pptx>=0.6.21
+# Office compatibility dependencies (choose one, CairoSVG preferred)
# Office 兼容模式依赖(二选一,优先使用 cairosvg)
+# Converts SVG to PNG fallback images for Office LTSC 2021 etc.
# 用于将 SVG 转换为 PNG 后备图片,确保 Office LTSC 2021 等版本正常显示
#
-# 方案 A: CairoSVG(推荐,渐变/滤镜完整,约 25MB)
+# Option A / 方案 A: CairoSVG (recommended / 推荐, ~25MB, full gradient/filter support)
# pip install cairosvg
-# macOS 需先: brew install cairo
+# macOS: brew install cairo
#
-# 方案 B: svglib(轻量,约 5MB,部分渐变可能丢失)
+# Option B / 方案 B: svglib (lightweight / 轻量, ~5MB, some gradients may be lost)
svglib>=1.5.0
reportlab>=4.0.0
# ─────────────────────────────────────────────────────────────
-# PDF 转 Markdown 工具 (skills/ppt-master/scripts/pdf_to_md.py)
+# PDF to Markdown tool / PDF 转 Markdown 工具 (skills/ppt-master/scripts/pdf_to_md.py)
# ─────────────────────────────────────────────────────────────
+# Converts PDF to Markdown with text, image, and table extraction.
# 用于将 PDF 文件转换为 Markdown 格式,支持文本、图片、表格提取
PyMuPDF>=1.23.0
# ─────────────────────────────────────────────────────────────
-# 文档转 Markdown 工具 (skills/ppt-master/scripts/doc_to_md.py)
+# Document to Markdown tool / 文档转 Markdown 工具 (skills/ppt-master/scripts/doc_to_md.py)
# ─────────────────────────────────────────────────────────────
+# Uses Pandoc to convert DOCX/EPUB/HTML/LaTeX/RST etc. to Markdown.
# 使用 Pandoc 将 DOCX/EPUB/HTML/LaTeX/RST 等格式转换为 Markdown
+# No Python package dependencies. Requires system-level pandoc:
# 无 Python 包依赖,需要系统安装 pandoc:
# macOS: brew install pandoc
# Ubuntu: sudo apt install pandoc
# Windows: https://pandoc.org/installing.html
# ─────────────────────────────────────────────────────────────
-# 图片处理工具
+# Image processing tools / 图片处理工具
# ─────────────────────────────────────────────────────────────
+# fix_image_aspect.py - Fix image aspect ratio (prevent stretching during PPT shape conversion)
# fix_image_aspect.py - 修复图片宽高比(防止 PPT 转形状时拉伸)
+# gemini_watermark_remover.py - Remove watermarks from Gemini-generated images
# gemini_watermark_remover.py - 去除 Gemini 生成图片的水印
Pillow>=9.0.0
numpy>=1.20.0
# ─────────────────────────────────────────────────────────────
-# 网页转 Markdown 工具 (skills/ppt-master/scripts/web_to_md.py)
+# Web to Markdown tool / 网页转 Markdown 工具 (skills/ppt-master/scripts/web_to_md.py)
# ─────────────────────────────────────────────────────────────
requests>=2.31.0
beautifulsoup4>=4.12.0
# ─────────────────────────────────────────────────────────────
-# AI 图片生成工具 (skills/ppt-master/scripts/nano_banana_gen.py)
+# AI image generation tool / AI 图片生成工具 (skills/ppt-master/scripts/image_gen.py)
# ─────────────────────────────────────────────────────────────
-# 用于调用 Google Gemini API 生成高质量图片(需要 API Key)
+# Gemini backend / Gemini 后端 (IMAGE_BACKEND=gemini)
google-genai>=1.0.0
+# OpenAI-compatible backend / OpenAI 兼容后端 (IMAGE_BACKEND=openai)
+openai>=1.0.0
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index f0e52797..ef93c905 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/nano_banana_gen.py` | AI image generation (Gemini API) |
+| `${SKILL_DIR}/scripts/image_gen.py` | AI image generation (Gemini / OpenAI) |
| `${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) |
@@ -200,7 +200,7 @@ Read `references/image-generator.md`
2. Generate prompt document → `<project_path>/images/image_prompts.md`
3. Generate images (CLI tool recommended):
```bash
- python3 ${SKILL_DIR}/scripts/nano_banana_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
+ python3 ${SKILL_DIR}/scripts/image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o <project_path>/images
```
**✅ Checkpoint — Confirm all images are ready, proceed to Step 6**:
diff --git a/skills/ppt-master/references/image-generator.md b/skills/ppt-master/references/image-generator.md
index 31c051f5..bd1d56a8 100644
--- a/skills/ppt-master/references/image-generator.md
+++ b/skills/ppt-master/references/image-generator.md
@@ -106,7 +106,7 @@ Full directive: "color palette: deep navy blue (#1E3A5F), light gray (#F8F9FA),
| WeChat Moments | 1:1 | 1080x1080 |
| Story | 9:16 | 1080x1920 |
-> Nano Banana supported aspect ratios: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`
+> Supported aspect ratios: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` (Gemini also supports `1:4`, `1:8`, `4:1`, `8:1`)
---
@@ -221,10 +221,10 @@ For each image with "Pending" status:
> Prerequisite: Section 4.2 must be complete; `images/image_prompts.md` must exist
-#### Method 1: Nano Banana CLI Tool (Recommended)
+#### Method 1: Unified CLI Tool (Recommended)
```bash
-python3 scripts/nano_banana_gen.py "your prompt" \
+python3 scripts/image_gen.py "your prompt" \
--aspect_ratio 16:9 --image_size 1K \
--output project/images --filename cover_bg
```
@@ -233,14 +233,25 @@ python3 scripts/nano_banana_gen.py "your prompt" \
| Parameter | Short | Description | Default |
|-----------|-------|-------------|---------|
-| `prompt` | - | Positive prompt (positional arg) | `Nano Banana` |
+| `prompt` | - | Positive prompt (positional arg) | - |
| `--negative_prompt` | `-n` | Negative prompt | None |
| `--aspect_ratio` | - | Image aspect ratio | `1:1` |
| `--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 |
+| `--model` | `-m` | Model name | Backend default |
-**Environment variables**: Required: `GEMINI_API_KEY`. Optional: `GEMINI_BASE_URL`
+**Environment variables**:
+
+| 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 |
+
+> Legacy: `GEMINI_API_KEY` / `GEMINI_BASE_URL` still work for backward compatibility.
**Generation pacing (mandatory)**:
- Execute only one generation command at a time; wait for file confirmation before the next
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index f49fcf0f..eee220f6 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -50,7 +50,7 @@ graph TB
F2[analyze_images.py]
F3[svg_position_calculator.py]
F4[config.py]
- F5[nano_banana_gen.py]
+ F5[image_gen.py]
end
A1 --> B1
@@ -92,7 +92,7 @@ Source Document → [pdf_to_md / doc_to_md / web_to_md] → Markdown
| **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** | `nano_banana_gen.py` | Generate high-quality images via Gemini Nano |
+| **Asset Generation** | `image_gen.py` | AI image generation (Gemini / OpenAI) |
| **Utilities** | `config.py`, `analyze_images.py`, `rotate_images.py` | Configuration and image processing |
---
@@ -1221,61 +1221,75 @@ pip install Pillow numpy
---
-### 14. nano_banana_gen.py — Nano Banana Image Generation Tool
+### 14. image_gen.py — Unified AI Image Generation Tool
-Uses the Google GenAI API to call Gemini models for generating high-quality image assets.
+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
-- **Auto-save**: Automatically names and saves output as PNG format based on the prompt
**Usage**:
```bash
-# Generate a default image
-python3 scripts/nano_banana_gen.py "A modern futuristic workspace"
+# Generate an image
+python3 scripts/image_gen.py "A modern futuristic workspace"
# Specify aspect ratio and size
-python3 scripts/nano_banana_gen.py "Abstract tech background" --aspect_ratio 16:9 --image_size 4K
+python3 scripts/image_gen.py "Abstract tech background" --aspect_ratio 16:9 --image_size 4K
# Specify output directory
-python3 scripts/nano_banana_gen.py "Concept car" -o projects/demo/images
+python3 scripts/image_gen.py "Concept car" -o projects/demo/images
# Use negative prompt
-python3 scripts/nano_banana_gen.py "Beautiful landscape" -n "low quality, blurry, watermark"
+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` | - | Nano Banana | Prompt string |
+| `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` | - | `4K` | `1K`, `2K`, `4K` |
+| `--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**:
-Set the following environment variables before use:
-
```bash
-# Required: Gemini API Key
-export GEMINI_API_KEY="YOUR_GEMINI_API_KEY"
+# Backend selection (optional, auto-detects if not set)
+export IMAGE_BACKEND="gemini" # or "openai"
+
+# API Key (required)
+export IMAGE_API_KEY="your-api-key"
-# Optional: Custom API endpoint (for proxy services)
-export GEMINI_BASE_URL="YOUR_API_BASE_URL"
+# 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"
```
-> **Tip**: You can add environment variables to `~/.zshrc` or `~/.bashrc` for persistent configuration.
+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
+pip install google-genai # Gemini backend
+pip install openai # OpenAI backend
```
---
@@ -1411,6 +1425,6 @@ pip install python-pptx
_Last updated: 2026-02-03_
-_nano_banana_gen.py documentation updated: 2026-02-03_
+_image_gen.py documentation updated: 2026-03-26_
_gemini_watermark_remover.py documentation updated: 2025-12-20_
diff --git a/skills/ppt-master/scripts/nano_banana_gen.py b/skills/ppt-master/scripts/backend_gemini.py
similarity index 60%
rename from skills/ppt-master/scripts/nano_banana_gen.py
rename to skills/ppt-master/scripts/backend_gemini.py
index a57fad13..0c0c0c96 100644
--- a/skills/ppt-master/scripts/nano_banana_gen.py
+++ b/skills/ppt-master/scripts/backend_gemini.py
@@ -1,19 +1,14 @@
#!/usr/bin/env python3
"""
-Nano Banana Image Generator (Gemini Nano)
-A tool for generating high-quality images via the Google GenAI API (Gemini).
+Gemini Image Generation Backend
-Environment variables:
- GEMINI_API_KEY (required) Gemini API Key, obtained from https://aistudio.google.com/apikey
- GEMINI_BASE_URL (optional) Custom API endpoint for proxy services
+Generates images via the Google GenAI API (Gemini).
+Used by image_gen.py as a backend module.
- Configuration example:
- export GEMINI_API_KEY="your-api-key"
- export GEMINI_BASE_URL="https://your-proxy-url.com/v1beta" # Only needed when using a proxy
-
-Connection modes:
- - Without GEMINI_BASE_URL -> Direct connection to the official Google API
- - With GEMINI_BASE_URL -> Via proxy API (using the same Official protocol)
+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
Dependencies:
pip install google-genai Pillow
@@ -22,7 +17,7 @@ Dependencies:
import os
import sys
import time
-import argparse
+import threading
from google import genai
from google.genai import types
@@ -34,32 +29,28 @@ except ImportError:
HAS_PIL = False
-# ╔══════════════════════════════════════════════════════════════════╗
+# ╔══════════════════════════════���═══════════════════════════════════╗
# ║ Constants ║
-# ╚══════════════════════════════════════════════════════════════════╝
+# ╚═══════════��═════════════════════════════��════════════════════════╝
-# All aspect ratios supported by Gemini 3.1 Flash Image (including new 1:4, 4:1, 1:8, 8:1)
VALID_ASPECT_RATIOS = [
"1:1", "1:4", "1:8",
"2:3", "3:2", "3:4", "4:1", "4:3",
"4:5", "5:4", "8:1", "9:16", "16:9", "21:9"
]
-# Official docs: "512px", "1K", "2K", "4K" (K must be uppercase)
VALID_IMAGE_SIZES = ["512px", "1K", "2K", "4K"]
-# Default model
DEFAULT_MODEL = "gemini-3.1-flash-image-preview"
-# Retry configuration
-MAX_RETRIES = 3 # Maximum number of retries
-RETRY_BASE_DELAY = 10 # Initial retry wait (seconds)
-RETRY_BACKOFF = 2 # Exponential backoff multiplier
+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"""
@@ -115,8 +106,8 @@ def _is_rate_limit_error(e: Exception) -> bool:
return "429" in err_str or "rate" in err_str or "quota" in err_str or "resource_exhausted" in err_str
-# ╔══════════════════════════════════════════════════════════════════╗
-# ║ Image Generation — Unified generation logic (Official / Proxy) ║
+# ╔══════���═══════════════════════════════════════════════��═══════════╗
+# ║ Image Generation ║
# ╚══════════════════════════════════════════════════════════════════╝
def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
@@ -124,16 +115,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
output_dir: str = None, filename: str = None,
model: str = DEFAULT_MODEL, base_url: str = None) -> str:
"""
- Unified image generation function (streaming).
-
- Automatically selects connection mode based on whether base_url is provided:
- - Without base_url -> Direct connection to the official Google API
- - With base_url -> Via proxy API (using the same Official protocol)
-
- Uses generate_content_stream for streaming reception with real-time progress feedback:
- - Displays elapsed time
- - Shows chunk number and data size when a chunk is received
- - Keeps the last image chunk (highest quality)
+ Image generation via Gemini API (streaming).
Returns:
Path of the saved image file
@@ -141,13 +123,11 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
Raises:
RuntimeError: When generation fails
"""
- # Create client based on whether base_url is provided
if base_url:
client = genai.Client(api_key=api_key, http_options={'base_url': base_url})
else:
client = genai.Client(api_key=api_key)
- # Build prompt
final_prompt = prompt
if negative_prompt:
final_prompt += f"\n\nNegative prompt: {negative_prompt}"
@@ -159,7 +139,6 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
image_size=image_size,
),
}
- # ThinkingConfig is only supported by flash series models
if "flash" in model.lower():
config_kwargs["thinking_config"] = types.ThinkingConfig(
thinking_level="MINIMAL",
@@ -167,7 +146,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
config = types.GenerateContentConfig(**config_kwargs)
mode_label = "Proxy Mode" if base_url else "Official Mode"
- print(f"[{mode_label}]")
+ print(f"[Gemini - {mode_label}]")
if base_url:
print(f" Base URL: {base_url}")
print(f" Model: {model}")
@@ -176,12 +155,9 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
print(f" Image Size: {image_size}")
print()
- # Stream response for real-time progress feedback
start_time = time.time()
print(f" ⏳ Generating...", end="", flush=True)
- # Heartbeat thread: print elapsed time every 5s while waiting
- import threading
heartbeat_stop = threading.Event()
def _heartbeat():
@@ -194,7 +170,7 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
hb_thread = threading.Thread(target=_heartbeat, daemon=True)
hb_thread.start()
- last_image_data = None # (PIL.Image or bytes, mime_type)
+ last_image_data = None
chunk_count = 0
total_bytes = 0
@@ -219,7 +195,6 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
print(f"\n 📦 Chunk #{chunk_count} received ({size_str}, {elapsed:.1f}s)", end="", flush=True)
last_image_data = part
- # Stop heartbeat
heartbeat_stop.set()
hb_thread.join(timeout=1)
@@ -239,58 +214,54 @@ def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
raise RuntimeError("No image was generated. The server may have refused the request.")
-# ╔══════════════════════════════════════════════════════════════════╗
-# ║ Entry Point ║
-# ╚══════════════════════════════════════════════════════════════════╝
+# ╔���═══════════════════════════════════���═════════════════════════════╗
+# ║ Public Entry Point ║
+# ╚═════════════���═══════════════════════════���════════════════════════╝
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 = DEFAULT_MODEL,
- max_retries: int = MAX_RETRIES) -> str:
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
"""
- Image generation entry point (with automatic retry).
-
- Automatically selects connection mode based on the GEMINI_BASE_URL environment variable:
- - Without GEMINI_BASE_URL -> Direct connection to the official Google API
- - With GEMINI_BASE_URL -> Via proxy API (using the same Official protocol)
+ Gemini image generation with automatic retry.
- Automatically retries with exponential backoff on 429 Rate Limit errors.
+ Reads credentials from environment variables:
+ IMAGE_API_KEY / GEMINI_API_KEY (fallback)
+ IMAGE_BASE_URL / GEMINI_BASE_URL (fallback)
+ IMAGE_MODEL (optional override)
Args:
prompt: Positive prompt text
negative_prompt: Negative prompt text
- aspect_ratio: Aspect ratio
+ aspect_ratio: Aspect ratio (e.g. "16:9", "1:1")
image_size: Image size ("512px", "1K", "2K", "4K", case-insensitive)
output_dir: Output directory
filename: Output filename (without extension)
- model: Model name (default gemini-3.1-flash-image-preview)
+ model: Model name (default: gemini-3.1-flash-image-preview)
max_retries: Maximum number of retries
Returns:
Path of the saved image file
-
- Raises:
- ValueError: When parameters are invalid
- RuntimeError: When generation fails after all retries are exhausted
"""
- api_key = os.environ.get("GEMINI_API_KEY")
- base_url = os.environ.get("GEMINI_BASE_URL")
+ 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")
if not api_key:
- raise ValueError("GEMINI_API_KEY environment variable is not set.")
+ raise ValueError(
+ "No API key found. Set IMAGE_API_KEY or GEMINI_API_KEY environment variable."
+ )
+
+ if model is None:
+ model = os.environ.get("IMAGE_MODEL") or DEFAULT_MODEL
- # Case-insensitive normalization
image_size = _normalize_image_size(image_size)
- # Validate inputs
if aspect_ratio not in VALID_ASPECT_RATIOS:
raise ValueError(f"Invalid aspect ratio '{aspect_ratio}'. Valid: {VALID_ASPECT_RATIOS}")
if image_size not in VALID_IMAGE_SIZES:
raise ValueError(f"Invalid image size '{image_size}'. Valid: {VALID_IMAGE_SIZES}")
- # ── Retry loop ──
last_error = None
for attempt in range(max_retries + 1):
try:
@@ -313,52 +284,3 @@ def generate(prompt: str, negative_prompt: str = None,
break
raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(
- description="Generate images using Gemini Nano Banana."
- )
- parser.add_argument(
- "prompt", nargs="?", default="Nano Banana",
- help="The text prompt for image generation."
- )
- parser.add_argument(
- "--negative_prompt", "-n", default=None,
- help="Negative prompt to specify what to avoid."
- )
- parser.add_argument(
- "--aspect_ratio", default="1:1", choices=VALID_ASPECT_RATIOS,
- help=f"Aspect ratio. Choices: {VALID_ASPECT_RATIOS}. Default: 1:1."
- )
- parser.add_argument(
- "--image_size", default="1K",
- help=f"Image size. Choices: {VALID_IMAGE_SIZES}. Default: 1K. (case-insensitive)"
- )
- parser.add_argument(
- "--output", "-o", default=None,
- help="Output directory. Default: current directory."
- )
- parser.add_argument(
- "--filename", "-f", default=None,
- help="Output filename (without extension). Overrides auto-naming."
- )
- parser.add_argument(
- "--model", "-m", default=DEFAULT_MODEL,
- help=f"Model name. Default: {DEFAULT_MODEL}."
- )
-
- args = parser.parse_args()
-
- try:
- generate(args.prompt, args.negative_prompt, args.aspect_ratio,
- args.image_size, args.output, args.filename, args.model)
- except (ValueError, FileNotFoundError) as e:
- print(f"Error: {e}")
- sys.exit(1)
- except RuntimeError as e:
- print(f"Error: {e}")
- sys.exit(1)
- except KeyboardInterrupt:
- print("\n\nInterrupted by user.")
- sys.exit(130)
diff --git a/skills/ppt-master/scripts/backend_openai.py b/skills/ppt-master/scripts/backend_openai.py
new file mode 100644
index 00000000..5a7a1cf4
--- /dev/null
+++ b/skills/ppt-master/scripts/backend_openai.py
@@ -0,0 +1,276 @@
+#!/usr/bin/env python3
+"""
+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)
+
+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 PIL import Image as PILImage
+ HAS_PIL = True
+except ImportError:
+ HAS_PIL = False
+
+
+# ╔══════════════════════════════════════════════════════════════════╗
+# ║ Constants ║
+# ╚══════════════════════════════════════════════════════════════════╝
+
+# Aspect ratio -> OpenAI size mapping
+# Covers common PPT/social media ratios
+ASPECT_RATIO_TO_SIZE = {
+ "1:1": "1024x1024",
+ "16:9": "1792x1024",
+ "9:16": "1024x1792",
+ "3:2": "1536x1024",
+ "2:3": "1024x1536",
+ "4:3": "1536x1024", # closest available
+ "3:4": "1024x1536", # closest available
+ "4:5": "1024x1024", # fallback to square
+ "5:4": "1024x1024", # fallback to square
+ "21:9": "1792x1024", # closest wide format
+}
+
+VALID_ASPECT_RATIOS = list(ASPECT_RATIO_TO_SIZE.keys())
+
+# image_size -> quality mapping
+IMAGE_SIZE_TO_QUALITY = {
+ "512px": "low",
+ "1K": "auto",
+ "2K": "high",
+ "4K": "high",
+}
+
+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 ║
+# ╚══════════════════════════════════════════════════════════════════╝
+
+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 = None) -> str:
+ """
+ Image generation via OpenAI-compatible API.
+
+ Maps aspect_ratio to OpenAI's size parameter, and image_size to quality.
+
+ Returns:
+ Path of the saved image file
+
+ Raises:
+ RuntimeError: When generation fails
+ """
+ client = OpenAI(api_key=api_key, base_url=base_url)
+
+ # Build prompt (OpenAI has no native negative_prompt, append to prompt)
+ final_prompt = prompt
+ if negative_prompt:
+ final_prompt += f"\n\nAvoid the following: {negative_prompt}"
+
+ # Map parameters
+ size = ASPECT_RATIO_TO_SIZE.get(aspect_ratio, "1024x1024")
+ quality = IMAGE_SIZE_TO_QUALITY.get(image_size, "auto")
+
+ mode_label = f"Proxy: {base_url}" if base_url else "OpenAI API"
+ print(f"[OpenAI - {mode_label}]")
+ print(f" Model: {model}")
+ print(f" Prompt: {final_prompt[:120]}{'...' if len(final_prompt) > 120 else ''}")
+ print(f" Size: {size} (from aspect_ratio={aspect_ratio})")
+ print(f" Quality: {quality} (from image_size={image_size})")
+ print()
+
+ start_time = time.time()
+ print(f" ⏳ Generating...", end="", flush=True)
+
+ # Heartbeat thread
+ heartbeat_stop = threading.Event()
+
+ def _heartbeat():
+ while not heartbeat_stop.is_set():
+ heartbeat_stop.wait(5)
+ if not heartbeat_stop.is_set():
+ elapsed = time.time() - start_time
+ print(f" {elapsed:.0f}s...", end="", flush=True)
+
+ hb_thread = threading.Thread(target=_heartbeat, daemon=True)
+ hb_thread.start()
+
+ try:
+ resp = client.images.generate(
+ prompt=final_prompt,
+ model=model,
+ size=size,
+ quality=quality,
+ n=1,
+ response_format="b64_json",
+ )
+ finally:
+ heartbeat_stop.set()
+ hb_thread.join(timeout=1)
+
+ elapsed = time.time() - start_time
+ 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")
+ image_data = base64.b64decode(resp.data[0].b64_json)
+
+ if HAS_PIL:
+ image = PILImage.open(io.BytesIO(image_data))
+ image.save(path)
+ else:
+ with open(path, "wb") as f:
+ f.write(image_data)
+
+ print(f" File saved to: {path}")
+ _report_resolution(path)
+ return path
+
+ raise RuntimeError("No image was generated. The server may have refused the request.")
+
+
+# ╔══════════════════════════════════════════════════════════════════╗
+# ║ Public Entry Point ║
+# ╚══════════════════════════════════════════════════════════════════╝
+
+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:
+ """
+ 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)
+
+ Args:
+ prompt: Positive prompt text
+ negative_prompt: Negative prompt text (appended to prompt as "Avoid...")
+ aspect_ratio: Aspect ratio, mapped to OpenAI size
+ image_size: Image size, mapped to OpenAI quality
+ output_dir: Output directory
+ filename: Output filename (without extension)
+ model: Model name (default: gpt-image-1)
+ max_retries: Maximum number of retries
+
+ 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")
+
+ if not api_key:
+ raise ValueError(
+ "No API key found. Set IMAGE_API_KEY or OPENAI_API_KEY environment variable."
+ )
+
+ if model is None:
+ model = os.environ.get("IMAGE_MODEL") or DEFAULT_MODEL
+
+ image_size = _normalize_image_size(image_size)
+
+ if aspect_ratio not in ASPECT_RATIO_TO_SIZE:
+ supported = list(ASPECT_RATIO_TO_SIZE.keys())
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for OpenAI backend. "
+ f"Supported: {supported}"
+ )
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(api_key, prompt, negative_prompt,
+ aspect_ratio, image_size, output_dir,
+ 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)
+ 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
+ print(f"\n ⚠️ Error (attempt {attempt + 1}/{max_retries + 1}): {e}. "
+ f"Retrying in {delay}s...")
+ time.sleep(delay)
+ else:
+ break
+
+ 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
new file mode 100644
index 00000000..b5fbd224
--- /dev/null
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""
+Unified Image Generation Tool
+
+Dispatches to the appropriate backend (Gemini or OpenAI) based on 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
+
+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
+
+ Legacy support (Gemini only):
+ GEMINI_API_KEY / GEMINI_BASE_URL still work when IMAGE_BACKEND is not set.
+
+Usage:
+ python3 image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o images/
+"""
+
+import os
+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
+
+# All aspect ratios accepted by the unified CLI
+# (each backend validates its own subset internally)
+ALL_ASPECT_RATIOS = [
+ "1:1", "1:4", "1:8",
+ "2:3", "3:2", "3:4", "4:1", "4:3",
+ "4:5", "5:4", "8:1", "9:16", "16:9", "21:9"
+]
+
+ALL_IMAGE_SIZES = ["512px", "1K", "2K", "4K"]
+
+
+def _resolve_backend():
+ """
+ Determine which backend to use based on environment variables.
+
+ Returns:
+ A backend module with a generate() function.
+ """
+ backend_name = os.environ.get("IMAGE_BACKEND", "").strip().lower()
+
+ if backend_name == "gemini":
+ import backend_gemini
+ return backend_gemini, "gemini"
+
+ if backend_name == "openai":
+ import backend_openai
+ return backend_openai, "openai"
+
+ if backend_name and backend_name not in ("gemini", "openai"):
+ print(f"Error: Unknown IMAGE_BACKEND='{backend_name}'. Supported: gemini, openai")
+ sys.exit(1)
+
+ # 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"
+
+ print(
+ "Error: No image backend configured.\n"
+ "\n"
+ "Set environment variables:\n"
+ " IMAGE_BACKEND=gemini # or openai\n"
+ " IMAGE_API_KEY=your-key\n"
+ "\n"
+ "Or for legacy Gemini usage:\n"
+ " GEMINI_API_KEY=your-key\n"
+ )
+ sys.exit(1)
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description="Generate images using AI (Gemini or OpenAI backend)."
+ )
+ parser.add_argument(
+ "prompt", nargs="?", default="a beautiful landscape",
+ help="The text prompt for image generation."
+ )
+ parser.add_argument(
+ "--negative_prompt", "-n", default=None,
+ help="Negative prompt to specify what to avoid."
+ )
+ parser.add_argument(
+ "--aspect_ratio", default="1:1", choices=ALL_ASPECT_RATIOS,
+ help=f"Aspect ratio. Default: 1:1."
+ )
+ parser.add_argument(
+ "--image_size", default="1K",
+ help=f"Image size. Choices: {ALL_IMAGE_SIZES}. Default: 1K. (case-insensitive)"
+ )
+ parser.add_argument(
+ "--output", "-o", default=None,
+ help="Output directory. Default: current directory."
+ )
+ parser.add_argument(
+ "--filename", "-f", default=None,
+ help="Output filename (without extension). Overrides auto-naming."
+ )
+ parser.add_argument(
+ "--model", "-m", default=None,
+ help="Model name. Default depends on backend."
+ )
+ parser.add_argument(
+ "--backend", "-b", default=None, choices=["gemini", "openai"],
+ help="Override IMAGE_BACKEND env var."
+ )
+
+ args = parser.parse_args()
+
+ # CLI --backend overrides env var
+ if args.backend:
+ os.environ["IMAGE_BACKEND"] = args.backend
+
+ backend, backend_name = _resolve_backend()
+ print(f"Using backend: {backend_name}\n")
+
+ try:
+ backend.generate(
+ prompt=args.prompt,
+ negative_prompt=args.negative_prompt,
+ aspect_ratio=args.aspect_ratio,
+ image_size=args.image_size,
+ output_dir=args.output,
+ filename=args.filename,
+ model=args.model,
+ )
+ except (ValueError, FileNotFoundError) as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+ except RuntimeError as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+ except KeyboardInterrupt:
+ print("\n\nInterrupted by user.")
+ sys.exit(130)
+
+
+if __name__ == "__main__":
+ main()