| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | SiliconFlow image generation backend. |
| 4 | |
| 5 | Configuration keys: |
| 6 | SILICONFLOW_API_KEY (required) |
| 7 | SILICONFLOW_BASE_URL (optional) |
| 8 | SILICONFLOW_MODEL (optional; Qwen/Qwen-Image 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 siliconflow") |
| 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 | DEFAULT_ENDPOINT = "https://api.siliconflow.cn/v1/images/generations" |
| 46 | DEFAULT_MODEL = "Qwen/Qwen-Image" |
| 47 | SUPPORTED_MODELS = {DEFAULT_MODEL} |
| 48 | |
| 49 | ASPECT_RATIO_SIZE_MAP = { |
| 50 | "1K": { |
| 51 | "1:1": "1328x1328", |
| 52 | "2:3": "1056x1584", |
| 53 | "3:2": "1584x1056", |
| 54 | "3:4": "1140x1472", |
| 55 | "4:3": "1472x1140", |
| 56 | "9:16": "928x1664", |
| 57 | "16:9": "1664x928", |
| 58 | }, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | def _validate_model(model: str) -> str: |
| 63 | """Limit the backend to the Qwen-Image contract implemented below.""" |
| 64 | resolved = model.strip() |
| 65 | if resolved not in SUPPORTED_MODELS: |
| 66 | raise ValueError( |
| 67 | f"Unsupported SiliconFlow model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}" |
| 68 | ) |
| 69 | return resolved |
| 70 | |
| 71 | |
| 72 | def _resolve_url(base_url: str) -> str: |
| 73 | """Resolve the SiliconFlow generation endpoint.""" |
| 74 | base = base_url.rstrip("/") |
| 75 | if base.endswith("/images/generations"): |
| 76 | return base |
| 77 | return base + "/v1/images/generations" |
| 78 | |
| 79 | |
| 80 | def _resolve_size(aspect_ratio: str, image_size: str) -> str: |
| 81 | """Resolve the target resolution for a ratio and logical size preset.""" |
| 82 | normalized = normalize_image_size(image_size) |
| 83 | sizes = ASPECT_RATIO_SIZE_MAP.get(normalized) |
| 84 | if sizes is None: |
| 85 | supported_sizes = ", ".join(ASPECT_RATIO_SIZE_MAP) |
| 86 | raise ValueError( |
| 87 | f"Unsupported image size '{image_size}' for SiliconFlow backend. " |
| 88 | f"Qwen/Qwen-Image supports these logical sizes: {supported_sizes}." |
| 89 | ) |
| 90 | size = sizes.get(aspect_ratio) |
| 91 | if not size: |
| 92 | supported = sorted(sizes) |
| 93 | raise ValueError( |
| 94 | f"Unsupported aspect ratio '{aspect_ratio}' for SiliconFlow backend. " |
| 95 | f"Supported: {supported}" |
| 96 | ) |
| 97 | return size |
| 98 | |
| 99 | |
| 100 | def _generate_image(api_key: str, prompt: str, |
| 101 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 102 | output_dir: str = None, filename: str = None, |
| 103 | model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str: |
| 104 | """Generate one image with the SiliconFlow backend.""" |
| 105 | model = _validate_model(model) |
| 106 | size = _resolve_size(aspect_ratio, image_size) |
| 107 | url = _resolve_url(base_url) |
| 108 | headers = { |
| 109 | "Authorization": f"Bearer {api_key}", |
| 110 | "Content-Type": "application/json", |
| 111 | } |
| 112 | payload = { |
| 113 | "model": model, |
| 114 | "prompt": prompt, |
| 115 | "image_size": size, |
| 116 | } |
| 117 | |
| 118 | print("[SiliconFlow]") |
| 119 | print(f" Model: {model}") |
| 120 | print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}") |
| 121 | print(f" Aspect Ratio: {aspect_ratio}") |
| 122 | print(f" Resolution: {size}") |
| 123 | print() |
| 124 | print(" [..] Generating...", end="", flush=True) |
| 125 | start = time.time() |
| 126 | response = requests.post(url, headers=headers, json=payload, timeout=300) |
| 127 | elapsed = time.time() - start |
| 128 | print(f"\n [DONE] Response received ({elapsed:.1f}s)") |
| 129 | |
| 130 | if response.status_code != 200: |
| 131 | raise http_error(response, "SiliconFlow image generation") |
| 132 | |
| 133 | data = response.json() |
| 134 | images = data.get("images") or [] |
| 135 | image_url = images[0].get("url") if images else None |
| 136 | if not image_url: |
| 137 | raise RuntimeError(f"SiliconFlow response missing image URL: {data}") |
| 138 | |
| 139 | path = resolve_output_path(prompt, output_dir, filename, ".png") |
| 140 | return download_image(image_url, path) |
| 141 | |
| 142 | |
| 143 | def generate(prompt: str, |
| 144 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 145 | output_dir: str = None, filename: str = None, |
| 146 | model: str = None, max_retries: int = MAX_RETRIES) -> str: |
| 147 | """Generate an image with retries using the SiliconFlow backend.""" |
| 148 | resolved_model = model or os.environ.get("SILICONFLOW_MODEL") or DEFAULT_MODEL |
| 149 | _validate_model(resolved_model) |
| 150 | normalized_size = normalize_image_size(image_size) |
| 151 | _resolve_size(aspect_ratio, normalized_size) |
| 152 | api_key = require_api_key( |
| 153 | "SILICONFLOW_API_KEY", |
| 154 | message="No API key found. Set SILICONFLOW_API_KEY in the current environment or a .env file.", |
| 155 | ) |
| 156 | base_url = os.environ.get("SILICONFLOW_BASE_URL") or DEFAULT_ENDPOINT |
| 157 | |
| 158 | last_error = None |
| 159 | for attempt in range(max_retries + 1): |
| 160 | try: |
| 161 | return _generate_image( |
| 162 | api_key=api_key, |
| 163 | prompt=prompt, |
| 164 | aspect_ratio=aspect_ratio, |
| 165 | image_size=normalized_size, |
| 166 | output_dir=output_dir, |
| 167 | filename=filename, |
| 168 | model=resolved_model, |
| 169 | base_url=base_url, |
| 170 | ) |
| 171 | except Exception as exc: |
| 172 | last_error = exc |
| 173 | if is_permanent_error(exc): |
| 174 | raise |
| 175 | if attempt >= max_retries: |
| 176 | break |
| 177 | limited = is_rate_limit_error(exc) |
| 178 | delay = retry_delay(attempt, rate_limited=limited) |
| 179 | label = "Rate limit hit" if limited else f"Error: {exc}" |
| 180 | print(f"\n [WARN] {label}. Retrying in {delay}s...") |
| 181 | time.sleep(delay) |
| 182 | |
| 183 | raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}") |
| 184 |