| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Ideogram image generation backend. |
| 4 | |
| 5 | Configuration keys: |
| 6 | IDEOGRAM_API_KEY (required) |
| 7 | IDEOGRAM_BASE_URL (optional) |
| 8 | IDEOGRAM_MODEL (optional) |
| 9 | """ |
| 10 | |
| 11 | import sys |
| 12 | from pathlib import Path |
| 13 | |
| 14 | _SCRIPTS_DIR = Path(__file__).resolve().parents[1] |
| 15 | if str(_SCRIPTS_DIR) not in sys.path: |
| 16 | sys.path.insert(0, str(_SCRIPTS_DIR)) |
| 17 | |
| 18 | from console_encoding import configure_utf8_stdio # noqa: E402 |
| 19 | |
| 20 | configure_utf8_stdio() |
| 21 | |
| 22 | if __name__ == "__main__": |
| 23 | print(__doc__) |
| 24 | print("Use via: python3 skills/ppt-master/scripts/image_gen.py \"prompt\" --backend ideogram") |
| 25 | raise SystemExit(0 if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]) else 1) |
| 26 | |
| 27 | import os |
| 28 | import time |
| 29 | |
| 30 | import requests |
| 31 | |
| 32 | from image_backends.backend_common import ( |
| 33 | MAX_RETRIES, |
| 34 | download_image, |
| 35 | http_error, |
| 36 | is_permanent_error, |
| 37 | is_rate_limit_error, |
| 38 | normalize_image_size, |
| 39 | require_api_key, |
| 40 | resolve_output_path, |
| 41 | retry_delay, |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | ASPECT_RATIO_MAP = { |
| 46 | "1:1": "1x1", |
| 47 | "1:2": "1x2", |
| 48 | "1:3": "1x3", |
| 49 | "2:1": "2x1", |
| 50 | "2:3": "2x3", |
| 51 | "3:1": "3x1", |
| 52 | "3:2": "3x2", |
| 53 | "3:4": "3x4", |
| 54 | "4:3": "4x3", |
| 55 | "4:5": "4x5", |
| 56 | "5:4": "5x4", |
| 57 | "9:16": "9x16", |
| 58 | "10:16": "10x16", |
| 59 | "16:9": "16x9", |
| 60 | "16:10": "16x10", |
| 61 | } |
| 62 | |
| 63 | DEFAULT_BASE_URL = "https://api.ideogram.ai" |
| 64 | DEFAULT_MODEL = "ideogram-v3" |
| 65 | MODEL_ALIASES = {"ideogram-v3", "v3"} |
| 66 | |
| 67 | DEFAULT_RENDERING_SPEED = "DEFAULT" |
| 68 | |
| 69 | |
| 70 | def _resolve_request_options( |
| 71 | aspect_ratio: str, |
| 72 | image_size: str, |
| 73 | model: str, |
| 74 | ) -> tuple[str, str]: |
| 75 | """Validate request options and return normalized model and ratio values.""" |
| 76 | normalized_model = model.strip().lower() |
| 77 | if normalized_model not in MODEL_ALIASES: |
| 78 | raise ValueError( |
| 79 | f"Unsupported Ideogram model '{model}'. Supported: {sorted(MODEL_ALIASES)}" |
| 80 | ) |
| 81 | mapped_ratio = ASPECT_RATIO_MAP.get(aspect_ratio) |
| 82 | if not mapped_ratio: |
| 83 | raise ValueError( |
| 84 | f"Unsupported aspect ratio '{aspect_ratio}' for Ideogram backend. " |
| 85 | f"Supported: {sorted(ASPECT_RATIO_MAP)}" |
| 86 | ) |
| 87 | normalized_size = normalize_image_size(image_size) |
| 88 | if normalized_size != "1K": |
| 89 | raise ValueError( |
| 90 | "Ideogram V3 aspect-ratio generation only supports the default '1K' preset; " |
| 91 | f"got '{image_size}'." |
| 92 | ) |
| 93 | return normalized_model, mapped_ratio |
| 94 | |
| 95 | |
| 96 | def _resolve_url(base_url: str) -> str: |
| 97 | """Resolve the Ideogram generation endpoint.""" |
| 98 | base = base_url.rstrip("/") |
| 99 | if base.endswith("/generate"): |
| 100 | return base |
| 101 | return base + "/v1/ideogram-v3/generate" |
| 102 | |
| 103 | |
| 104 | def _generate_image(api_key: str, prompt: str, |
| 105 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 106 | output_dir: str = None, filename: str = None, |
| 107 | model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str: |
| 108 | """Generate one image with the Ideogram backend.""" |
| 109 | normalized_model, mapped_ratio = _resolve_request_options( |
| 110 | aspect_ratio, |
| 111 | image_size, |
| 112 | model, |
| 113 | ) |
| 114 | |
| 115 | url = _resolve_url(base_url) |
| 116 | headers = {"Api-Key": api_key} |
| 117 | files = { |
| 118 | "prompt": (None, prompt), |
| 119 | "aspect_ratio": (None, mapped_ratio), |
| 120 | "rendering_speed": (None, DEFAULT_RENDERING_SPEED), |
| 121 | } |
| 122 | |
| 123 | print("[Ideogram]") |
| 124 | print(f" Model: {normalized_model}") |
| 125 | print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}") |
| 126 | print(f" Aspect Ratio: {aspect_ratio} -> {mapped_ratio}") |
| 127 | print(f" Render Speed: {DEFAULT_RENDERING_SPEED}") |
| 128 | print() |
| 129 | print(" [..] Generating...", end="", flush=True) |
| 130 | start = time.time() |
| 131 | response = requests.post(url, headers=headers, files=files, timeout=300) |
| 132 | elapsed = time.time() - start |
| 133 | print(f"\n [DONE] Response received ({elapsed:.1f}s)") |
| 134 | |
| 135 | if response.status_code != 200: |
| 136 | raise http_error(response, "Ideogram generation") |
| 137 | |
| 138 | payload = response.json() |
| 139 | data = payload.get("data") or [] |
| 140 | image_url = data[0].get("url") if data else None |
| 141 | if not image_url: |
| 142 | raise RuntimeError(f"Ideogram response missing image URL: {payload}") |
| 143 | |
| 144 | path = resolve_output_path(prompt, output_dir, filename, ".png") |
| 145 | return download_image(image_url, path) |
| 146 | |
| 147 | |
| 148 | def generate(prompt: str, |
| 149 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 150 | output_dir: str = None, filename: str = None, |
| 151 | model: str = None, max_retries: int = MAX_RETRIES) -> str: |
| 152 | """Generate an image with retries using the Ideogram backend.""" |
| 153 | resolved_model = model or os.environ.get("IDEOGRAM_MODEL") or DEFAULT_MODEL |
| 154 | _resolve_request_options(aspect_ratio, image_size, resolved_model) |
| 155 | api_key = require_api_key( |
| 156 | "IDEOGRAM_API_KEY", |
| 157 | message="No API key found. Set IDEOGRAM_API_KEY in the current environment or a .env file.", |
| 158 | ) |
| 159 | base_url = os.environ.get("IDEOGRAM_BASE_URL") or DEFAULT_BASE_URL |
| 160 | |
| 161 | last_error = None |
| 162 | for attempt in range(max_retries + 1): |
| 163 | try: |
| 164 | return _generate_image( |
| 165 | api_key=api_key, |
| 166 | prompt=prompt, |
| 167 | aspect_ratio=aspect_ratio, |
| 168 | image_size=image_size, |
| 169 | output_dir=output_dir, |
| 170 | filename=filename, |
| 171 | model=resolved_model, |
| 172 | base_url=base_url, |
| 173 | ) |
| 174 | except Exception as exc: |
| 175 | last_error = exc |
| 176 | if is_permanent_error(exc): |
| 177 | raise |
| 178 | if attempt >= max_retries: |
| 179 | break |
| 180 | limited = is_rate_limit_error(exc) |
| 181 | delay = retry_delay(attempt, rate_limited=limited) |
| 182 | label = "Rate limit hit" if limited else f"Error: {exc}" |
| 183 | print(f"\n [WARN] {label}. Retrying in {delay}s...") |
| 184 | time.sleep(delay) |
| 185 | |
| 186 | raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}") |
| 187 |