| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | ModelScope image generation backend. |
| 4 | |
| 5 | Configuration keys: |
| 6 | MODELSCOPE_API_KEY (required) |
| 7 | MODELSCOPE_MODEL (optional) |
| 8 | MODELSCOPE_BASE_URL (optional) |
| 9 | """ |
| 10 | |
| 11 | import os |
| 12 | import time |
| 13 | |
| 14 | import requests |
| 15 | |
| 16 | from image_backends.backend_common import ( |
| 17 | MAX_RETRIES, |
| 18 | http_error, |
| 19 | is_rate_limit_error, |
| 20 | normalize_image_size, |
| 21 | require_api_key, |
| 22 | resolve_output_path, |
| 23 | retry_delay, |
| 24 | poll_json, |
| 25 | download_image |
| 26 | ) |
| 27 | |
| 28 | DEFAULT_ENDPOINT = "https://api-inference.modelscope.cn" |
| 29 | DEFAULT_MODEL = "Tongyi-MAI/Z-Image-Turbo" |
| 30 | |
| 31 | # Resolution must be 64-aligned. |
| 32 | ASPECT_RATIO_SIZE_MAP = { |
| 33 | "512px": { |
| 34 | "1:1": "1024*1024", |
| 35 | "3:4": "768*1024", |
| 36 | "4:3": "1024*768", |
| 37 | "9:16": "576*1024", |
| 38 | "16:9": "1024*576" |
| 39 | }, |
| 40 | "1K": { |
| 41 | "1:1": "1280*1280", |
| 42 | "3:4": "960*1280", |
| 43 | "4:3": "1280*960", |
| 44 | "9:16": "576*1024", |
| 45 | "16:9": "1024*576" |
| 46 | }, |
| 47 | "2K": { |
| 48 | "1:1": "2048*2048", |
| 49 | "3:4": "1536*2048", |
| 50 | "4:3": "2048*1536", |
| 51 | "9:16": "1152*2048", |
| 52 | "16:9": "2048*1152" |
| 53 | }, |
| 54 | "4K": { |
| 55 | "1:1": "2048*2048", |
| 56 | "3:4": "1920*2560", |
| 57 | "4:3": "2560*1920", |
| 58 | "9:16": "1728*3072", |
| 59 | "16:9": "3072*1728" |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | def _resolve_url(base_url: str) -> str: |
| 64 | """Resolve the ModelScope generation endpoint.""" |
| 65 | base = base_url.rstrip("/") |
| 66 | if base.endswith("/v1"): |
| 67 | base = base.removesuffix("/v1") |
| 68 | return base |
| 69 | |
| 70 | def _resolve_size(aspect_ratio: str, image_size: str) -> str: |
| 71 | """Resolve the target resolution for a ratio and logical size preset. |
| 72 | |
| 73 | Args: |
| 74 | aspect_ratio (str): The aspect ratio string. Supported values: '1:1', '3:4', '4:3', '9:16', '16:9'. |
| 75 | image_size (str): The logical size preset. Supported values: '512px', '1K', '2K', '4K'. |
| 76 | """ |
| 77 | normalized = normalize_image_size(image_size) |
| 78 | size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio) |
| 79 | if not size: |
| 80 | supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"]) |
| 81 | raise ValueError( |
| 82 | f"Unsupported aspect ratio '{aspect_ratio}' for ModelScope backend. " |
| 83 | f"Supported: {supported}" |
| 84 | ) |
| 85 | return size |
| 86 | |
| 87 | |
| 88 | def _generate_image(api_key: str, prompt: str, |
| 89 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 90 | output_dir: str = None, filename: str = None, |
| 91 | model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str: |
| 92 | """Generate one image with the ModelScope backend.""" |
| 93 | size = _resolve_size(aspect_ratio, image_size) |
| 94 | url = _resolve_url(base_url)+'/v1/images/generations' |
| 95 | common_headers = { |
| 96 | "Authorization": f"Bearer {api_key}", |
| 97 | "Content-Type": "application/json", |
| 98 | } |
| 99 | payload = { |
| 100 | "model": model, |
| 101 | "prompt": prompt, |
| 102 | "size": size.replace("*", "x"), |
| 103 | |
| 104 | } |
| 105 | |
| 106 | print("[ModelScope Models]") |
| 107 | print(f" Model: {model}") |
| 108 | print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}") |
| 109 | print(f" Aspect Ratio: {aspect_ratio}") |
| 110 | print(f" Resolution: {size}") |
| 111 | print() |
| 112 | print(" [..] Generating...", end="", flush=True) |
| 113 | start = time.time() |
| 114 | response = requests.post(url, headers={**common_headers,"X-ModelScope-Async-Mode": "true"}, json=payload, timeout=300) |
| 115 | |
| 116 | if (response.status_code != 200): |
| 117 | raise http_error(response, "ModelScope image generation") |
| 118 | |
| 119 | task_id = response.json()["task_id"] |
| 120 | data = poll_json( |
| 121 | url=f"{_resolve_url(base_url)}/v1/tasks/{task_id}", |
| 122 | headers={**common_headers, "X-ModelScope-Task-Type": "image_generation"}, |
| 123 | status_label="task_status", |
| 124 | ready_values=["SUCCEED"], |
| 125 | failed_values=["FAILED"], |
| 126 | ) |
| 127 | elapsed = time.time() - start |
| 128 | print(f"\n [DONE] Response received ({elapsed:.1f}s)") |
| 129 | path = resolve_output_path(prompt, output_dir, filename, ".png") |
| 130 | return download_image(data["output_images"][0], path) |
| 131 | |
| 132 | def generate(prompt: str, |
| 133 | aspect_ratio: str = "1:1", image_size: str = "1K", |
| 134 | output_dir: str = None, filename: str = None, |
| 135 | model: str = None, max_retries: int = MAX_RETRIES) -> str: |
| 136 | """Generate an image with retries using the ModelScope backend.""" |
| 137 | api_key = require_api_key( |
| 138 | "MODELSCOPE_API_KEY", |
| 139 | message="No API key found. Set MODELSCOPE_API_KEY in the current environment or the project-root .env.", |
| 140 | ) |
| 141 | base_url = os.environ.get("MODELSCOPE_BASE_URL") or DEFAULT_ENDPOINT |
| 142 | resolved_model = model or os.environ.get("MODELSCOPE_MODEL") or DEFAULT_MODEL |
| 143 | |
| 144 | last_error = None |
| 145 | for attempt in range(max_retries + 1): |
| 146 | try: |
| 147 | return _generate_image( |
| 148 | api_key=api_key, |
| 149 | prompt=prompt, |
| 150 | aspect_ratio=aspect_ratio, |
| 151 | image_size=image_size, |
| 152 | output_dir=output_dir, |
| 153 | filename=filename, |
| 154 | model=resolved_model, |
| 155 | base_url=base_url, |
| 156 | ) |
| 157 | except Exception as exc: |
| 158 | last_error = exc |
| 159 | if attempt >= max_retries: |
| 160 | break |
| 161 | limited = is_rate_limit_error(exc) |
| 162 | delay = retry_delay(attempt, rate_limited=limited) |
| 163 | label = "Rate limit hit" if limited else f"Error: {exc}" |
| 164 | print(f"\n [WARN] {label}. Retrying in {delay}s...") |
| 165 | time.sleep(delay) |
| 166 | |
| 167 | raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}") |
| 168 | |
| 169 |