Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

feat(video): add MuAPI material source (#1367)

Anil Chandra Naidu Matcha5ddb15d7e7cc
diff --git a/README-en.md b/README-en.md
index ceb48be3..bf326922 100644
--- a/README-en.md
+++ b/README-en.md
@@ -197,6 +197,7 @@ Thanks to [Kimi](https://platform.kimi.ai?track_id=track-f6b0a640d35c41deb03b247
- [x] Use the native [Volcano Engine Ark Seedance](https://console.volcengine.com/ark/region:ark+cn-beijing/apikey) integration to generate cohesive visuals from individual script segments
- [x] Turn script keywords into original video footage with [WaveSpeed AI](https://wavespeed.ai)
- [x] Access Seedance, Wan, and other text-to-video models through [OFox](https://ofox.ai) with a single API key
+- [x] Generate 3–12 second AI video materials through the asynchronous [MuAPI](https://muapi.ai) text-to-video API, with configurable endpoint, aspect ratio, resolution, and polling
- [x] Connect [OpenAI-compatible text-to-image](https://platform.openai.com/docs/guides/image-generation) services or custom image gateways and turn generated images into animated video clips
- [x] Adjust clip duration, frame fitting, and material order to suit different aspect ratios and storytelling styles
diff --git a/README-ja.md b/README-ja.md
index b856fb6d..7e79298a 100644
--- a/README-ja.md
+++ b/README-ja.md
@@ -176,6 +176,7 @@
- [x] [Volcano Engine Ark Seedance](https://console.volcengine.com/ark/region:ark+cn-beijing/apikey) をネイティブに統合し、台本の各セグメントから一貫した動画素材を生成可能
- [x] [WaveSpeed AI](https://wavespeed.ai) によるテキスト動画生成で、台本のキーワードからオリジナル素材を作成可能
- [x] [OFox](https://ofox.ai) のマルチモデルテキスト動画生成に対応し、1 つの API キーで Seedance、Wan などのモデルを利用可能
+- [x] 非同期の [MuAPI](https://muapi.ai) テキスト動画 API で 3~12 秒の AI 素材を生成し、Endpoint、アスペクト比、解像度、ポーリングを設定可能
- [x] [OpenAI 互換の画像生成](https://platform.openai.com/docs/guides/image-generation)サービスや独自の画像ゲートウェイを接続し、生成画像を動きのある動画クリップに変換可能
- [x] クリップの長さ、フレームへの合わせ方、素材の使用順を調整し、アスペクト比や構成に合わせた編集が可能
diff --git a/README.md b/README.md
index e5a645dd..45154707 100644
--- a/README.md
+++ b/README.md
@@ -197,6 +197,7 @@
- [x] 原生接入 [火山引擎方舟 Seedance](https://console.volcengine.com/ark/region:ark+cn-beijing/apikey),可根据脚本片段生成连贯的视频画面
- [x] 支持 [WaveSpeed AI](https://wavespeed.ai) 文生视频,可根据脚本关键词快速生成原创素材
- [x] 支持 [OFox](https://ofox.ai) 多模型文生视频,一个 API Key 即可调用 Seedance、Wan 等模型
+- [x] 通过异步 [MuAPI](https://muapi.ai) 文生视频接口生成 3~12 秒 AI 视频素材,并支持配置 Endpoint、画幅、分辨率和轮询参数
- [x] 支持 [OpenAI 兼容文生图](https://platform.openai.com/docs/guides/image-generation),可连接云端服务或自定义图片网关,并将生成图片转换为动态视频片段
- [x] 支持调整片段时长、画面适配方式和素材匹配顺序,以适配不同画幅和叙事节奏
diff --git a/app/services/material.py b/app/services/material.py
index f1de37ae..7797013e 100644
--- a/app/services/material.py
+++ b/app/services/material.py
@@ -20,6 +20,7 @@ from app.models.schema import MaterialInfo, VideoAspect, VideoConcatMode
from app.services import (
material_cache,
metaso_minimax,
+ muapi,
ofox,
task_artifacts,
video,
@@ -1004,6 +1005,33 @@ def _save_generated_video_with_retry(
return ""
+def _get_downloaded_video_duration(video_path: str) -> float:
+ """Read the usable duration from the downloaded media file."""
+ clip = None
+ try:
+ clip = VideoFileClip(video_path)
+ duration = float(clip.duration or 0)
+ except Exception as exc:
+ raise ValueError(
+ f"downloaded video duration could not be measured: {video_path}"
+ ) from exc
+ finally:
+ if clip is not None:
+ try:
+ clip.close()
+ except Exception as close_error:
+ logger.warning(
+ "failed to close downloaded video after duration probe: "
+ f"path={video_path}, error={type(close_error).__name__}, "
+ f"detail={close_error}"
+ )
+ if not math.isfinite(duration) or duration <= 0:
+ raise ValueError(
+ f"downloaded video duration is not positive and finite: {video_path}"
+ )
+ return duration
+
+
def save_video(video_url: str, save_dir: str = "") -> str:
if not save_dir:
save_dir = utils.storage_dir("cache_videos")
@@ -1729,6 +1757,17 @@ def download_videos(
max_clip_duration=max_clip_duration,
material_directory=material_directory,
)
+ if source == "muapi":
+ # MuAPI 的模型端点会创建异步付费任务。逐段提交并在覆盖配音时长后
+ # 停止,避免把未使用的脚本关键词也发送到远端。
+ return _download_videos_muapi_on_demand(
+ task_id=task_id,
+ search_terms=search_terms,
+ video_aspect=video_aspect,
+ audio_duration=audio_duration,
+ max_clip_duration=max_clip_duration,
+ material_directory=material_directory,
+ )
if source == "metaso_minimax":
# 秘塔 MiniMax 同样按远端异步任务计费。它与火山方舟的请求体相似,
# 但任务查询路径和响应结构不同,因此只共享本地按需生成语义,不复用
@@ -2126,6 +2165,126 @@ def _download_videos_ofox_on_demand(
return video_paths
+def _download_videos_muapi_on_demand(
+ *,
+ task_id: str,
+ search_terms: List[str],
+ video_aspect: VideoAspect,
+ audio_duration: float,
+ max_clip_duration: int,
+ material_directory: str,
+) -> List[str]:
+ """Generate MuAPI materials until the narration duration is covered."""
+ video_paths: List[str] = []
+ material_sources: list[dict[str, Any]] = []
+
+ try:
+ required_duration = float(audio_duration)
+ except (TypeError, ValueError) as exc:
+ raise muapi.MuAPIError(
+ "MuAPI audio duration must be a finite number"
+ ) from exc
+ if not math.isfinite(required_duration):
+ raise muapi.MuAPIError("MuAPI audio duration must be a finite number")
+ if required_duration <= 0:
+ logger.warning(
+ "skip MuAPI paid generation because required audio duration is "
+ f"not positive: duration={required_duration}"
+ )
+ _persist_material_sources(task_id, material_sources)
+ return video_paths
+
+ try:
+ clip_duration = int(max_clip_duration)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise muapi.MuAPIError(
+ "MuAPI clip duration must be a positive integer"
+ ) from exc
+ if clip_duration <= 0:
+ raise muapi.MuAPIError("MuAPI clip duration must be a positive integer")
+
+ total_duration = 0.0
+ for search_term in search_terms:
+ try:
+ video_items = muapi.generate_videos(
+ search_term=search_term,
+ minimum_duration=clip_duration,
+ video_aspect=video_aspect,
+ )
+ except muapi.MuAPIUnconfirmedTaskError as exc:
+ # An ambiguous paid submission must stop the loop: retrying with the
+ # next keyword could create a duplicate charge. The task ID is kept
+ # for task-service recovery when the provider returned one.
+ logger.error(
+ "stop submitting new MuAPI tasks because the last paid task "
+ f"is unconfirmed: task_id={exc.task_id or 'unknown'}, "
+ f"detail={exc}"
+ )
+ _persist_material_sources(task_id, material_sources)
+ raise
+ except muapi.MuAPIError as exc:
+ logger.error(f"MuAPI generation failed before completion: {exc}")
+ _persist_material_sources(task_id, material_sources)
+ raise
+
+ for item in video_items:
+ saved_video_path = _save_generated_video_with_retry(
+ item.url, material_directory, "muapi"
+ )
+ if not saved_video_path:
+ # The remote job completed and may already have incurred a
+ # charge. Do not submit a replacement task after download
+ # failure; return the remote ID for manual recovery instead.
+ source_info = (
+ item.source_info if isinstance(item.source_info, dict) else {}
+ )
+ remote_task_id = str(source_info.get("asset_id") or "").strip()
+ _persist_material_sources(task_id, material_sources)
+ raise muapi.MuAPIDownloadError(
+ "MuAPI generated a paid video but the result could not be "
+ f"downloaded: id={remote_task_id or 'unknown'}",
+ task_id=remote_task_id,
+ )
+ logger.info(f"video saved: {saved_video_path}")
+ video_paths.append(saved_video_path)
+ try:
+ material_sources.append(_material_source_record(item, saved_video_path))
+ except Exception as source_error:
+ logger.warning(
+ "failed to prepare generated material source record: "
+ f"provider=muapi, error={type(source_error).__name__}, "
+ f"detail={source_error}"
+ )
+ try:
+ downloaded_duration = _get_downloaded_video_duration(saved_video_path)
+ except Exception as duration_error:
+ source_info = (
+ item.source_info if isinstance(item.source_info, dict) else {}
+ )
+ remote_task_id = str(source_info.get("asset_id") or "").strip()
+ _persist_material_sources(task_id, material_sources)
+ raise muapi.MuAPIDownloadError(
+ "MuAPI generated a paid video but its downloaded duration "
+ "could not be measured: "
+ f"id={remote_task_id or 'unknown'}",
+ task_id=remote_task_id,
+ ) from duration_error
+ total_duration += min(clip_duration, downloaded_duration)
+ if total_duration >= required_duration:
+ break
+ if total_duration >= required_duration:
+ logger.info(
+ "generated MuAPI materials cover the required duration; stop "
+ f"submitting paid tasks: generated={total_duration:.1f}s, "
+ f"required={required_duration:.1f}s"
+ )
+ break
+
+ logger.success(f"generated and downloaded {len(video_paths)} MuAPI videos")
+ _persist_material_sources(task_id, material_sources)
+ return video_paths
+
+
def _download_videos_metaso_minimax_on_demand(
*,
task_id: str,
diff --git a/app/services/muapi.py b/app/services/muapi.py
new file mode 100644
index 00000000..7ea66bc1
--- /dev/null
+++ b/app/services/muapi.py
@@ -0,0 +1,456 @@
+"""MuAPI asynchronous text-to-video client.
+
+The provider-specific submit/poll protocol lives here so the material service
+only needs to deal with ``MaterialInfo`` and local downloads. MuAPI jobs are
+billable once accepted, so submission is deliberately never retried when the
+response is ambiguous.
+"""
+
+from __future__ import annotations
+
+import math
+import os
+import time
+from collections.abc import Mapping
+from typing import Any
+from urllib.parse import quote_plus, urlsplit
+
+import requests
+from loguru import logger
+
+from app.config import config
+from app.models.schema import MaterialInfo, VideoAspect
+
+
+DEFAULT_BASE_URL = "https://api.muapi.ai/api/v1"
+# The budget Seedance Lite route supports the three MoneyPrinterTurbo aspect
+# ratios, 3-12 second clips, and 480p/720p/1080p output.
+DEFAULT_ENDPOINT = "seedance-lite-t2v"
+DEFAULT_RESOLUTION = "480p"
+DEFAULT_MIN_DURATION_SECONDS = 3
+DEFAULT_MAX_DURATION_SECONDS = 12
+DEFAULT_POLL_INTERVAL_SECONDS = 5.0
+DEFAULT_RUN_TIMEOUT_SECONDS = 1800.0
+MAX_POLL_RETRIES = 5
+RETRY_BASE_SECONDS = 1.0
+MAX_ERROR_TEXT_LENGTH = 500
+RETRYABLE_STATUS_CODES = frozenset({429, 500, 502, 503, 504})
+ACTIVE_STATUSES = frozenset({"queued", "pending", "processing"})
+TERMINAL_SUCCESS_STATUSES = frozenset({"completed"})
+TERMINAL_FAILURE_STATUSES = frozenset(
+ {"failed", "cancelled", "canceled", "expired"}
+)
+
+
+class MuAPIError(RuntimeError):
+ """Deterministic configuration, request, or response error."""
+
+ def __init__(self, message: str, task_id: str = ""):
+ super().__init__(message)
+ self.task_id = task_id
+
+
+class MuAPIUnconfirmedTaskError(MuAPIError):
+ """The remote job may exist, but its final state cannot be confirmed."""
+
+
+class MuAPIDownloadError(MuAPIError):
+ """A billable job completed, but its output could not be downloaded."""
+
+
+def get_api_key(settings: Mapping[str, Any] | None = None) -> str:
+ """Read the dedicated MuAPI key, then the provider-specific environment key."""
+ settings = config.app if settings is None else settings
+ configured = str(settings.get("muapi_api_key", "") or "").strip()
+ environment_key = os.getenv("MUAPI_API_KEY", "").strip()
+ return configured or environment_key
+
+
+def is_enabled(settings: Mapping[str, Any] | None = None) -> bool:
+ return bool(get_api_key(settings))
+
+
+def _base_url() -> str:
+ value = str(
+ config.app.get("muapi_base_url", DEFAULT_BASE_URL) or DEFAULT_BASE_URL
+ ).strip().rstrip("/")
+ parsed = urlsplit(value)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise MuAPIError("muapi_base_url must be an absolute HTTP(S) URL")
+ return value
+
+
+def _endpoint() -> str:
+ value = str(
+ config.app.get("muapi_video_endpoint", DEFAULT_ENDPOINT) or DEFAULT_ENDPOINT
+ ).strip().strip("/")
+ # The setting is a path below /api/v1, never an arbitrary URL. This keeps
+ # credentials in the configured MuAPI host and makes the generated request
+ # straightforward to audit.
+ if not value or "://" in value or "?" in value or "#" in value:
+ raise MuAPIError(
+ "muapi_video_endpoint must be a non-empty relative endpoint path"
+ )
+ return value
+
+
+def _resolution() -> str:
+ value = str(
+ config.app.get("muapi_resolution", DEFAULT_RESOLUTION) or ""
+ ).strip()
+ return value or DEFAULT_RESOLUTION
+
+
+def _config_bool(key: str, default: bool) -> bool:
+ value = config.app.get(key, default)
+ if isinstance(value, str):
+ return value.strip().lower() not in {"0", "false", "no", "off", ""}
+ return bool(value)
+
+
+def _bounded_float(key: str, default: float, minimum: float, maximum: float) -> float:
+ try:
+ value = float(config.app.get(key, default))
+ except (TypeError, ValueError):
+ return default
+ if not math.isfinite(value):
+ return default
+ return min(max(value, minimum), maximum)
+
+
+def _duration_bounds() -> tuple[int, int]:
+ def read(key: str, default: int) -> int:
+ try:
+ value = int(config.app.get(key, default))
+ except (TypeError, ValueError):
+ return default
+ return value if value >= 1 else default
+
+ minimum = read("muapi_min_duration", DEFAULT_MIN_DURATION_SECONDS)
+ maximum = read("muapi_max_duration", DEFAULT_MAX_DURATION_SECONDS)
+ return minimum, max(minimum, maximum)
+
+
+def _tls_verify() -> bool:
+ return _config_bool("tls_verify", True)
+
+
+def _status_code(response: Any) -> int:
+ try:
+ return int(getattr(response, "status_code", 200))
+ except (TypeError, ValueError):
+ return 200
+
+
+def _redact_secret(value: Any, secret: str) -> str:
+ text = str(value or "")
+ if secret:
+ text = text.replace(secret, "***")
+ encoded = quote_plus(secret)
+ if encoded != secret:
+ text = text.replace(encoded, "***")
+ for proxy_url in config.proxy.values():
+ proxy_secret = str(proxy_url or "")
+ if proxy_secret:
+ text = text.replace(proxy_secret, "***")
+ return text[:MAX_ERROR_TEXT_LENGTH]
+
+
+def _response_error(response: Any, api_key: str) -> str:
+ try:
+ payload = response.json()
+ except Exception:
+ return f"HTTP {_status_code(response)}"
+ if not isinstance(payload, dict):
+ return f"HTTP {_status_code(response)}"
+
+ error = payload.get("error")
+ if isinstance(error, dict):
+ detail = error.get("message") or error.get("detail") or error.get("code")
+ else:
+ detail = payload.get("detail") or payload.get("message") or error
+ if isinstance(detail, list):
+ detail = "; ".join(str(item) for item in detail)
+ return _redact_secret(detail or f"HTTP {_status_code(response)}", api_key)
+
+
+def _is_retryable_error(error: Exception) -> bool:
+ if isinstance(
+ error,
+ (
+ requests.exceptions.ConnectionError,
+ requests.exceptions.Timeout,
+ requests.exceptions.ChunkedEncodingError,
+ ),
+ ):
+ return True
+ response = getattr(error, "response", None)
+ return response is not None and _status_code(response) in RETRYABLE_STATUS_CODES
+
+
+def generate_videos(
+ search_term: str,
+ minimum_duration: int,
+ video_aspect: VideoAspect = VideoAspect.portrait,
+) -> list[MaterialInfo]:
+ """Submit one MuAPI text-to-video job and wait for its downloadable output."""
+ api_key = get_api_key()
+ if not api_key:
+ raise MuAPIError("MuAPI video generation requires a MuAPI API key")
+
+ term = str(search_term or "").strip()
+ if not term:
+ raise MuAPIError("MuAPI search term must not be empty")
+
+ try:
+ aspect = VideoAspect(video_aspect)
+ except (TypeError, ValueError) as exc:
+ raise MuAPIError("MuAPI video aspect is invalid") from exc
+ try:
+ requested_duration = max(int(minimum_duration), 1)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise MuAPIError("MuAPI clip duration must be a positive integer") from exc
+ minimum, maximum = _duration_bounds()
+ duration = min(max(requested_duration, minimum), maximum)
+ if duration != requested_duration:
+ logger.info(
+ "muapi clip duration clamped to the configured endpoint range: "
+ f"requested={requested_duration}s, using={duration}s "
+ f"(configured {minimum}-{maximum}s)"
+ )
+
+ base_url = _base_url()
+ endpoint = _endpoint()
+ videos_url = f"{base_url}/{endpoint}"
+ payload = {
+ "prompt": term,
+ "aspect_ratio": aspect.value,
+ "resolution": _resolution(),
+ "duration": duration,
+ }
+ headers = {"x-api-key": api_key, "Content-Type": "application/json"}
+ logger.info(
+ "generating video with MuAPI: "
+ f"endpoint={endpoint}, term={term!r}, duration={duration}s"
+ )
+
+ # A timeout or 5xx after POST may mean that MuAPI accepted and billed the
+ # job. Retrying the submission could create a second paid generation.
+ try:
+ response = requests.post(
+ videos_url,
+ json=payload,
+ headers=headers,
+ proxies=config.proxy,
+ verify=_tls_verify(),
+ timeout=(30, 60),
+ allow_redirects=False,
+ )
+ except Exception as exc:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI submission returned no response; a paid task may already "
+ "exist remotely: "
+ f"error={type(exc).__name__}, detail={_redact_secret(exc, api_key)}"
+ ) from exc
+
+ status_code = _status_code(response)
+ if 300 <= status_code < 400:
+ location = getattr(response, "headers", {}).get("Location", "")
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI submission returned an unexpected redirect; the paid task "
+ "state is unknown: "
+ f"HTTP {status_code}, location={_redact_secret(location, api_key)}"
+ )
+ if status_code >= 500:
+ raise MuAPIUnconfirmedTaskError(
+ f"MuAPI submission failed with HTTP {status_code}; a paid task may "
+ "already exist remotely"
+ )
+ if not 200 <= status_code < 300:
+ raise MuAPIError(
+ "MuAPI video generation request rejected: "
+ f"HTTP {status_code}, {_response_error(response, api_key)}"
+ )
+ try:
+ body = response.json()
+ except Exception as exc:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI submission returned an unreadable response; a paid task may "
+ f"already exist remotely: error={type(exc).__name__}"
+ ) from exc
+ task_id = str(
+ body.get("request_id") or body.get("id") or ""
+ ).strip() if isinstance(body, dict) else ""
+ if not task_id:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI accepted the submission without returning a request id"
+ )
+ logger.info(f"MuAPI video task created: id={task_id}")
+
+ task = _wait_for_task(
+ task_id=task_id,
+ base_url=base_url,
+ headers=headers,
+ api_key=api_key,
+ )
+ if task is None:
+ return []
+
+ outputs = task.get("outputs")
+ candidates = [outputs] if isinstance(outputs, str) else outputs
+ video_url = ""
+ for candidate in candidates if isinstance(candidates, list) else []:
+ if isinstance(candidate, str) and candidate.startswith(("http://", "https://")):
+ video_url = candidate
+ break
+ if not video_url:
+ raise MuAPIError(
+ f"MuAPI task completed without a downloadable video: id={task_id}",
+ task_id=task_id,
+ )
+
+ video_width, video_height = aspect.to_resolution()
+ return [
+ MaterialInfo(
+ provider="muapi",
+ url=video_url,
+ duration=duration,
+ source_info={
+ "provider": "muapi",
+ "search_term": term,
+ "asset_id": task_id,
+ "rendition": {
+ "id": task_id,
+ "width": video_width,
+ "height": video_height,
+ },
+ },
+ )
+ ]
+
+
+def _wait_for_task(
+ *,
+ task_id: str,
+ base_url: str,
+ headers: dict[str, str],
+ api_key: str,
+) -> dict[str, Any] | None:
+ deadline = time.monotonic() + _bounded_float(
+ "muapi_run_timeout",
+ DEFAULT_RUN_TIMEOUT_SECONDS,
+ 60.0,
+ 7200.0,
+ )
+ poll_interval = _bounded_float(
+ "muapi_poll_interval",
+ DEFAULT_POLL_INTERVAL_SECONDS,
+ 0.5,
+ 60.0,
+ )
+ result_url = f"{base_url}/predictions/{task_id}/result"
+ consecutive_failures = 0
+
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI task is still running after the configured local wait "
+ f"timeout: id={task_id}",
+ task_id=task_id,
+ )
+
+ phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)
+ try:
+ response = requests.get(
+ result_url,
+ headers=headers,
+ proxies=config.proxy,
+ verify=_tls_verify(),
+ timeout=(phase_timeout, phase_timeout),
+ allow_redirects=False,
+ )
+ status_code = _status_code(response)
+ if 300 <= status_code < 400:
+ location = getattr(response, "headers", {}).get("Location", "")
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI polling returned an unexpected redirect; the paid "
+ "task state is unknown: "
+ f"HTTP {status_code}, location={_redact_secret(location, api_key)}",
+ task_id=task_id,
+ )
+ if status_code in RETRYABLE_STATUS_CODES:
+ raise requests.exceptions.HTTPError(
+ f"HTTP {status_code}", response=response
+ )
+ if not 200 <= status_code < 300:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI task status is unknown: "
+ f"http_status={status_code}, "
+ f"detail={_response_error(response, api_key)}",
+ task_id=task_id,
+ )
+ body = response.json()
+ if not isinstance(body, dict):
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI task status response is malformed", task_id=task_id
+ )
+ except MuAPIUnconfirmedTaskError:
+ raise
+ except Exception as exc:
+ if not _is_retryable_error(exc):
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI polling failed and the task state is unknown: "
+ f"error={type(exc).__name__}, "
+ f"detail={_redact_secret(exc, api_key)}",
+ task_id=task_id,
+ ) from exc
+
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI task is still running after the configured local wait "
+ f"timeout: id={task_id}",
+ task_id=task_id,
+ ) from exc
+ consecutive_failures += 1
+ if consecutive_failures > MAX_POLL_RETRIES:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI polling failed after retries; the paid task may still "
+ f"be running remotely: id={task_id}",
+ task_id=task_id,
+ ) from exc
+ delay = min(RETRY_BASE_SECONDS * consecutive_failures, remaining)
+ logger.warning(
+ "MuAPI polling hit a transient error; retrying the same task: "
+ f"id={task_id}, attempt={consecutive_failures}/{MAX_POLL_RETRIES}, "
+ f"retry_in={delay:.1f}s"
+ )
+ time.sleep(delay)
+ continue
+
+ consecutive_failures = 0
+ status = str(body.get("status") or "").strip().lower()
+ if status in TERMINAL_SUCCESS_STATUSES:
+ return body
+ if status in TERMINAL_FAILURE_STATUSES:
+ logger.error(
+ "MuAPI task did not produce a video: "
+ f"id={task_id}, status={status}, "
+ f"detail={_redact_secret(body.get('error'), api_key)}"
+ )
+ return None
+ if status not in ACTIVE_STATUSES:
+ raise MuAPIUnconfirmedTaskError(
+ f"MuAPI returned an unknown task status: id={task_id}, "
+ f"status={status!r}",
+ task_id=task_id,
+ )
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise MuAPIUnconfirmedTaskError(
+ "MuAPI task is still running after the configured local wait "
+ f"timeout: id={task_id}",
+ task_id=task_id,
+ )
+ time.sleep(min(poll_interval, remaining))
diff --git a/app/services/task.py b/app/services/task.py
index 89fe5e70..6be13086 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -22,6 +22,7 @@ from app.services import (
loomloom,
material,
metaso_minimax,
+ muapi,
ofox,
sonilo,
subtitle,
@@ -781,6 +782,19 @@ def get_video_materials(
details=details,
)
return None
+ except muapi.MuAPIError as exc:
+ # MuAPI tasks are billable after acceptance. Preserve the remote
+ # request ID on any ambiguous or post-completion failure so the
+ # user can recover it from the provider dashboard.
+ remote_task_id = str(getattr(exc, "task_id", "") or "").strip()
+ details = {"muapi_task_id": remote_task_id} if remote_task_id else None
+ _mark_task_failed(
+ task_id,
+ "materials",
+ str(exc),
+ details=details,
+ )
+ return None
if not downloaded_videos:
_mark_task_failed(
task_id,
@@ -1394,6 +1408,17 @@ def _run_pipeline(
"Metaso MiniMax requires an API key",
)
+ if (
+ stop_at in {"materials", "video"}
+ and params.video_source == "muapi"
+ and not muapi.is_enabled()
+ ):
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ "MuAPI video generation requires a MuAPI API key",
+ )
+
if (
stop_at in {"materials", "video"}
and params.video_source == "openai_image"
diff --git a/cli.py b/cli.py
index 92eb7703..fc9cc6a0 100644
--- a/cli.py
+++ b/cli.py
@@ -45,6 +45,7 @@ _CLI_VIDEO_SOURCES = (
"volcengine_seedance",
"ofox",
"metaso_minimax",
+ "muapi",
"openai_image",
"local",
)
@@ -393,6 +394,14 @@ Batch manifests:
"with --video-source metaso_minimax for materials or video output"
),
)
+ material_group.add_argument(
+ "--confirm-muapi-charge",
+ action="store_true",
+ help=(
+ "confirm that MuAPI video generation creates paid tasks; required "
+ "with --video-source muapi for materials or video output"
+ ),
+ )
video_group = parser.add_argument_group("video output")
video_group.add_argument(
@@ -757,6 +766,15 @@ Batch manifests:
"--confirm-metaso-minimax-charge is required with "
"--video-source metaso_minimax"
)
+ if (
+ not args.batch_file
+ and args.video_source == "muapi"
+ and stage_requires_materials
+ and not args.confirm_muapi_charge
+ ):
+ parser.error(
+ "--confirm-muapi-charge is required with --video-source muapi"
+ )
if args.bgm_file:
if args.bgm_type in (None, "custom"):
@@ -1158,6 +1176,7 @@ def _validate_batch_task_params(
seedance_charge_confirmed: bool,
ofox_charge_confirmed: bool,
metaso_minimax_charge_confirmed: bool,
+ muapi_charge_confirmed: bool,
) -> None:
if not params.video_subject.strip() and not params.video_script.strip():
raise ValueError("one of video_subject or video_script is required")
@@ -1220,6 +1239,12 @@ def _validate_batch_task_params(
raise ValueError(
"--confirm-metaso-minimax-charge is required for Metaso MiniMax H3"
)
+ if (
+ params.video_source == "muapi"
+ and stop_at in {"materials", "video"}
+ and not muapi_charge_confirmed
+ ):
+ raise ValueError("--confirm-muapi-charge is required for MuAPI video generation")
if stop_at == "subtitle" and not params.subtitle_enabled:
raise ValueError("stop_at=subtitle cannot be combined with disabled subtitles")
@@ -1333,6 +1358,7 @@ def _build_batch_tasks(args: argparse.Namespace) -> list[VideoParams]:
metaso_minimax_charge_confirmed=(
args.confirm_metaso_minimax_charge
),
+ muapi_charge_confirmed=args.confirm_muapi_charge,
)
except (TypeError, ValueError) as exc:
raise ValueError(f"invalid batch task {index}: {exc}") from exc
diff --git a/config.example.toml b/config.example.toml
index ea0e2dbe..80166ad7 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -63,7 +63,7 @@ tls_verify = true
# -----------------------------------------------------------------------------
# Available values: "pexels", "pixabay", "coverr", "wavespeed",
-# "volcengine_seedance", "ofox", "metaso_minimax", "loomloom",
+# "volcengine_seedance", "ofox", "metaso_minimax", "muapi", "loomloom",
# "openai_image", "local".
# "wavespeed" generates brand-new clips with WaveSpeed AI text-to-video models
# instead of searching stock footage; generation is billed per request.
@@ -157,6 +157,21 @@ ofox_provider = "byteplus"
ofox_poll_interval = 5
ofox_run_timeout = 1800
+# MuAPI exposes asynchronous text-to-video endpoints under the public API.
+# Create a key at https://muapi.ai and keep the API base URL rooted at
+# https://api.muapi.ai/api/v1 (the endpoint value is a relative path below it).
+# When empty, MUAPI_API_KEY is used. Generation is billed per submitted clip;
+# the WebUI and CLI require explicit charge confirmation before generation.
+muapi_api_key = ""
+muapi_base_url = "https://api.muapi.ai/api/v1"
+# The budget Seedance Lite route accepts 3-12 second clips and 480p/720p/1080p.
+muapi_video_endpoint = "seedance-lite-t2v"
+muapi_resolution = "480p"
+muapi_min_duration = 3
+muapi_max_duration = 12
+muapi_poll_interval = 5
+muapi_run_timeout = 1800
+
# Metaso proxies the MiniMax H3 V2 asynchronous video API. Register and obtain
# an independent API key through https://metaso.cn/minimax-h3/?s=MPT. Its mk-*
# key belongs to a separate credential system and must not reuse the MiniMax LLM key.
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index b7c26631..a14ae6b4 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -112,6 +112,7 @@ MPT_PEXELS_API_KEY
MPT_VOLCENGINE_ARK_API_KEY
MPT_OFOX_API_KEY
MPT_METASO_MINIMAX_API_KEY
+MPT_MUAPI_API_KEY
```
When `SEEDANCE_CHARGE_CONFIRMATION_REQUIRED` is present, explain that every
@@ -132,6 +133,10 @@ every generated MiniMax H3 clip creates a paid Metaso task. Only after the user
explicitly confirms, rerun with `--confirm-metaso-minimax-charge`; never add
this flag silently.
+When `MUAPI_CHARGE_CONFIRMATION_REQUIRED` is present, explain that every
+generated MuAPI clip creates a paid task. Only after the user explicitly
+confirms, rerun with `--confirm-muapi-charge`; never add this flag silently.
+
### Exit code 1: repair or report
Use `MPT_ERROR` and `LOG_FILE` to repair a recoverable problem and retry once. Ask the user only if the repair requires a new API key. If the retry fails, report the failed stage, a short error, and the log path.
diff --git a/docs/skill/mpt_agent.py b/docs/skill/mpt_agent.py
index f22bb067..b7eb6cfe 100644
--- a/docs/skill/mpt_agent.py
+++ b/docs/skill/mpt_agent.py
@@ -33,6 +33,7 @@ SUPPORTED_SOURCES = {
"volcengine_seedance",
"ofox",
"metaso_minimax",
+ "muapi",
# Keep this list aligned with ``_CLI_VIDEO_SOURCES`` in cli.py. A source that
# the CLI accepts must not be rejected here as unsupported.
"openai_image",
@@ -42,6 +43,7 @@ VOLCENGINE_ARK_API_KEY_URL = (
"https://console.volcengine.com/ark/region:ark+cn-beijing/apikey"
)
OFOX_API_KEY_URL = "https://ofox.ai"
+MUAPI_API_KEY_URL = "https://muapi.ai"
PEXELS_API_KEY_URL = "https://www.pexels.com/api/"
PEXELS_VALIDATION_URL = "https://api.pexels.com/v1/collections?per_page=1"
PEXELS_API_KEY_HELP_URL = (
@@ -233,6 +235,7 @@ def apply_environment_config(config_path: Path) -> None:
metaso_minimax_key = os.environ.get(
"MPT_METASO_MINIMAX_API_KEY", ""
).strip()
+ muapi_key = os.environ.get("MPT_MUAPI_API_KEY", "").strip()
if not any(
(
provider,
@@ -243,6 +246,7 @@ def apply_environment_config(config_path: Path) -> None:
seedance_key,
ofox_key,
metaso_minimax_key,
+ muapi_key,
)
):
return
@@ -279,6 +283,9 @@ def apply_environment_config(config_path: Path) -> None:
text, "metaso_minimax_api_key", metaso_minimax_key
)
changes.append("metaso_minimax_api_key")
+ if muapi_key:
+ text = _replace_config_value(text, "muapi_api_key", muapi_key)
+ changes.append("muapi_api_key")
config_path.write_text(text, encoding="utf-8")
log("updated configuration fields: " + ", ".join(changes))
@@ -401,6 +408,15 @@ def missing_config(config_path: Path, cli_args: list[str]) -> tuple[str, list[st
missing.append("metaso_minimax_api_key")
if not has_cli_option(cli_args, "--confirm-metaso-minimax-charge"):
missing.append("confirm_metaso_minimax_charge")
+ elif source == "muapi":
+ value = (
+ _plain_config_value(text, "muapi_api_key")
+ or os.environ.get("MUAPI_API_KEY", "").strip()
+ )
+ if not _has_configured_value(value):
+ missing.append("muapi_api_key")
+ if not has_cli_option(cli_args, "--confirm-muapi-charge"):
+ missing.append("confirm_muapi_charge")
elif source == "openai_image":
# 与运行时的 is_openai_image_enabled() 保持一致:文生图素材源只要求端点
# 与模型名。完全本地的 ComfyUI/SD 网关允许不配置 API Key,因此这里不
@@ -427,6 +443,7 @@ def report_missing_config(provider: str, missing: list[str]) -> int:
"volcengine_seedance_api_key",
"ofox_api_key",
"metaso_minimax_api_key",
+ "muapi_api_key",
}
for field in missing
):
@@ -471,6 +488,11 @@ def report_missing_config(provider: str, missing: list[str]) -> int:
"METASO_MINIMAX_CHARGE_CONFIRMATION_REQUIRED="
"--confirm-metaso-minimax-charge"
)
+ if "muapi_api_key" in missing:
+ print(f"MUAPI_API_KEY_URL={MUAPI_API_KEY_URL}")
+ print("MUAPI_API_KEY_ENV=MPT_MUAPI_API_KEY")
+ if "confirm_muapi_charge" in missing:
+ print("MUAPI_CHARGE_CONFIRMATION_REQUIRED=--confirm-muapi-charge")
print("Request only the listed values, set the environment variables, and rerun the same command.")
return NEEDS_INPUT_EXIT_CODE
diff --git a/test/services/test_cli.py b/test/services/test_cli.py
index 90293e27..6d79746c 100644
--- a/test/services/test_cli.py
+++ b/test/services/test_cli.py
@@ -422,6 +422,74 @@ class TestCli(unittest.TestCase):
)
self.assertEqual(args.video_source, "metaso_minimax")
+ def test_muapi_video_source_requires_explicit_charge_confirmation(self):
+ with self.assertRaises(SystemExit) as raised:
+ cli.parse_args(
+ ["--video-subject", "test", "--video-source", "muapi"]
+ )
+ self.assertEqual(raised.exception.code, 2)
+
+ args = cli.parse_args(
+ [
+ "--video-subject",
+ "test",
+ "--video-source",
+ "muapi",
+ "--confirm-muapi-charge",
+ ]
+ )
+ self.assertEqual(cli.build_video_params(args).video_source, "muapi")
+
+ def test_muapi_confirmation_is_not_required_before_material_stage(self):
+ args = cli.parse_args(
+ [
+ "--video-subject",
+ "test",
+ "--video-source",
+ "muapi",
+ "--stop-at",
+ "script",
+ ]
+ )
+ self.assertEqual(args.video_source, "muapi")
+
+ def test_batch_muapi_source_uses_global_charge_confirmation(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ manifest = Path(temp_dir) / "tasks.json"
+ manifest.write_text(
+ json.dumps(
+ [{"video_subject": "MuAPI batch task", "video_source": "muapi"}]
+ ),
+ encoding="utf-8",
+ )
+ with patch("app.services.task.start") as start:
+ rejected = cli.run_cli(
+ ["--batch-file", str(manifest), "--stop-at", "materials"]
+ )
+ self.assertEqual(rejected, 2)
+ start.assert_not_called()
+
+ with (
+ patch(
+ "app.services.task.start",
+ return_value={"state": 1, "materials": ["ok"]},
+ ) as start,
+ patch("app.utils.utils.get_uuid", return_value="task-muapi"),
+ redirect_stdout(io.StringIO()),
+ ):
+ accepted = cli.run_cli(
+ [
+ "--batch-file",
+ str(manifest),
+ "--stop-at",
+ "materials",
+ "--confirm-muapi-charge",
+ ]
+ )
+
+ self.assertEqual(accepted, 0)
+ start.assert_called_once()
+
def test_batch_seedance_source_uses_global_charge_confirmation(self):
with tempfile.TemporaryDirectory() as temp_dir:
manifest = Path(temp_dir) / "tasks.json"
diff --git a/test/services/test_config.py b/test/services/test_config.py
index 3821093d..e304b87b 100644
--- a/test/services/test_config.py
+++ b/test/services/test_config.py
@@ -45,6 +45,7 @@ class TestConfigPersistence:
"volcengine_seedance",
"ofox",
"metaso_minimax",
+ "muapi",
"loomloom",
"local",
}
@@ -61,6 +62,12 @@ class TestConfigPersistence:
assert app_config["metaso_minimax_api_key"] == ""
assert app_config["metaso_minimax_base_url"].startswith("https://")
assert app_config["metaso_minimax_resolution"] in {"768P", "2K"}
+ assert app_config["muapi_api_key"] == ""
+ assert app_config["muapi_base_url"].startswith("https://")
+ assert app_config["muapi_video_endpoint"]
+ assert app_config["muapi_resolution"]
+ assert app_config["muapi_min_duration"] == 3
+ assert app_config["muapi_max_duration"] == 12
assert "loomloom_market_listing_id" not in app_config
assert "loomloom_video_market_listing_id" not in app_config
assert app_config["shengsuanyun_api_key"] == ""
diff --git a/test/services/test_mpt_agent_skill.py b/test/services/test_mpt_agent_skill.py
index f653bd67..a101e53d 100644
--- a/test/services/test_mpt_agent_skill.py
+++ b/test/services/test_mpt_agent_skill.py
@@ -34,6 +34,7 @@ coverr_api_keys = []
volcengine_seedance_api_key = ""
ofox_api_key = ""
metaso_minimax_api_key = ""
+muapi_api_key = ""
openai_image_base_url = ""
openai_image_model = ""
openai_image_api_keys = []
@@ -109,6 +110,7 @@ class TestMptAgentSkill(unittest.TestCase):
pexels_key = "secret-pexels-key"
seedance_key = "secret-ark-key"
metaso_key = "secret-metaso-key"
+ muapi_key = "secret-muapi-key"
with patch.dict(
os.environ,
@@ -118,6 +120,7 @@ class TestMptAgentSkill(unittest.TestCase):
"MPT_PEXELS_API_KEY": pexels_key,
"MPT_VOLCENGINE_ARK_API_KEY": seedance_key,
"MPT_METASO_MINIMAX_API_KEY": metaso_key,
+ "MPT_MUAPI_API_KEY": muapi_key,
},
clear=True,
), redirect_stdout(output):
@@ -131,10 +134,12 @@ class TestMptAgentSkill(unittest.TestCase):
f'volcengine_seedance_api_key = "{seedance_key}"', config
)
self.assertIn(f'metaso_minimax_api_key = "{metaso_key}"', config)
+ self.assertIn(f'muapi_api_key = "{muapi_key}"', config)
self.assertNotIn(llm_key, output.getvalue())
self.assertNotIn(pexels_key, output.getvalue())
self.assertNotIn(seedance_key, output.getvalue())
self.assertNotIn(metaso_key, output.getvalue())
+ self.assertNotIn(muapi_key, output.getvalue())
def test_material_key_check_matches_selected_source(self):
with tempfile.TemporaryDirectory() as temp_dir:
@@ -454,6 +459,55 @@ class TestMptAgentSkill(unittest.TestCase):
)
self.assertEqual(confirmed_missing, [])
+ def test_muapi_source_requires_its_own_key_and_charge_confirmation(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config_path = Path(temp_dir) / "config.toml"
+ config_path.write_text(
+ MINIMAL_CONFIG.replace(
+ 'moonshot_api_key = ""', 'moonshot_api_key = "configured"'
+ ),
+ encoding="utf-8",
+ )
+
+ with patch.dict(os.environ, {}, clear=True):
+ _, missing = mpt_agent.missing_config(
+ config_path, ["--video-source", "muapi"]
+ )
+ self.assertEqual(missing, ["muapi_api_key", "confirm_muapi_charge"])
+
+ config_path.write_text(
+ config_path.read_text(encoding="utf-8").replace(
+ 'muapi_api_key = ""', 'muapi_api_key = "configured"'
+ ),
+ encoding="utf-8",
+ )
+ with patch.dict(os.environ, {}, clear=True):
+ _, confirmed_missing = mpt_agent.missing_config(
+ config_path,
+ ["--video-source", "muapi", "--confirm-muapi-charge"],
+ )
+ self.assertEqual(confirmed_missing, [])
+
+ def test_muapi_source_accepts_provider_environment_key(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ config_path = Path(temp_dir) / "config.toml"
+ config_path.write_text(
+ MINIMAL_CONFIG.replace(
+ 'moonshot_api_key = ""', 'moonshot_api_key = "configured"'
+ ),
+ encoding="utf-8",
+ )
+ with patch.dict(
+ os.environ,
+ {"MUAPI_API_KEY": "environment-muapi-key"},
+ clear=True,
+ ):
+ _, missing = mpt_agent.missing_config(
+ config_path,
+ ["--video-source", "muapi", "--confirm-muapi-charge"],
+ )
+ self.assertEqual(missing, [])
+
def test_existing_provider_key_is_reused_without_asking_user(self):
with tempfile.TemporaryDirectory() as temp_dir:
config_path = Path(temp_dir) / "config.toml"
@@ -571,6 +625,22 @@ class TestMptAgentSkill(unittest.TestCase):
)
self.assertNotIn("LLM_PROVIDER_OPTIONS_BEGIN", text)
+ def test_missing_muapi_inputs_report_key_environment_and_charge_flag(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = mpt_agent.report_missing_config(
+ "deepseek", ["muapi_api_key", "confirm_muapi_charge"]
+ )
+
+ text = output.getvalue()
+ self.assertEqual(code, mpt_agent.NEEDS_INPUT_EXIT_CODE)
+ self.assertIn(f"MUAPI_API_KEY_URL={mpt_agent.MUAPI_API_KEY_URL}", text)
+ self.assertIn("MUAPI_API_KEY_ENV=MPT_MUAPI_API_KEY", text)
+ self.assertIn(
+ "MUAPI_CHARGE_CONFIRMATION_REQUIRED=--confirm-muapi-charge", text
+ )
+ self.assertNotIn("LLM_PROVIDER_OPTIONS_BEGIN", text)
+
def test_custom_openai_compatible_provider_requires_connection_details(self):
with tempfile.TemporaryDirectory() as temp_dir:
config_path = Path(temp_dir) / "config.toml"
diff --git a/test/services/test_muapi.py b/test/services/test_muapi.py
new file mode 100644
index 00000000..98ff9199
--- /dev/null
+++ b/test/services/test_muapi.py
@@ -0,0 +1,454 @@
+import os
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+import requests
+
+from app.config import config
+from app.models.schema import MaterialInfo, VideoAspect, VideoParams
+from app.services import material, muapi, state as sm
+from app.services import task as task_service
+
+
+def _response(payload, status_code=200, headers=None):
+ return SimpleNamespace(
+ status_code=status_code,
+ headers=headers or {},
+ json=lambda: payload,
+ )
+
+
[email protected](autouse=True)
+def restore_config():
+ original_app = dict(config.app)
+ original_proxy = dict(config.proxy)
+ config.app.update(
+ {
+ "muapi_api_key": "muapi-test-key",
+ "muapi_base_url": muapi.DEFAULT_BASE_URL,
+ "muapi_video_endpoint": muapi.DEFAULT_ENDPOINT,
+ "muapi_resolution": muapi.DEFAULT_RESOLUTION,
+ "muapi_poll_interval": 5,
+ "muapi_run_timeout": 1800,
+ }
+ )
+ config.proxy.clear()
+ yield
+ config.app.clear()
+ config.app.update(original_app)
+ config.proxy.clear()
+ config.proxy.update(original_proxy)
+
+
+def test_api_key_prefers_config_then_muapi_environment():
+ with patch.dict(os.environ, {"MUAPI_API_KEY": "environment-key"}, clear=False):
+ assert muapi.get_api_key() == "muapi-test-key"
+ config.app["muapi_api_key"] = ""
+ assert muapi.get_api_key() == "environment-key"
+ os.environ["MUAPI_API_KEY"] = ""
+ assert muapi.get_api_key() == ""
+
+
[email protected]("term", ["", " ", None])
+def test_invalid_input_fails_before_paid_submission(term):
+ with patch.object(muapi.requests, "post") as post:
+ with pytest.raises(muapi.MuAPIError):
+ muapi.generate_videos(term, 5)
+ post.assert_not_called()
+
+
+def test_submit_poll_and_parse_successful_video():
+ submit = _response({"request_id": "muapi-task-1", "status": "queued"}, 202)
+ polls = [
+ _response({"request_id": "muapi-task-1", "status": "processing"}),
+ _response(
+ {
+ "request_id": "muapi-task-1",
+ "status": "completed",
+ "outputs": ["https://cdn.example.com/video.mp4"],
+ }
+ ),
+ ]
+ with (
+ patch.object(muapi.requests, "post", return_value=submit) as post,
+ patch.object(muapi.requests, "get", side_effect=polls) as get,
+ patch.object(muapi.time, "sleep") as sleep,
+ ):
+ result = muapi.generate_videos(
+ " sunrise over mountains ",
+ minimum_duration=5,
+ video_aspect=VideoAspect.portrait,
+ )
+
+ assert len(result) == 1
+ item = result[0]
+ assert item.provider == "muapi"
+ assert item.url == "https://cdn.example.com/video.mp4"
+ assert item.duration == 5
+ assert item.source_info == {
+ "provider": "muapi",
+ "search_term": "sunrise over mountains",
+ "asset_id": "muapi-task-1",
+ "rendition": {
+ "id": "muapi-task-1",
+ "width": 1080,
+ "height": 1920,
+ },
+ }
+ assert post.call_args.args[0] == (
+ f"{muapi.DEFAULT_BASE_URL}/{muapi.DEFAULT_ENDPOINT}"
+ )
+ assert post.call_args.kwargs["headers"] == {
+ "x-api-key": "muapi-test-key",
+ "Content-Type": "application/json",
+ }
+ assert post.call_args.kwargs["allow_redirects"] is False
+ assert post.call_args.kwargs["json"] == {
+ "prompt": "sunrise over mountains",
+ "aspect_ratio": "9:16",
+ "resolution": "480p",
+ "duration": 5,
+ }
+ assert get.call_count == 2
+ assert all(
+ call.args[0].endswith("/predictions/muapi-task-1/result")
+ for call in get.call_args_list
+ )
+ assert all(call.kwargs["allow_redirects"] is False for call in get.call_args_list)
+ sleep.assert_called_once_with(muapi.DEFAULT_POLL_INTERVAL_SECONDS)
+
+
+def test_configured_endpoint_resolution_and_duration_bounds_are_applied():
+ config.app.update(
+ {
+ "muapi_base_url": "https://muapi.example.test/api/v1/",
+ "muapi_video_endpoint": "seedance-2-text-to-video",
+ "muapi_resolution": "1080p",
+ "muapi_min_duration": 4,
+ "muapi_max_duration": 8,
+ }
+ )
+ submit = _response({"id": "muapi-bounds"}, 202)
+ completed = _response(
+ {
+ "id": "muapi-bounds",
+ "status": "completed",
+ "outputs": ["https://cdn.example.com/bounds.mp4"],
+ }
+ )
+ with (
+ patch.object(muapi.requests, "post", return_value=submit) as post,
+ patch.object(muapi.requests, "get", return_value=completed),
+ ):
+ result = muapi.generate_videos("city", 99, VideoAspect.landscape)
+
+ assert result[0].duration == 8
+ assert post.call_args.args[0] == (
+ "https://muapi.example.test/api/v1/seedance-2-text-to-video"
+ )
+ assert post.call_args.kwargs["json"] == {
+ "prompt": "city",
+ "aspect_ratio": "16:9",
+ "resolution": "1080p",
+ "duration": 8,
+ }
+
+
+def test_submission_errors_are_not_retried_and_secret_is_redacted():
+ rejected = _response({"detail": "rejected muapi-test-key"}, status_code=400)
+ with patch.object(muapi.requests, "post", return_value=rejected) as post:
+ with pytest.raises(muapi.MuAPIError) as raised:
+ muapi.generate_videos("unsafe", 5)
+ assert "muapi-test-key" not in str(raised.value)
+ assert post.call_count == 1
+
+ for side_effect, response in (
+ (requests.exceptions.ConnectionError("offline"), None),
+ (None, _response({"message": "bad gateway"}, status_code=502)),
+ ):
+ with patch.object(
+ muapi.requests,
+ "post",
+ side_effect=side_effect,
+ return_value=response,
+ ) as post:
+ with pytest.raises(muapi.MuAPIUnconfirmedTaskError):
+ muapi.generate_videos("sunrise", 5)
+ assert post.call_count == 1
+
+
+def test_submission_redirect_is_unconfirmed_and_never_followed():
+ redirect = _response(
+ {},
+ status_code=307,
+ headers={"Location": "https://attacker.example/submit?key=muapi-test-key"},
+ )
+ with (
+ patch.object(muapi.requests, "post", return_value=redirect) as post,
+ patch.object(muapi.requests, "get") as get,
+ ):
+ with pytest.raises(muapi.MuAPIUnconfirmedTaskError) as raised:
+ muapi.generate_videos("sunrise", 5)
+
+ assert "muapi-test-key" not in str(raised.value)
+ assert post.call_count == 1
+ assert post.call_args.kwargs["allow_redirects"] is False
+ get.assert_not_called()
+
+
+def test_poll_redirect_is_unconfirmed_and_never_retried():
+ submit = _response({"request_id": "muapi-redirect"}, 202)
+ redirect = _response(
+ {},
+ status_code=307,
+ headers={"Location": "https://attacker.example/result"},
+ )
+ with (
+ patch.object(muapi.requests, "post", return_value=submit) as post,
+ patch.object(muapi.requests, "get", return_value=redirect) as get,
+ ):
+ with pytest.raises(muapi.MuAPIUnconfirmedTaskError) as raised:
+ muapi.generate_videos("sunrise", 5)
+
+ assert raised.value.task_id == "muapi-redirect"
+ assert post.call_count == 1
+ assert get.call_count == 1
+ assert get.call_args.kwargs["allow_redirects"] is False
+
+
+def test_poll_retries_transient_errors_on_same_task():
+ submit = _response({"request_id": "muapi-retry"}, 202)
+ completed = _response(
+ {
+ "request_id": "muapi-retry",
+ "status": "completed",
+ "outputs": ["https://cdn.example.com/retry.mp4"],
+ }
+ )
+ with (
+ patch.object(muapi.requests, "post", return_value=submit) as post,
+ patch.object(
+ muapi.requests,
+ "get",
+ side_effect=[
+ _response({}, status_code=429),
+ requests.exceptions.ConnectionError("offline"),
+ completed,
+ ],
+ ) as get,
+ patch.object(muapi.time, "sleep") as sleep,
+ ):
+ result = muapi.generate_videos("sunrise", 5)
+
+ assert len(result) == 1
+ assert post.call_count == 1
+ assert get.call_count == 3
+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 2.0]
+
+
[email protected]("payload", [{}, {"request_id": " "}, [], None])
+def test_missing_task_id_is_unconfirmed_and_never_polled(payload):
+ with (
+ patch.object(muapi.requests, "post", return_value=_response(payload, 202)),
+ patch.object(muapi.requests, "get") as get,
+ ):
+ with pytest.raises(muapi.MuAPIUnconfirmedTaskError):
+ muapi.generate_videos("sunrise", 5)
+ get.assert_not_called()
+
+
+def test_completed_task_without_video_url_preserves_task_id():
+ with (
+ patch.object(
+ muapi.requests,
+ "post",
+ return_value=_response({"request_id": "muapi-no-url"}, 202),
+ ),
+ patch.object(
+ muapi.requests,
+ "get",
+ return_value=_response(
+ {
+ "request_id": "muapi-no-url",
+ "status": "completed",
+ "outputs": [],
+ }
+ ),
+ ),
+ ):
+ with pytest.raises(muapi.MuAPIError) as raised:
+ muapi.generate_videos("sunrise", 5)
+ assert raised.value.task_id == "muapi-no-url"
+
+
[email protected]("status", sorted(muapi.TERMINAL_FAILURE_STATUSES))
+def test_terminal_failure_returns_empty_result(status):
+ with patch.object(
+ muapi.requests,
+ "get",
+ return_value=_response(
+ {
+ "request_id": "muapi-failed",
+ "status": status,
+ "error": {"message": "generation failed"},
+ }
+ ),
+ ):
+ result = muapi._wait_for_task(
+ task_id="muapi-failed",
+ base_url=muapi.DEFAULT_BASE_URL,
+ headers={},
+ api_key="muapi-test-key",
+ )
+ assert result is None
+
+
+def test_on_demand_generation_stops_after_required_duration():
+ generated_item = MaterialInfo(
+ provider="muapi",
+ url="https://cdn.example.com/video.mp4",
+ duration=5,
+ source_info={"asset_id": "muapi-paid-1"},
+ )
+ with (
+ patch.object(muapi, "generate_videos", return_value=[generated_item]) as generate,
+ patch.object(material, "_save_generated_video_with_retry", return_value="/tmp/video.mp4"),
+ patch.object(material, "_get_downloaded_video_duration", return_value=5.0),
+ patch.object(material, "_persist_material_sources"),
+ ):
+ paths = material._download_videos_muapi_on_demand(
+ task_id="local-task",
+ search_terms=["first", "second"],
+ video_aspect=VideoAspect.landscape,
+ audio_duration=5,
+ max_clip_duration=5,
+ material_directory="/tmp",
+ )
+
+ assert paths == ["/tmp/video.mp4"]
+ assert generate.call_count == 1
+ assert generate.call_args.kwargs["search_term"] == "first"
+
+
+def test_on_demand_counts_actual_downloaded_duration_before_next_paid_submission():
+ generated_items = [
+ MaterialInfo(
+ provider="muapi",
+ url="https://cdn.example.com/short.mp4",
+ duration=5,
+ source_info={"asset_id": "muapi-paid-short"},
+ ),
+ MaterialInfo(
+ provider="muapi",
+ url="https://cdn.example.com/full.mp4",
+ duration=5,
+ source_info={"asset_id": "muapi-paid-full"},
+ ),
+ ]
+ with (
+ patch.object(
+ muapi,
+ "generate_videos",
+ side_effect=[[generated_items[0]], [generated_items[1]]],
+ ) as generate,
+ patch.object(
+ material,
+ "_save_generated_video_with_retry",
+ side_effect=["/tmp/short.mp4", "/tmp/full.mp4"],
+ ),
+ patch.object(
+ material,
+ "_get_downloaded_video_duration",
+ side_effect=[2.0, 5.0],
+ ),
+ patch.object(material, "_persist_material_sources"),
+ ):
+ paths = material._download_videos_muapi_on_demand(
+ task_id="local-task",
+ search_terms=["short scene", "full scene"],
+ video_aspect=VideoAspect.landscape,
+ audio_duration=5,
+ max_clip_duration=5,
+ material_directory="/tmp",
+ )
+
+ assert paths == ["/tmp/short.mp4", "/tmp/full.mp4"]
+ assert generate.call_count == 2
+ assert [call.kwargs["search_term"] for call in generate.call_args_list] == [
+ "short scene",
+ "full scene",
+ ]
+
+
[email protected]("audio_duration", [float("nan"), float("inf"), None, "bad"])
+def test_on_demand_rejects_invalid_audio_duration_before_submission(audio_duration):
+ with patch.object(muapi, "generate_videos") as generate:
+ with pytest.raises(muapi.MuAPIError, match="audio duration"):
+ material.download_videos(
+ task_id="muapi-invalid-audio",
+ search_terms=["one", "two"],
+ source="muapi",
+ audio_duration=audio_duration,
+ max_clip_duration=5,
+ )
+ generate.assert_not_called()
+
+
+def test_download_failure_stops_later_paid_submissions_and_keeps_task_id():
+ generated_item = MaterialInfo(
+ provider="muapi",
+ url="https://cdn.example.com/video.mp4",
+ duration=5,
+ source_info={"asset_id": "muapi-paid-download"},
+ )
+ with (
+ patch.object(muapi, "generate_videos", return_value=[generated_item]) as generate,
+ patch.object(material, "_save_generated_video_with_retry", return_value=""),
+ ):
+ with pytest.raises(muapi.MuAPIDownloadError) as raised:
+ material.download_videos(
+ task_id="muapi-download-failed",
+ search_terms=["one", "two"],
+ source="muapi",
+ audio_duration=10,
+ max_clip_duration=5,
+ )
+ assert raised.value.task_id == "muapi-paid-download"
+ assert generate.call_count == 1
+
+
+def test_task_preflight_rejects_missing_key_before_script_generation():
+ params = VideoParams(video_subject="MuAPI preflight", video_source="muapi")
+ memory_state = sm.MemoryState()
+ with (
+ patch.object(muapi, "is_enabled", return_value=False),
+ patch.object(task_service.sm, "state", memory_state),
+ patch.object(task_service, "generate_script") as generate_script,
+ ):
+ result = task_service.start("muapi-preflight", params, stop_at="materials")
+
+ assert result["failed_stage"] == "preflight"
+ assert "MuAPI video generation requires a MuAPI API key" in result["error"]
+ generate_script.assert_not_called()
+
+
+def test_material_failure_keeps_muapi_remote_task_id():
+ params = VideoParams(video_subject="space fleet", video_source="muapi")
+ failure = muapi.MuAPIUnconfirmedTaskError(
+ "remote state unknown", task_id="muapi-recover-1"
+ )
+ with (
+ patch.object(task_service.material, "download_videos", side_effect=failure),
+ patch.object(sm.state, "update_task") as update_task,
+ ):
+ result = task_service.get_video_materials(
+ "local-task",
+ params,
+ ["space fleet"],
+ audio_duration=5,
+ )
+
+ assert result is None
+ failed_update = update_task.call_args.kwargs
+ assert failed_update["muapi_task_id"] == "muapi-recover-1"
diff --git a/test/services/test_webui_grouped_select.py b/test/services/test_webui_grouped_select.py
index 70131f8e..ce98319c 100644
--- a/test/services/test_webui_grouped_select.py
+++ b/test/services/test_webui_grouped_select.py
@@ -123,6 +123,7 @@ def test_grouped_video_source_keeps_groups_and_accessible_label_binding():
"loomloom",
"volcengine_seedance",
"wavespeed",
+ "muapi",
"openai_image",
"local",
]
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index 3f2062ac..53e19e60 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -73,6 +73,22 @@ ENGLISH_FALLBACK_KEYS = frozenset(
"Confirm Metaso MiniMax Charge",
"Confirm Metaso MiniMax Charge Help",
"Confirm Metaso MiniMax Charge Required",
+ "MuAPI AI Video",
+ "MuAPI AI Video Help",
+ "MuAPI API Key",
+ "MuAPI API Key Help",
+ "MuAPI Base URL",
+ "MuAPI Base URL Help",
+ "MuAPI Video Endpoint",
+ "MuAPI Video Endpoint Help",
+ "MuAPI Resolution",
+ "MuAPI Resolution Help",
+ "Please Enter the MuAPI API Key",
+ "MuAPI Billing Notice",
+ "MuAPI Billing Notice Without Script",
+ "Confirm MuAPI Charge",
+ "Confirm MuAPI Charge Help",
+ "Confirm MuAPI Charge Required",
"Script Generation Method",
"Script Generation Method Help",
"Shengsuan Cloud AI Video",
diff --git a/test/services/test_webui_muapi.py b/test/services/test_webui_muapi.py
new file mode 100644
index 00000000..9102296c
--- /dev/null
+++ b/test/services/test_webui_muapi.py
@@ -0,0 +1,59 @@
+from pathlib import Path
+from unittest.mock import patch
+
+from streamlit.testing.v1 import AppTest
+
+from app.config import config
+
+
+ROOT_DIR = Path(__file__).parent.parent.parent
+WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"
+
+
+def _widget_by_key(elements, key):
+ return next(
+ item
+ for item in elements
+ if str(getattr(item, "key", "")) == key
+ or str(getattr(item, "key", "")).startswith(f"{key}_")
+ )
+
+
+def test_muapi_source_requires_confirmation_then_submits_without_secret_in_params():
+ test_config = dict(
+ config.app,
+ llm_provider="openai",
+ video_source="pexels",
+ muapi_api_key="muapi-secret",
+ )
+ with (
+ patch.object(config, "app", test_config),
+ patch.object(config, "try_save_config", return_value=True),
+ patch("app.services.webui_task.submit_generation") as submit_generation,
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.run()
+
+ _widget_by_key(app.text_area, "video_subject").set_value("AI office").run()
+ _widget_by_key(app.text_area, "video_script").set_value(
+ "AI helps people work faster."
+ ).run()
+ _widget_by_key(app.text_area, "video_terms").set_value(
+ "office worker, AI assistant"
+ ).run()
+ app.session_state["video_source_select_en"] = "muapi"
+ app.run()
+
+ _widget_by_key(app.button, "generate_video_button").click().run()
+ assert submit_generation.call_count == 0
+ assert any("confirm" in str(item.value).lower() for item in app.error)
+
+ _widget_by_key(app.checkbox, "muapi_confirm_charge").check().run()
+ _widget_by_key(app.button, "generate_video_button").click().run()
+
+ assert submit_generation.call_count == 1
+ submitted_params = submit_generation.call_args.kwargs["params"]
+ assert submitted_params.video_source == "muapi"
+ assert "muapi-secret" not in submitted_params.model_dump_json()
+ assert [str(item.value) for item in app.exception] == []
diff --git a/test/services/test_webui_ofox_placement.py b/test/services/test_webui_ofox_placement.py
index 7cf43e85..88ee73fd 100644
--- a/test/services/test_webui_ofox_placement.py
+++ b/test/services/test_webui_ofox_placement.py
@@ -25,7 +25,7 @@ def test_ai_video_source_order_keeps_ofox_below_metaso():
)
groups = ast.literal_eval(assignment.value)
assert groups["ai_video"] == (
- "metaso_minimax", "ofox", "loomloom", "volcengine_seedance", "wavespeed"
+ "metaso_minimax", "ofox", "loomloom", "volcengine_seedance", "wavespeed", "muapi"
)
assert groups["stock_video"] == ("pexels", "pixabay", "coverr")
diff --git a/webui/Main.py b/webui/Main.py
index db68db0e..ed3774a6 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -50,6 +50,7 @@ from app.services import (
loomloom,
material,
metaso_minimax,
+ muapi,
ofox,
video,
volcengine_seedance,
@@ -121,6 +122,7 @@ VIDEO_SOURCE_GROUPS = {
"loomloom",
"volcengine_seedance",
"wavespeed",
+ "muapi",
),
"ai_image": ("openai_image",),
"local": ("local",),
@@ -708,6 +710,7 @@ def _initialize_session_state():
"volcengine_seedance_confirm_charge": False,
"ofox_confirm_charge": False,
"metaso_minimax_confirm_charge": False,
+ "muapi_confirm_charge": False,
# AI 视频按素材段计费,默认只生成一段,用户确认效果后再主动增加数量。
"loomloom_video_scene_count": _saved_ui_number(
"loomloom_video_scene_count",
@@ -3784,6 +3787,78 @@ def _render_settings_dialog():
)
_save_material_api_keys("wavespeed_api_keys", wavespeed_api_key)
+ st.divider()
+ st.markdown(f"**{tr('MuAPI AI Video')}**")
+ st.caption(tr("MuAPI AI Video Help"))
+ muapi_api_key = st.text_input(
+ tr("MuAPI API Key"),
+ value=str(config.app.get("muapi_api_key", "") or ""),
+ type="password",
+ help=tr("MuAPI API Key Help"),
+ key="muapi_api_key_input",
+ )
+ _set_runtime_config("app", "muapi_api_key", muapi_api_key.strip())
+ configured_muapi_base_url = str(
+ config.app.get("muapi_base_url", muapi.DEFAULT_BASE_URL)
+ or muapi.DEFAULT_BASE_URL
+ ).strip()
+ muapi_base_url = st.text_input(
+ tr("MuAPI Base URL"),
+ value=(
+ ""
+ if configured_muapi_base_url == muapi.DEFAULT_BASE_URL
+ else configured_muapi_base_url
+ ),
+ placeholder=muapi.DEFAULT_BASE_URL,
+ key="muapi_base_url_input",
+ help=tr("MuAPI Base URL Help"),
+ )
+ _set_runtime_config(
+ "app",
+ "muapi_base_url",
+ muapi_base_url.strip() or muapi.DEFAULT_BASE_URL,
+ )
+ configured_muapi_endpoint = str(
+ config.app.get("muapi_video_endpoint", muapi.DEFAULT_ENDPOINT)
+ or muapi.DEFAULT_ENDPOINT
+ ).strip()
+ muapi_endpoint = st.text_input(
+ tr("MuAPI Video Endpoint"),
+ value=(
+ ""
+ if configured_muapi_endpoint == muapi.DEFAULT_ENDPOINT
+ else configured_muapi_endpoint
+ ),
+ placeholder=muapi.DEFAULT_ENDPOINT,
+ key="muapi_video_endpoint_input",
+ help=tr("MuAPI Video Endpoint Help"),
+ )
+ _set_runtime_config(
+ "app",
+ "muapi_video_endpoint",
+ muapi_endpoint.strip() or muapi.DEFAULT_ENDPOINT,
+ )
+ configured_muapi_resolution = str(
+ config.app.get("muapi_resolution", muapi.DEFAULT_RESOLUTION)
+ or muapi.DEFAULT_RESOLUTION
+ ).strip()
+ muapi_resolution = st.text_input(
+ tr("MuAPI Resolution"),
+ value=(
+ ""
+ if configured_muapi_resolution == muapi.DEFAULT_RESOLUTION
+ else configured_muapi_resolution
+ ),
+ placeholder=muapi.DEFAULT_RESOLUTION,
+ key="muapi_resolution_input",
+ help=tr("MuAPI Resolution Help"),
+ )
+ _set_runtime_config(
+ "app",
+ "muapi_resolution",
+ muapi_resolution.strip() or muapi.DEFAULT_RESOLUTION,
+ )
+
with st.container(border=True):
st.markdown(f"#### {tr('AI Image Generation APIs')}")
@@ -4965,6 +5040,7 @@ def _render_video_settings(panel, params):
"volcengine_seedance": tr("Volcano Engine Seedance"),
"ofox": tr("OFox AI Video"),
"metaso_minimax": tr("Metaso MiniMax H3"),
+ "muapi": tr("MuAPI AI Video"),
"loomloom": tr("Shengsuan Cloud AI Video"),
"openai_image": tr("OpenAI Compatible Text-to-Image"),
"local": tr("Local file"),
@@ -5004,6 +5080,8 @@ def _render_video_settings(panel, params):
st.caption(f"[OfoxAI]({OFOX_REFERRAL_URL}) · {tr('OFox AI Video Help')}")
if params.video_source == "metaso_minimax":
st.caption(tr("Metaso MiniMax H3 Help"))
+ if params.video_source == "muapi":
+ st.caption(tr("MuAPI AI Video Help"))
if params.video_source == "local":
# Streamlit 的文件类型校验对扩展名大小写敏感,这里同时放行大小写两种形式。
local_file_types = sorted(
@@ -5149,23 +5227,31 @@ def _render_video_settings(panel, params):
# MiniMax H3 的远端时长范围是 4~15 秒。选择秘塔时使用完整能力
# 范围,既避免 2/3 秒被按 4 秒计费,也让 WebUI 与 CLI、服务层一致。
- video_clip_durations = (
- list(
+ if params.video_source == "metaso_minimax":
+ video_clip_durations = list(
range(
metaso_minimax.DEFAULT_MIN_DURATION_SECONDS,
metaso_minimax.DEFAULT_MAX_DURATION_SECONDS + 1,
)
)
- if params.video_source == "metaso_minimax"
- else [2, 3, 4, 5, 6, 7, 8, 9, 10]
- )
+ elif params.video_source == "muapi":
+ video_clip_durations = list(
+ range(
+ muapi.DEFAULT_MIN_DURATION_SECONDS,
+ muapi.DEFAULT_MAX_DURATION_SECONDS + 1,
+ )
+ )
+ else:
+ video_clip_durations = [2, 3, 4, 5, 6, 7, 8, 9, 10]
params.video_clip_duration = stable_selectbox(
tr("Clip Duration"),
options=video_clip_durations,
default_value=_saved_ui_choice(
"video_clip_duration",
video_clip_durations,
- 5 if params.video_source == "metaso_minimax" else 3,
+ 5
+ if params.video_source in {"metaso_minimax", "muapi"}
+ else 3,
),
key="video_clip_duration_select",
help=tr("Clip Duration Help"),
@@ -5248,6 +5334,8 @@ def _render_video_settings(panel, params):
_render_ofox_video_settings(params)
if params.video_source == "metaso_minimax":
_render_metaso_minimax_video_settings(params)
+ if params.video_source == "muapi":
+ _render_muapi_video_settings(params)
return uploaded_files
@@ -5387,6 +5475,29 @@ def _render_metaso_minimax_video_settings(params):
)
+def _render_muapi_video_settings(params):
+ """Show an estimated MuAPI task count and require explicit billing consent."""
+ clip_duration = max(int(params.video_clip_duration or 1), 1)
+ video_count = max(int(params.video_count or 1), 1)
+ if estimated_range := _estimate_voiceover_duration_range(
+ str(params.video_script or ""), params.voice_rate
+ ):
+ min_clips = max(math.ceil(estimated_range[0] * video_count / clip_duration), 1)
+ max_clips = max(
+ math.ceil(estimated_range[1] * video_count / clip_duration), min_clips
+ )
+ st.warning(
+ tr("MuAPI Billing Notice").format(min=min_clips, max=max_clips)
+ )
+ else:
+ st.warning(tr("MuAPI Billing Notice Without Script"))
+ st.checkbox(
+ tr("Confirm MuAPI Charge"),
+ key="muapi_confirm_charge",
+ help=tr("Confirm MuAPI Charge Help"),
+ )
+
+
def _estimate_voiceover_duration_range(
text: str, voice_rate: float
) -> tuple[float, float] | None:
@@ -7343,6 +7454,7 @@ def _render_generation_controls(
"volcengine_seedance",
"ofox",
"metaso_minimax",
+ "muapi",
"loomloom",
"openai_image",
"local",
@@ -7432,6 +7544,20 @@ def _render_generation_controls(
st.error(tr("Confirm Metaso MiniMax Charge Required"))
st.stop()
+ if params.video_source == "muapi" and not (
+ muapi.is_enabled(config.snapshot_config_with_pending(config.app))
+ ):
+ _remove_active_generation_task(task_id)
+ st.error(tr("Please Enter the MuAPI API Key"))
+ st.stop()
+
+ if params.video_source == "muapi" and not st.session_state.get(
+ "muapi_confirm_charge", False
+ ):
+ _remove_active_generation_task(task_id)
+ st.error(tr("Confirm MuAPI Charge Required"))
+ st.stop()
+
if params.video_source == "openai_image" and not material.is_openai_image_enabled(
config.snapshot_config_with_pending(config.app)
):
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index b3ecbf2e..806bd022 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -525,6 +525,22 @@
"OFox Upstream Vendor Help": "Which upstream vendor serves OFox video generation. BytePlus (international) is the default with a consistent content policy; Volcano Engine is the mainland-China vendor; Auto lets the OFox gateway load-balance across vendors.",
"OFox Vendor BytePlus": "BytePlus (International, default)",
"OFox Vendor Volcengine": "Volcano Engine (Mainland China)",
- "OFox Vendor Auto": "Auto (gateway load balancing)"
+ "OFox Vendor Auto": "Auto (gateway load balancing)",
+ "MuAPI AI Video": "MuAPI AI Video",
+ "MuAPI AI Video Help": "Generate paid AI video clips through MuAPI's asynchronous text-to-video API, then reuse the existing narration, subtitle, and editing pipeline.",
+ "MuAPI API Key": "MuAPI API Key ([Get API Key](https://muapi.ai))",
+ "MuAPI API Key Help": "Create a MuAPI API key and keep it private. MuAPI generation is billed per submitted task.",
+ "MuAPI Base URL": "MuAPI Base URL",
+ "MuAPI Base URL Help": "The API root used for MuAPI requests. The default is https://api.muapi.ai/api/v1.",
+ "MuAPI Video Endpoint": "MuAPI Video Endpoint",
+ "MuAPI Video Endpoint Help": "A relative asynchronous text-to-video endpoint below the MuAPI base URL, for example seedance-lite-t2v.",
+ "MuAPI Resolution": "MuAPI Resolution",
+ "MuAPI Resolution Help": "Resolution sent to the selected MuAPI endpoint. The default budget route accepts 480p, 720p, and 1080p.",
+ "Please Enter the MuAPI API Key": "Please enter the **MuAPI API Key**",
+ "MuAPI Billing Notice": "Each generated clip is billed by MuAPI. Based on the estimated voiceover duration and clip duration, roughly {min}-{max} paid task(s) will be submitted. Generation stops as soon as enough footage is collected.",
+ "MuAPI Billing Notice Without Script": "Each generated clip is billed by MuAPI. Enter or generate the video script to see an estimated task count.",
+ "Confirm MuAPI Charge": "I understand MuAPI video generation creates paid tasks",
+ "Confirm MuAPI Charge Help": "MuAPI clips are submitted one at a time and stop once they cover the voiceover duration. An ambiguous submission is not retried because it may already have created a billable remote task.",
+ "Confirm MuAPI Charge Required": "Please confirm the MuAPI charge before generating the video."
}
}
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index e9bcd24f..d3637064 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -525,6 +525,22 @@
"OFox Upstream Vendor Help": "OFox 视频生成使用的上游厂商。BytePlus(国际)为默认值,内容政策一致;火山引擎为大陆厂商;自动分发由 OFox 网关按权重在可用厂商间调度。",
"OFox Vendor BytePlus": "BytePlus(国际,默认)",
"OFox Vendor Volcengine": "火山引擎(中国大陆)",
- "OFox Vendor Auto": "自动分发(网关调度)"
+ "OFox Vendor Auto": "自动分发(网关调度)",
+ "MuAPI AI Video": "MuAPI AI 视频",
+ "MuAPI AI Video Help": "通过 MuAPI 异步文生视频接口付费生成 AI 视频素材,并复用现有的配音、字幕和剪辑流程。",
+ "MuAPI API Key": "MuAPI API Key([获取 API Key](https://muapi.ai))",
+ "MuAPI API Key Help": "创建 MuAPI API Key 并妥善保管。MuAPI 按实际提交的任务计费。",
+ "MuAPI Base URL": "MuAPI Base URL",
+ "MuAPI Base URL Help": "MuAPI 请求使用的 API 根地址,默认值为 https://api.muapi.ai/api/v1。",
+ "MuAPI Video Endpoint": "MuAPI 视频 Endpoint",
+ "MuAPI Video Endpoint Help": "MuAPI Base URL 下的异步文生视频相对路径,例如 seedance-lite-t2v。",
+ "MuAPI Resolution": "MuAPI 分辨率",
+ "MuAPI Resolution Help": "发送给所选 MuAPI Endpoint 的分辨率。默认预算路由支持 480p、720p 和 1080p。",
+ "Please Enter the MuAPI API Key": "请输入 **MuAPI API Key**",
+ "MuAPI Billing Notice": "每段生成视频都会由 MuAPI 计费。根据预计配音时长和片段时长,将提交约 {min}-{max} 个付费任务;凑够所需素材后会立即停止。",
+ "MuAPI Billing Notice Without Script": "每段生成视频都会由 MuAPI 计费。填写或生成视频文案后可查看预计任务数量。",
+ "Confirm MuAPI Charge": "我已了解 MuAPI 视频生成会创建付费任务",
+ "Confirm MuAPI Charge Help": "MuAPI 素材按脚本片段逐段提交,凑够配音所需时长后立即停止。提交状态不明确时不会自动重试,因为远端任务可能已经创建并产生费用。",
+ "Confirm MuAPI Charge Required": "请确认 MuAPI 生成费用后再生成视频。"
}
}