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