返回 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_rate_limit_error,
37 poll_json,
38 require_api_key,
39 resolve_output_path,
40 retry_delay,
41 )
42
43
44 VALID_ASPECT_RATIOS = [
45 "1:1", "2:3", "3:2", "3:4", "4:3",
46 "4:5", "5:4", "9:16", "16:9", "21:9",
47 ]
48
49 DEFAULT_BASE_URL = "https://api.bfl.ai"
50 DEFAULT_MODEL = "flux-pro-1.1-ultra"
51
52 MODEL_ENDPOINTS = {
53 "flux-pro-1.1": "/v1/flux-pro-1.1",
54 "flux-pro-1.1-ultra": "/v1/flux-pro-1.1-ultra",
55 "flux-dev": "/v1/flux-dev",
56 }
57
58 ASPECT_RATIO_TO_DIMENSIONS = {
59 "1:1": (1024, 1024),
60 "2:3": (1024, 1536),
61 "3:2": (1536, 1024),
62 "3:4": (1024, 1365),
63 "4:3": (1365, 1024),
64 "4:5": (1024, 1280),
65 "5:4": (1280, 1024),
66 "9:16": (1024, 1820),
67 "16:9": (1820, 1024),
68 "21:9": (2048, 878),
69 }
70
71
72 def _submit_request(url: str, headers: dict, payload: dict) -> dict:
73 """Submit a BFL generation request and return the JSON response."""
74 response = requests.post(url, headers=headers, json=payload, timeout=180)
75 if response.status_code != 200:
76 raise http_error(response, "BFL generation request")
77 return response.json()
78
79
80 def _generate_image(api_key: str, prompt: str,
81 aspect_ratio: str = "1:1", image_size: str = "1K",
82 output_dir: str = None, filename: str = None,
83 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
84 """Generate one image with the Black Forest Labs backend."""
85 del image_size # BFL quality is primarily controlled by model choice.
86
87 if aspect_ratio not in VALID_ASPECT_RATIOS:
88 raise ValueError(
89 f"Unsupported aspect ratio '{aspect_ratio}' for BFL backend. "
90 f"Supported: {VALID_ASPECT_RATIOS}"
91 )
92
93 normalized_model = model.strip().lower()
94 endpoint = MODEL_ENDPOINTS.get(normalized_model)
95 if not endpoint:
96 supported = sorted(MODEL_ENDPOINTS)
97 raise ValueError(f"Unsupported BFL model '{model}'. Supported: {supported}")
98
99 headers = {
100 "x-key": api_key,
101 "accept": "application/json",
102 "Content-Type": "application/json",
103 }
104
105 payload = {
106 "prompt": prompt,
107 "prompt_upsampling": False,
108 "output_format": "png",
109 }
110
111 if normalized_model.endswith("-ultra"):
112 payload["aspect_ratio"] = aspect_ratio
113 payload["raw"] = False
114 else:
115 width, height = ASPECT_RATIO_TO_DIMENSIONS[aspect_ratio]
116 payload["width"] = width
117 payload["height"] = height
118
119 url = base_url.rstrip("/") + endpoint
120
121 print("[Black Forest Labs]")
122 print(f" Model: {normalized_model}")
123 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
124 print(f" Aspect Ratio: {aspect_ratio}")
125 print()
126 print(" [..] Submitting request...", end="", flush=True)
127 start = time.time()
128 request_payload = _submit_request(url, headers, payload)
129 elapsed = time.time() - start
130 print(f"\n [DONE] Request accepted ({elapsed:.1f}s)")
131
132 polling_url = request_payload.get("polling_url")
133 if not polling_url:
134 raise RuntimeError(f"BFL response missing polling_url: {request_payload}")
135
136 print(" [..] Polling result...")
137 result_payload = poll_json(
138 polling_url,
139 {"x-key": api_key, "accept": "application/json"},
140 status_label="status",
141 ready_values=["Ready"],
142 failed_values=["Error", "Failed", "Request Moderated", "Content Moderated"],
143 )
144
145 image_url = ((result_payload.get("result") or {}).get("sample"))
146 if not image_url:
147 raise RuntimeError(f"BFL result missing sample URL: {result_payload}")
148
149 path = resolve_output_path(prompt, output_dir, filename, ".png")
150 return download_image(image_url, path)
151
152
153 def generate(prompt: str,
154 aspect_ratio: str = "1:1", image_size: str = "1K",
155 output_dir: str = None, filename: str = None,
156 model: str = None, max_retries: int = MAX_RETRIES) -> str:
157 """Generate an image with retries using the BFL backend."""
158 api_key = require_api_key(
159 "BFL_API_KEY",
160 message="No API key found. Set BFL_API_KEY in the current environment or a .env file.",
161 )
162 base_url = os.environ.get("BFL_BASE_URL") or DEFAULT_BASE_URL
163 resolved_model = model or os.environ.get("BFL_MODEL") or DEFAULT_MODEL
164
165 last_error = None
166 for attempt in range(max_retries + 1):
167 try:
168 return _generate_image(
169 api_key=api_key,
170 prompt=prompt,
171 aspect_ratio=aspect_ratio,
172 image_size=image_size,
173 output_dir=output_dir,
174 filename=filename,
175 model=resolved_model,
176 base_url=base_url,
177 )
178 except Exception as exc:
179 last_error = exc
180 if attempt >= max_retries:
181 break
182 limited = is_rate_limit_error(exc)
183 delay = retry_delay(attempt, rate_limited=limited)
184 label = "Rate limit hit" if limited else f"Error: {exc}"
185 print(f"\n [WARN] {label}. Retrying in {delay}s...")
186 time.sleep(delay)
187
188 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
189
189 lines PYTHON