返回 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; glm-image 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 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_permanent_error,
37 is_rate_limit_error,
38 normalize_image_size,
39 require_api_key,
40 resolve_output_path,
41 retry_delay,
42 )
43
44
45 DEFAULT_ENDPOINT = "https://open.bigmodel.cn/api/paas/v4/images/generations"
46 DEFAULT_MODEL = "glm-image"
47 SUPPORTED_MODELS = {DEFAULT_MODEL}
48
49 ASPECT_RATIO_SIZE_MAP = {
50 "1K": {
51 "1:1": "1280x1280",
52 "2:3": "1056x1568",
53 "3:2": "1568x1056",
54 "3:4": "1088x1472",
55 "4:3": "1472x1088",
56 "4:5": "1024x1280",
57 "5:4": "1280x1024",
58 "9:16": "960x1728",
59 "16:9": "1728x960",
60 "21:9": "1568x672",
61 },
62 "2K": {
63 "1:1": "2048x2048",
64 "2:3": "1344x2016",
65 "3:2": "2016x1344",
66 "3:4": "1536x2048",
67 "4:3": "2048x1536",
68 "4:5": "1536x1920",
69 "5:4": "1920x1536",
70 "9:16": "1152x2048",
71 "16:9": "2048x1152",
72 "21:9": "2016x864",
73 },
74 }
75
76
77 def _validate_model(model: str) -> str:
78 """Limit the backend to the GLM-Image contract implemented below."""
79 resolved = model.strip()
80 if resolved not in SUPPORTED_MODELS:
81 raise ValueError(
82 f"Unsupported Zhipu model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}"
83 )
84 return resolved
85
86
87 def _resolve_url(base_url: str) -> str:
88 """Resolve the Zhipu generation endpoint."""
89 base = base_url.rstrip("/")
90 if base.endswith("/images/generations"):
91 return base
92 return base + "/api/paas/v4/images/generations"
93
94
95 def _resolve_size(aspect_ratio: str, image_size: str) -> str:
96 """Resolve the target resolution for a ratio and logical size preset."""
97 normalized = normalize_image_size(image_size)
98 sizes = ASPECT_RATIO_SIZE_MAP.get(normalized)
99 if sizes is None:
100 supported_sizes = ", ".join(ASPECT_RATIO_SIZE_MAP)
101 raise ValueError(
102 f"Unsupported image size '{image_size}' for Zhipu backend. "
103 f"GLM-Image supports these logical sizes: {supported_sizes}."
104 )
105 size = sizes.get(aspect_ratio)
106 if not size:
107 supported = sorted(sizes)
108 raise ValueError(
109 f"Unsupported aspect ratio '{aspect_ratio}' for Zhipu backend. "
110 f"Supported: {supported}"
111 )
112 return size
113
114
115 def _generate_image(api_key: str, prompt: str,
116 aspect_ratio: str = "1:1", image_size: str = "1K",
117 output_dir: str = None, filename: str = None,
118 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
119 """Generate one image with the Zhipu backend."""
120 model = _validate_model(model)
121 size = _resolve_size(aspect_ratio, image_size)
122 url = _resolve_url(base_url)
123 headers = {
124 "Authorization": f"Bearer {api_key}",
125 "Content-Type": "application/json",
126 }
127
128 payload = {
129 "model": model,
130 "prompt": prompt,
131 "size": size,
132 }
133
134 print("[Zhipu GLM-Image]")
135 print(f" Model: {model}")
136 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
137 print(f" Aspect Ratio: {aspect_ratio}")
138 print(f" Resolution: {size}")
139 print()
140 print(" [..] Generating...", end="", flush=True)
141 start = time.time()
142 response = requests.post(url, headers=headers, json=payload, timeout=300)
143 elapsed = time.time() - start
144 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
145
146 if response.status_code != 200:
147 raise http_error(response, "Zhipu image generation")
148
149 data = response.json()
150 items = data.get("data") or []
151 image_url = items[0].get("url") if items else None
152 if not image_url:
153 raise RuntimeError(f"Zhipu response missing image URL: {data}")
154
155 path = resolve_output_path(prompt, output_dir, filename, ".png")
156 return download_image(image_url, path)
157
158
159 def generate(prompt: str,
160 aspect_ratio: str = "1:1", image_size: str = "1K",
161 output_dir: str = None, filename: str = None,
162 model: str = None, max_retries: int = MAX_RETRIES) -> str:
163 """Generate an image with retries using the Zhipu backend."""
164 resolved_model = model or os.environ.get("ZHIPU_MODEL") or DEFAULT_MODEL
165 _validate_model(resolved_model)
166 normalized_size = normalize_image_size(image_size)
167 _resolve_size(aspect_ratio, normalized_size)
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
175 last_error = None
176 for attempt in range(max_retries + 1):
177 try:
178 return _generate_image(
179 api_key=api_key,
180 prompt=prompt,
181 aspect_ratio=aspect_ratio,
182 image_size=normalized_size,
183 output_dir=output_dir,
184 filename=filename,
185 model=resolved_model,
186 base_url=base_url,
187 )
188 except Exception as exc:
189 last_error = exc
190 if is_permanent_error(exc):
191 raise
192 if attempt >= max_retries:
193 break
194 limited = is_rate_limit_error(exc)
195 delay = retry_delay(attempt, rate_limited=limited)
196 label = "Rate limit hit" if limited else f"Error: {exc}"
197 print(f"\n [WARN] {label}. Retrying in {delay}s...")
198 time.sleep(delay)
199
200 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
201
201 lines PYTHON