返回 ppt-master
backend_zhipu.py
根目录 / skills / ppt-master / scripts / image_backends / backend_zhipu.py
1 #!/usr/bin/env python3
2 """
3 Zhipu GLM-Image generation backend.
4
5 Configuration keys:
6 ZHIPU_API_KEY / BIGMODEL_API_KEY (required)
7 ZHIPU_BASE_URL (optional)
8 ZHIPU_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 zhipu")
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 normalize_image_size,
38 require_api_key,
39 resolve_output_path,
40 retry_delay,
41 )
42
43
44 DEFAULT_ENDPOINT = "https://open.bigmodel.cn/api/paas/v4/images/generations"
45 DEFAULT_MODEL = "glm-image"
46
47 ASPECT_RATIO_SIZE_MAP = {
48 "512px": {
49 "1:1": "1024x1024",
50 "2:3": "768x1152",
51 "3:2": "1152x768",
52 "3:4": "864x1152",
53 "4:3": "1152x864",
54 "4:5": "1024x1280",
55 "5:4": "1280x1024",
56 "9:16": "720x1440",
57 "16:9": "1440x720",
58 "21:9": "1536x640",
59 },
60 "1K": {
61 "1:1": "1280x1280",
62 "2:3": "960x1440",
63 "3:2": "1440x960",
64 "3:4": "1024x1365",
65 "4:3": "1365x1024",
66 "4:5": "1024x1280",
67 "5:4": "1280x1024",
68 "9:16": "768x1344",
69 "16:9": "1344x768",
70 "21:9": "1536x640",
71 },
72 "2K": {
73 "1:1": "1440x1440",
74 "2:3": "1152x1728",
75 "3:2": "1728x1152",
76 "3:4": "1152x1536",
77 "4:3": "1536x1152",
78 "4:5": "1280x1600",
79 "5:4": "1600x1280",
80 "9:16": "720x1440",
81 "16:9": "1440x720",
82 "21:9": "1792x768",
83 },
84 "4K": {
85 "1:1": "1440x1440",
86 "2:3": "1152x1728",
87 "3:2": "1728x1152",
88 "3:4": "1152x1536",
89 "4:3": "1536x1152",
90 "4:5": "1280x1600",
91 "5:4": "1600x1280",
92 "9:16": "720x1440",
93 "16:9": "1440x720",
94 "21:9": "1792x768",
95 },
96 }
97
98
99 def _resolve_url(base_url: str) -> str:
100 """Resolve the Zhipu generation endpoint."""
101 base = base_url.rstrip("/")
102 if base.endswith("/images/generations"):
103 return base
104 return base + "/api/paas/v4/images/generations"
105
106
107 def _resolve_size(aspect_ratio: str, image_size: str) -> str:
108 """Resolve the target resolution for a ratio and logical size preset."""
109 normalized = normalize_image_size(image_size)
110 size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
111 if not size:
112 supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
113 raise ValueError(
114 f"Unsupported aspect ratio '{aspect_ratio}' for Zhipu backend. "
115 f"Supported: {supported}"
116 )
117 return size
118
119
120 def _generate_image(api_key: str, prompt: str,
121 aspect_ratio: str = "1:1", image_size: str = "1K",
122 output_dir: str = None, filename: str = None,
123 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
124 """Generate one image with the Zhipu backend."""
125 size = _resolve_size(aspect_ratio, image_size)
126 url = _resolve_url(base_url)
127 headers = {
128 "Authorization": f"Bearer {api_key}",
129 "Content-Type": "application/json",
130 }
131
132 payload = {
133 "model": model,
134 "prompt": prompt,
135 "size": size,
136 }
137
138 print("[Zhipu GLM-Image]")
139 print(f" Model: {model}")
140 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
141 print(f" Aspect Ratio: {aspect_ratio}")
142 print(f" Resolution: {size}")
143 print()
144 print(" [..] Generating...", end="", flush=True)
145 start = time.time()
146 response = requests.post(url, headers=headers, json=payload, timeout=300)
147 elapsed = time.time() - start
148 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
149
150 if response.status_code != 200:
151 raise http_error(response, "Zhipu image generation")
152
153 data = response.json()
154 items = data.get("data") or []
155 image_url = items[0].get("url") if items else None
156 if not image_url:
157 raise RuntimeError(f"Zhipu response missing image URL: {data}")
158
159 path = resolve_output_path(prompt, output_dir, filename, ".png")
160 return download_image(image_url, path)
161
162
163 def generate(prompt: str,
164 aspect_ratio: str = "1:1", image_size: str = "1K",
165 output_dir: str = None, filename: str = None,
166 model: str = None, max_retries: int = MAX_RETRIES) -> str:
167 """Generate an image with retries using the Zhipu backend."""
168 api_key = require_api_key(
169 "ZHIPU_API_KEY",
170 "BIGMODEL_API_KEY",
171 message="No API key found. Set ZHIPU_API_KEY or BIGMODEL_API_KEY in the current environment or a .env file.",
172 )
173 base_url = os.environ.get("ZHIPU_BASE_URL") or DEFAULT_ENDPOINT
174 resolved_model = model or os.environ.get("ZHIPU_MODEL") or DEFAULT_MODEL
175
176 last_error = None
177 for attempt in range(max_retries + 1):
178 try:
179 return _generate_image(
180 api_key=api_key,
181 prompt=prompt,
182 aspect_ratio=aspect_ratio,
183 image_size=image_size,
184 output_dir=output_dir,
185 filename=filename,
186 model=resolved_model,
187 base_url=base_url,
188 )
189 except Exception as exc:
190 last_error = exc
191 if attempt >= max_retries:
192 break
193 limited = is_rate_limit_error(exc)
194 delay = retry_delay(attempt, rate_limited=limited)
195 label = "Rate limit hit" if limited else f"Error: {exc}"
196 print(f"\n [WARN] {label}. Retrying in {delay}s...")
197 time.sleep(delay)
198
199 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
200
200 lines PYTHON