返回 ppt-master
backend_qwen.py
根目录 / skills / ppt-master / scripts / image_backends / backend_qwen.py
1 #!/usr/bin/env python3
2 """
3 Alibaba Cloud Qwen image generation backend.
4
5 Configuration keys:
6 QWEN_API_KEY / DASHSCOPE_API_KEY (required)
7 QWEN_BASE_URL (optional)
8 QWEN_MODEL (optional; qwen-image-2.0-pro 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 qwen")
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://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
46 DEFAULT_MODEL = "qwen-image-2.0-pro"
47 SUPPORTED_MODELS = {DEFAULT_MODEL}
48
49 ASPECT_RATIO_SIZE_MAP = {
50 "512px": {
51 "1:1": "1024*1024",
52 "2:3": "768*1152",
53 "3:2": "1152*768",
54 "3:4": "864*1152",
55 "4:3": "1152*864",
56 "4:5": "896*1120",
57 "5:4": "1120*896",
58 "9:16": "720*1280",
59 "16:9": "1280*720",
60 "21:9": "1344*576",
61 },
62 "1K": {
63 "1:1": "1536*1536",
64 "2:3": "1024*1536",
65 "3:2": "1536*1024",
66 "3:4": "1152*1536",
67 "4:3": "1536*1152",
68 "4:5": "1216*1536",
69 "5:4": "1536*1216",
70 "9:16": "896*1600",
71 "16:9": "1600*896",
72 "21:9": "1792*768",
73 },
74 "2K": {
75 "1:1": "2048*2048",
76 "2:3": "1536*2048",
77 "3:2": "2048*1536",
78 "3:4": "1728*2368",
79 "4:3": "2368*1728",
80 "4:5": "1792*2240",
81 "5:4": "2240*1792",
82 "9:16": "1536*2688",
83 "16:9": "2688*1536",
84 "21:9": "2688*1152",
85 },
86 }
87
88
89 def _validate_model(model: str) -> str:
90 """Limit the backend to the model contract implemented below."""
91 resolved = model.strip()
92 if resolved not in SUPPORTED_MODELS:
93 raise ValueError(
94 f"Unsupported Qwen model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}"
95 )
96 return resolved
97
98
99 def _resolve_url(base_url: str) -> str:
100 """Resolve the Qwen generation endpoint."""
101 base = base_url.rstrip("/")
102 if base.endswith("/generation"):
103 return base
104 if base.endswith("/api/v1"):
105 return base + "/services/aigc/multimodal-generation/generation"
106 return base + "/api/v1/services/aigc/multimodal-generation/generation"
107
108
109 def _resolve_size(aspect_ratio: str, image_size: str) -> str:
110 """Resolve the target resolution for a ratio and logical size preset."""
111 normalized = normalize_image_size(image_size)
112 sizes = ASPECT_RATIO_SIZE_MAP.get(normalized)
113 if sizes is None:
114 supported_sizes = ", ".join(ASPECT_RATIO_SIZE_MAP)
115 raise ValueError(
116 f"Unsupported image size '{image_size}' for Qwen backend. "
117 f"qwen-image-2.0-pro supports these logical sizes: {supported_sizes}."
118 )
119 size = sizes.get(aspect_ratio)
120 if not size:
121 supported = sorted(sizes)
122 raise ValueError(
123 f"Unsupported aspect ratio '{aspect_ratio}' for Qwen backend. "
124 f"Supported: {supported}"
125 )
126 return size
127
128
129 def _generate_image(api_key: str, prompt: str,
130 aspect_ratio: str = "1:1", image_size: str = "1K",
131 output_dir: str = None, filename: str = None,
132 model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
133 """Generate one image with the Qwen backend."""
134 model = _validate_model(model)
135 size = _resolve_size(aspect_ratio, image_size)
136 url = _resolve_url(base_url)
137 headers = {
138 "Authorization": f"Bearer {api_key}",
139 "Content-Type": "application/json",
140 }
141 payload = {
142 "model": model,
143 "input": {
144 "messages": [
145 {
146 "role": "user",
147 "content": [{"text": prompt}],
148 }
149 ]
150 },
151 "parameters": {
152 "size": size,
153 "prompt_extend": True,
154 "watermark": False,
155 },
156 }
157
158 print("[Alibaba Qwen Image]")
159 print(f" Model: {model}")
160 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
161 print(f" Aspect Ratio: {aspect_ratio}")
162 print(f" Resolution: {size}")
163 print()
164 print(" [..] Generating...", end="", flush=True)
165 start = time.time()
166 response = requests.post(url, headers=headers, json=payload, timeout=300)
167 elapsed = time.time() - start
168 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
169
170 if response.status_code != 200:
171 raise http_error(response, "Qwen image generation")
172
173 data = response.json()
174 choices = ((data.get("output") or {}).get("choices") or [])
175 contents = (((choices[0] if choices else {}).get("message") or {}).get("content") or [])
176 image_url = contents[0].get("image") if contents else None
177 if not image_url:
178 raise RuntimeError(f"Qwen response missing image URL: {data}")
179
180 path = resolve_output_path(prompt, output_dir, filename, ".png")
181 return download_image(image_url, path)
182
183
184 def generate(prompt: str,
185 aspect_ratio: str = "1:1", image_size: str = "1K",
186 output_dir: str = None, filename: str = None,
187 model: str = None, max_retries: int = MAX_RETRIES) -> str:
188 """Generate an image with retries using the Qwen backend."""
189 resolved_model = model or os.environ.get("QWEN_MODEL") or DEFAULT_MODEL
190 _validate_model(resolved_model)
191 normalized_size = normalize_image_size(image_size)
192 _resolve_size(aspect_ratio, normalized_size)
193 api_key = require_api_key(
194 "QWEN_API_KEY",
195 "DASHSCOPE_API_KEY",
196 message="No API key found. Set QWEN_API_KEY or DASHSCOPE_API_KEY in the current environment or a .env file.",
197 )
198 base_url = os.environ.get("QWEN_BASE_URL") or DEFAULT_ENDPOINT
199
200 last_error = None
201 for attempt in range(max_retries + 1):
202 try:
203 return _generate_image(
204 api_key=api_key,
205 prompt=prompt,
206 aspect_ratio=aspect_ratio,
207 image_size=normalized_size,
208 output_dir=output_dir,
209 filename=filename,
210 model=resolved_model,
211 base_url=base_url,
212 )
213 except Exception as exc:
214 last_error = exc
215 if is_permanent_error(exc):
216 raise
217 if attempt >= max_retries:
218 break
219 limited = is_rate_limit_error(exc)
220 delay = retry_delay(attempt, rate_limited=limited)
221 label = "Rate limit hit" if limited else f"Error: {exc}"
222 print(f"\n [WARN] {label}. Retrying in {delay}s...")
223 time.sleep(delay)
224
225 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
226
226 lines PYTHON