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: add openrouter backend (#57)
scientificworld767a53629f12
diff --git a/.env.example b/.env.exampleindex 6e3ac7ab..920c6f88 100644--- a/.env.example+++ b/.env.example@@ -101,6 +101,10 @@# REPLICATE_API_TOKEN=r8_xxx# REPLICATE_MODEL=black-forest-labs/flux-1.1-pro# REPLICATE_BASE_URL=https://api.replicate.com/v1/predictions+#+# OPENROUTER_API_KEY=sk-or-v1-xxx+# OPENROUTER_MODEL=google/gemini-3.1-flash-image-preview+# OPENROUTER_BASE_URL=https://openrouter.ai/api/v1# ─────────────────────────────────────────────────────────────# Multi-provider example / 多提供商共存示例diff --git a/skills/ppt-master/scripts/image_backends/backend_openrouter.py b/skills/ppt-master/scripts/image_backends/backend_openrouter.pynew file mode 100644index 00000000..875bb037--- /dev/null+++ b/skills/ppt-master/scripts/image_backends/backend_openrouter.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""+OpenRouter image generation backend.++Configuration keys:+ OPENROUTER_API_KEY (required)+ OPENROUTER_BASE_URL (optional)+ OPENROUTER_MODEL (optional)+"""++import base64+import os+import time+import threading+import requests++from image_backends.backend_common import (+ MAX_RETRIES,+ is_rate_limit_error,+ normalize_image_size,+ resolve_output_path,+ retry_delay,+ save_image_bytes,+)+++# ╔══════════════════════════════════════════════════════════════════╗+# ║ Constants ║+# ╚══════════════════════════════════════════════════════════════════╝++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"+]++VALID_IMAGE_SIZES = ["1K", "2K", "4K", "0.5K"]++DEFAULT_MODEL = "google/gemini-3.1-flash-image-preview"+DEFAULT_ENDPOINT = "https://openrouter.ai/api/v1"++# ╔══════════════════════════════════════════════════════════════════╗+# ║ Image Generation ║+# ╚══════════════════════════════════════════════════════════════════╝++def _resolve_url(base_url: str) -> str:+ """Resolve the OpenRouter generation endpoint."""+ return base_url.rstrip("/") + "/chat/completions"++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:+ """+ Image generation via OpenRouter's API.+ """++ url = _resolve_url(base_url)++ final_prompt = prompt+ if negative_prompt:+ final_prompt += f"\n\nAvoid the following: {negative_prompt}"++ headers = {+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json"+ }++ payload = {+ "model": model,+ "messages": [+ {+ "role": "user",+ "content": final_prompt+ }+ ],+ "modalities": ["image", "text"],+ "image_config": {+ "aspect_ratio": aspect_ratio,+ "image_size": image_size+ }+ }++ print(f"[OpenRouter]")+ print(f" Model: {model}")+ print(f" Prompt: {final_prompt[:120]}{'...' if len(final_prompt) > 120 else ''}")+ print(f" Aspect Ratio: {aspect_ratio}")+ print(f" 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:+ result = requests.post(url, headers=headers, json=payload, timeout=300).json()+ finally:+ heartbeat_stop.set()+ hb_thread.join(timeout=1)++ elapsed = time.time() - start_time+ print(f"\n [DONE] Image generated ({elapsed:.1f}s)")++ if result.get("choices"):+ message = result["choices"][0]["message"]+ if message.get("images"):+ path = resolve_output_path(prompt, output_dir, filename, ".png")+ # strip "data:image/png;base64,"+ image_data = base64.urlsafe_b64decode(message["images"][0]["image_url"]["url"][22:])+ return save_image_bytes(image_data, 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:+ """+ OpenRouter image generation with automatic retry.++ Reads credentials from the current process environment or the project-root `.env`:+ OPENROUTER_API_KEY+ OPENROUTER_BASE_URL+ OPENROUTER_MODEL (optional override)+ """+ api_key = os.environ.get("OPENROUTER_API_KEY")+ base_url = os.environ.get("OPENROUTER_BASE_URL")++ if not api_key:+ raise ValueError(+ "No API key found. Set OPENROUTER_API_KEY in the current environment or the project-root .env."+ )++ if model is None:+ model = os.environ.get("OPENROUTER_MODEL") or DEFAULT_MODEL++ 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}")++ if image_size not in VALID_IMAGE_SIZES:+ raise ValueError(f"Invalid image size '{image_size}'. Valid: {VALID_IMAGE_SIZES}")++ 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_delay(attempt, rate_limited=True)+ print(f"\n [WARN] Rate limit hit (attempt {attempt + 1}/{max_retries + 1}). "+ f"Waiting {delay}s before retry...")+ time.sleep(delay)+ elif attempt < max_retries:+ delay = retry_delay(attempt, rate_limited=False)+ print(f"\n [WARN] 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.pyindex 21f087d8..e2213ce6 100644--- a/skills/ppt-master/scripts/image_gen.py+++ b/skills/ppt-master/scripts/image_gen.py@@ -5,18 +5,19 @@ Unified Image Generation ToolDispatches to the appropriate backend based on explicit provider configuration.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=minimax -> MiniMax image backend- 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=gemini -> Gemini backend (google-genai SDK)+ IMAGE_BACKEND=openai -> OpenAI-compatible backend (openai SDK)+ IMAGE_BACKEND=minimax -> MiniMax image backend+ 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 backendIMAGE_BACKEND=siliconflow -> SiliconFlow backend- IMAGE_BACKEND=fal -> fal.ai backend- IMAGE_BACKEND=replicate -> Replicate backend+ IMAGE_BACKEND=fal -> fal.ai backend+ IMAGE_BACKEND=replicate -> Replicate backend+ IMAGE_BACKEND=openrouter -> OpenRouter backendConfiguration source:1. Current process environment variables@@ -59,6 +60,7 @@ IMAGE_ENV_PREFIXES = ("SILICONFLOW_","FAL_","REPLICATE_",+ "OPENROUTER_",)DEPRECATED_IMAGE_KEYS = {"IMAGE_API_KEY",@@ -171,6 +173,13 @@ BACKEND_REGISTRY = {"default_model": "black-forest-labs/flux-1.1-pro","key_hint": "REPLICATE_API_TOKEN / REPLICATE_API_KEY",},+ "openrouter": {+ "module": "backend_openrouter",+ "tier": "experimental",+ "label": "OpenRouter",+ "default_model": "google/gemini-3.1-flash-image-preview",+ "key_hint": "OPENROUTER_API_KEY",+ },}TIER_ORDER = {"core": 0, "extended": 1, "experimental": 2}