返回 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)
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_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://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation"
45 DEFAULT_MODEL = "qwen-image-2.0-pro"
46
47 ASPECT_RATIO_SIZE_MAP = {
48 "512px": {
49 "1:1": "1024*1024",
50 "2:3": "768*1152",
51 "3:2": "1152*768",
52 "3:4": "864*1152",
53 "4:3": "1152*864",
54 "4:5": "896*1120",
55 "5:4": "1120*896",
56 "9:16": "720*1280",
57 "16:9": "1280*720",
58 "21:9": "1344*576",
59 },
60 "1K": {
61 "1:1": "1536*1536",
62 "2:3": "1024*1536",
63 "3:2": "1536*1024",
64 "3:4": "1152*1536",
65 "4:3": "1536*1152",
66 "4:5": "1216*1536",
67 "5:4": "1536*1216",
68 "9:16": "896*1600",
69 "16:9": "1600*896",
70 "21:9": "1792*768",
71 },
72 "2K": {
73 "1:1": "2048*2048",
74 "2:3": "1536*2048",
75 "3:2": "2048*1536",
76 "3:4": "1728*2368",
77 "4:3": "2368*1728",
78 "4:5": "1792*2240",
79 "5:4": "2240*1792",
80 "9:16": "1536*2688",
81 "16:9": "2688*1536",
82 "21:9": "2688*1152",
83 },
84 "4K": {
85 "1:1": "2048*2048",
86 "2:3": "1536*2048",
87 "3:2": "2048*1536",
88 "3:4": "1728*2368",
89 "4:3": "2368*1728",
90 "4:5": "1792*2240",
91 "5:4": "2240*1792",
92 "9:16": "1536*2688",
93 "16:9": "2688*1536",
94 "21:9": "2688*1152",
95 },
96 }
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 return base + "/api/v1/services/aigc/multimodal-generation/generation"
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 Qwen 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 Qwen 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 payload = {
132 "model": model,
133 "input": {
134 "messages": [
135 {
136 "role": "user",
137 "content": [{"text": prompt}],
138 }
139 ]
140 },
141 "parameters": {
142 "size": size,
143 "prompt_extend": True,
144 "watermark": False,
145 },
146 }
147
148 print("[Alibaba Qwen Image]")
149 print(f" Model: {model}")
150 print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
151 print(f" Aspect Ratio: {aspect_ratio}")
152 print(f" Resolution: {size}")
153 print()
154 print(" [..] Generating...", end="", flush=True)
155 start = time.time()
156 response = requests.post(url, headers=headers, json=payload, timeout=300)
157 elapsed = time.time() - start
158 print(f"\n [DONE] Response received ({elapsed:.1f}s)")
159
160 if response.status_code != 200:
161 raise http_error(response, "Qwen image generation")
162
163 data = response.json()
164 choices = ((data.get("output") or {}).get("choices") or [])
165 contents = (((choices[0] if choices else {}).get("message") or {}).get("content") or [])
166 image_url = contents[0].get("image") if contents else None
167 if not image_url:
168 raise RuntimeError(f"Qwen response missing image URL: {data}")
169
170 path = resolve_output_path(prompt, output_dir, filename, ".png")
171 return download_image(image_url, path)
172
173
174 def generate(prompt: str,
175 aspect_ratio: str = "1:1", image_size: str = "1K",
176 output_dir: str = None, filename: str = None,
177 model: str = None, max_retries: int = MAX_RETRIES) -> str:
178 """Generate an image with retries using the Qwen backend."""
179 api_key = require_api_key(
180 "QWEN_API_KEY",
181 "DASHSCOPE_API_KEY",
182 message="No API key found. Set QWEN_API_KEY or DASHSCOPE_API_KEY in the current environment or a .env file.",
183 )
184 base_url = os.environ.get("QWEN_BASE_URL") or DEFAULT_ENDPOINT
185 resolved_model = model or os.environ.get("QWEN_MODEL") or DEFAULT_MODEL
186
187 last_error = None
188 for attempt in range(max_retries + 1):
189 try:
190 return _generate_image(
191 api_key=api_key,
192 prompt=prompt,
193 aspect_ratio=aspect_ratio,
194 image_size=image_size,
195 output_dir=output_dir,
196 filename=filename,
197 model=resolved_model,
198 base_url=base_url,
199 )
200 except Exception as exc:
201 last_error = exc
202 if attempt >= max_retries:
203 break
204 limited = is_rate_limit_error(exc)
205 delay = retry_delay(attempt, rate_limited=limited)
206 label = "Rate limit hit" if limited else f"Error: {exc}"
207 print(f"\n [WARN] {label}. Retrying in {delay}s...")
208 time.sleep(delay)
209
210 raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
211
211 lines PYTHON