|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# /// script |
| 3 | +# requires-python = ">=3.10" |
| 4 | +# dependencies = [ |
| 5 | +# "openai", |
| 6 | +# ] |
| 7 | +# /// |
| 8 | +""" |
| 9 | +Generate or edit images via OpenRouter using openai-python. |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import base64 |
| 14 | +import mimetypes |
| 15 | +import os |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +from openai import OpenAI |
| 19 | + |
| 20 | + |
| 21 | +# Configuration |
| 22 | +MAX_INPUT_IMAGES = 3 |
| 23 | +MIME_TO_EXT = { |
| 24 | + "image/png": ".png", |
| 25 | + "image/jpeg": ".jpg", |
| 26 | + "image/jpg": ".jpg", |
| 27 | + "image/webp": ".webp", |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +def parse_args(): |
| 32 | + parser = argparse.ArgumentParser(description="Generate or edit images via OpenRouter.") |
| 33 | + parser.add_argument("--prompt", required=True, help="Prompt describing the desired image.") |
| 34 | + parser.add_argument("--filename", required=True, help="Output filename (relative to CWD).") |
| 35 | + parser.add_argument( |
| 36 | + "--resolution", |
| 37 | + type=str.upper, |
| 38 | + choices=["1K", "2K", "4K"], |
| 39 | + default="1K", |
| 40 | + help="Output resolution: 1K, 2K, or 4K.", |
| 41 | + ) |
| 42 | + parser.add_argument( |
| 43 | + "--input-image", |
| 44 | + action="append", |
| 45 | + default=[], |
| 46 | + help=f"Optional input image path (repeatable, max {MAX_INPUT_IMAGES}).", |
| 47 | + ) |
| 48 | + return parser.parse_args() |
| 49 | + |
| 50 | + |
| 51 | +def require_api_key(): |
| 52 | + api_key = os.environ.get("OPENROUTER_API_KEY") |
| 53 | + if not api_key: |
| 54 | + raise SystemExit("OPENROUTER_API_KEY is not set in the environment.") |
| 55 | + return api_key |
| 56 | + |
| 57 | + |
| 58 | +def encode_image_to_data_url(path: Path) -> str: |
| 59 | + if not path.exists(): |
| 60 | + raise SystemExit(f"Input image not found: {path}") |
| 61 | + mime, _ = mimetypes.guess_type(str(path)) |
| 62 | + if not mime: |
| 63 | + mime = "image/png" |
| 64 | + data = path.read_bytes() |
| 65 | + encoded = base64.b64encode(data).decode("utf-8") |
| 66 | + return f"data:{mime};base64,{encoded}" |
| 67 | + |
| 68 | + |
| 69 | +def build_message_content(prompt: str, input_images: list[str]) -> list[dict]: |
| 70 | + content: list[dict] = [{"type": "text", "text": prompt}] |
| 71 | + for image_path in input_images: |
| 72 | + data_url = encode_image_to_data_url(Path(image_path)) |
| 73 | + content.append({"type": "image_url", "image_url": {"url": data_url}}) |
| 74 | + return content |
| 75 | + |
| 76 | + |
| 77 | +def parse_data_url(data_url: str) -> tuple[str, bytes]: |
| 78 | + if not data_url.startswith("data:") or ";base64," not in data_url: |
| 79 | + raise SystemExit("Image URL is not a base64 data URL.") |
| 80 | + header, encoded = data_url.split(",", 1) |
| 81 | + mime = header[5:].split(";", 1)[0] |
| 82 | + try: |
| 83 | + raw = base64.b64decode(encoded) |
| 84 | + except Exception as e: |
| 85 | + raise SystemExit(f"Failed to decode base64 image payload: {e}") |
| 86 | + return mime, raw |
| 87 | + |
| 88 | + |
| 89 | +def resolve_output_path(filename: str, image_index: int, total_count: int, mime: str) -> Path: |
| 90 | + output_path = Path(filename) |
| 91 | + suffix = output_path.suffix |
| 92 | + |
| 93 | + # Validate/correct suffix matches MIME type |
| 94 | + expected_suffix = MIME_TO_EXT.get(mime, ".png") |
| 95 | + if suffix and suffix.lower() != expected_suffix.lower(): |
| 96 | + print(f"Warning: filename extension '{suffix}' doesn't match returned MIME type '{mime}'. Using '{expected_suffix}' instead.") |
| 97 | + suffix = expected_suffix |
| 98 | + elif not suffix: |
| 99 | + suffix = expected_suffix |
| 100 | + |
| 101 | + # Single image: use original stem + corrected suffix |
| 102 | + if total_count <= 1: |
| 103 | + return output_path.with_suffix(suffix) |
| 104 | + |
| 105 | + # Multiple images: append numbering |
| 106 | + return output_path.with_name(f"{output_path.stem}-{image_index + 1}{suffix}") |
| 107 | + |
| 108 | + |
| 109 | +def extract_image_url(image: dict | object) -> str | None: |
| 110 | + if isinstance(image, dict): |
| 111 | + return image.get("image_url", {}).get("url") or image.get("url") |
| 112 | + return None |
| 113 | + |
| 114 | + |
| 115 | +def load_system_prompt(): |
| 116 | + """Load system prompt from assets/SYSTEM_TEMPLATE if it exists and is not empty.""" |
| 117 | + script_dir = Path(__file__).parent.parent |
| 118 | + template_path = script_dir / "assets" / "SYSTEM_TEMPLATE" |
| 119 | + |
| 120 | + if template_path.exists(): |
| 121 | + content = template_path.read_text(encoding="utf-8").strip() |
| 122 | + if content: |
| 123 | + return content |
| 124 | + return None |
| 125 | + |
| 126 | + |
| 127 | +def main(): |
| 128 | + args = parse_args() |
| 129 | + |
| 130 | + if len(args.input_image) > MAX_INPUT_IMAGES: |
| 131 | + raise SystemExit(f"Too many input images: {len(args.input_image)} (max {MAX_INPUT_IMAGES}).") |
| 132 | + |
| 133 | + image_size = args.resolution |
| 134 | + |
| 135 | + client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=require_api_key()) |
| 136 | + |
| 137 | + # Build messages with optional system prompt |
| 138 | + messages = [] |
| 139 | + |
| 140 | + system_prompt = load_system_prompt() |
| 141 | + if system_prompt: |
| 142 | + messages.append({ |
| 143 | + "role": "system", |
| 144 | + "content": system_prompt, |
| 145 | + }) |
| 146 | + |
| 147 | + messages.append({ |
| 148 | + "role": "user", |
| 149 | + "content": build_message_content(args.prompt, args.input_image), |
| 150 | + }) |
| 151 | + |
| 152 | + response = client.chat.completions.create( |
| 153 | + model="google/gemini-3-pro-image-preview", |
| 154 | + messages=messages, |
| 155 | + extra_body={ |
| 156 | + "modalities": ["image", "text"], |
| 157 | + # https://openrouter.ai/docs/guides/overview/multimodal/image-generation#image-configuration-options |
| 158 | + "image_config": { |
| 159 | + # "aspect_ratio": "16:9", |
| 160 | + "image_size": image_size, |
| 161 | + } |
| 162 | + }, |
| 163 | + ) |
| 164 | + |
| 165 | + message = response.choices[0].message |
| 166 | + images = getattr(message, "images", None) |
| 167 | + if not images: |
| 168 | + raise SystemExit("No images returned by the API.") |
| 169 | + |
| 170 | + # Create output directory once before processing images |
| 171 | + output_base_path = Path(args.filename) |
| 172 | + if output_base_path.parent and str(output_base_path.parent) != '.': |
| 173 | + output_base_path.parent.mkdir(parents=True, exist_ok=True) |
| 174 | + |
| 175 | + saved_paths = [] |
| 176 | + for idx, image in enumerate(images): |
| 177 | + image_url = extract_image_url(image) |
| 178 | + if not image_url: |
| 179 | + raise SystemExit("Image payload missing image_url.url.") |
| 180 | + mime, raw = parse_data_url(image_url) |
| 181 | + output_path = resolve_output_path(args.filename, idx, len(images), mime) |
| 182 | + output_path.write_bytes(raw) |
| 183 | + saved_paths.append(output_path.resolve()) |
| 184 | + |
| 185 | + for path in saved_paths: |
| 186 | + print(f"Saved image to: {path}") |
| 187 | + print(f"MEDIA: {path}") |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + main() |
0 commit comments