Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(image-gen): add ModelScope backend for image generation (#83)

张子平ec44aa066eca
diff --git a/.env.example b/.env.example
index c4a1f52e..c282c483 100644
--- a/.env.example
+++ b/.env.example
@@ -116,6 +116,11 @@
# OPENROUTER_API_KEY=sk-or-v1-xxx
# OPENROUTER_MODEL=google/gemini-3.1-flash-image-preview
# OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
+#
+# IMAGE_BACKEND=modelscope
+# MODELSCOPE_API_KEY=your-modelscope-key
+# MODELSCOPE_MODEL=Tongyi-MAI/Z-Image-Turbo
+# MODELSCOPE_BASE_URL=https://api-inference.modelscope.cn/v1
# ─────────────────────────────────────────────────────────────
# Multi-provider example / 多提供商共存示例
diff --git a/.gitignore b/.gitignore
index 5e7e87cc..bab91b96 100644
--- a/.gitignore
+++ b/.gitignore
@@ -168,4 +168,4 @@ PERSONAL_NOTES.md
# Completed projects should be moved to examples/
# Use cloud sync (iCloud/Dropbox) for backup and multi-device access
projects/*
-!projects/README.md
\ No newline at end of file
+!projects/README.md
diff --git a/skills/ppt-master/scripts/image_backends/backend_modelscope.py b/skills/ppt-master/scripts/image_backends/backend_modelscope.py
new file mode 100644
index 00000000..0a760c71
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_modelscope.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python3
+"""
+ModelScope image generation backend.
+
+Configuration keys:
+ MODELSCOPE_API_KEY (required)
+ MODELSCOPE_MODEL (optional)
+ MODELSCOPE_BASE_URL (optional)
+"""
+
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import (
+ MAX_RETRIES,
+ http_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+ poll_json,
+ download_image
+)
+
+DEFAULT_ENDPOINT = "https://api-inference.modelscope.cn"
+DEFAULT_MODEL = "Tongyi-MAI/Z-Image-Turbo"
+
+# Resolution must be 64-aligned.
+ASPECT_RATIO_SIZE_MAP = {
+ "512px": {
+ "1:1": "1024*1024",
+ "3:4": "768*1024",
+ "4:3": "1024*768",
+ "9:16": "576*1024",
+ "16:9": "1024*576"
+ },
+ "1K": {
+ "1:1": "1280*1280",
+ "3:4": "960*1280",
+ "4:3": "1280*960",
+ "9:16": "576*1024",
+ "16:9": "1024*576"
+ },
+ "2K": {
+ "1:1": "2048*2048",
+ "3:4": "1536*2048",
+ "4:3": "2048*1536",
+ "9:16": "1152*2048",
+ "16:9": "2048*1152"
+ },
+ "4K": {
+ "1:1": "2048*2048",
+ "3:4": "1920*2560",
+ "4:3": "2560*1920",
+ "9:16": "1728*3072",
+ "16:9": "3072*1728"
+ }
+}
+
+def _resolve_url(base_url: str) -> str:
+ """Resolve the ModelScope generation endpoint."""
+ base = base_url.rstrip("/")
+ if base.endswith("/v1"):
+ base = base.removesuffix("/v1")
+ return base
+
+def _resolve_size(aspect_ratio: str, image_size: str) -> str:
+ """Resolve the target resolution for a ratio and logical size preset.
+
+ Args:
+ aspect_ratio (str): The aspect ratio string. Supported values: '1:1', '3:4', '4:3', '9:16', '16:9'.
+ image_size (str): The logical size preset. Supported values: '512px', '1K', '2K', '4K'.
+ """
+ normalized = normalize_image_size(image_size)
+ size = (ASPECT_RATIO_SIZE_MAP.get(normalized) or {}).get(aspect_ratio)
+ if not size:
+ supported = sorted(ASPECT_RATIO_SIZE_MAP["1K"])
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for ModelScope backend. "
+ f"Supported: {supported}"
+ )
+ return size
+
+
+def _generate_image(api_key: str, prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_ENDPOINT) -> str:
+ """Generate one image with the ModelScope backend."""
+ size = _resolve_size(aspect_ratio, image_size)
+ url = _resolve_url(base_url)+'/v1/images/generations'
+ common_headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "negative_prompt":negative_prompt,
+ "size": size.replace("*", "x"),
+
+ }
+
+ print("[ModelScope Models]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ print(f" Resolution: {size}")
+ print()
+ print(" [..] Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers={**common_headers,"X-ModelScope-Async-Mode": "true"}, json=payload, timeout=300)
+
+ if (response.status_code != 200):
+ raise http_error(response, "ModelScope image generation")
+
+ task_id = response.json()["task_id"]
+ data = poll_json(
+ url=f"{_resolve_url(base_url)}/v1/tasks/{task_id}",
+ headers={**common_headers, "X-ModelScope-Task-Type": "image_generation"},
+ status_label="task_status",
+ ready_values=["SUCCEED"],
+ failed_values=["FAILED"],
+ )
+ elapsed = time.time() - start
+ print(f"\n [DONE] Response received ({elapsed:.1f}s)")
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
+ return download_image(data["output_images"][0], path)
+
+def generate(prompt: str, negative_prompt: str = None,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = None, max_retries: int = MAX_RETRIES) -> str:
+ """Generate an image with retries using the ModelScope backend."""
+ api_key = require_api_key(
+ "MODELSCOPE_API_KEY",
+ message="No API key found. Set MODELSCOPE_API_KEY in the current environment or the project-root .env.",
+ )
+ base_url = os.environ.get("MODELSCOPE_BASE_URL") or DEFAULT_ENDPOINT
+ resolved_model = model or os.environ.get("MODELSCOPE_MODEL") or DEFAULT_MODEL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=image_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if attempt >= max_retries:
+ break
+ limited = is_rate_limit_error(exc)
+ delay = retry_delay(attempt, rate_limited=limited)
+ label = "Rate limit hit" if limited else f"Error: {exc}"
+ print(f"\n [WARN] {label}. Retrying in {delay}s...")
+ time.sleep(delay)
+
+ raise RuntimeError(f"Failed after {max_retries + 1} attempts. Last error: {last_error}")
+
diff --git a/skills/ppt-master/scripts/image_gen.py b/skills/ppt-master/scripts/image_gen.py
index 21e7be86..54f6beef 100644
--- a/skills/ppt-master/scripts/image_gen.py
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -14,6 +14,7 @@ Backend selection (`IMAGE_BACKEND` in `.env` or the current process environment)
IMAGE_BACKEND=qwen -> Alibaba Qwen image backend
IMAGE_BACKEND=zhipu -> Zhipu GLM-Image backend
IMAGE_BACKEND=volcengine -> Volcengine Seedream backend
+ IMAGE_BACKEND=modelscope -> ModelScope backend
IMAGE_BACKEND=siliconflow -> SiliconFlow backend
IMAGE_BACKEND=fal -> fal.ai backend
IMAGE_BACKEND=replicate -> Replicate backend
@@ -78,6 +79,7 @@ IMAGE_ENV_PREFIXES = (
"BIGMODEL_",
"VOLCENGINE_",
"ARK_",
+ "MODELSCOPE_",
"SILICONFLOW_",
"FAL_",
"REPLICATE_",
@@ -148,6 +150,14 @@ BACKEND_REGISTRY = {
"key_hint": "VOLCENGINE_API_KEY / ARK_API_KEY",
"aliases": ["ark", "doubao", "seedream"],
},
+ "modelscope": {
+ "module": "backend_modelscope",
+ "tier": "experimental",
+ "label": "ModelScope",
+ "default_model": "Tongyi-MAI/Z-Image-Turbo",
+ "key_hint": "MODELSCOPE_API_KEY",
+ "aliases": ["modelscope", "model-scope"]
+ },
"stability": {
"module": "backend_stability",
"tier": "extended",