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