返回 ppt-master
backend_bfl.py
根目录 / skills / ppt-master / scripts / image_backends / backend_bfl.py
1 #!/usr/bin/env python3
2 """
3 Black Forest Labs FLUX image generation backend.
4
5 Configuration keys:
6 BFL_API_KEY (required)
7 BFL_BASE_URL (optional)
8 BFL_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 bfl")
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 = [
47 "1:1", "2:3", "3:2", "3:4", "4:3",
48 "4:5", "5:4", "9:16", "16:9", "21:9",
49 ]
50
51 DEFAULT_BASE_URL = "https://api.bfl.ai"
52 DEFAULT_MODEL = "flux-pro-1.1-ultra"
53
54 MODEL_ENDPOINTS = {
55 "flux-pro-1.1": "/v1/flux-pro-1.1",
56 "flux-pro-1.1-ultra": "/v1/flux-pro-1.1-ultra",
57 "flux-dev": "/v1/flux-dev",
58 }
59
60 ASPECT_RATIO_TO_DIMENSIONS = {
61 "1:1": (1024, 1024),
62 "2:3": (960, 1440),
63 "3:2": (1440, 960),
64 "3:4": (1056, 1408),
65 "4:3": (1408, 1056),
66 "4:5": (1024, 1280),
67 "5:4": (1280, 1024),
68 "9:16": (576, 1024),
69 "16:9": (1024, 576),
70 "21:9": (1344, 576),
71 }
72
73
74 def _resolve_request_options(
75 aspect_ratio: str,
76 image_size: str,
77 model: str,
78 ) -> tuple[str, str]:
79 """Validate request options and return the normalized model and endpoint."""
80 if aspect_ratio not in VALID_ASPECT_RATIOS:
81 raise ValueError(
82 f"Unsupported aspect ratio '{aspect_ratio}' for BFL backend. "
83 f"Supported: {VALID_ASPECT_RATIOS}"
84 )
85 normalized_model = model.strip().lower()
86 endpoint = MODEL_ENDPOINTS.get(normalized_model)
87 if not endpoint:
88 supported = sorted(MODEL_ENDPOINTS)
89 raise ValueError(f"Unsupported BFL model '{model}'. Supported: {supported}")
90 normalized_size = normalize_image_size(image_size)
91 if normalized_size != "1K":
92 raise ValueError(
93 f"BFL model '{normalized_model}' does not expose the unified image_size preset; "
94 f"only the default '1K' is supported, got '{image_size}'."
95 )
96 return normalized_model, endpoint
97
98
99 def _submit_request(url: str, headers: dict, payload: dict) -> dict:
100 """Submit a BFL generation request and return the JSON response."""
101 response = requests.post(url, headers=headers, json=payload, timeout=180)
102 if response.status_code != 200:
103 raise http_error(response, "BFL generation request")
104 return response.json()
105
106
107 def _generate_image(api_key: str, prompt: str,
108 aspect_ratio: str = "1:1", image_size: str = "1K",
109 output_dir: str = None, filename: str = None,
110 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
111 """Generate one image with the Black Forest Labs backend."""
112 normalized_model, endpoint = _resolve_request_options(
113 aspect_ratio,
114 image_size,
115 model,
116 )
117
118 headers = {
119 "x-key": api_key,
120 "accept": "application/json",
121 "Content-Type": "application/json",
122 }
123
124 payload = {
125 "prompt": prompt,
126 "prompt_upsampling": False,
127 "output_format": "png",
128 }
129
130 if normalized_model.endswith("-ultra"):
131 payload["aspect_ratio"] = aspect_ratio
132 payload["raw"] = False
133 else:
134 width, height = ASPECT_RATIO_TO_DIMENSIONS[aspect_ratio]
135 payload["width"] = width
136 payload["height"] = height
137
138 url = base_url.rstrip("/") + endpoint
139
140 print("[Black Forest Labs]")
141 print(f" Model: {normalized_model}")
142 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
143 print(f" Aspect Ratio: {aspect_ratio}")
144 print()
145 print(" [..] Submitting request...", end="", flush=True)
146 start = time.time()
147 request_payload = _submit_request(url, headers, payload)
148 elapsed = time.time() - start
149 print(f"\n [DONE] Request accepted ({elapsed:.1f}s)")
150
151 polling_url = request_payload.get("polling_url")
152 if not polling_url:
153 raise RuntimeError(f"BFL response missing polling_url: {request_payload}")
154
155 print(" [..] Polling result...")
156 result_payload = poll_json(
157 polling_url,
158 {"x-key": api_key, "accept": "application/json"},
159 status_label="status",
160 ready_values=["Ready"],
161 failed_values=[
162 "Error",
163 "Failed",
164 "Task not found",
165 "Request Moderated",
166 "Content Moderated",
167 ],
168 )
169
170 image_url = ((result_payload.get("result") or {}).get("sample"))
171 if not image_url:
172 raise RuntimeError(f"BFL result missing sample URL: {result_payload}")
173
174 path = resolve_output_path(prompt, output_dir, filename, ".png")
175 return download_image(image_url, path)
176
177
178 def generate(prompt: str,
179 aspect_ratio: str = "1:1", image_size: str = "1K",
180 output_dir: str = None, filename: str = None,
181 model: str = None, max_retries: int = MAX_RETRIES) -> str:
182 """Generate an image with retries using the BFL backend."""
183 resolved_model = model or os.environ.get("BFL_MODEL") or DEFAULT_MODEL
184 _resolve_request_options(aspect_ratio, image_size, resolved_model)
185 api_key = require_api_key(
186 "BFL_API_KEY",
187 message="No API key found. Set BFL_API_KEY in the current environment or a .env file.",
188 )
189 base_url = os.environ.get("BFL_BASE_URL") or DEFAULT_BASE_URL
190
191 last_error = None
192 for attempt in range(max_retries + 1):
193 try:
194 return _generate_image(
195 api_key=api_key,
196 prompt=prompt,
197 aspect_ratio=aspect_ratio,
198 image_size=image_size,
199 output_dir=output_dir,
200 filename=filename,
201 model=resolved_model,
202 base_url=base_url,
203 )
204 except Exception as exc:
205 last_error = exc
206 if is_permanent_error(exc):
207 raise
208 if attempt >= max_retries:
209 break
210 limited = is_rate_limit_error(exc)
211 delay = retry_delay(attempt, rate_limited=limited)
212 label = "Rate limit hit" if limited else f"Error: {exc}"
213 print(f"\n [WARN] {label}. Retrying in {delay}s...")
214 time.sleep(delay)
215
216 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
217
217 lines PYTHON