| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Replicate image generation backend. |
| 4 | |
| 5 | Configuration keys: |
| 6 | REPLICATE_API_KEY / REPLICATE_API_TOKEN (required) |
| 7 | REPLICATE_BASE_URL (optional) |
| 8 | REPLICATE_MODEL (optional; FLUX 1.1 Pro only) |
| 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 replicate") |
| 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 | poll_json, |
| 40 | require_api_key, |
| 41 | resolve_output_path, |
| 42 | retry_delay, |
| 43 | ) |
| 44 | |
| 45 | |
| 46 | VALID_ASPECT_RATIOS = ["1:1", "16:9", "9:16", "3:4", "4:3", "3:2", "2:3", "4:5", "5:4", "21:9"] |
| 47 | DEFAULT_BASE_URL = "https://api.replicate.com/v1" |
| 48 | DEFAULT_MODEL = "black-forest-labs/flux-1.1-pro" |
| 49 | SUPPORTED_MODELS = {DEFAULT_MODEL} |
| 50 | |
| 51 | |
| 52 | def _split_model(model: str) -> tuple[str, str]: |
| 53 | """Split a Replicate model reference into owner and name.""" |
| 54 | parts = [part for part in model.strip().split("/") if part] |
| 55 | if len(parts) != 2: |
| 56 | raise ValueError( |
| 57 | f"Replicate model must be in 'owner/name' format, got '{model}'." |
| 58 | ) |
| 59 | return parts[0], parts[1] |
| 60 | |
| 61 | |
| 62 | def _resolve_request_options( |
| 63 | aspect_ratio: str, |
| 64 | image_size: str, |
| 65 | model: str, |
| 66 | ) -> tuple[str, str]: |
| 67 | """Validate request options and return the Replicate model path.""" |
| 68 | resolved_model = model.strip() |
| 69 | if resolved_model not in SUPPORTED_MODELS: |
| 70 | raise ValueError( |
| 71 | f"Unsupported Replicate model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}" |
| 72 | ) |
| 73 | if aspect_ratio not in VALID_ASPECT_RATIOS: |
| 74 | raise ValueError( |
| 75 | f"Unsupported aspect ratio '{aspect_ratio}' for Replicate backend. " |
| 76 | f"Supported: {VALID_ASPECT_RATIOS}" |
| 77 | ) |
| 78 | normalized_size = normalize_image_size(image_size) |
| 79 | if normalized_size != "1K": |
| 80 | raise ValueError( |
| 81 | "Replicate FLUX 1.1 Pro does not expose the unified image_size preset; " |
| 82 | f"only the default '1K' is supported, got '{image_size}'." |
| 83 | ) |
| 84 | return _split_model(resolved_model) |
| 85 | |
| 86 | |
| 87 | def _extract_output_url(payload: dict) -> str | None: |
| 88 | """Extract an output URL from a Replicate prediction payload.""" |
| 89 | output = payload.get("output") |
| 90 | if isinstance(output, str): |
| 91 | return output |
| 92 | if isinstance(output, list) and output: |
| 93 | first = output[0] |
| 94 | if isinstance(first, str): |
| 95 | return first |
| 96 | if isinstance(first, dict): |
| 97 | return first.get("url") |
| 98 | if isinstance(output, dict): |
| 99 | return output.get("url") |
| 100 | return None |
| 101 | |
| 102 | |
| 103 | def _generate_image(api_key: str, prompt: str, |
| 104 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 105 | output_dir: str = None, filename: str = None, |
| 106 | model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str: |
| 107 | """Generate one image with the Replicate backend.""" |
| 108 | owner, name = _resolve_request_options(aspect_ratio, image_size, model) |
| 109 | url = f"{base_url.rstrip('/')}/models/{owner}/{name}/predictions" |
| 110 | headers = { |
| 111 | "Authorization": f"Bearer {api_key}", |
| 112 | "Content-Type": "application/json", |
| 113 | "Prefer": "wait=60", |
| 114 | } |
| 115 | |
| 116 | payload = { |
| 117 | "input": { |
| 118 | "prompt": prompt, |
| 119 | "aspect_ratio": aspect_ratio, |
| 120 | "output_format": "png", |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | print("[Replicate]") |
| 125 | print(f" Model: {model}") |
| 126 | print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}") |
| 127 | print(f" Aspect Ratio: {aspect_ratio}") |
| 128 | print() |
| 129 | print(" [..] Generating...", end="", flush=True) |
| 130 | start = time.time() |
| 131 | response = requests.post(url, headers=headers, json=payload, timeout=180) |
| 132 | elapsed = time.time() - start |
| 133 | print(f"\n [DONE] Initial response received ({elapsed:.1f}s)") |
| 134 | |
| 135 | if response.status_code not in (200, 201): |
| 136 | raise http_error(response, "Replicate generation request") |
| 137 | |
| 138 | data = response.json() |
| 139 | status = str(data.get("status", "")).lower() |
| 140 | if status != "succeeded": |
| 141 | poll_url = ((data.get("urls") or {}).get("get")) |
| 142 | if not poll_url: |
| 143 | prediction_id = data.get("id") |
| 144 | if prediction_id: |
| 145 | poll_url = f"{base_url.rstrip('/')}/predictions/{prediction_id}" |
| 146 | if not poll_url: |
| 147 | raise RuntimeError(f"Replicate response missing poll URL: {data}") |
| 148 | |
| 149 | print(" [..] Polling result...") |
| 150 | data = poll_json( |
| 151 | poll_url, |
| 152 | {"Authorization": f"Bearer {api_key}"}, |
| 153 | status_label="status", |
| 154 | ready_values=["succeeded"], |
| 155 | failed_values=["failed", "canceled"], |
| 156 | ) |
| 157 | |
| 158 | image_url = _extract_output_url(data) |
| 159 | if not image_url: |
| 160 | raise RuntimeError(f"Replicate response missing output URL: {data}") |
| 161 | |
| 162 | path = resolve_output_path(prompt, output_dir, filename, ".png") |
| 163 | return download_image(image_url, path) |
| 164 | |
| 165 | |
| 166 | def generate(prompt: str, |
| 167 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 168 | output_dir: str = None, filename: str = None, |
| 169 | model: str = None, max_retries: int = MAX_RETRIES) -> str: |
| 170 | """Generate an image with retries using the Replicate backend.""" |
| 171 | resolved_model = model or os.environ.get("REPLICATE_MODEL") or DEFAULT_MODEL |
| 172 | _resolve_request_options(aspect_ratio, image_size, resolved_model) |
| 173 | api_key = require_api_key( |
| 174 | "REPLICATE_API_KEY", |
| 175 | "REPLICATE_API_TOKEN", |
| 176 | message="No API key found. Set REPLICATE_API_KEY or REPLICATE_API_TOKEN in the current environment or a .env file.", |
| 177 | ) |
| 178 | base_url = os.environ.get("REPLICATE_BASE_URL") or DEFAULT_BASE_URL |
| 179 | |
| 180 | last_error = None |
| 181 | for attempt in range(max_retries + 1): |
| 182 | try: |
| 183 | return _generate_image( |
| 184 | api_key=api_key, |
| 185 | prompt=prompt, |
| 186 | aspect_ratio=aspect_ratio, |
| 187 | image_size=image_size, |
| 188 | output_dir=output_dir, |
| 189 | filename=filename, |
| 190 | model=resolved_model, |
| 191 | base_url=base_url, |
| 192 | ) |
| 193 | except Exception as exc: |
| 194 | last_error = exc |
| 195 | if is_permanent_error(exc): |
| 196 | raise |
| 197 | if attempt >= max_retries: |
| 198 | break |
| 199 | limited = is_rate_limit_error(exc) |
| 200 | delay = retry_delay(attempt, rate_limited=limited) |
| 201 | label = "Rate limit hit" if limited else f"Error: {exc}" |
| 202 | print(f"\n [WARN] {label}. Retrying in {delay}s...") |
| 203 | time.sleep(delay) |
| 204 | |
| 205 | raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}") |
| 206 |