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

feat(image-gen): add --reference-image edit support for OpenAI backend

WodenJay6615584c7e68
diff --git a/skills/ppt-master/scripts/image_backends/backend_openai.py b/skills/ppt-master/scripts/image_backends/backend_openai.py
index e0616ad6..5f314a65 100644
--- a/skills/ppt-master/scripts/image_backends/backend_openai.py
+++ b/skills/ppt-master/scripts/image_backends/backend_openai.py
@@ -17,6 +17,11 @@ Configuration keys:
OPENAI_BACKGROUND (optional) auto or opaque for gpt-image-2
OPENAI_MODERATION (optional) auto or low for GPT image models
+Image editing (image-to-image):
+ When image_gen.py passes reference_image=<path> (single-image CLI only,
+ via --reference-image), this backend calls /v1/images/edits with the source
+ image + the prompt as an edit instruction, instead of /v1/images/generations.
+
Dependencies:
pip install requests Pillow
"""
@@ -38,6 +43,7 @@ if __name__ == "__main__":
raise SystemExit(0 if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]) else 1)
import base64
+import mimetypes
import os
import time
import threading
@@ -171,6 +177,10 @@ GPT_IMAGE_BACKGROUNDS = {"auto", "opaque", "transparent"}
GPT_IMAGE_MODERATION_VALUES = {"auto", "low"}
DEFAULT_BASE_URL = "https://api.openai.com/v1"
+# Signals to image_gen.py that this backend can accept a reference_image
+# (image-to-image edit via /v1/images/edits). Other backends omit this marker.
+SUPPORTS_REFERENCE_IMAGE = True
+
def _field(value, name: str):
"""Read a response field from either an SDK object or a dict."""
@@ -312,6 +322,16 @@ def _image_generations_url(base_url: str | None) -> str:
return f"{base}/images/generations"
+def _image_edits_url(base_url: str | None) -> str:
+ base = (base_url or DEFAULT_BASE_URL).rstrip("/")
+ if base.endswith("/images/edits"):
+ return base
+ if base.endswith("/images/generations"):
+ # Swap the sibling endpoint rather than appending to a full URL.
+ return base[: -len("/generations")] + "/edits"
+ return f"{base}/images/edits"
+
+
def _read_size_preset() -> str | None:
"""Read the optional size mapping preset for OpenAI-compatible providers."""
return _read_env_choice("OPENAI_SIZE_PRESET", OPENAI_SIZE_PRESETS)
@@ -363,6 +383,32 @@ def _post_image_generation(api_key: str, base_url: str | None, request: dict) ->
raise RuntimeError("OpenAI image generation returned invalid JSON.") from exc
+def _post_image_edit(api_key: str, base_url: str | None,
+ data: dict, image_path: str) -> dict:
+ headers = {"Authorization": f"Bearer {api_key}"}
+ # GPT Image models take the image list field 'image[]'; dall-e-2 and other
+ # OpenAI-compatible edit models use the singular 'image'.
+ model = str(data.get("model", ""))
+ field = "image[]" if _is_gpt_image_model(model) else "image"
+ mime_type = mimetypes.guess_type(image_path)[0] or "application/octet-stream"
+ # Let requests build the multipart/form-data body (and its Content-Type
+ # boundary) from files=; do not set Content-Type by hand.
+ with open(image_path, "rb") as image_file:
+ response = requests.post(
+ _image_edits_url(base_url),
+ headers=headers,
+ data=data,
+ files=[(field, (Path(image_path).name, image_file, mime_type))],
+ timeout=300,
+ )
+ if not response.ok:
+ raise http_error(response, "OpenAI image edit")
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise RuntimeError("OpenAI image edit returned invalid JSON.") from exc
+
+
# ╔══════════════════════════════════════════════════════════════════╗
# ║ Image Generation ║
# ╚══════════════════════════════════════════════════════════════════╝
@@ -465,6 +511,103 @@ def _generate_image(api_key: str, prompt: str,
raise RuntimeError("No image was generated. The server may have refused the request.")
+def _edit_image(api_key: str, prompt: str, reference_image: str,
+ 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-to-image edit via the OpenAI-compatible /v1/images/edits endpoint.
+
+ Sends the reference image plus the prompt (used as the edit instruction).
+ Mirrors _generate_image's size/quality/format handling but posts
+ multipart/form-data instead of JSON.
+
+ Returns:
+ Path of the saved image file
+ """
+ size_preset = _read_size_preset()
+ size = _select_size(model, aspect_ratio, image_size, size_preset)
+ quality = _read_quality(image_size)
+ output_ext = ".png"
+ request = {
+ "prompt": prompt,
+ "model": model,
+ "size": size,
+ "n": 1,
+ }
+ if quality is not None:
+ request["quality"] = quality
+ if _is_gpt_image_model(model):
+ gpt_options, output_ext = _gpt_image_options(model)
+ request.update(gpt_options)
+ _apply_response_format(request, model)
+
+ mode_label = f"Proxy: {base_url}" if base_url else "OpenAI API"
+ print(f"[OpenAI - {mode_label}]")
+ print(f" Mode: edit (image-to-image)")
+ print(f" Model: {model}")
+ print(f" Reference: {reference_image}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Size: {size} (from aspect_ratio={aspect_ratio})")
+ if size_preset and size_preset != "auto":
+ print(f" Size Preset: {size_preset}")
+ if quality is not None:
+ print(f" Quality: {quality} (from image_size={image_size})")
+ else:
+ print(" Quality: omitted")
+ if request.get("response_format"):
+ print(f" Response: {request['response_format']}")
+ elif _read_response_format() == "omit":
+ print(" Response: omitted")
+ 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()
+ print(f" [..] Editing...", end="", flush=True)
+
+ 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 = _post_image_edit(api_key, base_url, request, reference_image)
+ finally:
+ heartbeat_stop.set()
+ hb_thread.join(timeout=1)
+
+ elapsed = time.time() - start_time
+ print(f"\n [DONE] Image edited ({elapsed:.1f}s)")
+
+ data = _field(resp, "data") if resp is not None else None
+ if data:
+ 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")
+ if b64_json:
+ image_data = base64.b64decode(b64_json)
+ return save_image_bytes(image_data, path)
+ if image_url:
+ return download_image(image_url, path)
+
+ raise RuntimeError("No image was returned. The server may have refused the edit request.")
+
+
# ╔══════════════════════════════════════════════════════════════════╗
# ║ Public Entry Point ║
# ╚══════════════════════════════════════════════════════════════════╝
@@ -472,9 +615,10 @@ def _generate_image(api_key: str, prompt: str,
def generate(prompt: str,
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:
+ model: str = None, max_retries: int = MAX_RETRIES,
+ reference_image: str = None) -> str:
"""
- OpenAI-compatible image generation with automatic retry.
+ OpenAI-compatible image generation (or image-to-image edit) with retry.
Reads credentials from the current process environment or a `.env` file:
OPENAI_API_KEY
@@ -482,13 +626,16 @@ def generate(prompt: str,
OPENAI_MODEL (optional override)
Args:
- prompt: Prompt text
+ prompt: Prompt text (edit instruction when reference_image is set)
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-2)
max_retries: Maximum number of retries
+ reference_image: Optional source image path. When set, the request
+ goes to /v1/images/edits (image-to-image) instead of
+ /v1/images/generations.
Returns:
Path of the saved image file
@@ -516,6 +663,10 @@ def generate(prompt: str,
last_error = None
for attempt in range(max_retries + 1):
try:
+ if reference_image is not None:
+ return _edit_image(api_key, prompt, reference_image,
+ aspect_ratio, image_size, output_dir,
+ filename, model, base_url)
return _generate_image(api_key, prompt,
aspect_ratio, image_size, output_dir,
filename, model, base_url)
diff --git a/skills/ppt-master/scripts/image_gen.py b/skills/ppt-master/scripts/image_gen.py
index 1c26b716..3645cbf8 100644
--- a/skills/ppt-master/scripts/image_gen.py
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -39,6 +39,7 @@ Supported keys:
Usage:
python3 image_gen.py "prompt" --aspect_ratio 16:9 --image_size 1K -o images/
+ python3 image_gen.py "edit instruction" --reference-image src.png -o images/
python3 image_gen.py --manifest project/images/image_prompts.json -o project/images/
python3 image_gen.py --list-backends
"""
@@ -690,8 +691,11 @@ def main() -> None:
description="Generate images using AI image model providers."
)
parser.add_argument(
- "prompt", nargs="?", default="a beautiful landscape",
- help="The text prompt for image generation."
+ "prompt", nargs="?", default=None,
+ help=(
+ "The text prompt for image generation. With --reference-image, "
+ "this is the edit instruction (required in that mode)."
+ )
)
parser.add_argument(
"--aspect_ratio", default="1:1", choices=ALL_ASPECT_RATIOS,
@@ -743,9 +747,42 @@ def main() -> None:
"next to the manifest, then exit. No backend / network needed."
),
)
+ parser.add_argument(
+ "--reference-image", dest="reference_image", default=None, metavar="PATH",
+ help=(
+ "Source image for image-to-image editing (single-image mode only). "
+ "When set, the prompt is used as the edit instruction. Only backends "
+ "that support editing accept this (currently: openai). Not valid with "
+ "--manifest / --render-md / --list-backends."
+ ),
+ )
args = parser.parse_args()
+ if args.reference_image is not None:
+ # Reference editing is a single-image-only enhancement; keep it out of
+ # the manifest / sidecar / list surfaces entirely.
+ conflicting = [
+ name for name, val in (
+ ("--manifest", args.manifest),
+ ("--render-md", args.render_md),
+ ("--list-backends", args.list_backends),
+ ) if val
+ ]
+ if conflicting:
+ parser.error(
+ "--reference-image is single-image mode only and cannot be "
+ f"combined with {', '.join(conflicting)}."
+ )
+ if not args.prompt or not args.prompt.strip():
+ parser.error(
+ "--reference-image requires a prompt to use as the edit instruction."
+ )
+ if not os.path.isfile(args.reference_image):
+ parser.error(
+ f"--reference-image file not found: {args.reference_image}"
+ )
+
if args.list_backends:
_print_backend_list()
return
@@ -806,15 +843,30 @@ def main() -> None:
print(f"Rendered Markdown sidecar: {md_path}")
sys.exit(1 if failed else 0)
+ # Single-image mode. Backfill the historical default prompt only here, so
+ # plain generation is byte-for-byte unchanged while edit mode still requires
+ # an explicit instruction (enforced above).
+ prompt = args.prompt if args.prompt is not None else "a beautiful landscape"
+
+ gen_kwargs = {
+ "prompt": prompt,
+ "aspect_ratio": args.aspect_ratio,
+ "image_size": args.image_size,
+ "output_dir": args.output,
+ "filename": args.filename,
+ "model": args.model,
+ }
+ if args.reference_image is not None:
+ if not getattr(backend, "SUPPORTS_REFERENCE_IMAGE", False):
+ print(
+ f"Error: backend '{backend_name}' does not support image editing "
+ "(--reference-image). Use a backend that does (currently: openai)."
+ )
+ sys.exit(1)
+ gen_kwargs["reference_image"] = args.reference_image
+
try:
- backend.generate(
- prompt=args.prompt,
- aspect_ratio=args.aspect_ratio,
- image_size=args.image_size,
- output_dir=args.output,
- filename=args.filename,
- model=args.model,
- )
+ backend.generate(**gen_kwargs)
except (ValueError, FileNotFoundError) as e:
print(f"Error: {e}")
sys.exit(1)