返回 ppt-master
backend_minimax.py
根目录 / skills / ppt-master / scripts / image_backends / backend_minimax.py
1 #!/usr/bin/env python3
2 """
3 MiniMax image generation backend.
4
5 Configuration keys:
6 MINIMAX_API_KEY (required)
7 MINIMAX_BASE_URL (optional)
8 MINIMAX_MODEL (optional; image-01 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 minimax")
25 raise SystemExit(0 if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]) else 1)
26
27 import base64
28 import os
29 import time
30
31 import requests
32
33 from image_backends.backend_common import (
34 MAX_RETRIES,
35 detect_image_extension,
36 download_image,
37 http_error,
38 is_permanent_error,
39 is_rate_limit_error,
40 normalize_image_size,
41 require_api_key,
42 resolve_output_path,
43 retry_delay,
44 save_image_bytes,
45 )
46
47
48 DEFAULT_ENDPOINT = "https://api.minimaxi.com/v1/image_generation"
49 DEFAULT_MODEL = "image-01"
50 SUPPORTED_MODELS = {DEFAULT_MODEL}
51
52 # Request the documented default response format. The API returns hosted links
53 # in `data.image_urls` for "url" and inline strings in `data.image_base64` for
54 # "base64"; both shapes are handled when the response is parsed.
55 DEFAULT_RESPONSE_FORMAT = "url"
56
57 # International fallback: set MINIMAX_BASE_URL=https://api.minimax.io if needed
58
59 ASPECT_RATIO_SIZE_MAP = {
60 "512px": {
61 "1:1": (512, 512),
62 "16:9": (912, 512),
63 "4:3": (680, 512),
64 "3:2": (768, 512),
65 "2:3": (512, 768),
66 "3:4": (512, 680),
67 "9:16": (512, 912),
68 "21:9": (1192, 512),
69 },
70 "1K": {
71 "1:1": (1024, 1024),
72 "16:9": (1280, 720),
73 "4:3": (1152, 864),
74 "3:2": (1248, 832),
75 "2:3": (832, 1248),
76 "3:4": (864, 1152),
77 "9:16": (720, 1280),
78 "21:9": (1344, 576),
79 },
80 "2K": {
81 "1:1": (2048, 2048),
82 "16:9": (2048, 1152),
83 "4:3": (2048, 1536),
84 "3:2": (2048, 1368),
85 "2:3": (1368, 2048),
86 "3:4": (1536, 2048),
87 "9:16": (1152, 2048),
88 "21:9": (2048, 880),
89 },
90 }
91
92
93 def _validate_model(model: str) -> str:
94 """Limit the backend to the model contract implemented below."""
95 resolved = model.strip()
96 if resolved not in SUPPORTED_MODELS:
97 raise ValueError(
98 f"Unsupported MiniMax model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}"
99 )
100 return resolved
101
102
103 def _resolve_url(base_url: str) -> str:
104 """Resolve the MiniMax image generation endpoint.
105
106 Accepts three forms of MINIMAX_BASE_URL:
107 - Full endpoint: https://api.minimax.io/v1/image_generation → used as-is
108 - Versioned base: https://api.minimax.io/v1 → appends /image_generation
109 - Root base: https://api.minimax.io → appends /v1/image_generation
110 """
111 base = base_url.rstrip("/")
112 if base.endswith("/image_generation"):
113 return base
114 if base.endswith("/v1"):
115 return base + "/image_generation"
116 return base + "/v1/image_generation"
117
118
119 def _resolve_dimensions(aspect_ratio: str, image_size: str) -> tuple[int, int]:
120 """Resolve width and height from the unified aspect_ratio/image_size pair."""
121 normalized = normalize_image_size(image_size)
122 sizes = ASPECT_RATIO_SIZE_MAP.get(normalized)
123 if sizes is None:
124 supported_sizes = ", ".join(ASPECT_RATIO_SIZE_MAP)
125 raise ValueError(
126 f"Unsupported image size '{image_size}' for MiniMax backend. "
127 f"image-01 supports these logical sizes: {supported_sizes}."
128 )
129 dimensions = sizes.get(aspect_ratio)
130 if not dimensions:
131 supported = sorted(sizes)
132 raise ValueError(
133 f"Unsupported aspect ratio '{aspect_ratio}' for MiniMax backend. "
134 f"Supported: {supported}"
135 )
136 return dimensions
137
138
139 def _extract_image_bytes(payload: dict) -> bytes | None:
140 """Extract inline base64 image bytes from a MiniMax response payload."""
141 data = payload.get("data") or {}
142 image_base64 = data.get("image_base64") or []
143 if image_base64:
144 return base64.b64decode(image_base64[0])
145 return None
146
147
148 def _extract_image_url(payload: dict) -> str | None:
149 """Extract the first hosted image URL from a MiniMax response payload."""
150 data = payload.get("data") or {}
151 image_urls = data.get("image_urls") or []
152 if image_urls:
153 return image_urls[0]
154 return None
155
156
157 def _generate_image(api_key: str, prompt: str,
158 aspect_ratio: str = "1:1", image_size: str = "1K",
159 output_dir: str = None, filename: str = None,
160 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
161 """Generate one image with the MiniMax backend."""
162 model = _validate_model(model)
163 width, height = _resolve_dimensions(aspect_ratio, image_size)
164 url = _resolve_url(base_url)
165
166 headers = {
167 "Authorization": f"Bearer {api_key}",
168 "Content-Type": "application/json",
169 }
170 payload = {
171 "model": model,
172 "prompt": prompt,
173 "width": width,
174 "height": height,
175 "response_format": DEFAULT_RESPONSE_FORMAT,
176 "n": 1,
177 }
178
179 print("[MiniMax Image]")
180 print(f" Model: {model}")
181 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
182 print(f" Aspect Ratio: {aspect_ratio}")
183 print(f" Resolution: {width}x{height} (from image_size={image_size})")
184 print()
185 print(" [..] Generating...", end="", flush=True)
186 start = time.time()
187 response = requests.post(url, headers=headers, json=payload, timeout=300)
188 elapsed = time.time() - start
189 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
190
191 if response.status_code != 200:
192 raise http_error(response, "MiniMax image generation")
193
194 data = response.json()
195 base_resp = data.get("base_resp") or {}
196 if base_resp.get("status_code") not in (None, 0, "0"):
197 raise RuntimeError(f"MiniMax image generation failed: {data}")
198
199 image_bytes = _extract_image_bytes(data)
200 if image_bytes:
201 ext = detect_image_extension(image_bytes) or ".jpeg"
202 path = resolve_output_path(prompt, output_dir, filename, ext)
203 return save_image_bytes(image_bytes, path)
204
205 image_url = _extract_image_url(data)
206 if image_url:
207 # image-01 serves JPEG; save_image_bytes realigns the extension when the
208 # downloaded bytes are a different format.
209 path = resolve_output_path(prompt, output_dir, filename, ".jpeg")
210 return download_image(image_url, path)
211
212 raise RuntimeError(f"MiniMax response missing image data: {data}")
213
214
215 def generate(prompt: str,
216 aspect_ratio: str = "1:1", image_size: str = "1K",
217 output_dir: str = None, filename: str = None,
218 model: str = None, max_retries: int = MAX_RETRIES) -> str:
219 """Generate an image with retries using the MiniMax backend."""
220 resolved_model = model or os.environ.get("MINIMAX_MODEL") or DEFAULT_MODEL
221 _validate_model(resolved_model)
222 normalized_size = normalize_image_size(image_size)
223 _resolve_dimensions(aspect_ratio, normalized_size)
224 api_key = require_api_key(
225 "MINIMAX_API_KEY",
226 message="No API key found. Set MINIMAX_API_KEY in the current environment or a .env file.",
227 )
228 base_url = os.environ.get("MINIMAX_BASE_URL") or DEFAULT_ENDPOINT
229
230 last_error = None
231 for attempt in range(max_retries + 1):
232 try:
233 return _generate_image(
234 api_key=api_key,
235 prompt=prompt,
236 aspect_ratio=aspect_ratio,
237 image_size=normalized_size,
238 output_dir=output_dir,
239 filename=filename,
240 model=resolved_model,
241 base_url=base_url,
242 )
243 except Exception as exc:
244 last_error = exc
245 if is_permanent_error(exc):
246 raise
247 if attempt >= max_retries:
248 break
249 limited = is_rate_limit_error(exc)
250 delay = retry_delay(attempt, rate_limited=limited)
251 label = "Rate limit hit" if limited else f"Error: {exc}"
252 print(f"\n [WARN] {label}. Retrying in {delay}s...")
253 time.sleep(delay)
254
255 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
256
256 lines PYTHON