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(scripts): add the Tencent Cloud TokenHub image backend

hugohe3a32818da7d08
diff --git a/.env.example b/.env.example
index e390ce51..89365e6d 100644
--- a/.env.example
+++ b/.env.example
@@ -107,6 +107,21 @@
# VOLCENGINE_MODEL=doubao-seedream-4-5-251128
# VOLCENGINE_BASE_URL=https://operator.las.cn-beijing.volces.com/api/v1
+# ─────────────────────────────────────────────────────────────
+# Example: Tencent Cloud TokenHub / 腾讯云 TokenHub 生图示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=tencent
+# TENCENT_API_KEY=your-tokenhub-key
+# Alternative key / 备选密钥:TOKENHUB_API_KEY
+# TENCENT_MODEL=hy-image-v3
+# TENCENT_BASE_URL=https://tokenhub.tencentmaas.com
+# International base / 国际基址:https://tokenhub-intl.tencentmaas.com
+# Hy: hy-image-v3 uses /v1/wand/hunyuan-image/v3-generation / 混元模型使用此端点
+# Seedream: seedream-image-v5.0-pro / seedream-image-v5.0-lite use /v1/wand/si-image/generation / 即梦模型使用此端点
+# TENCENT_REVISE=true # Hy only / 仅混元
+# TENCENT_WATERMARK=false # Seedream only / 仅即梦
+# TENCENT_OUTPUT_FORMAT=png # Seedream: png / jpeg / 即梦输出格式
+
# ─────────────────────────────────────────────────────────────
# Extended / Experimental backends
# 扩展 / 实验后端
diff --git a/skills/ppt-master/.env.example b/skills/ppt-master/.env.example
index f5af2d98..a7d76da9 100644
--- a/skills/ppt-master/.env.example
+++ b/skills/ppt-master/.env.example
@@ -97,6 +97,21 @@
# VOLCENGINE_MODEL=doubao-seedream-4-5-251128
# VOLCENGINE_BASE_URL=https://operator.las.cn-beijing.volces.com/api/v1
+# ─────────────────────────────────────────────────────────────
+# Example: Tencent Cloud TokenHub / 腾讯云 TokenHub 生图示例
+# ─────────────────────────────────────────────────────────────
+# IMAGE_BACKEND=tencent
+# TENCENT_API_KEY=your-tokenhub-key
+# Alternative key / 备选密钥:TOKENHUB_API_KEY
+# TENCENT_MODEL=hy-image-v3
+# TENCENT_BASE_URL=https://tokenhub.tencentmaas.com
+# International base / 国际基址:https://tokenhub-intl.tencentmaas.com
+# Hy: hy-image-v3 uses /v1/wand/hunyuan-image/v3-generation / 混元模型使用此端点
+# Seedream: seedream-image-v5.0-pro / seedream-image-v5.0-lite use /v1/wand/si-image/generation / 即梦模型使用此端点
+# TENCENT_REVISE=true # Hy only / 仅混元
+# TENCENT_WATERMARK=false # Seedream only / 仅即梦
+# TENCENT_OUTPUT_FORMAT=png # Seedream: png / jpeg / 即梦输出格式
+
# ─────────────────────────────────────────────────────────────
# Extended / Experimental backends
# 扩展 / 实验后端
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.md
index 5c0afd44..1b902529 100644
--- a/skills/ppt-master/scripts/docs/image.md
+++ b/skills/ppt-master/scripts/docs/image.md
@@ -57,6 +57,7 @@ python3 scripts/image_gen.py "A cinematic portrait" --backend minimax
python3 scripts/image_gen.py "A product launch hero image" --backend qwen
python3 scripts/image_gen.py "科技感背景图" --backend zhipu
python3 scripts/image_gen.py "A product KV in cinematic style" --backend volcengine
+python3 scripts/image_gen.py "A mountain landscape" --backend tencent
```
Configuration sources:
diff --git a/skills/ppt-master/scripts/image_backends/backend_tencent.py b/skills/ppt-master/scripts/image_backends/backend_tencent.py
new file mode 100644
index 00000000..f2e7d727
--- /dev/null
+++ b/skills/ppt-master/scripts/image_backends/backend_tencent.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python3
+"""
+Tencent Cloud TokenHub image generation backend.
+
+Configuration keys:
+ TENCENT_API_KEY / TOKENHUB_API_KEY (required)
+ TENCENT_BASE_URL (optional; domestic base or full endpoint)
+ TENCENT_MODEL (optional; defaults to hy-image-v3)
+ TENCENT_REVISE (optional; Hy only, defaults to true)
+ TENCENT_WATERMARK (optional; Seedream only, defaults to false)
+ TENCENT_OUTPUT_FORMAT (optional; Seedream only, png or jpeg)
+"""
+
+import sys
+from pathlib import Path
+
+_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(_SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(_SCRIPTS_DIR))
+
+from console_encoding import configure_utf8_stdio # noqa: E402
+
+configure_utf8_stdio()
+
+if __name__ == "__main__":
+ print(__doc__)
+ print("Use via: python3 skills/ppt-master/scripts/image_gen.py \"prompt\" --backend tencent")
+ raise SystemExit(0 if any(arg in {"-h", "--help", "help"} for arg in sys.argv[1:]) else 1)
+
+import base64
+import math
+import os
+import time
+
+import requests
+
+from image_backends.backend_common import ( # noqa: E402
+ MAX_RETRIES,
+ download_image,
+ http_error,
+ is_permanent_error,
+ is_rate_limit_error,
+ normalize_image_size,
+ require_api_key,
+ resolve_output_path,
+ retry_delay,
+ save_image_bytes,
+)
+
+
+DEFAULT_BASE_URL = "https://tokenhub.tencentmaas.com"
+DEFAULT_MODEL = "hy-image-v3"
+MODEL_ENDPOINTS = {
+ DEFAULT_MODEL: "/v1/wand/hunyuan-image/v3-generation",
+ "seedream-image-v5.0-pro": "/v1/wand/si-image/generation",
+ "seedream-image-v5.0-lite": "/v1/wand/si-image/generation",
+}
+SUPPORTED_MODELS = set(MODEL_ENDPOINTS)
+IMAGE_SIZE_PIXELS = {"512px": 512, "1K": 1024, "2K": 2048, "4K": 4096}
+
+
+def _validate_model(model: str) -> str:
+ """Limit the backend to the synchronous TokenHub image contracts."""
+ resolved = model.strip()
+ if resolved not in SUPPORTED_MODELS:
+ detail = ""
+ if resolved.startswith("vidu"):
+ detail = " Vidu uses an asynchronous submit/query API that is not supported."
+ raise ValueError(
+ f"Unsupported Tencent model '{model}'. Supported: {sorted(SUPPORTED_MODELS)}.{detail}"
+ )
+ return resolved
+
+
+def _resolve_url(base_url: str, model: str = DEFAULT_MODEL) -> str:
+ """Resolve the model endpoint while accepting a full TokenHub URL."""
+ base = base_url.strip().rstrip("/")
+ if "/v1/wand/" in base:
+ return base
+ return base + MODEL_ENDPOINTS[model]
+
+
+def _resolve_size(aspect_ratio: str, image_size: str, model: str = DEFAULT_MODEL) -> str:
+ """Resolve a pixel size from the requested area and aspect ratio."""
+ normalized = normalize_image_size(image_size)
+ pixels = IMAGE_SIZE_PIXELS.get(normalized)
+ if pixels is None:
+ raise ValueError(
+ f"Unsupported image size '{image_size}' for Tencent backend. "
+ f"Supported logical sizes: {list(IMAGE_SIZE_PIXELS)}."
+ )
+ try:
+ ratio_width, ratio_height = (int(value) for value in aspect_ratio.split(":"))
+ if ratio_width <= 0 or ratio_height <= 0:
+ raise ValueError
+ except ValueError as exc:
+ raise ValueError(
+ f"Unsupported aspect ratio '{aspect_ratio}' for Tencent backend. "
+ "Use positive width:height integers, such as 16:9."
+ ) from exc
+
+ if model == "seedream-image-v5.0-lite":
+ pixels = max(pixels, 2048)
+ elif model == "seedream-image-v5.0-pro" and normalized not in {"1K", "2K"}:
+ raise ValueError(
+ f"Unsupported image size '{image_size}' for Seedream pro. "
+ "Use 1K or 2K; 4K requires seedream-image-v5.0-lite."
+ )
+
+ ratio = ratio_width / ratio_height
+ step = 16 if model == DEFAULT_MODEL else 1
+ width = math.floor(pixels * math.sqrt(ratio) / step) * step
+ height = math.floor(pixels / math.sqrt(ratio) / step) * step
+ if model == DEFAULT_MODEL and (
+ pixels > 1024
+ or not (512 <= width <= 2048 and 512 <= height <= 2048)
+ or width * height > 1024 * 1024
+ ):
+ raise ValueError(
+ f"Unsupported image size '{image_size}' / aspect ratio '{aspect_ratio}' for Hy-Image-3.0. "
+ "Width and height must each be 512-2048 pixels in multiples of 16, "
+ "with area <= 1024x1024. Use 1K with a ratio from 1:4 to 4:1, or 512px at 1:1."
+ )
+ return f"{width}x{height}"
+
+
+def _read_bool(name: str, default: bool) -> bool:
+ """Read a boolean provider option without silently accepting typos."""
+ value = os.environ.get(name, str(default)).strip().lower()
+ if value in {"true", "1", "yes", "on"}:
+ return True
+ if value in {"false", "0", "no", "off"}:
+ return False
+ raise ValueError(f"Invalid argument: set {name} to true or false.")
+
+
+def _generate_image(api_key: str, prompt: str,
+ aspect_ratio: str = "1:1", image_size: str = "1K",
+ output_dir: str = None, filename: str = None,
+ model: str = DEFAULT_MODEL, base_url: str = DEFAULT_BASE_URL) -> str:
+ """Generate one image with the Tencent backend."""
+ model = _validate_model(model)
+ size = _resolve_size(aspect_ratio, image_size, model)
+ url = _resolve_url(base_url, model)
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": model,
+ "prompt": prompt,
+ "size": size,
+ }
+ output_format = "png"
+ if model == DEFAULT_MODEL:
+ payload["revise"] = _read_bool("TENCENT_REVISE", True)
+ else:
+ output_format = (os.environ.get("TENCENT_OUTPUT_FORMAT") or "png").strip().lower()
+ if output_format not in {"png", "jpeg"}:
+ raise ValueError("Invalid argument: set TENCENT_OUTPUT_FORMAT to png or jpeg.")
+ payload.update({
+ "watermark": _read_bool("TENCENT_WATERMARK", False),
+ "response_format": "url",
+ "output_format": output_format,
+ })
+
+ print("[Tencent Cloud TokenHub]")
+ print(f" Model: {model}")
+ print(f" Prompt: {prompt[:120]}{'...' if len(prompt) > 120 else ''}")
+ print(f" Aspect Ratio: {aspect_ratio}")
+ if model == "seedream-image-v5.0-lite" and normalize_image_size(image_size) in {"512px", "1K"}:
+ print(f" [INFO] Seedream lite requires at least 2K; upgrading {image_size} to 2K.")
+ print(f" Resolution: {size}")
+ print()
+ print(" [..] Generating...", end="", flush=True)
+ start = time.time()
+ response = requests.post(url, headers=headers, json=payload, timeout=300)
+ elapsed = time.time() - start
+ print(f"\n [DONE] Response received ({elapsed:.1f}s)")
+
+ if response.status_code != 200:
+ raise http_error(response, "Tencent image generation")
+
+ data = response.json()
+ items = data.get("data") or []
+ item = items[0] if items and isinstance(items[0], dict) else {}
+ image_url = item.get("url")
+ image_b64 = item.get("b64_json") if model != DEFAULT_MODEL else None
+ if not image_url and not image_b64:
+ raise RuntimeError(f"Tencent response missing image URL or base64 data: {data}")
+
+ path = resolve_output_path(prompt, output_dir, filename, f".{output_format}")
+ if image_url:
+ return download_image(image_url, path)
+ return save_image_bytes(base64.b64decode(image_b64), path, content_type=f"image/{output_format}")
+
+
+def generate(prompt: str,
+ 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 Tencent backend."""
+ resolved_model = _validate_model(model or os.environ.get("TENCENT_MODEL") or DEFAULT_MODEL)
+ normalized_size = normalize_image_size(image_size)
+ _resolve_size(aspect_ratio, normalized_size, resolved_model)
+ prompt_limit = 8192 if resolved_model == DEFAULT_MODEL else 600
+ if not prompt or len(prompt) > prompt_limit:
+ raise ValueError(f"Invalid request: {resolved_model} requires a prompt of 1-{prompt_limit} characters.")
+ api_key = require_api_key(
+ "TENCENT_API_KEY",
+ "TOKENHUB_API_KEY",
+ message=(
+ "No API key found. Set TENCENT_API_KEY or TOKENHUB_API_KEY "
+ "in the current environment or a .env file."
+ ),
+ )
+ base_url = os.environ.get("TENCENT_BASE_URL") or DEFAULT_BASE_URL
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ try:
+ return _generate_image(
+ api_key=api_key,
+ prompt=prompt,
+ aspect_ratio=aspect_ratio,
+ image_size=normalized_size,
+ output_dir=output_dir,
+ filename=filename,
+ model=resolved_model,
+ base_url=base_url,
+ )
+ except Exception as exc:
+ last_error = exc
+ if is_permanent_error(exc):
+ raise
+ 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 12b6eeb5..7e99db30 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=tencent -> Tencent Cloud TokenHub backend
IMAGE_BACKEND=modelscope -> ModelScope backend
IMAGE_BACKEND=siliconflow -> SiliconFlow backend
IMAGE_BACKEND=fal -> fal.ai backend
@@ -76,6 +77,8 @@ IMAGE_ENV_PREFIXES = (
"VOLCENGINE_",
"LAS_",
"ARK_",
+ "TENCENT_",
+ "TOKENHUB_",
"MODELSCOPE_",
"SILICONFLOW_",
"FAL_",
@@ -154,6 +157,15 @@ BACKEND_REGISTRY = {
"key_hint": "LAS_API_KEY / VOLCENGINE_API_KEY / ARK_API_KEY",
"aliases": ["ark", "doubao", "seedream"],
},
+ "tencent": {
+ "module": "backend_tencent",
+ "tier": "extended",
+ "label": "Tencent Cloud TokenHub",
+ "default_model": "hy-image-v3",
+ "default_image_size": "1K",
+ "key_hint": "TENCENT_API_KEY / TOKENHUB_API_KEY",
+ "aliases": ["tokenhub", "hunyuan", "tencentmaas"],
+ },
"modelscope": {
"module": "backend_modelscope",
"tier": "experimental",
diff --git a/skills/ppt-master/scripts/tests/test_image_backend_tencent.py b/skills/ppt-master/scripts/tests/test_image_backend_tencent.py
new file mode 100644
index 00000000..2e6486e6
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_image_backend_tencent.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""Regression tests for the Tencent Cloud TokenHub image backend."""
+
+import base64
+import io
+import os
+import sys
+import tempfile
+import unittest
+from contextlib import ExitStack, redirect_stdout
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+import image_gen # noqa: E402
+from image_backends import backend_tencent # noqa: E402
+
+
+class TencentBackendTests(unittest.TestCase):
+ def setUp(self) -> None:
+ stack = ExitStack()
+ self.addCleanup(stack.close)
+ stack.enter_context(patch.dict(os.environ, {"TENCENT_API_KEY": "test-key"}, clear=True))
+ self.stdout = stack.enter_context(redirect_stdout(io.StringIO()))
+ self.response = Mock(status_code=200)
+ self.response.json.return_value = {
+ "data": [{"url": "https://example.invalid/result.png"}],
+ "request_id": "test-request",
+ }
+ self.post = stack.enter_context(patch.object(
+ backend_tencent.requests, "post", return_value=self.response,
+ ))
+ stack.enter_context(patch.object(
+ backend_tencent.requests, "get", side_effect=AssertionError("Unexpected network request"),
+ ))
+ self.download = stack.enter_context(patch.object(
+ backend_tencent, "download_image", side_effect=lambda url, path: path,
+ ))
+ self.save = stack.enter_context(patch.object(
+ backend_tencent, "save_image_bytes", side_effect=lambda data, path, **kwargs: path,
+ ))
+ self.sleep = stack.enter_context(patch.object(backend_tencent.time, "sleep"))
+
+ def test_hy_endpoint_payload_and_download(self) -> None:
+ result = backend_tencent.generate("A mountain", aspect_ratio="16:9", filename="hero.png")
+
+ self.post.assert_called_once_with(
+ "https://tokenhub.tencentmaas.com/v1/wand/hunyuan-image/v3-generation",
+ headers={"Authorization": "Bearer test-key", "Content-Type": "application/json"},
+ json={
+ "model": "hy-image-v3", "prompt": "A mountain",
+ "size": "1360x768", "revise": True,
+ },
+ timeout=300,
+ )
+ self.download.assert_called_once_with("https://example.invalid/result.png", "hero.png")
+ self.save.assert_not_called()
+ self.assertEqual(result, "hero.png")
+ self.assertIn("Resolution: 1360x768", self.stdout.getvalue())
+
+ def test_seedream_endpoints_and_payloads(self) -> None:
+ for model, resolution in (
+ ("seedream-image-v5.0-pro", "1024x1024"),
+ ("seedream-image-v5.0-lite", "2048x2048"),
+ ):
+ with self.subTest(model=model):
+ self.post.reset_mock()
+ backend_tencent.generate("A mountain", model=model)
+ self.post.assert_called_once_with(
+ "https://tokenhub.tencentmaas.com/v1/wand/si-image/generation",
+ headers={"Authorization": "Bearer test-key", "Content-Type": "application/json"},
+ json={
+ "model": model, "prompt": "A mountain", "size": resolution,
+ "watermark": False, "response_format": "url", "output_format": "png",
+ },
+ timeout=300,
+ )
+
+ def test_hy_area_limit_and_orientation(self) -> None:
+ for ratio in ("16:9", "1:1", "9:16"):
+ with self.subTest(ratio=ratio):
+ resolution = backend_tencent._resolve_size(ratio, "1K")
+ width, height = map(int, resolution.split("x"))
+ expected_width, expected_height = map(int, ratio.split(":"))
+ self.assertLessEqual(width * height, 1024 * 1024)
+ self.assertGreater(width * height, 0.97 * 1024 * 1024)
+ self.assertAlmostEqual(width / height, expected_width / expected_height, delta=0.02)
+ for dimension in (width, height):
+ self.assertGreaterEqual(dimension, 512)
+ self.assertLessEqual(dimension, 2048)
+ self.assertEqual(dimension % 16, 0)
+
+ def test_hy_dimension_boundaries(self) -> None:
+ for ratio, logical_size, resolution in (
+ ("1:1", "512px", "512x512"),
+ ("4:1", "1K", "2048x512"),
+ ("1:4", "1K", "512x2048"),
+ ):
+ with self.subTest(ratio=ratio, size=logical_size):
+ self.assertEqual(backend_tencent._resolve_size(ratio, logical_size), resolution)
+
+ def test_hy_rejects_impossible_sizes_before_request(self) -> None:
+ for ratio, logical_size in (
+ ("1:1", "2K"), ("1:1", "4K"), ("16:9", "512px"),
+ ("1:8", "1K"), ("8:1", "1K"),
+ ):
+ with self.subTest(ratio=ratio, size=logical_size):
+ with self.assertRaisesRegex(ValueError, "512-2048.*multiples of 16.*1024x1024"):
+ backend_tencent.generate("test", aspect_ratio=ratio, image_size=logical_size)
+ self.post.assert_not_called()
+
+ def test_seedream_lite_upgrades_small_sizes_once(self) -> None:
+ for logical_size in ("1K", "512px"):
+ with self.subTest(size=logical_size):
+ self.stdout.seek(0)
+ self.stdout.truncate(0)
+ backend_tencent.generate("test", model="seedream-image-v5.0-lite", image_size=logical_size)
+ self.assertEqual(self.post.call_args.kwargs["json"]["size"], "2048x2048")
+ self.assertEqual(self.stdout.getvalue().count(f"upgrading {logical_size} to 2K"), 1)
+ self.assertIn("Resolution: 2048x2048", self.stdout.getvalue())
+
+ def test_seedream_area_scales_across_cli_ratios(self) -> None:
+ for model, logical_size, side in (
+ ("seedream-image-v5.0-pro", "1K", 1024),
+ ("seedream-image-v5.0-pro", "2K", 2048),
+ ("seedream-image-v5.0-lite", "2K", 2048),
+ ("seedream-image-v5.0-lite", "4K", 4096),
+ ):
+ for ratio in image_gen.ALL_ASPECT_RATIOS:
+ with self.subTest(model=model, size=logical_size, ratio=ratio):
+ size = backend_tencent._resolve_size(ratio, logical_size, model)
+ width, height = map(int, size.split("x"))
+ ratio_width, ratio_height = map(int, ratio.split(":"))
+ self.assertAlmostEqual(width * height / side ** 2, 1.0, delta=0.004)
+ self.assertAlmostEqual(width / height, ratio_width / ratio_height, delta=0.025)
+
+ def test_seedream_pro_rejects_512px_and_4k(self) -> None:
+ for logical_size in ("512px", "4K"):
+ with self.subTest(size=logical_size):
+ with self.assertRaisesRegex(ValueError, "Use 1K or 2K"):
+ backend_tencent.generate("test", model="seedream-image-v5.0-pro", image_size=logical_size)
+ self.post.assert_not_called()
+
+ def test_invalid_ratio_and_size_fail_before_request(self) -> None:
+ for ratio in ("invalid", "0:1", "1:0", "-1:2", "1:2:3"):
+ with self.subTest(ratio=ratio):
+ with self.assertRaisesRegex(ValueError, "Unsupported aspect ratio"):
+ backend_tencent.generate("test", aspect_ratio=ratio)
+ with self.assertRaisesRegex(ValueError, "Unsupported image size"):
+ backend_tencent.generate("test", image_size="3K")
+ self.post.assert_not_called()
+
+ def test_unknown_model_lists_supported_models(self) -> None:
+ with self.assertRaises(ValueError) as caught:
+ backend_tencent.generate("test", model="other-model")
+ for model in backend_tencent.SUPPORTED_MODELS:
+ self.assertIn(model, str(caught.exception))
+ self.post.assert_not_called()
+
+ def test_vidu_reports_unsupported_async_api(self) -> None:
+ with self.assertRaisesRegex(ValueError, "Vidu.*asynchronous submit/query API.*not supported"):
+ backend_tencent.generate("test", model="vidu-image-q2")
+ self.post.assert_not_called()
+
+ def test_missing_key_names_both_options(self) -> None:
+ os.environ.pop("TENCENT_API_KEY")
+ with self.assertRaisesRegex(ValueError, "No API key found.*TENCENT_API_KEY or TOKENHUB_API_KEY"):
+ backend_tencent.generate("test")
+ self.post.assert_not_called()
+ self.sleep.assert_not_called()
+
+ def test_key_fallback_and_primary_precedence(self) -> None:
+ os.environ["TOKENHUB_API_KEY"] = "fallback-key"
+ backend_tencent.generate("test")
+ self.assertEqual(self.post.call_args.kwargs["headers"]["Authorization"], "Bearer test-key")
+ os.environ["TENCENT_API_KEY"] = ""
+ backend_tencent.generate("test")
+ self.assertEqual(self.post.call_args.kwargs["headers"]["Authorization"], "Bearer fallback-key")
+
+ def test_missing_image_includes_response_body(self) -> None:
+ for model in backend_tencent.SUPPORTED_MODELS:
+ for items in (None, [], [{}], [{"url": ""}]):
+ with self.subTest(model=model, items=items):
+ self.response.json.return_value = {"data": items, "request_id": "missing-image"}
+ with self.assertRaisesRegex(RuntimeError, "missing image URL.*missing-image"):
+ backend_tencent.generate("test", model=model, max_retries=0)
+ self.download.assert_not_called()
+ self.save.assert_not_called()
+
+ def test_full_endpoint_is_used_without_appending_path(self) -> None:
+ for model, endpoint in backend_tencent.MODEL_ENDPOINTS.items():
+ with self.subTest(model=model):
+ url = "https://tokenhub-intl.tencentmaas.com" + endpoint
+ os.environ["TENCENT_BASE_URL"] = url + "/"
+ backend_tencent.generate("test", model=model)
+ self.assertEqual(self.post.call_args.args[0], url)
+
+ def test_international_base_selects_model_endpoint(self) -> None:
+ os.environ["TENCENT_BASE_URL"] = "https://tokenhub-intl.tencentmaas.com/"
+ backend_tencent.generate("test")
+ self.assertEqual(
+ self.post.call_args.args[0],
+ "https://tokenhub-intl.tencentmaas.com/v1/wand/hunyuan-image/v3-generation",
+ )
+
+ def test_provider_options_apply_only_to_their_model(self) -> None:
+ os.environ.update({
+ "TENCENT_REVISE": "false", "TENCENT_WATERMARK": "true", "TENCENT_OUTPUT_FORMAT": "jpeg",
+ })
+ self.assertEqual(backend_tencent.generate("test"), "test.png")
+ self.assertIs(self.post.call_args.kwargs["json"]["revise"], False)
+ self.assertNotIn("watermark", self.post.call_args.kwargs["json"])
+ self.assertNotIn("output_format", self.post.call_args.kwargs["json"])
+ self.assertEqual(backend_tencent.generate("test", model="seedream-image-v5.0-pro"), "test.jpeg")
+ self.assertIs(self.post.call_args.kwargs["json"]["watermark"], True)
+ self.assertEqual(self.post.call_args.kwargs["json"]["output_format"], "jpeg")
+ self.assertNotIn("revise", self.post.call_args.kwargs["json"])
+
+ def test_seedream_base64_response_uses_shared_save(self) -> None:
+ image_bytes = b"\x89PNG\r\n\x1a\nminimal-mocked-image"
+ self.response.json.return_value = {"data": [{"b64_json": base64.b64encode(image_bytes).decode("ascii")}]}
+ result = backend_tencent.generate("test", model="seedream-image-v5.0-pro")
+ self.save.assert_called_once_with(image_bytes, "test.png", content_type="image/png")
+ self.download.assert_not_called()
+ self.assertEqual(result, "test.png")
+
+ def test_permanent_http_errors_do_not_retry(self) -> None:
+ for status, code in ((400, "FieldInvalid"), (401, "Unauthorized"), (422, "CreationPolicyViolation")):
+ with self.subTest(status=status):
+ self.post.reset_mock()
+ self.response.status_code = status
+ self.response.text = '{"error": {"code": "' + code + '"}}'
+ with self.assertRaisesRegex(RuntimeError, rf"\({status}\).*{code}"):
+ backend_tencent.generate("test")
+ self.post.assert_called_once()
+ self.sleep.assert_not_called()
+
+ def test_rate_limit_uses_shared_exponential_backoff(self) -> None:
+ limited = Mock(status_code=429, text='{"error": {"code": "ConcurrencyLimit"}}')
+ self.post.side_effect = [limited, limited, self.response]
+ backend_tencent.generate("test")
+ self.assertEqual(self.post.call_count, 3)
+ self.assertEqual([call.args[0] for call in self.sleep.call_args_list], [10, 20])
+
+ def test_server_error_is_retried(self) -> None:
+ failure = Mock(status_code=500, text='{"error": {"code": "InternalError"}}')
+ self.post.side_effect = [failure, self.response]
+ backend_tencent.generate("test")
+ self.sleep.assert_called_once_with(5)
+ self.assertEqual(self.post.call_count, 2)
+
+ def test_prompt_limits_fail_before_request(self) -> None:
+ for model, limit in (("hy-image-v3", 8192), ("seedream-image-v5.0-pro", 600)):
+ with self.subTest(model=model):
+ with self.assertRaisesRegex(ValueError, f"1-{limit} characters"):
+ backend_tencent.generate("x" * (limit + 1), model=model)
+ self.post.assert_not_called()
+
+ def test_invalid_provider_options_do_not_retry(self) -> None:
+ for key, model in (
+ ("TENCENT_REVISE", "hy-image-v3"),
+ ("TENCENT_WATERMARK", "seedream-image-v5.0-pro"),
+ ("TENCENT_OUTPUT_FORMAT", "seedream-image-v5.0-pro"),
+ ):
+ with self.subTest(key=key), patch.dict(os.environ, {key: "invalid"}):
+ with self.assertRaisesRegex(ValueError, key):
+ backend_tencent.generate("test", model=model)
+ self.post.assert_not_called()
+ self.sleep.assert_not_called()
+
+ def test_registry_aliases_and_env_file_reach_backend(self) -> None:
+ env_text = (
+ "IMAGE_BACKEND=tokenhub\nTOKENHUB_API_KEY=dotenv-key\n"
+ "TENCENT_MODEL=seedream-image-v5.0-pro\n"
+ "TENCENT_BASE_URL=https://tokenhub-intl.tencentmaas.com\n"
+ "TENCENT_WATERMARK=true\nTENCENT_OUTPUT_FORMAT=jpeg\nTENCENT_REVISE=false\n"
+ )
+ os.environ.pop("TENCENT_API_KEY")
+ with tempfile.TemporaryDirectory() as temp_dir:
+ env_path = Path(temp_dir) / ".env"
+ env_path.write_text(env_text, encoding="utf-8")
+ with patch("config.resolve_env_path", return_value=env_path):
+ image_gen._load_image_env_file()
+ self.assertEqual(os.environ["TENCENT_REVISE"], "false")
+ for alias in ("tencent", "tokenhub", "hunyuan", "tencentmaas"):
+ self.assertEqual(image_gen.BACKEND_ALIASES[alias], "tencent")
+ backend, name = image_gen._resolve_backend()
+ self.assertEqual(name, "tencent")
+ self.assertIs(backend, backend_tencent)
+ self.assertEqual(backend.generate("test"), "test.jpeg")
+ self.assertEqual(
+ self.post.call_args.args[0], "https://tokenhub-intl.tencentmaas.com/v1/wand/si-image/generation",
+ )
+ self.assertEqual(self.post.call_args.kwargs["headers"]["Authorization"], "Bearer dotenv-key")
+ self.assertIs(self.post.call_args.kwargs["json"]["watermark"], True)
+
+
+if __name__ == "__main__":
+ unittest.main()