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
feat(tools): 新增 Nano Banana 图像生成工具并更新文档
hugohe39a59bded6bca
diff --git a/roles/Image_Generator.md b/roles/Image_Generator.mdindex c2ed5c45..6d589a9e 100644--- a/roles/Image_Generator.md+++ b/roles/Image_Generator.md@@ -129,6 +129,9 @@| 朋友圈 | 1:1 | 1080×1080 || Story | 9:16 | 1080×1920 |+> ⚠️ **Nano Banana 工具支持的宽高比**(生成提示词时必须使用以下格式):+> `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`+---## 3. 图片类型分类与处理@@ -360,18 +363,25 @@ subtle and elegant, suitable for presentation slide corners> ⚠️ **前置条件**: 必须先完成 4.2,确保 `images/image_prompts.md` 已创建-**方式一:自动生成**(如果 AI 工具支持)+**方式一:使用 Nano Banana 命令行工具** ⭐ 推荐-- 直接调用图像生成 API-- 下载并保存到 `项目/images/` 目录+- 使用本项目工具 `tools/nano_banana_gen.py` 直接生成高分辨率图片+- 首次使用需配置:复制 `tools/nano_banana_config.example.json` 为 `tools/nano_banana_config.json`,填入 API Key+- 命令格式:+ ```bash+ python tools/nano_banana_gen.py "你的提示词" --aspect_ratio 16:9 --image_size 4K --output 项目/images+ ```+- 支持的宽高比: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`+- 支持的尺寸: `1K`, `2K`, `4K`(默认)+- 使用 `--output` 或 `-o` 参数指定输出目录,图片将保存到与 `image_prompts.md` 相同的 `images/` 目录-**方式二:手动生成**(常用方式)+**方式二:手动生成**(使用其他 AI 平台)- 提示词已保存在 `images/image_prompts.md`,告知用户文件位置- 用户自行到 AI 平台(Midjourney、DALL-E、Stable Diffusion、文心一格、通义万相)生成- 用户将生成的图片放入 `项目/images/` 目录-**方式三:使用 Gemini 生成**(推荐高分辨率)+**方式三:使用 Gemini 网页版**- 在 [Gemini](https://gemini.google.com/) 中生成图片- 选择 **Download full size** 下载高分辨率版本@@ -380,6 +390,11 @@ subtle and elegant, suitable for presentation slide corners- 或使用 [gemini-watermark-remover](https://github.com/journey-ad/gemini-watermark-remover)- 将处理后的图片放入 `项目/images/` 目录+**方式四:自动生成**(如果 AI 工具支持)++- 直接调用图像生成 API+- 下载并保存到 `项目/images/` 目录+### 4.4 验证阶段- 确认所有图片已保存到 `images/` 目录diff --git a/tools/README.md b/tools/README.mdindex 3f3b4497..d4911760 100644--- a/tools/README.md+++ b/tools/README.md@@ -49,6 +49,7 @@ graph TBF2[analyze_images.py]F3[svg_position_calculator.py]F4[config.py]+ F5[nano_banana_gen.py]endA1 --> B1@@ -90,6 +91,7 @@ graph TB| **导出** | `svg_to_pptx.py` | SVG 转 PowerPoint || **讲稿处理** | `total_md_split.py` | 讲稿拆分工具 || **质量检查** | `svg_quality_checker.py`, `batch_validate.py` | 验证 SVG 规范 |+| **素材生成** | `nano_banana_gen.py` | 利用 Gemini Nano 生成高品质图片 || **辅助** | `config.py`, `analyze_images.py`, `rotate_images.py` | 配置和图片处理 |---@@ -1169,7 +1171,65 @@ pip install Pillow numpy----### 14. embed_icons.py — SVG 图标嵌入工具+### 14. nano_banana_gen.py — Nano Banana 图像生成工具++利用 Google GenAI API 调用 Gemini 模型生成高质量图片素材。++**功能**:++- **高分辨率**: 支持最高 4K 分辨率生成+- **自定义宽高比**: 支持 `16:9`, `4:3`, `1:1`, `9:16` 等主流比例+- **提示词工程**: 内置负面提示词支持,自动优化生成质量+- **自动保存**: 自动根据提示词命名并保存为 PNG 格式++**用法**:++```bash+# 生成默认图片+python3 tools/nano_banana_gen.py "A modern futuristic workspace"++# 指定宽高比和尺寸+python3 tools/nano_banana_gen.py "Abstract tech background" --aspect_ratio 16:9 --image_size 4K++# 指定输出目录+python3 tools/nano_banana_gen.py "Concept car" -o projects/demo/images++# 使用负面提示词+python3 tools/nano_banana_gen.py "Beautiful landscape" -n "low quality, blurry, watermark"+```++**参数说明**:++| 参数 | 缩写 | 默认值 | 可选值 |+|------|------|--------|--------|+| `prompt` | - | Nano Banana | 提示词字符串 |+| `--negative_prompt` | `-n` | None | 负面提示词 |+| `--aspect_ratio` | - | `1:1` | `1:1`, `16:9`, `4:3`, `3:2`, `9:16`, `21:9` 等 |+| `--image_size` | - | `4K` | `1K`, `2K`, `4K` |+| `--output` | `-o` | 当前工作目录 | 图片保存目录 |++**配置**:++首次使用建议配置 `tools/nano_banana_config.json`:++```json+{+ "api_key": "YOUR_GEMINI_API_KEY",+ "base_url": "YOUR_API_BASE_URL"+}+```++或者设置环境变量 `GEMINI_API_KEY`。++**依赖**:++```bash+pip install google-genai+```++---++### 15. embed_icons.py — SVG 图标嵌入工具将 SVG 文件中的图标占位符 (`<use ...>`) 替换为实际的图标路径数据,实现图标的“零依赖”嵌入。@@ -1298,6 +1358,8 @@ pip install python-pptx----_最后更新: 2025-12-20_+_最后更新: 2026-02-03_++_nano_banana_gen.py 文档更新: 2026-02-03__gemini_watermark_remover.py 文档更新: 2025-12-20_diff --git a/tools/nano_banana_gen.py b/tools/nano_banana_gen.pynew file mode 100644index 00000000..e0db5ede--- /dev/null+++ b/tools/nano_banana_gen.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""+Nano Banana Image Generator (Gemini Nano)+通过 Google GenAI API (Gemini Nano) 生成高质量图片的工具。++支持功能:+- 高达 4K 分辨率的图像生成+- 自定义宽高比 (16:9, 4:3, 1:1, 9:16 等)+- 负面提示词支持 (通过 Prompt 工程实现)+- 自动保存为 PNG 格式+- 环境变量配置 (安全优先)++依赖:+ pip install google-genai+"""++import os+import json+import base64+import argparse+import mimetypes+from google import genai+from google.genai import types++# Predefined configuration presets+VALID_ASPECT_RATIOS = [+ "1:1", "2:3", "3:2", "3:4", "4:3",+ "4:5", "5:4", "9:16", "16:9", "21:9"+]+VALID_IMAGE_SIZES = ["1K", "2K", "4K"]+++def save_binary_file(file_name: str, data: bytes):+ """保存二进制数据到文件"""+ with open(file_name, "wb") as f:+ f.write(data)+ print(f"File saved to: {file_name}")+++def generate(prompt: str, negative_prompt: str = None,+ aspect_ratio: str = "1:1", image_size: str = "4K",+ output_dir: str = None):+ """+ 调用 Gemini API 生成图像++ Args:+ prompt: 正向提示词+ negative_prompt: 负面提示词 (可选)+ aspect_ratio: 图片宽高比 (默认 1:1)+ image_size: 图片尺寸 (1K, 2K, 4K)+ output_dir: 输出目录 (可选,默认为当前目录)+ """+ # Load configuration+ # Priority: Environment Variables > Config File++ api_key = os.environ.get("GEMINI_API_KEY")+ base_url = os.environ.get("GEMINI_BASE_URL")++ config_path = os.path.join(os.path.dirname(__file__), "nano_banana_config.json")++ # If config file exists, load it directly to supplement missing env vars or as fallback+ if os.path.exists(config_path):+ try:+ with open(config_path, "r") as f:+ config = json.load(f)+ if not api_key:+ api_key = config.get("api_key")+ if not base_url:+ base_url = config.get("base_url")+ except Exception as e:+ print(f"Warning: Error reading configuration file: {e}")++ if not api_key:+ print("Error: API Key not found. Please set GEMINI_API_KEY env var or valid config file.")+ return++ # Validate aspect_ratio+ if aspect_ratio not in VALID_ASPECT_RATIOS:+ print(f"Error: Invalid aspect ratio '{aspect_ratio}'. Valid options: {VALID_ASPECT_RATIOS}")+ return++ # Validate image_size+ size_upper = str(image_size).upper()+ if size_upper not in VALID_IMAGE_SIZES:+ print(f"Error: Invalid image size '{image_size}'. Valid options: {VALID_IMAGE_SIZES}")+ return++ client = genai.Client(+ api_key=api_key,+ http_options={+ 'base_url': base_url+ }+ )++ base_model = "gemini-3-pro-image-preview"+ model = base_model++ # Handle image size model selection (2K or 4K adds suffix, 1K is default/no suffix)+ if size_upper in ["2K", "4K"]:+ model += f"-{size_upper.lower()}"++ # Handle Aspect Ratio in model name (e.g. -16x9)+ # This assumes the backend routes specific model names to specific aspect ratio pipelines+ if aspect_ratio:+ ratio_suffix = aspect_ratio.replace(":", "x")+ model += f"-{ratio_suffix}"++ # Append aspect ratio to prompt for models that support prompt-based config+ prompt_with_config = f"{prompt} --ar {aspect_ratio}"++ # Structure the prompt to include negative prompt if provided+ # Note: While some APIs have a dedicated negative_prompt field, putting it in the text+ # is a robust fallback for this specific client wrapper if the field isn't exposed.+ # We will try to pass it clearly in the text.+ final_prompt_text = prompt_with_config+ if negative_prompt:+ # Common convention for text-to-image prompts+ final_prompt_text += f"\n\nNegative prompt: {negative_prompt}"++ print(f"Generating image with prompt: '{final_prompt_text}'")+ print(f"Using Model: {model}")+ print(f"Configuration: Aspect Ratio={aspect_ratio}, Size={image_size}")++ parts = [types.Part.from_text(text=final_prompt_text)]++ contents = [+ types.Content(+ role="user",+ parts=parts,+ ),+ ]++ generate_content_config = types.GenerateContentConfig(+ response_modalities=[+ "IMAGE",+ ],+ image_config=types.ImageConfig(+ aspect_ratio=aspect_ratio,+ image_size=image_size,+ output_mime_type="image/png",+ ),+ )++ file_index = 0+ try:+ for chunk in client.models.generate_content_stream(+ model=model,+ contents=contents,+ config=generate_content_config,+ ):+ if (+ chunk.candidates is None+ or chunk.candidates[0].content is None+ or chunk.candidates[0].content.parts is None+ ):+ continue++ part = chunk.candidates[0].content.parts[0]+ if part.inline_data and part.inline_data.data:+ # Use a descriptive filename based on prompt (sanitized) or default+ # We use the ORIGINAL prompt for naming, not the one with flags+ safe_prompt = "".join([c for c in prompt if c.isalnum() or c in (' ', '_')]).rstrip()+ safe_prompt = safe_prompt.replace(" ", "_").lower()[:30] # Increased length+ if not safe_prompt:+ safe_prompt = "generated_image"++ file_name = f"{safe_prompt}_{file_index}"+ file_index += 1+ inline_data = part.inline_data+ data_buffer = inline_data.data++ # specific handling for requested mime type, though guess_extension is usually good+ file_extension = mimetypes.guess_extension(inline_data.mime_type) or ".png"+ # Clean up extension (mimetypes can return .jpe for jpeg)+ if file_extension in ['.jpe', '.jpeg']:+ file_extension = '.jpg'++ file_name_with_ext = f"{file_name}{file_extension}"+ if output_dir:+ os.makedirs(output_dir, exist_ok=True)+ full_path = os.path.join(output_dir, file_name_with_ext)+ else:+ full_path = file_name_with_ext+ save_binary_file(full_path, data_buffer)+ else:+ pass # Text content or other non-image content++ except Exception as e:+ print(f"An error occurred: {e}")++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 in the image."+ )+ parser.add_argument(+ "--aspect_ratio",+ default="1:1",+ choices=VALID_ASPECT_RATIOS,+ help=f"Aspect ratio of the generated image. Choices: {VALID_ASPECT_RATIOS}. Default is '1:1'."+ )+ parser.add_argument(+ "--image_size",+ default="4K",+ choices=VALID_IMAGE_SIZES,+ help=f"Size of the generated image. Choices: {VALID_IMAGE_SIZES}. Default is '4K'."+ )+ parser.add_argument(+ "--output", "-o",+ default=None,+ help="Output directory for generated images. If not specified, saves to current directory."+ )++ args = parser.parse_args()++ generate(args.prompt, args.negative_prompt, args.aspect_ratio, args.image_size, args.output)