返回 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)
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 http_error,
37 is_rate_limit_error,
38 normalize_image_size,
39 require_api_key,
40 resolve_output_path,
41 retry_delay,
42 save_image_bytes,
43 )
44
45
46 DEFAULT_ENDPOINT = "https://api.minimaxi.com/v1/image_generation"
47 DEFAULT_MODEL = "image-01"
48
49 # International fallback: set MINIMAX_BASE_URL=https://api.minimax.io if needed
50
51 ASPECT_RATIO_SIZE_MAP = {
52 "512px": {
53 "1:1": (512, 512),
54 "16:9": (640, 360),
55 "4:3": (576, 432),
56 "3:2": (624, 416),
57 "2:3": (416, 624),
58 "3:4": (432, 576),
59 "9:16": (360, 640),
60 "21:9": (672, 288),
61 },
62 "1K": {
63 "1:1": (1024, 1024),
64 "16:9": (1280, 720),
65 "4:3": (1152, 864),
66 "3:2": (1248, 832),
67 "2:3": (832, 1248),
68 "3:4": (864, 1152),
69 "9:16": (720, 1280),
70 "21:9": (1344, 576),
71 },
72 "2K": {
73 "1:1": (2048, 2048),
74 "16:9": (2048, 1152),
75 "4:3": (2048, 1536),
76 "3:2": (2048, 1368),
77 "2:3": (1368, 2048),
78 "3:4": (1536, 2048),
79 "9:16": (1152, 2048),
80 "21:9": (2048, 880),
81 },
82 "4K": {
83 "1:1": (2048, 2048),
84 "16:9": (2048, 1152),
85 "4:3": (2048, 1536),
86 "3:2": (2048, 1368),
87 "2:3": (1368, 2048),
88 "3:4": (1536, 2048),
89 "9:16": (1152, 2048),
90 "21:9": (2048, 880),
91 },
92 }
93
94
95 def _resolve_url(base_url: str) -> str:
96 """Resolve the MiniMax image generation endpoint.
97
98 Accepts three forms of MINIMAX_BASE_URL:
99 - Full endpoint: https://api.minimax.io/v1/image_generation → used as-is
100 - Versioned base: https://api.minimax.io/v1 → appends /image_generation
101 - Root base: https://api.minimax.io → appends /v1/image_generation
102 """
103 base = base_url.rstrip("/")
104 if base.endswith("/image_generation"):
105 return base
106 if base.endswith("/v1"):
107 return base + "/image_generation"
108 return base + "/v1/image_generation"
109
110
111 def _resolve_dimensions(aspect_ratio: str, image_size: str) -> tuple[int, int]:
112 """Resolve width and height from the unified aspect_ratio/image_size pair."""
113 normalized = normalize_image_size(image_size)
114 dimensions = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
115 if not dimensions:
116 supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
117 raise ValueError(
118 f"Unsupported aspect ratio '{aspect_ratio}' for MiniMax backend. "
119 f"Supported: {supported}"
120 )
121 return dimensions
122
123
124 def _extract_image_bytes(payload: dict) -> bytes | None:
125 """Extract image bytes from a MiniMax response payload."""
126 data = payload.get("data") or {}
127 image_base64 = data.get("image_base64") or []
128 if image_base64:
129 return base64.b64decode(image_base64[0])
130 return None
131
132
133 def _generate_image(api_key: str, prompt: str,
134 aspect_ratio: str = "1:1", image_size: str = "1K",
135 output_dir: str = None, filename: str = None,
136 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
137 """Generate one image with the MiniMax backend."""
138 width, height = _resolve_dimensions(aspect_ratio, image_size)
139 url = _resolve_url(base_url)
140
141 headers = {
142 "Authorization": f"Bearer {api_key}",
143 "Content-Type": "application/json",
144 }
145 payload = {
146 "model": model,
147 "prompt": prompt,
148 "width": width,
149 "height": height,
150 "response_format": "base64",
151 "n": 1,
152 }
153
154 print("[MiniMax Image]")
155 print(f" Model: {model}")
156 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
157 print(f" Aspect Ratio: {aspect_ratio}")
158 print(f" Resolution: {width}x{height} (from image_size={image_size})")
159 print()
160 print(" [..] Generating...", end="", flush=True)
161 start = time.time()
162 response = requests.post(url, headers=headers, json=payload, timeout=300)
163 elapsed = time.time() - start
164 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
165
166 if response.status_code != 200:
167 raise http_error(response, "MiniMax image generation")
168
169 data = response.json()
170 base_resp = data.get("base_resp") or {}
171 if base_resp.get("status_code") not in (None, 0, "0"):
172 raise RuntimeError(f"MiniMax image generation failed: {data}")
173
174 image_bytes = _extract_image_bytes(data)
175 if not image_bytes:
176 raise RuntimeError(f"MiniMax response missing image data: {data}")
177
178 ext = detect_image_extension(image_bytes) or ".jpeg"
179 path = resolve_output_path(prompt, output_dir, filename, ext)
180 return save_image_bytes(image_bytes, path)
181
182
183 def generate(prompt: str,
184 aspect_ratio: str = "1:1", image_size: str = "1K",
185 output_dir: str = None, filename: str = None,
186 model: str = None, max_retries: int = MAX_RETRIES) -> str:
187 """Generate an image with retries using the MiniMax backend."""
188 api_key = require_api_key(
189 "MINIMAX_API_KEY",
190 message="No API key found. Set MINIMAX_API_KEY in the current environment or a .env file.",
191 )
192 base_url = os.environ.get("MINIMAX_BASE_URL") or DEFAULT_ENDPOINT
193 resolved_model = model or os.environ.get("MINIMAX_MODEL") or DEFAULT_MODEL
194 normalized_size = normalize_image_size(image_size)
195
196 last_error = None
197 for attempt in range(max_retries + 1):
198 try:
199 return _generate_image(
200 api_key=api_key,
201 prompt=prompt,
202 aspect_ratio=aspect_ratio,
203 image_size=normalized_size,
204 output_dir=output_dir,
205 filename=filename,
206 model=resolved_model,
207 base_url=base_url,
208 )
209 except Exception as exc:
210 last_error = exc
211 if attempt >= max_retries:
212 break
213 limited = is_rate_limit_error(exc)
214 delay = retry_delay(attempt, rate_limited=limited)
215 label = "Rate limit hit" if limited else f"Error: {exc}"
216 print(f"\n [WARN] {label}. Retrying in {delay}s...")
217 time.sleep(delay)
218
219 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
220
220 lines PYTHON