返回 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 LAS_API_KEY / VOLCENGINE_API_KEY / ARK_API_KEY (required)
7 VOLCENGINE_BASE_URL (optional)
8 VOLCENGINE_MODEL (optional; Seedream 4.5 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 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_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://operator.las.cn-beijing.volces.com/api/v1/images/generations"
46 DEFAULT_MODEL = "doubao-seedream-4-5-251128"
47 DEFAULT_IMAGE_SIZE = "2K"
48 SUPPORTED_MODELS = {DEFAULT_MODEL}
49
50 ASPECT_RATIO_SIZE_MAP = {
51 "2K": {
52 "1:1": "2048x2048",
53 "2:3": "1664x2496",
54 "3:2": "2496x1664",
55 "3:4": "1728x2304",
56 "4:3": "2304x1728",
57 "9:16": "1600x2848",
58 "16:9": "2848x1600",
59 "21:9": "3136x1344",
60 },
61 "4K": {
62 "1:1": "4096x4096",
63 "2:3": "3328x4992",
64 "3:2": "4992x3328",
65 "3:4": "3520x4704",
66 "4:3": "4704x3520",
67 "9:16": "3040x5504",
68 "16:9": "5504x3040",
69 "21:9": "6240x2656",
70 },
71 }
72
73
74 def _validate_model(model: str) -> str:
75 """Limit the backend to the Seedream 4.5 contract implemented below."""
76 resolved = model.strip()
77 if resolved not in SUPPORTED_MODELS:
78 raise ValueError(
79 f"Unsupported Volcengine model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}"
80 )
81 return resolved
82
83
84 def _resolve_url(base_url: str) -> str:
85 """Resolve the Volcengine generation endpoint."""
86 base = base_url.rstrip("/")
87 if base.endswith("/images/generations"):
88 return base
89 if base.endswith("/api/v1"):
90 return base + "/images/generations"
91 return base + "/api/v1/images/generations"
92
93
94 def _resolve_size(aspect_ratio: str, image_size: str) -> str:
95 """Resolve the target resolution for a ratio and logical size preset."""
96 normalized = normalize_image_size(image_size)
97 sizes = ASPECT_RATIO_SIZE_MAP.get(normalized)
98 if sizes is None:
99 supported_sizes = ", ".join(ASPECT_RATIO_SIZE_MAP)
100 raise ValueError(
101 f"Unsupported image size '{image_size}' for Volcengine backend. "
102 f"Seedream 4.5 supports these sizes: {supported_sizes}."
103 )
104 size = sizes.get(aspect_ratio)
105 if not size:
106 supported = sorted(sizes)
107 raise ValueError(
108 f"Unsupported aspect ratio '{aspect_ratio}' for Volcengine backend. "
109 f"Supported: {supported}"
110 )
111 return size
112
113
114 def _generate_image(api_key: str, prompt: str,
115 aspect_ratio: str = "1:1", image_size: str = DEFAULT_IMAGE_SIZE,
116 output_dir: str = None, filename: str = None,
117 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
118 """Generate one image with the Volcengine backend."""
119 model = _validate_model(model)
120 size = _resolve_size(aspect_ratio, image_size)
121 url = _resolve_url(base_url)
122 headers = {
123 "Authorization": f"Bearer {api_key}",
124 "Content-Type": "application/json",
125 }
126 payload = {
127 "model": model,
128 "prompt": prompt,
129 "size": size,
130 "response_format": "url",
131 "watermark": False,
132 }
133
134 print("[Volcengine Seedream]")
135 print(f" Model: {model}")
136 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
137 print(f" Aspect Ratio: {aspect_ratio}")
138 print(f" Resolution: {size}")
139 print()
140 print(" [..] Generating...", end="", flush=True)
141 start = time.time()
142 response = requests.post(url, headers=headers, json=payload, timeout=300)
143 elapsed = time.time() - start
144 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
145
146 if response.status_code != 200:
147 raise http_error(response, "Volcengine image generation")
148
149 data = response.json()
150 items = data.get("data") or []
151 image_url = items[0].get("url") if items else None
152 if not image_url:
153 raise RuntimeError(f"Volcengine response missing image URL: {data}")
154
155 path = resolve_output_path(prompt, output_dir, filename, ".jpeg")
156 return download_image(image_url, path)
157
158
159 def generate(prompt: str,
160 aspect_ratio: str = "1:1", image_size: str = DEFAULT_IMAGE_SIZE,
161 output_dir: str = None, filename: str = None,
162 model: str = None, max_retries: int = MAX_RETRIES) -> str:
163 """Generate an image with retries using the Volcengine backend."""
164 resolved_model = model or os.environ.get("VOLCENGINE_MODEL") or DEFAULT_MODEL
165 _validate_model(resolved_model)
166 normalized_size = normalize_image_size(image_size)
167 _resolve_size(aspect_ratio, normalized_size)
168 api_key = require_api_key(
169 "LAS_API_KEY",
170 "VOLCENGINE_API_KEY",
171 "ARK_API_KEY",
172 message=(
173 "No API key found. Set LAS_API_KEY, VOLCENGINE_API_KEY, or "
174 "ARK_API_KEY in the current environment or a .env file."
175 ),
176 )
177 base_url = os.environ.get("VOLCENGINE_BASE_URL") or DEFAULT_ENDPOINT
178
179 last_error = None
180 for attempt in range(max_retries + 1):
181 try:
182 return _generate_image(
183 api_key=api_key,
184 prompt=prompt,
185 aspect_ratio=aspect_ratio,
186 image_size=normalized_size,
187 output_dir=output_dir,
188 filename=filename,
189 model=resolved_model,
190 base_url=base_url,
191 )
192 except Exception as exc:
193 last_error = exc
194 if is_permanent_error(exc):
195 raise
196 if attempt >= max_retries:
197 break
198 limited = is_rate_limit_error(exc)
199 delay = retry_delay(attempt, rate_limited=limited)
200 label = "Rate limit hit" if limited else f"Error: {exc}"
201 print(f"\n [WARN] {label}. Retrying in {delay}s...")
202 time.sleep(delay)
203
204 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
205
205 lines PYTHON