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
fix(image): validate OpenAI gpt-image-2 request options
hugohe3ec289b56fa0d
diff --git a/.env.example b/.env.exampleindex c282c483..24773e57 100644--- a/.env.example+++ b/.env.example@@ -38,6 +38,10 @@# OPENAI_API_KEY=sk-xxx# OPENAI_MODEL=gpt-image-2# OPENAI_BASE_URL=http://127.0.0.1:3000/v1+# OPENAI_OUTPUT_FORMAT=png # png / jpeg / webp+# OPENAI_OUTPUT_COMPRESSION=80 # jpeg/webp only, 0-100+# OPENAI_BACKGROUND=auto # gpt-image-2: auto / opaque+# OPENAI_MODERATION=auto # auto / low# ─────────────────────────────────────────────────────────────# Example: Gemini / Gemini 示例@@ -128,6 +132,7 @@# IMAGE_BACKEND=openai# OPENAI_API_KEY=sk-xxx# OPENAI_MODEL=gpt-image-2+# OPENAI_OUTPUT_FORMAT=png# GEMINI_API_KEY=your-gemini-api-key# GEMINI_MODEL=gemini-3.1-flash-image-preview#diff --git a/skills/ppt-master/.env.example b/skills/ppt-master/.env.exampleindex c282c483..24773e57 100644--- a/skills/ppt-master/.env.example+++ b/skills/ppt-master/.env.example@@ -38,6 +38,10 @@# OPENAI_API_KEY=sk-xxx# OPENAI_MODEL=gpt-image-2# OPENAI_BASE_URL=http://127.0.0.1:3000/v1+# OPENAI_OUTPUT_FORMAT=png # png / jpeg / webp+# OPENAI_OUTPUT_COMPRESSION=80 # jpeg/webp only, 0-100+# OPENAI_BACKGROUND=auto # gpt-image-2: auto / opaque+# OPENAI_MODERATION=auto # auto / low# ─────────────────────────────────────────────────────────────# Example: Gemini / Gemini 示例@@ -128,6 +132,7 @@# IMAGE_BACKEND=openai# OPENAI_API_KEY=sk-xxx# OPENAI_MODEL=gpt-image-2+# OPENAI_OUTPUT_FORMAT=png# GEMINI_API_KEY=your-gemini-api-key# GEMINI_MODEL=gemini-3.1-flash-image-preview#diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.mdindex 0bdfcff4..9fb0d1b8 100644--- a/skills/ppt-master/scripts/docs/image.md+++ b/skills/ppt-master/scripts/docs/image.md@@ -45,6 +45,10 @@ IMAGE_BACKEND=openaiOPENAI_API_KEY=sk-xxxOPENAI_MODEL=gpt-image-2# OPENAI_BASE_URL=http://127.0.0.1:3000/v1 # optional proxy+# OPENAI_OUTPUT_FORMAT=png # png / jpeg / webp+# OPENAI_OUTPUT_COMPRESSION=80 # jpeg/webp only, 0-100+# OPENAI_BACKGROUND=auto # gpt-image-2: auto / opaque+# OPENAI_MODERATION=auto # auto / low```Example process environment:@@ -53,10 +57,17 @@ Example process environment:export IMAGE_BACKEND=openaiexport OPENAI_API_KEY=sk-xxxexport OPENAI_MODEL=gpt-image-2+export OPENAI_OUTPUT_FORMAT=png```Current process environment wins over `.env`.+OpenAI backend notes:+- `gpt-image-2` is the default OpenAI model.+- For `gpt-image-2`, `image_size=512px` means a low-quality draft preset, not a literal 512px edge. The model requires both edges to be multiples of 16px, a long:short ratio no greater than 3:1, and total pixels between 655,360 and 8,294,400.+- `OPENAI_BACKGROUND=transparent` is not supported by `gpt-image-2`; use `auto` or `opaque`.+- If `OPENAI_OUTPUT_FORMAT=jpeg` or `webp`, generated files use `.jpg` or `.webp` extensions instead of `.png`.+Use provider-specific keys only (e.g. `GEMINI_API_KEY`, `OPENAI_API_KEY`). See `.env.example` in clone mode or `${SKILL_DIR}/.env.example` in skill-install mode for the full list per backend.`IMAGE_API_KEY`, `IMAGE_MODEL`, and `IMAGE_BASE_URL` are intentionally unsupported.diff --git a/skills/ppt-master/scripts/image_backends/backend_openai.py b/skills/ppt-master/scripts/image_backends/backend_openai.pyindex 8ac0e6e9..6c835645 100644--- a/skills/ppt-master/scripts/image_backends/backend_openai.py+++ b/skills/ppt-master/scripts/image_backends/backend_openai.py@@ -9,6 +9,10 @@ Configuration keys:OPENAI_API_KEY (required) API keyOPENAI_BASE_URL (optional) Custom API endpoint (e.g. http://127.0.0.1:3000/v1)OPENAI_MODEL (optional) Model name (default: gpt-image-2)+ OPENAI_OUTPUT_FORMAT (optional) png, jpeg, or webp for GPT image models+ OPENAI_OUTPUT_COMPRESSION (optional) 0-100, only for jpeg/webp GPT image output+ OPENAI_BACKGROUND (optional) auto or opaque for gpt-image-2+ OPENAI_MODERATION (optional) auto or low for GPT image modelsDependencies:pip install openai Pillow@@ -76,13 +80,13 @@ GPT_IMAGE_LEGACY_ASPECT_RATIO_TO_SIZE = {# the edge ratio is <= 3:1, and the total pixels are within model limits.GPT_IMAGE_2_SIZES = {"512px": {- "1:1": "1024x1024", "16:9": "1152x648", "9:16": "648x1152",+ "1:1": "1024x1024", "16:9": "1280x720", "9:16": "720x1280","3:2": "1248x832", "2:3": "832x1248", "4:3": "1024x768","3:4": "768x1024", "4:5": "896x1120", "5:4": "1120x896","21:9": "1280x544",},"1K": {- "1:1": "1024x1024", "16:9": "1152x648", "9:16": "648x1152",+ "1:1": "1024x1024", "16:9": "1280x720", "9:16": "720x1280","3:2": "1248x832", "2:3": "832x1248", "4:3": "1024x768","3:4": "768x1024", "4:5": "896x1120", "5:4": "1120x896","21:9": "1280x544",@@ -113,13 +117,27 @@ VALID_ASPECT_RATIOS = list(LEGACY_COMPAT_ASPECT_RATIO_TO_SIZE.keys())# image_size -> quality mappingIMAGE_SIZE_TO_QUALITY = {"512px": "low",- "1K": "auto",+ "1K": "medium","2K": "high","4K": "high",}DEFAULT_MODEL = "gpt-image-2"+GPT_IMAGE_2_MIN_PIXELS = 655_360+GPT_IMAGE_2_MAX_PIXELS = 8_294_400+GPT_IMAGE_2_MAX_EDGE = 3840+GPT_IMAGE_2_MAX_RATIO = 3++GPT_IMAGE_OUTPUT_FORMATS = {"png", "jpeg", "webp"}+GPT_IMAGE_OUTPUT_EXTENSIONS = {+ "png": ".png",+ "jpeg": ".jpg",+ "webp": ".webp",+}+GPT_IMAGE_BACKGROUNDS = {"auto", "opaque", "transparent"}+GPT_IMAGE_MODERATION_VALUES = {"auto", "low"}+def _field(value, name: str):"""Read a response field from either an SDK object or a dict."""@@ -144,10 +162,42 @@ def _is_dall_e_2(model: str) -> bool:return _normalized_model(model) == "dall-e-2"+def _parse_size(size: str) -> tuple[int, int]:+ try:+ width_s, height_s = size.lower().split("x", 1)+ return int(width_s), int(height_s)+ except Exception as exc:+ raise ValueError(f"Invalid image size '{size}'. Expected WIDTHxHEIGHT.") from exc+++def _validate_gpt_image_2_size(size: str) -> None:+ width, height = _parse_size(size)+ total_pixels = width * height+ long_edge = max(width, height)+ short_edge = min(width, height)++ errors = []+ if long_edge > GPT_IMAGE_2_MAX_EDGE:+ errors.append(f"max edge {long_edge}px exceeds {GPT_IMAGE_2_MAX_EDGE}px")+ if width % 16 != 0 or height % 16 != 0:+ errors.append("both edges must be multiples of 16px")+ if long_edge / short_edge > GPT_IMAGE_2_MAX_RATIO:+ errors.append("long:short edge ratio must not exceed 3:1")+ if not (GPT_IMAGE_2_MIN_PIXELS <= total_pixels <= GPT_IMAGE_2_MAX_PIXELS):+ errors.append(+ f"total pixels {total_pixels:,} must be between "+ f"{GPT_IMAGE_2_MIN_PIXELS:,} and {GPT_IMAGE_2_MAX_PIXELS:,}"+ )+ if errors:+ raise ValueError(f"Invalid gpt-image-2 size '{size}': {', '.join(errors)}")++def _select_size(model: str, aspect_ratio: str, image_size: str) -> str:"""Select a model-compatible size while preserving legacy fallbacks."""if _is_gpt_image_2(model):- return GPT_IMAGE_2_SIZES[image_size][aspect_ratio]+ size = GPT_IMAGE_2_SIZES[image_size][aspect_ratio]+ _validate_gpt_image_2_size(size)+ return sizeif _is_gpt_image_model(model):return GPT_IMAGE_LEGACY_ASPECT_RATIO_TO_SIZE[aspect_ratio]if _is_dall_e_2(model):@@ -160,6 +210,60 @@ def _supports_response_format(model: str) -> bool:return not _is_gpt_image_model(model)+def _read_env_choice(name: str, allowed: set[str]) -> str | None:+ value = os.environ.get(name)+ if value is None or not value.strip():+ return None+ normalized = value.strip().lower()+ if normalized not in allowed:+ allowed_list = ", ".join(sorted(allowed))+ raise ValueError(f"Invalid {name}='{value}'. Supported: {allowed_list}")+ return normalized+++def _read_env_int(name: str, minimum: int, maximum: int) -> int | None:+ value = os.environ.get(name)+ if value is None or not value.strip():+ return None+ try:+ parsed = int(value)+ except ValueError as exc:+ raise ValueError(f"Invalid {name}='{value}'. Expected integer {minimum}-{maximum}.") from exc+ if not (minimum <= parsed <= maximum):+ raise ValueError(f"Invalid {name}={parsed}. Expected integer {minimum}-{maximum}.")+ return parsed+++def _gpt_image_options(model: str) -> tuple[dict, str]:+ """Read optional GPT Image request parameters from environment."""+ output_format = _read_env_choice("OPENAI_OUTPUT_FORMAT", GPT_IMAGE_OUTPUT_FORMATS)+ output_ext = GPT_IMAGE_OUTPUT_EXTENSIONS[output_format] if output_format else ".png"+ options = {}+ if output_format:+ options["output_format"] = output_format++ output_compression = _read_env_int("OPENAI_OUTPUT_COMPRESSION", 0, 100)+ if output_compression is not None:+ if output_format not in {"jpeg", "webp"}:+ raise ValueError(+ "OPENAI_OUTPUT_COMPRESSION is only supported when "+ "OPENAI_OUTPUT_FORMAT is jpeg or webp."+ )+ options["output_compression"] = output_compression++ background = _read_env_choice("OPENAI_BACKGROUND", GPT_IMAGE_BACKGROUNDS)+ if background:+ if _is_gpt_image_2(model) and background == "transparent":+ raise ValueError("gpt-image-2 does not support OPENAI_BACKGROUND=transparent.")+ options["background"] = background++ moderation = _read_env_choice("OPENAI_MODERATION", GPT_IMAGE_MODERATION_VALUES)+ if moderation:+ options["moderation"] = moderation++ return options, output_ext++# ╔══════════════════════════════════════════════════════════════════╗# ║ Image Generation ║# ╚══════════════════════════════════════════════════════════════════╝@@ -184,6 +288,19 @@ def _generate_image(api_key: str, prompt: str,# Map parameterssize = _select_size(model, aspect_ratio, image_size)quality = IMAGE_SIZE_TO_QUALITY.get(image_size, "auto")+ output_ext = ".png"+ request = {+ "prompt": prompt,+ "model": model,+ "size": size,+ "quality": quality,+ "n": 1,+ }+ if _is_gpt_image_model(model):+ gpt_options, output_ext = _gpt_image_options(model)+ request.update(gpt_options)+ elif _supports_response_format(model):+ request["response_format"] = "b64_json"mode_label = f"Proxy: {base_url}" if base_url else "OpenAI API"print(f"[OpenAI - {mode_label}]")@@ -191,6 +308,14 @@ def _generate_image(api_key: str, prompt: str,print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")print(f" Size: {size} (from aspect_ratio={aspect_ratio})")print(f" Quality: {quality} (from image_size={image_size})")+ if request.get("output_format"):+ print(f" Format: {request['output_format']}")+ if request.get("output_compression") is not None:+ print(f" Compression: {request['output_compression']}")+ if request.get("background"):+ print(f" Background: {request['background']}")+ if request.get("moderation"):+ print(f" Moderation: {request['moderation']}")print()start_time = time.time()@@ -210,16 +335,6 @@ def _generate_image(api_key: str, prompt: str,hb_thread.start()try:- request = {- "prompt": prompt,- "model": model,- "size": size,- "quality": quality,- "n": 1,- }- if _supports_response_format(model):- request["response_format"] = "b64_json"-resp = client.images.generate(**request)finally:heartbeat_stop.set()@@ -230,7 +345,7 @@ def _generate_image(api_key: str, prompt: str,data = _field(resp, "data") if resp is not None else Noneif data:- path = resolve_output_path(prompt, output_dir, filename, ".png")+ path = resolve_output_path(prompt, output_dir, filename, output_ext)first_image = data[0]b64_json = _field(first_image, "b64_json")image_url = _field(first_image, "url")