Skip to content

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

feat(video): add Metaso MiniMax provider

harry070344ce430e6a21
diff --git a/app/services/material.py b/app/services/material.py
index a2a24568..f1de37ae 100644
--- a/app/services/material.py
+++ b/app/services/material.py
@@ -19,6 +19,7 @@ from app.config import config
from app.models.schema import MaterialInfo, VideoAspect, VideoConcatMode
from app.services import (
material_cache,
+ metaso_minimax,
ofox,
task_artifacts,
video,
@@ -1728,6 +1729,18 @@ def download_videos(
max_clip_duration=max_clip_duration,
material_directory=material_directory,
)
+ if source == "metaso_minimax":
+ # 秘塔 MiniMax 同样按远端异步任务计费。它与火山方舟的请求体相似,
+ # 但任务查询路径和响应结构不同,因此只共享本地按需生成语义,不复用
+ # 供应商客户端,避免协议差异渗入素材编排层。
+ return _download_videos_metaso_minimax_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 == "openai_image":
# 与 WaveSpeed 相同的按需付费语义:文生图按张计费,逐段生成、凑够
# 所需时长立即停止。生成结果是一次性的本地图片文件,也不参与 24
@@ -2113,6 +2126,120 @@ def _download_videos_ofox_on_demand(
return video_paths
+def _download_videos_metaso_minimax_on_demand(
+ *,
+ task_id: str,
+ search_terms: List[str],
+ video_aspect: VideoAspect,
+ audio_duration: float,
+ max_clip_duration: int,
+ material_directory: str,
+) -> List[str]:
+ """顺序生成秘塔 MiniMax 素材,覆盖配音时长后立即停止付费下单。"""
+ video_paths: List[str] = []
+ material_sources: list[dict[str, Any]] = []
+
+ # 远端最短生成 4 秒,但本地仍按用户片段时长裁剪和累计。提前验证循环
+ # 控制参数,避免 NaN、Infinity 或非正数让停止条件永远无法满足,进而把
+ # 所有关键词都提交为付费任务。
+ try:
+ required_duration = float(audio_duration)
+ except (TypeError, ValueError) as exc:
+ raise metaso_minimax.MetasoMiniMaxError(
+ "Metaso MiniMax audio duration must be a finite number"
+ ) from exc
+ if not math.isfinite(required_duration):
+ raise metaso_minimax.MetasoMiniMaxError(
+ "Metaso MiniMax audio duration must be a finite number"
+ )
+ if required_duration <= 0:
+ logger.warning(
+ "skip Metaso MiniMax paid generation because required audio duration "
+ f"is 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 metaso_minimax.MetasoMiniMaxError(
+ "Metaso MiniMax clip duration must be a positive integer"
+ ) from exc
+ if clip_duration <= 0:
+ raise metaso_minimax.MetasoMiniMaxError(
+ "Metaso MiniMax clip duration must be a positive integer"
+ )
+
+ total_duration = 0.0
+ for search_term in search_terms:
+ try:
+ video_items = metaso_minimax.generate_videos(
+ search_term=search_term,
+ minimum_duration=clip_duration,
+ video_aspect=video_aspect,
+ )
+ except metaso_minimax.MetasoMiniMaxUnconfirmedTaskError as exc:
+ # 请求或轮询状态不明时,远端任务仍可能成功并计费。立即停止整个
+ # 生成循环,防止后续关键词继续下单,并把任务 ID 交给任务服务保存。
+ logger.error(
+ "stop submitting new Metaso MiniMax tasks because the last paid "
+ f"task is unconfirmed: task_id={exc.task_id or 'unknown'}, "
+ f"detail={exc}"
+ )
+ _persist_material_sources(task_id, material_sources)
+ raise
+ except metaso_minimax.MetasoMiniMaxError as exc:
+ logger.error(f"Metaso MiniMax 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, "metaso_minimax"
+ )
+ if not saved_video_path:
+ # 生成成功已产生费用,下载失败时不能继续创建新任务来替代。
+ # 抛出携带远端 ID 的专用错误,供任务状态和人工恢复使用。
+ 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 metaso_minimax.MetasoMiniMaxDownloadError(
+ "Metaso MiniMax generated a paid video but the result could "
+ f"not be 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=metaso_minimax, error={type(source_error).__name__}, "
+ f"detail={source_error}"
+ )
+
+ # 本地成片只使用用户选择的片段长度;即使 H3 因最短时长约束生成
+ # 了更长素材,也不能把未使用部分计入覆盖时长并少生成必要画面。
+ total_duration += min(clip_duration, item.duration)
+ if total_duration >= required_duration:
+ break
+ if total_duration >= required_duration:
+ logger.info(
+ "generated Metaso MiniMax materials cover the required duration; "
+ f"stop submitting paid tasks: generated={total_duration:.1f}s, "
+ f"required={required_duration:.1f}s"
+ )
+ break
+
+ logger.success(f"generated and downloaded {len(video_paths)} Metaso MiniMax videos")
+ _persist_material_sources(task_id, material_sources)
+ return video_paths
+
+
def _download_videos_by_script_order(
task_id: str,
search_terms: List[str],
diff --git a/app/services/metaso_minimax.py b/app/services/metaso_minimax.py
new file mode 100644
index 00000000..c8958401
--- /dev/null
+++ b/app/services/metaso_minimax.py
@@ -0,0 +1,461 @@
+"""秘塔 MiniMax H3 文生视频客户端。
+
+该模块只负责秘塔代理的 MiniMax V2 协议:提交付费任务、轮询同一个任务、
+解析生成结果。素材按需生成、文件下载和成片拼接仍由 ``material`` 服务负责,
+避免供应商协议与本地视频工作流相互耦合。
+"""
+
+from __future__ import annotations
+
+import math
+import os
+import time
+from collections.abc import Mapping
+from typing import Any
+from urllib.parse import quote, 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://metaso.cn/api/minimax"
+DEFAULT_MODEL_ID = "MiniMax-H3"
+DEFAULT_RESOLUTION = "2K"
+DEFAULT_MIN_DURATION_SECONDS = 4
+DEFAULT_MAX_DURATION_SECONDS = 15
+DEFAULT_POLL_INTERVAL_SECONDS = 10.0
+DEFAULT_RUN_TIMEOUT_SECONDS = 1800.0
+MAX_PROMPT_LENGTH = 7000
+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", "running"})
+TERMINAL_FAILURE_STATUSES = frozenset({"failed", "cancelled", "canceled"})
+SUPPORTED_RESOLUTIONS = frozenset({"768P", "2K"})
+
+
+class MetasoMiniMaxError(RuntimeError):
+ """秘塔 MiniMax 的确定性配置、请求或响应错误。"""
+
+ def __init__(self, message: str, task_id: str = ""):
+ super().__init__(message)
+ # 远端任务一旦创建,所有后续异常都携带同一个 ID。任务服务可以统一
+ # 保存恢复线索,不需要了解轮询、结果解析或下载分别在哪一步失败。
+ self.task_id = task_id
+
+
+class MetasoMiniMaxUnconfirmedTaskError(MetasoMiniMaxError):
+ """远端可能已创建付费任务,但本机无法确认其最终状态。"""
+
+
+class MetasoMiniMaxDownloadError(MetasoMiniMaxError):
+ """远端付费任务已成功,但成片未能下载到本机。"""
+
+
+def get_api_key(settings: Mapping[str, Any] | None = None) -> str:
+ """
+ 按固定优先级读取秘塔凭据。
+
+ 秘塔 ``mk-`` Key 与 MiniMax 官方 Key 属于不同账户体系,因此不能复用
+ 项目已有的 ``minimax_api_key``。独立配置和独立环境变量也能防止用户在
+ 切换 LLM Provider 时意外改变视频生成凭据。
+ """
+ settings = config.app if settings is None else settings
+ configured = str(settings.get("metaso_minimax_api_key", "") or "").strip()
+ environment_key = os.getenv("METASO_MINIMAX_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("metaso_minimax_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 MetasoMiniMaxError(
+ "metaso_minimax_base_url must be an absolute HTTP(S) URL"
+ )
+ return value
+
+
+def _resolution() -> str:
+ configured = config.app.get("metaso_minimax_resolution", DEFAULT_RESOLUTION)
+ value = str(configured).strip().upper()
+ if value not in SUPPORTED_RESOLUTIONS:
+ supported = ", ".join(sorted(SUPPORTED_RESOLUTIONS))
+ # 分辨率直接影响生成费用,用户显式写错时不能静默退回 2K。只有配置项
+ # 完全缺失时才使用默认值,避免无意间创建比预期更贵的任务。
+ raise MetasoMiniMaxError(
+ f"Unsupported Metaso MiniMax resolution {value!r}; "
+ f"expected one of: {supported}"
+ )
+ return value
+
+
+def _tls_verify() -> bool:
+ value = config.app.get("tls_verify", True)
+ 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 _status_code(response: Any) -> int:
+ try:
+ return int(getattr(response, "status_code", 200))
+ except (TypeError, ValueError):
+ return 200
+
+
+def _redact_secret(value: Any, api_key: str) -> str:
+ """保留可排障文本,同时移除 API Key、URL 编码 Key 和代理凭据。"""
+ text = str(value or "")
+ if api_key:
+ text = text.replace(api_key, "***")
+ encoded = quote_plus(api_key)
+ if encoded != api_key:
+ 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:
+ """兼容 MiniMax V2 的嵌套错误结构,并限制日志中的响应长度。"""
+ 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):
+ error_type = error.get("type")
+ message = error.get("message")
+ http_code = error.get("http_code")
+ else:
+ error_type = None
+ message = payload.get("message") or error
+ http_code = payload.get("code")
+ detail = ": ".join(
+ str(item) for item in (error_type, http_code, message) if item not in (None, "")
+ )
+ 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 _normalize_duration(minimum_duration: int) -> tuple[int, int]:
+ """返回“用户请求时长、实际提交时长”,用于日志解释最短 4 秒约束。"""
+ try:
+ requested = int(minimum_duration)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise MetasoMiniMaxError(
+ "Metaso MiniMax clip duration must be a positive integer"
+ ) from exc
+ if requested <= 0:
+ raise MetasoMiniMaxError(
+ "Metaso MiniMax clip duration must be a positive integer"
+ )
+ duration = min(
+ max(requested, DEFAULT_MIN_DURATION_SECONDS),
+ DEFAULT_MAX_DURATION_SECONDS,
+ )
+ return requested, duration
+
+
+def generate_videos(
+ search_term: str,
+ minimum_duration: int,
+ video_aspect: VideoAspect = VideoAspect.portrait,
+) -> list[MaterialInfo]:
+ """提交一个秘塔 MiniMax H3 文生视频任务并等待可下载的结果。"""
+ api_key = get_api_key()
+ if not api_key:
+ raise MetasoMiniMaxError("Metaso MiniMax requires an API key")
+
+ term = str(search_term or "").strip()
+ if not term:
+ # 空提示词通常表示上游脚本拆分失败。付费接口不能用无效输入试探,
+ # 否则即使远端接受也只会产生无法使用的计费素材。
+ raise MetasoMiniMaxError("Metaso MiniMax search term must not be empty")
+ if len(term) > MAX_PROMPT_LENGTH:
+ raise MetasoMiniMaxError(
+ f"Metaso MiniMax search term exceeds {MAX_PROMPT_LENGTH} characters"
+ )
+
+ aspect = VideoAspect(video_aspect)
+ requested_duration, duration = _normalize_duration(minimum_duration)
+ if duration != requested_duration:
+ logger.info(
+ "Metaso MiniMax clip duration adjusted to H3 limits: "
+ f"requested={requested_duration}s, using={duration}s, "
+ f"supported={DEFAULT_MIN_DURATION_SECONDS}-{DEFAULT_MAX_DURATION_SECONDS}s"
+ )
+ resolution = _resolution()
+ payload = {
+ "model": DEFAULT_MODEL_ID,
+ "content": [{"type": "text", "text": term}],
+ "resolution": resolution,
+ "duration": duration,
+ "ratio": aspect.value,
+ }
+ headers = {
+ "Authorization": f"Bearer {api_key}",
+ "Content-Type": "application/json",
+ }
+ base_url = _base_url()
+ create_url = f"{base_url}/v2/video_generation"
+ logger.info(
+ "generating video with Metaso MiniMax H3: "
+ f"resolution={resolution}, ratio={aspect.value}, duration={duration}s, "
+ f"prompt_length={len(term)}"
+ )
+
+ # POST 超时或 5xx 发生时,远端可能已经创建并计费。接口没有提供客户端
+ # 幂等键,因此这里绝不自动重发;上层会停止后续关键词,避免重复扣费。
+ try:
+ response = requests.post(
+ create_url,
+ json=payload,
+ headers=headers,
+ proxies=config.proxy,
+ verify=_tls_verify(),
+ timeout=(30, 60),
+ )
+ except Exception as exc:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax 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 status_code >= 500:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ f"Metaso MiniMax submission failed with HTTP {status_code}; a paid "
+ "task may already exist remotely"
+ )
+ if not 200 <= status_code < 300:
+ raise MetasoMiniMaxError(
+ "Metaso MiniMax video generation request rejected: "
+ f"HTTP {status_code}, {_response_error(response, api_key)}"
+ )
+ try:
+ body = response.json()
+ except Exception as exc:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax submission returned an unreadable response; a paid "
+ f"task may already exist remotely: error={type(exc).__name__}"
+ ) from exc
+
+ task_id = str(body.get("task_id") or "").strip() if isinstance(body, dict) else ""
+ if not task_id:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax accepted the submission without returning a task id"
+ )
+ logger.info(f"Metaso MiniMax paid task created: id={task_id}")
+
+ task = _wait_for_task(
+ task_id=task_id,
+ base_url=base_url,
+ headers=headers,
+ api_key=api_key,
+ )
+ content = task.get("content")
+ video_url = content.get("url") if isinstance(content, dict) else None
+ if not isinstance(video_url, str) or not video_url.startswith(
+ ("http://", "https://")
+ ):
+ raise MetasoMiniMaxError(
+ f"Metaso MiniMax task succeeded without a downloadable video: id={task_id}",
+ task_id=task_id,
+ )
+
+ actual_duration = task.get("duration", duration)
+ try:
+ actual_duration = int(actual_duration)
+ except (TypeError, ValueError, OverflowError):
+ actual_duration = duration
+ if actual_duration <= 0:
+ actual_duration = duration
+
+ return [
+ MaterialInfo(
+ provider="metaso_minimax",
+ url=video_url,
+ duration=actual_duration,
+ source_info={
+ "provider": "metaso_minimax",
+ "search_term": term,
+ "asset_id": task_id,
+ # MiniMax 的 2K/768P 是规格名称,接口没有承诺固定像素尺寸。
+ # 不猜测 width/height,后续若需要精确尺寸应以下载文件探测值为准。
+ "rendition": {"id": task_id},
+ },
+ )
+ ]
+
+
+def _wait_for_task(
+ *,
+ task_id: str,
+ base_url: str,
+ headers: dict[str, str],
+ api_key: str,
+) -> dict[str, Any]:
+ """轮询同一个付费任务,直到成功、明确失败或本地无法确认状态。"""
+ deadline = time.monotonic() + _bounded_float(
+ "metaso_minimax_run_timeout",
+ DEFAULT_RUN_TIMEOUT_SECONDS,
+ 60.0,
+ 7200.0,
+ )
+ poll_interval = _bounded_float(
+ "metaso_minimax_poll_interval",
+ DEFAULT_POLL_INTERVAL_SECONDS,
+ 1.0,
+ 60.0,
+ )
+ query_url = f"{base_url}/v2/query/video_generation/{quote(task_id, safe='')}"
+ consecutive_failures = 0
+
+ while True:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax task is still running after the configured local "
+ f"wait timeout: id={task_id}",
+ task_id=task_id,
+ )
+
+ # connect/read timeout 分别计时,均使用剩余时间的一半,保证一次 GET
+ # 不会有意越过任务总截止时间。到期后不会再发起下一次轮询。
+ phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)
+ try:
+ response = requests.get(
+ query_url,
+ headers=headers,
+ proxies=config.proxy,
+ verify=_tls_verify(),
+ timeout=(phase_timeout, phase_timeout),
+ )
+ status_code = _status_code(response)
+ if status_code in RETRYABLE_STATUS_CODES:
+ raise requests.exceptions.HTTPError(
+ f"HTTP {status_code}", response=response
+ )
+ if not 200 <= status_code < 300:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax task status is unknown: "
+ f"http_status={status_code}, "
+ f"detail={_response_error(response, api_key)}",
+ task_id=task_id,
+ )
+ body = response.json()
+ task = body.get("task") if isinstance(body, dict) else None
+ if not isinstance(task, dict):
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax task status response is malformed",
+ task_id=task_id,
+ )
+ except MetasoMiniMaxUnconfirmedTaskError:
+ raise
+ except Exception as exc:
+ if not _is_retryable_error(exc):
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax polling failed and the paid task state is "
+ f"unknown: 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 MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax task is still running after the configured "
+ f"local wait timeout: id={task_id}",
+ task_id=task_id,
+ ) from exc
+ consecutive_failures += 1
+ if consecutive_failures > MAX_POLL_RETRIES:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax polling failed after retries; the paid task "
+ f"may still be running remotely: id={task_id}",
+ task_id=task_id,
+ ) from exc
+ delay = min(RETRY_BASE_SECONDS * consecutive_failures, remaining)
+ logger.warning(
+ "Metaso MiniMax polling hit a transient error; retrying the same "
+ f"task: id={task_id}, attempt={consecutive_failures}/"
+ f"{MAX_POLL_RETRIES}, retry_in={delay:.1f}s"
+ )
+ time.sleep(delay)
+ continue
+
+ consecutive_failures = 0
+ status = str(task.get("status") or "").strip().lower()
+ logger.info(f"Metaso MiniMax task status: id={task_id}, status={status}")
+ if status == "succeeded":
+ return task
+ if status in TERMINAL_FAILURE_STATUSES:
+ raise MetasoMiniMaxError(
+ "Metaso MiniMax task did not produce a video: "
+ f"id={task_id}, status={status}, "
+ f"detail={_redact_secret(task.get('error'), api_key)}",
+ task_id=task_id,
+ )
+ if status not in ACTIVE_STATUSES:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax returned an unknown task status: "
+ f"id={task_id}, status={status!r}",
+ task_id=task_id,
+ )
+
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise MetasoMiniMaxUnconfirmedTaskError(
+ "Metaso MiniMax task is still running after the configured local "
+ f"wait 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 05a543db..6a96aae8 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -20,6 +20,7 @@ from app.services import (
llm,
loomloom,
material,
+ metaso_minimax,
ofox,
sonilo,
subtitle,
@@ -754,6 +755,21 @@ def get_video_materials(
details=details,
)
return None
+ except metaso_minimax.MetasoMiniMaxError as exc:
+ # 秘塔任务与方舟任务使用不同的恢复入口和字段名,不能合并成一个
+ # 模糊的 remote_task_id。保留明确 Provider 前缀便于 API、WebUI
+ # 和运维日志直接定位对应平台。
+ remote_task_id = str(getattr(exc, "task_id", "") or "").strip()
+ details = (
+ {"metaso_minimax_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,
@@ -1288,6 +1304,17 @@ def _run_pipeline(
"OFox video generation requires an OFox API key",
)
+ if (
+ stop_at in {"materials", "video"}
+ and params.video_source == "metaso_minimax"
+ and not metaso_minimax.is_enabled()
+ ):
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ "Metaso MiniMax requires an API key",
+ )
+
if (
stop_at in {"materials", "video"}
and params.video_source == "openai_image"
diff --git a/cli.py b/cli.py
index e8b618fa..75fca142 100644
--- a/cli.py
+++ b/cli.py
@@ -34,6 +34,19 @@ _PIPELINE_STAGES = ("script", "terms", "audio", "subtitle", "materials", "video"
_CUSTOM_AUDIO_EXTENSIONS = {".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg"}
_BATCH_FILE_MAX_BYTES = 1024 * 1024
_BATCH_TASK_MAX_COUNT = 100
+# 单任务 argparse 和批量清单必须共享同一来源集合。此前两处手工维护导致
+# openai_image 只在单任务入口可用;集中定义后,新增 Provider 不会再次遗漏
+# 批量校验。这里仅包含 CLI 已公开支持的来源,不强行暴露 WebUI 专属流程。
+_CLI_VIDEO_SOURCES = (
+ "pexels",
+ "pixabay",
+ "coverr",
+ "volcengine_seedance",
+ "ofox",
+ "metaso_minimax",
+ "openai_image",
+ "local",
+)
class _CliHelpFormatter(
@@ -263,15 +276,7 @@ Batch manifests:
material_group.add_argument(
"--video-source",
default="pexels",
- choices=[
- "pexels",
- "pixabay",
- "coverr",
- "volcengine_seedance",
- "ofox",
- "openai_image",
- "local",
- ],
+ choices=_CLI_VIDEO_SOURCES,
help="video material provider; online providers require matching API keys in config.toml",
)
material_group.add_argument(
@@ -306,6 +311,14 @@ Batch manifests:
"with --video-source ofox for materials or video output"
),
)
+ material_group.add_argument(
+ "--confirm-metaso-minimax-charge",
+ action="store_true",
+ help=(
+ "confirm that Metaso MiniMax H3 creates paid video tasks; required "
+ "with --video-source metaso_minimax for materials or video output"
+ ),
+ )
video_group = parser.add_argument_group("video output")
video_group.add_argument(
@@ -613,6 +626,16 @@ Batch manifests:
parser.error(
"--confirm-ofox-charge is required with --video-source ofox"
)
+ if (
+ not args.batch_file
+ and args.video_source == "metaso_minimax"
+ and stage_requires_materials
+ and not args.confirm_metaso_minimax_charge
+ ):
+ parser.error(
+ "--confirm-metaso-minimax-charge is required with "
+ "--video-source metaso_minimax"
+ )
if args.bgm_file:
if args.bgm_type in (None, "custom"):
@@ -990,21 +1013,14 @@ def _validate_batch_task_params(
custom_position_is_explicit: bool,
seedance_charge_confirmed: bool,
ofox_charge_confirmed: bool,
+ metaso_minimax_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")
- if params.video_source not in {
- "pexels",
- "pixabay",
- "coverr",
- "volcengine_seedance",
- "ofox",
- "local",
- }:
+ if params.video_source not in _CLI_VIDEO_SOURCES:
raise ValueError(
- "video_source must be one of: pexels, pixabay, coverr, "
- "volcengine_seedance, ofox, local"
+ "video_source must be one of: " + ", ".join(_CLI_VIDEO_SOURCES)
)
for field_name, value in (
("video_aspect", params.video_aspect),
@@ -1044,6 +1060,14 @@ def _validate_batch_task_params(
and not ofox_charge_confirmed
):
raise ValueError("--confirm-ofox-charge is required for OFox video generation")
+ if (
+ params.video_source == "metaso_minimax"
+ and stop_at in {"materials", "video"}
+ and not metaso_minimax_charge_confirmed
+ ):
+ raise ValueError(
+ "--confirm-metaso-minimax-charge is required for Metaso MiniMax H3"
+ )
if stop_at == "subtitle" and not params.subtitle_enabled:
raise ValueError("stop_at=subtitle cannot be combined with disabled subtitles")
@@ -1145,6 +1169,9 @@ def _build_batch_tasks(args: argparse.Namespace) -> list[VideoParams]:
),
seedance_charge_confirmed=args.confirm_seedance_charge,
ofox_charge_confirmed=args.confirm_ofox_charge,
+ metaso_minimax_charge_confirmed=(
+ args.confirm_metaso_minimax_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 975687a1..11a80eec 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -63,7 +63,8 @@ tls_verify = true
# -----------------------------------------------------------------------------
# Available values: "pexels", "pixabay", "coverr", "wavespeed",
-# "volcengine_seedance", "ofox", "loomloom", "openai_image", "local".
+# "volcengine_seedance", "ofox", "metaso_minimax", "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.
# "loomloom" is a paid Shengsuan Cloud source and requires explicit
@@ -156,6 +157,17 @@ ofox_provider = "byteplus"
ofox_poll_interval = 5
ofox_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.
+# When this value is empty, METASO_MINIMAX_API_KEY is used. Generation is billed
+# per submitted clip; the WebUI and CLI require explicit charge confirmation.
+metaso_minimax_api_key = ""
+metaso_minimax_base_url = "https://metaso.cn/api/minimax"
+metaso_minimax_resolution = "2K" # "768P" or "2K"
+metaso_minimax_poll_interval = 10
+metaso_minimax_run_timeout = 1800
+
# OpenAI-compatible text-to-image material source ("openai_image"). Point the
# base URL at any endpoint that speaks the OpenAI /images/generations protocol:
# a local ComfyUI/SD gateway, a self-hosted relay, or a cloud aggregator.
diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.md
index 5452f41e..a07ba9e6 100644
--- a/docs/skill/SKILL.md
+++ b/docs/skill/SKILL.md
@@ -111,6 +111,7 @@ MPT_LLM_MODEL_NAME
MPT_PEXELS_API_KEY
MPT_VOLCENGINE_ARK_API_KEY
MPT_OFOX_API_KEY
+MPT_METASO_MINIMAX_API_KEY
```
When `SEEDANCE_CHARGE_CONFIRMATION_REQUIRED` is present, explain that every
@@ -121,6 +122,11 @@ When `OFOX_CHARGE_CONFIRMATION_REQUIRED` is present, explain that every
generated OFox clip creates a paid task. Only after the user explicitly
confirms, rerun with `--confirm-ofox-charge`; never add this flag silently.
+When `METASO_MINIMAX_CHARGE_CONFIRMATION_REQUIRED` is present, explain that
+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.
+
### 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 d469fbb9..ef195030 100644
--- a/docs/skill/mpt_agent.py
+++ b/docs/skill/mpt_agent.py
@@ -31,6 +31,7 @@ SUPPORTED_SOURCES = {
"coverr",
"volcengine_seedance",
"ofox",
+ "metaso_minimax",
"local",
}
VOLCENGINE_ARK_API_KEY_URL = (
@@ -219,8 +220,20 @@ def apply_environment_config(config_path: Path) -> None:
pexels_key = os.environ.get("MPT_PEXELS_API_KEY", "").strip()
seedance_key = os.environ.get("MPT_VOLCENGINE_ARK_API_KEY", "").strip()
ofox_key = os.environ.get("MPT_OFOX_API_KEY", "").strip()
+ metaso_minimax_key = os.environ.get(
+ "MPT_METASO_MINIMAX_API_KEY", ""
+ ).strip()
if not any(
- (provider, llm_key, base_url, model_name, pexels_key, seedance_key, ofox_key)
+ (
+ provider,
+ llm_key,
+ base_url,
+ model_name,
+ pexels_key,
+ seedance_key,
+ ofox_key,
+ metaso_minimax_key,
+ )
):
return
@@ -251,6 +264,11 @@ def apply_environment_config(config_path: Path) -> None:
if ofox_key:
text = _replace_config_value(text, "ofox_api_key", ofox_key)
changes.append("ofox_api_key")
+ if metaso_minimax_key:
+ text = _replace_config_value(
+ text, "metaso_minimax_api_key", metaso_minimax_key
+ )
+ changes.append("metaso_minimax_api_key")
config_path.write_text(text, encoding="utf-8")
log("updated configuration fields: " + ", ".join(changes))
@@ -353,6 +371,17 @@ def missing_config(config_path: Path, cli_args: list[str]) -> tuple[str, list[st
missing.append("ofox_api_key")
if not has_cli_option(cli_args, "--confirm-ofox-charge"):
missing.append("confirm_ofox_charge")
+ elif source == "metaso_minimax":
+ # 秘塔 Key 与 MiniMax 官方 LLM Key 不互通,Skill 必须沿用运行时的
+ # 独立配置优先级,不能因为已经配置 minimax_api_key 就误判为可用。
+ value = (
+ _plain_config_value(text, "metaso_minimax_api_key")
+ or os.environ.get("METASO_MINIMAX_API_KEY", "").strip()
+ )
+ if not _has_configured_value(value):
+ 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 != "local":
value = _plain_config_value(text, f"{source}_api_keys")
if not _has_configured_value(value):
@@ -368,7 +397,11 @@ def report_missing_config(provider: str, missing: list[str]) -> int:
print(f"MISSING={field}")
if any(
field.endswith("_api_key")
- and field not in {"volcengine_seedance_api_key", "ofox_api_key"}
+ and field not in {
+ "volcengine_seedance_api_key",
+ "ofox_api_key",
+ "metaso_minimax_api_key",
+ }
for field in missing
):
print("LLM_PROVIDER_OPTIONS_BEGIN")
@@ -397,6 +430,13 @@ def report_missing_config(provider: str, missing: list[str]) -> int:
print("OFOX_API_KEY_ENV=MPT_OFOX_API_KEY")
if "confirm_ofox_charge" in missing:
print("OFOX_CHARGE_CONFIRMATION_REQUIRED=--confirm-ofox-charge")
+ if "metaso_minimax_api_key" in missing:
+ print("METASO_MINIMAX_API_KEY_ENV=MPT_METASO_MINIMAX_API_KEY")
+ if "confirm_metaso_minimax_charge" in missing:
+ print(
+ "METASO_MINIMAX_CHARGE_CONFIRMATION_REQUIRED="
+ "--confirm-metaso-minimax-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 9f3a4987..cdbcc8e9 100644
--- a/test/services/test_cli.py
+++ b/test/services/test_cli.py
@@ -295,6 +295,42 @@ class TestCli(unittest.TestCase):
)
self.assertEqual(args.video_source, "volcengine_seedance")
+ def test_metaso_minimax_video_source_requires_charge_confirmation(self):
+ with self.assertRaises(SystemExit) as raised:
+ cli.parse_args(
+ [
+ "--video-subject",
+ "test",
+ "--video-source",
+ "metaso_minimax",
+ ]
+ )
+ self.assertEqual(raised.exception.code, 2)
+
+ args = cli.parse_args(
+ [
+ "--video-subject",
+ "test",
+ "--video-source",
+ "metaso_minimax",
+ "--confirm-metaso-minimax-charge",
+ ]
+ )
+ self.assertEqual(cli.build_video_params(args).video_source, "metaso_minimax")
+
+ def test_metaso_confirmation_is_not_required_before_material_stage(self):
+ args = cli.parse_args(
+ [
+ "--video-subject",
+ "test",
+ "--video-source",
+ "metaso_minimax",
+ "--stop-at",
+ "script",
+ ]
+ )
+ self.assertEqual(args.video_source, "metaso_minimax")
+
def test_batch_seedance_source_uses_global_charge_confirmation(self):
with tempfile.TemporaryDirectory() as temp_dir:
manifest = Path(temp_dir) / "tasks.json"
@@ -337,6 +373,48 @@ class TestCli(unittest.TestCase):
self.assertEqual(accepted, 0)
start.assert_called_once()
+ def test_batch_metaso_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": "Metaso batch task",
+ "video_source": "metaso_minimax",
+ }
+ ]
+ ),
+ 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-metaso"),
+ redirect_stdout(io.StringIO()),
+ ):
+ accepted = cli.run_cli(
+ [
+ "--batch-file",
+ str(manifest),
+ "--stop-at",
+ "materials",
+ "--confirm-metaso-minimax-charge",
+ ]
+ )
+
+ self.assertEqual(accepted, 0)
+ start.assert_called_once()
+
def test_build_video_params_with_script_video_and_audio_options(self):
args = cli.parse_args(
[
@@ -869,6 +947,30 @@ class TestCli(unittest.TestCase):
{"index", "task_id", "status", "result", "failed_stage", "error"},
)
+ def test_batch_accepts_openai_image_source(self):
+ """批量入口必须接受单任务 CLI 已支持的 OpenAI 文生图素材源。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ manifest = Path(temp_dir) / "tasks.json"
+ manifest.write_text(
+ json.dumps(
+ [
+ {
+ "video_subject": "batch image source",
+ "video_source": "openai_image",
+ }
+ ]
+ ),
+ encoding="utf-8",
+ )
+ args = cli.parse_args(
+ ["--batch-file", str(manifest), "--stop-at", "script"]
+ )
+
+ tasks = cli._build_batch_tasks(args)
+
+ self.assertEqual(len(tasks), 1)
+ self.assertEqual(tasks[0].video_source, "openai_image")
+
def test_batch_jsonl_continues_after_runtime_and_structured_failures(self):
with tempfile.TemporaryDirectory() as temp_dir:
manifest = Path(temp_dir) / "tasks.jsonl"
diff --git a/test/services/test_config.py b/test/services/test_config.py
index 6ca3c8ac..2a165b1b 100644
--- a/test/services/test_config.py
+++ b/test/services/test_config.py
@@ -43,6 +43,7 @@ class TestConfigPersistence:
"coverr",
"volcengine_seedance",
"ofox",
+ "metaso_minimax",
"loomloom",
"local",
}
@@ -56,6 +57,9 @@ class TestConfigPersistence:
assert app_config["ofox_api_key"] == ""
assert app_config["ofox_base_url"].startswith("https://")
assert app_config["ofox_text_to_video_model"]
+ 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 "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_metaso_minimax.py b/test/services/test_metaso_minimax.py
new file mode 100644
index 00000000..b8c4b899
--- /dev/null
+++ b/test/services/test_metaso_minimax.py
@@ -0,0 +1,435 @@
+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, metaso_minimax, state as sm
+from app.services import task as task_service
+
+
+def _response(payload, status_code=200):
+ """构造只暴露服务层实际使用字段的轻量 HTTP 响应。"""
+ return SimpleNamespace(status_code=status_code, json=lambda: payload)
+
+
[email protected](autouse=True)
+def restore_config():
+ """隔离全局配置,避免供应商测试影响其它 Provider 用例。"""
+ original_app = dict(config.app)
+ original_proxy = dict(config.proxy)
+ config.app.update(
+ {
+ "metaso_minimax_api_key": "metaso-test-key",
+ "metaso_minimax_base_url": metaso_minimax.DEFAULT_BASE_URL,
+ "metaso_minimax_resolution": metaso_minimax.DEFAULT_RESOLUTION,
+ }
+ )
+ 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_provider_environment():
+ with patch.dict(
+ os.environ,
+ {
+ "METASO_MINIMAX_API_KEY": "environment-key",
+ "MINIMAX_API_KEY": "official-key-must-not-be-used",
+ },
+ clear=False,
+ ):
+ assert metaso_minimax.get_api_key() == "metaso-test-key"
+ config.app["metaso_minimax_api_key"] = ""
+ assert metaso_minimax.get_api_key() == "environment-key"
+ os.environ["METASO_MINIMAX_API_KEY"] = ""
+ config.app["minimax_api_key"] = "shared-key-must-not-be-used"
+ assert metaso_minimax.get_api_key() == ""
+
+
+def test_invalid_input_fails_before_paid_submission():
+ invalid_terms = ("", " ", None, "a" * (metaso_minimax.MAX_PROMPT_LENGTH + 1))
+ for term in invalid_terms:
+ with patch.object(metaso_minimax.requests, "post") as post:
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError):
+ metaso_minimax.generate_videos(term, 5)
+ post.assert_not_called()
+
+ config.app["metaso_minimax_api_key"] = ""
+ with (
+ patch.dict(os.environ, {"METASO_MINIMAX_API_KEY": ""}, clear=False),
+ patch.object(metaso_minimax.requests, "post") as post,
+ ):
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError):
+ metaso_minimax.generate_videos("sunrise", 5)
+ post.assert_not_called()
+
+
+def test_submit_poll_and_parse_successful_video():
+ submit = _response({"task_id": "metaso-task-1"})
+ polls = [
+ _response(
+ {
+ "task": {
+ "id": "metaso-task-1",
+ "status": "running",
+ }
+ }
+ ),
+ _response(
+ {
+ "task": {
+ "id": "metaso-task-1",
+ "status": "succeeded",
+ "content": {
+ "url": "https://cdn.example.com/video.mp4?signature=abc"
+ },
+ "duration": 5,
+ "resolution": "2K",
+ "ratio": "16:9",
+ }
+ }
+ ),
+ ]
+ with (
+ patch.object(metaso_minimax.requests, "post", return_value=submit) as post,
+ patch.object(metaso_minimax.requests, "get", side_effect=polls) as get,
+ patch.object(metaso_minimax.time, "sleep") as sleep,
+ ):
+ result = metaso_minimax.generate_videos(
+ " cinematic sunrise ",
+ minimum_duration=5,
+ video_aspect=VideoAspect.landscape,
+ )
+
+ assert len(result) == 1
+ item = result[0]
+ assert item.provider == "metaso_minimax"
+ assert item.url.endswith("video.mp4?signature=abc")
+ assert item.duration == 5
+ assert item.source_info == {
+ "provider": "metaso_minimax",
+ "search_term": "cinematic sunrise",
+ "asset_id": "metaso-task-1",
+ "rendition": {"id": "metaso-task-1"},
+ }
+ assert post.call_args.args[0] == (
+ f"{metaso_minimax.DEFAULT_BASE_URL}/v2/video_generation"
+ )
+ assert post.call_args.kwargs["headers"]["Authorization"] == (
+ "Bearer metaso-test-key"
+ )
+ assert post.call_args.kwargs["json"] == {
+ "model": "MiniMax-H3",
+ "content": [{"type": "text", "text": "cinematic sunrise"}],
+ "resolution": "2K",
+ "duration": 5,
+ "ratio": "16:9",
+ }
+ assert get.call_count == 2
+ assert all(
+ call.args[0].endswith("/v2/query/video_generation/metaso-task-1")
+ for call in get.call_args_list
+ )
+ sleep.assert_called_once_with(metaso_minimax.DEFAULT_POLL_INTERVAL_SECONDS)
+
+
+def test_duration_is_clamped_and_resolution_is_normalized():
+ config.app["metaso_minimax_resolution"] = " 768p "
+ submit = _response({"task_id": "metaso-task-bounds"})
+ completed = _response(
+ {
+ "task": {
+ "id": "metaso-task-bounds",
+ "status": "succeeded",
+ "content": {"url": "https://cdn.example.com/bounds.mp4"},
+ "duration": 4,
+ }
+ }
+ )
+ with (
+ patch.object(metaso_minimax.requests, "post", return_value=submit) as post,
+ patch.object(metaso_minimax.requests, "get", return_value=completed),
+ ):
+ result = metaso_minimax.generate_videos("city", 2)
+
+ assert post.call_args.kwargs["json"]["duration"] == 4
+ assert post.call_args.kwargs["json"]["resolution"] == "768P"
+ assert result[0].duration == 4
+
+
[email protected]("invalid", ["1080P", "", None, False, "4K"])
+def test_invalid_resolution_fails_before_paid_submission(invalid):
+ config.app["metaso_minimax_resolution"] = invalid
+ with patch.object(metaso_minimax.requests, "post") as post:
+ with pytest.raises(
+ metaso_minimax.MetasoMiniMaxError,
+ match="Unsupported Metaso MiniMax resolution",
+ ):
+ metaso_minimax.generate_videos("city", 5)
+ post.assert_not_called()
+
+
+def test_submission_errors_are_not_retried_and_secret_is_redacted():
+ rejected = _response(
+ {
+ "type": "error",
+ "error": {
+ "type": "bad_request_error",
+ "message": "rejected metaso-test-key",
+ "http_code": "400",
+ },
+ },
+ status_code=400,
+ )
+ with patch.object(metaso_minimax.requests, "post", return_value=rejected) as post:
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError) as raised:
+ metaso_minimax.generate_videos("unsafe", 5)
+ assert "metaso-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(
+ metaso_minimax.requests,
+ "post",
+ side_effect=side_effect,
+ return_value=response,
+ ) as post:
+ with pytest.raises(metaso_minimax.MetasoMiniMaxUnconfirmedTaskError):
+ metaso_minimax.generate_videos("sunrise", 5)
+ assert post.call_count == 1
+
+
+def test_poll_retries_transient_errors_on_same_task():
+ submit = _response({"task_id": "metaso-retry"})
+ rate_limited = _response({}, status_code=429)
+ completed = _response(
+ {
+ "task": {
+ "id": "metaso-retry",
+ "status": "succeeded",
+ "content": {"url": "https://cdn.example.com/retry.mp4"},
+ }
+ }
+ )
+ with (
+ patch.object(metaso_minimax.requests, "post", return_value=submit) as post,
+ patch.object(
+ metaso_minimax.requests,
+ "get",
+ side_effect=[
+ rate_limited,
+ requests.exceptions.ConnectionError("offline"),
+ completed,
+ ],
+ ) as get,
+ patch.object(metaso_minimax.time, "sleep") as sleep,
+ ):
+ result = metaso_minimax.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", [{}, {"task_id": " "}, [], None])
+def test_missing_task_id_is_unconfirmed_and_never_polled(payload):
+ with (
+ patch.object(metaso_minimax.requests, "post", return_value=_response(payload)),
+ patch.object(metaso_minimax.requests, "get") as get,
+ ):
+ with pytest.raises(metaso_minimax.MetasoMiniMaxUnconfirmedTaskError):
+ metaso_minimax.generate_videos("sunrise", 5)
+ get.assert_not_called()
+
+
+def test_succeeded_task_without_video_url_preserves_task_id():
+ with (
+ patch.object(
+ metaso_minimax.requests,
+ "post",
+ return_value=_response({"task_id": "metaso-no-url"}),
+ ),
+ patch.object(
+ metaso_minimax.requests,
+ "get",
+ return_value=_response(
+ {
+ "task": {
+ "id": "metaso-no-url",
+ "status": "succeeded",
+ "content": {},
+ }
+ }
+ ),
+ ),
+ ):
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError) as raised:
+ metaso_minimax.generate_videos("sunrise", 5)
+ assert raised.value.task_id == "metaso-no-url"
+
+
[email protected]("status", sorted(metaso_minimax.TERMINAL_FAILURE_STATUSES))
+def test_terminal_failure_preserves_task_id(status):
+ with patch.object(
+ metaso_minimax.requests,
+ "get",
+ return_value=_response(
+ {
+ "task": {
+ "id": "metaso-failed",
+ "status": status,
+ "error": {"message": "generation failed"},
+ }
+ }
+ ),
+ ):
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError) as raised:
+ metaso_minimax._wait_for_task(
+ task_id="metaso-failed",
+ base_url=metaso_minimax.DEFAULT_BASE_URL,
+ headers={},
+ api_key="metaso-test-key",
+ )
+ assert raised.value.task_id == "metaso-failed"
+
+
+def test_on_demand_generation_stops_after_required_duration():
+ generated_item = MaterialInfo(
+ provider="metaso_minimax",
+ url="https://cdn.example.com/video.mp4",
+ duration=5,
+ source_info={
+ "provider": "metaso_minimax",
+ "asset_id": "metaso-paid-1",
+ },
+ )
+ with (
+ patch.object(
+ metaso_minimax, "generate_videos", return_value=[generated_item]
+ ) as generate,
+ patch.object(
+ material,
+ "_save_generated_video_with_retry",
+ return_value="/tmp/video.mp4",
+ ),
+ patch.object(material, "_persist_material_sources"),
+ ):
+ paths = material._download_videos_metaso_minimax_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"
+
+
[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(metaso_minimax, "generate_videos") as generate:
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError, match="audio duration"):
+ material.download_videos(
+ task_id="metaso-invalid-audio",
+ search_terms=["one", "two"],
+ source="metaso_minimax",
+ audio_duration=audio_duration,
+ max_clip_duration=5,
+ )
+ generate.assert_not_called()
+
+
[email protected]("clip_duration", [0, -1, None, "bad", float("nan")])
+def test_on_demand_rejects_invalid_clip_duration_before_submission(clip_duration):
+ with patch.object(metaso_minimax, "generate_videos") as generate:
+ with pytest.raises(metaso_minimax.MetasoMiniMaxError, match="clip duration"):
+ material.download_videos(
+ task_id="metaso-invalid-clip",
+ search_terms=["one", "two"],
+ source="metaso_minimax",
+ audio_duration=5,
+ max_clip_duration=clip_duration,
+ )
+ generate.assert_not_called()
+
+
+def test_download_failure_stops_later_paid_submissions_and_keeps_task_id():
+ generated_item = MaterialInfo(
+ provider="metaso_minimax",
+ url="https://cdn.example.com/video.mp4",
+ duration=5,
+ source_info={"asset_id": "metaso-paid-download"},
+ )
+ with (
+ patch.object(
+ metaso_minimax, "generate_videos", return_value=[generated_item]
+ ) as generate,
+ patch.object(material, "_save_generated_video_with_retry", return_value=""),
+ ):
+ with pytest.raises(metaso_minimax.MetasoMiniMaxDownloadError) as raised:
+ material.download_videos(
+ task_id="metaso-download-failed",
+ search_terms=["one", "two"],
+ source="metaso_minimax",
+ audio_duration=10,
+ max_clip_duration=5,
+ )
+ assert raised.value.task_id == "metaso-paid-download"
+ assert generate.call_count == 1
+
+
+def test_task_preflight_rejects_missing_key_before_script_generation():
+ params = VideoParams(
+ video_subject="Metaso preflight",
+ video_source="metaso_minimax",
+ )
+ memory_state = sm.MemoryState()
+ with (
+ patch.object(metaso_minimax, "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("metaso-preflight", params, stop_at="materials")
+
+ assert result["failed_stage"] == "preflight"
+ assert "Metaso MiniMax requires an API key" in result["error"]
+ generate_script.assert_not_called()
+
+
+def test_material_failure_keeps_metaso_remote_task_id():
+ params = VideoParams(
+ video_subject="space fleet",
+ video_source="metaso_minimax",
+ )
+ failure = metaso_minimax.MetasoMiniMaxUnconfirmedTaskError(
+ "remote state unknown",
+ task_id="metaso-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["metaso_minimax_task_id"] == "metaso-recover-1"
diff --git a/test/services/test_mpt_agent_skill.py b/test/services/test_mpt_agent_skill.py
index af643dd6..7292eccb 100644
--- a/test/services/test_mpt_agent_skill.py
+++ b/test/services/test_mpt_agent_skill.py
@@ -30,6 +30,7 @@ pixabay_api_keys = []
coverr_api_keys = []
volcengine_seedance_api_key = ""
ofox_api_key = ""
+metaso_minimax_api_key = ""
oneapi_api_key = ""
oneapi_base_url = ""
oneapi_model_name = ""
@@ -101,6 +102,7 @@ class TestMptAgentSkill(unittest.TestCase):
llm_key = "secret-llm-key"
pexels_key = "secret-pexels-key"
seedance_key = "secret-ark-key"
+ metaso_key = "secret-metaso-key"
with patch.dict(
os.environ,
@@ -109,6 +111,7 @@ class TestMptAgentSkill(unittest.TestCase):
"MPT_LLM_API_KEY": llm_key,
"MPT_PEXELS_API_KEY": pexels_key,
"MPT_VOLCENGINE_ARK_API_KEY": seedance_key,
+ "MPT_METASO_MINIMAX_API_KEY": metaso_key,
},
clear=True,
), redirect_stdout(output):
@@ -121,9 +124,11 @@ class TestMptAgentSkill(unittest.TestCase):
self.assertIn(
f'volcengine_seedance_api_key = "{seedance_key}"', config
)
+ self.assertIn(f'metaso_minimax_api_key = "{metaso_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())
def test_material_key_check_matches_selected_source(self):
with tempfile.TemporaryDirectory() as temp_dir:
@@ -289,6 +294,39 @@ class TestMptAgentSkill(unittest.TestCase):
self.assertEqual(missing, [])
+ def test_metaso_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",
+ )
+
+ _, missing = mpt_agent.missing_config(
+ config_path, ["--video-source", "metaso_minimax"]
+ )
+ self.assertEqual(
+ missing,
+ ["metaso_minimax_api_key", "confirm_metaso_minimax_charge"],
+ )
+
+ with patch.dict(
+ os.environ,
+ {"METASO_MINIMAX_API_KEY": "environment-metaso-key"},
+ clear=True,
+ ):
+ _, confirmed_missing = mpt_agent.missing_config(
+ config_path,
+ [
+ "--video-source",
+ "metaso_minimax",
+ "--confirm-metaso-minimax-charge",
+ ],
+ )
+ self.assertEqual(confirmed_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"
@@ -346,6 +384,26 @@ class TestMptAgentSkill(unittest.TestCase):
)
self.assertNotIn("LLM_PROVIDER_OPTIONS_BEGIN", text)
+ def test_missing_metaso_inputs_report_key_environment_and_charge_flag(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = mpt_agent.report_missing_config(
+ "deepseek",
+ ["metaso_minimax_api_key", "confirm_metaso_minimax_charge"],
+ )
+
+ text = output.getvalue()
+ self.assertEqual(code, mpt_agent.NEEDS_INPUT_EXIT_CODE)
+ self.assertIn(
+ "METASO_MINIMAX_API_KEY_ENV=MPT_METASO_MINIMAX_API_KEY", text
+ )
+ self.assertIn(
+ "METASO_MINIMAX_CHARGE_CONFIRMATION_REQUIRED="
+ "--confirm-metaso-minimax-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_webui_grouped_select.py b/test/services/test_webui_grouped_select.py
index f7e7bda1..c044f661 100644
--- a/test/services/test_webui_grouped_select.py
+++ b/test/services/test_webui_grouped_select.py
@@ -118,10 +118,11 @@ def test_grouped_video_source_keeps_groups_and_accessible_label_binding():
"pexels",
"pixabay",
"coverr",
- "wavespeed",
+ "metaso_minimax",
+ "loomloom",
"volcengine_seedance",
+ "wavespeed",
"ofox",
- "loomloom",
"openai_image",
"local",
]
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index 5bf485a5..c873f2eb 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -46,6 +46,22 @@ ENGLISH_FALLBACK_KEYS = frozenset(
"Resume LoomLoom Status Check",
"LoomLoom Quote Summary Singular",
"LoomLoom Video Terms Reuse Help",
+ "Metaso MiniMax H3",
+ "Metaso MiniMax H3 Help",
+ "Metaso MiniMax API Key",
+ "Metaso MiniMax API Key Help",
+ "Metaso MiniMax Base URL",
+ "Metaso MiniMax Resolution",
+ "Metaso MiniMax Resolution Help",
+ "Metaso MiniMax Invalid Resolution",
+ "Select Metaso MiniMax Resolution",
+ "Please Enter the Metaso MiniMax API Key",
+ "Metaso MiniMax Billing Notice",
+ "Metaso MiniMax Billing Notice Uploaded Audio",
+ "Metaso MiniMax Billing Notice Without Script",
+ "Confirm Metaso MiniMax Charge",
+ "Confirm Metaso MiniMax Charge Help",
+ "Confirm Metaso MiniMax Charge Required",
"Script Generation Method",
"Script Generation Method Help",
"Shengsuan Cloud AI Video",
@@ -161,6 +177,15 @@ class TestWebuiI18n(unittest.TestCase):
)
self.assertEqual(_markdown_urls(rendered), expected_urls)
+ def test_metaso_api_key_label_keeps_mpt_referral_link(self):
+ """秘塔 Key 获取入口必须保留 MPT 追踪参数,避免赞助转化链路失效。"""
+ expected_url = "https://metaso.cn/minimax-h3/?s=MPT"
+
+ for locale in ("zh", "en"):
+ with self.subTest(locale=locale):
+ label = _load_translation(locale)["Metaso MiniMax API Key"]
+ self.assertEqual(_markdown_urls(label), {expected_url})
+
def test_secondary_locales_cover_english_locale(self):
en_translations = _load_translation("en")
required_en_keys = _required_translation_keys(en_translations)
diff --git a/test/services/test_webui_llm_settings.py b/test/services/test_webui_llm_settings.py
index a11351b2..1dd874ad 100644
--- a/test/services/test_webui_llm_settings.py
+++ b/test/services/test_webui_llm_settings.py
@@ -127,3 +127,61 @@ def test_material_settings_target_uses_localized_tab_state_and_is_consumed():
assert [str(item.value) for item in app.exception] == []
assert app.session_state["settings_dialog_tabs_zh"] == "素材来源设置"
assert "settings_dialog_target_tab" not in app.session_state
+
+
+def test_ai_video_settings_prioritize_sponsors_and_own_shengsuan_key():
+ """视频 Provider 应按约定的赞助商顺序展示,胜算云密钥只在设置中管理。"""
+ app_config = dict(
+ config.app,
+ llm_provider="openai",
+ script_generation_backend="loomloom",
+ video_source="pexels",
+ loomloom_api_token="initial-token",
+ )
+ ui_config = dict(config.ui, language="en")
+
+ with (
+ patch.object(config, "app", app_config),
+ patch.object(config, "ui", ui_config),
+ patch.object(config, "try_save_config", return_value=True),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.session_state["settings_dialog_open"] = True
+ app.session_state["settings_dialog_target_tab"] = "material"
+ app.run()
+
+ markdown_values = [str(item.value) for item in app.markdown]
+ provider_titles = [
+ "**Metaso · MiniMax H3**",
+ "**Shengsuan Cloud AI Video**",
+ "**Volcano Engine Ark · Seedance**",
+ "**WaveSpeed**",
+ "**OFox**",
+ ]
+ provider_positions = [
+ next(
+ index
+ for index, value in enumerate(markdown_values)
+ if value.startswith(title)
+ )
+ for title in provider_titles
+ ]
+ assert provider_positions == sorted(provider_positions)
+
+ settings_token = _widget_by_key(
+ app.text_input,
+ "loomloom_api_token_input",
+ )
+ assert settings_token.value == "initial-token"
+ assert all(
+ item.key != "loomloom_user_api_token" for item in app.text_input
+ )
+
+ settings_token.set_value("settings-token").run()
+ assert app_config["loomloom_api_token"] == "settings-token"
+ assert _widget_by_key(
+ app.text_input,
+ "loomloom_api_token_input",
+ ).value == "settings-token"
+ assert [str(item.value) for item in app.exception] == []
diff --git a/test/services/test_webui_loomloom.py b/test/services/test_webui_loomloom.py
index 413db2f9..b51f7764 100644
--- a/test/services/test_webui_loomloom.py
+++ b/test/services/test_webui_loomloom.py
@@ -126,7 +126,7 @@ def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():
llm_provider="openai",
script_generation_backend="loomloom",
loomloom_base_url="https://example.test/loom/v1",
- loomloom_api_token="test-token",
+ loomloom_api_token="user-token-1",
loomloom_market_listing_id="listing-1",
)
quote_result = loomloom.LoomLoomQuote(
@@ -173,9 +173,7 @@ def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():
assert execute_call.call_count == 0
_widget_by_key(app.text_area, "video_subject").set_value("AI daily life").run()
- _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
- "user-token-1"
- ).run()
+ assert all(item.key != "loomloom_user_api_token" for item in app.text_input)
_widget_by_key(app.button, "loomloom_quote_scripts").click().run()
assert quote_call.call_count == 1
@@ -183,14 +181,12 @@ def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():
assert execute_button.disabled
assert execute_call.call_count == 0
- _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
- "user-token-2"
- ).run()
+ test_config["loomloom_api_token"] = "user-token-2"
+ app.run()
assert _widget_by_key(app.button, "loomloom_execute_scripts").disabled
- _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
- "user-token-1"
- ).run()
+ test_config["loomloom_api_token"] = "user-token-1"
+ app.run()
_widget_by_key(app.checkbox, "loomloom_confirm_charge").check().run()
execute_button = _widget_by_key(app.button, "loomloom_execute_scripts")
assert not execute_button.disabled
@@ -214,7 +210,7 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():
script_generation_backend="local",
video_source="pexels",
loomloom_base_url="https://example.test/loom/v1",
- loomloom_api_token="",
+ loomloom_api_token="session-user-token",
)
quote_result = loomloom.LoomLoomQuote(
quote_id="video-quote-1",
@@ -249,9 +245,7 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():
).run()
app.session_state["video_source_select_en"] = "loomloom"
app.run()
- _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
- "session-user-token"
- ).run()
+ assert all(item.key != "loomloom_user_api_token" for item in app.text_input)
assert _widget_by_key(app.number_input, "loomloom_video_scene_count").value == 1
_widget_by_key(app.button, "loomloom_quote_videos").click().run()
assert quote_call.call_count == 1
@@ -270,7 +264,7 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():
assert [str(item.value) for item in app.exception] == []
-def test_selected_shengsuanyun_provider_hides_duplicate_loomloom_key_input():
+def test_generation_page_omits_shengsuan_key_input():
test_config = dict(
config.app,
llm_provider="shengsuanyun",
@@ -288,7 +282,6 @@ def test_selected_shengsuanyun_provider_hides_duplicate_loomloom_key_input():
app.run()
assert all(item.key != "loomloom_user_api_token" for item in app.text_input)
- assert any("reused" in str(item.value).lower() for item in app.caption)
assert [str(item.value) for item in app.exception] == []
diff --git a/test/services/test_webui_metaso_minimax.py b/test/services/test_webui_metaso_minimax.py
new file mode 100644
index 00000000..3f9c1bda
--- /dev/null
+++ b/test/services/test_webui_metaso_minimax.py
@@ -0,0 +1,129 @@
+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):
+ """按稳定业务 key 查找经过语言后缀处理的 Streamlit 控件。"""
+ return next(
+ item
+ for item in elements
+ if str(getattr(item, "key", "")) == key
+ or str(getattr(item, "key", "")).startswith(f"{key}_")
+ )
+
+
+def test_metaso_source_requires_confirmation_and_never_enters_task_params():
+ test_config = dict(
+ config.app,
+ llm_provider="openai",
+ video_source="pexels",
+ metaso_minimax_api_key="metaso-secret",
+ metaso_minimax_base_url="https://metaso.cn/api/minimax",
+ metaso_minimax_resolution="2K",
+ )
+ 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("Space fleet").run()
+ _widget_by_key(app.text_area, "video_script").set_value(
+ "A fleet jumps through space while its captain watches."
+ ).run()
+ _widget_by_key(app.text_area, "video_terms").set_value(
+ "cinematic space fleet"
+ ).run()
+ app.session_state["video_source_select_en"] = "metaso_minimax"
+ app.run()
+
+ clip_duration = _widget_by_key(app.selectbox, "video_clip_duration_select")
+ assert min(map(int, clip_duration.options)) == 4
+ assert max(map(int, clip_duration.options)) == 15
+ clip_duration.set_value(15).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, "metaso_minimax_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 == "metaso_minimax"
+ assert submitted_params.video_clip_duration == 15
+ assert "metaso-secret" not in submitted_params.model_dump_json()
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_invalid_metaso_resolution_requires_an_explicit_replacement():
+ """打开设置不能把无效分辨率静默改成价格更高的默认 2K。"""
+ test_config = dict(
+ config.app,
+ llm_provider="openai",
+ video_source="pexels",
+ metaso_minimax_resolution="720P",
+ )
+ test_ui = dict(config.ui, language="zh")
+ with (
+ patch.object(config, "app", test_config),
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "try_save_config", return_value=True),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["settings_dialog_open"] = True
+ app.session_state["settings_dialog_target_tab"] = "material"
+ app.run()
+
+ resolution = _widget_by_key(
+ app.selectbox, "metaso_minimax_resolution_input"
+ )
+ assert resolution.value is None
+ assert test_config["metaso_minimax_resolution"] == "720P"
+ assert any("720P" in str(item.value) for item in app.error)
+
+ resolution.set_value("768P").run()
+ assert test_config["metaso_minimax_resolution"] == "768P"
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_metaso_upload_voiceover_uses_actual_audio_billing_copy():
+ """上传配音时不得用脚本文字长度冒充真实的付费任务数量。"""
+ test_config = dict(
+ config.app,
+ video_source="metaso_minimax",
+ metaso_minimax_api_key="metaso-secret",
+ metaso_minimax_resolution="2K",
+ )
+ test_ui = dict(config.ui, language="en", voice_mode="upload")
+ with (
+ patch.object(config, "app", test_config),
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "try_save_config", return_value=True),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)
+ app.session_state["ui_language"] = "en"
+ app.run()
+
+ billing_warnings = [
+ str(item.value)
+ for item in app.warning
+ if "billed by Metaso" in str(item.value)
+ ]
+ assert len(billing_warnings) == 1
+ assert "audio file's actual duration" in billing_warnings[0]
+ assert "estimated" not in billing_warnings[0].lower()
+ assert [str(item.value) for item in app.exception] == []
diff --git a/test/services/test_webui_settings_transfer.py b/test/services/test_webui_settings_transfer.py
index 5df80f26..1674894b 100644
--- a/test/services/test_webui_settings_transfer.py
+++ b/test/services/test_webui_settings_transfer.py
@@ -359,7 +359,6 @@ def test_credential_widget_state_keys_cover_shared_input_aliases():
)
assert credential_widget_state_keys("app", "loomloom_api_token") == (
"loomloom_api_token_input",
- "loomloom_user_api_token",
)
@@ -370,7 +369,7 @@ def test_apply_key_backup_writes_config_and_clears_every_widget_alias():
{
"gemini_api_key_input": "stale-gemini",
"gemini_tts_api_key_input": "stale-gemini",
- "loomloom_user_api_token": "stale-loomloom",
+ "loomloom_api_token_input": "stale-loomloom",
"azure_speech_key_input": "stale-azure",
"elevenlabs_voices_stale-key": ["old voice"],
"video_subject": "untouched",
diff --git a/webui/Main.py b/webui/Main.py
index a7137268..4faf3fd1 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -49,8 +49,9 @@ from app.services import (
llm,
loomloom,
material,
- video,
+ metaso_minimax,
ofox,
+ video,
volcengine_seedance,
voice,
webui_task,
@@ -103,11 +104,18 @@ VOICE_MODE_UPLOAD = "upload"
VOICE_MODE_NONE = "none"
LOOMLOOM_MAX_POLL_FAILURES = 5
# WebUI 按素材能力分组展示视频来源,但底层仍保存原有 video_source 值。
-# 这样既能让用户先判断需要“搜索库存素材”还是“AI 生成”,又不会改变
-# config.toml、历史任务和 API 请求中的字段语义,旧用户升级后无需迁移配置。
+# AI 视频组与设置页共用同一业务顺序:合作服务商优先,并按秘塔、胜算云、
+# 火山引擎排列;其余服务随后展示。这样用户在两个入口看到的顺序一致,同时
+# 不改变 config.toml、历史任务和 API 请求中的字段语义,旧用户无需迁移配置。
VIDEO_SOURCE_GROUPS = {
"stock_video": ("pexels", "pixabay", "coverr"),
- "ai_video": ("wavespeed", "volcengine_seedance", "ofox", "loomloom"),
+ "ai_video": (
+ "metaso_minimax",
+ "loomloom",
+ "volcengine_seedance",
+ "wavespeed",
+ "ofox",
+ ),
"ai_image": ("openai_image",),
"local": ("local",),
}
@@ -220,12 +228,11 @@ NON_LLM_COMPANION_KEYS = {
"app": ("upload_post_username",)
}
# 同一个密钥在不同面板可能使用各自的控件 key:音频面板直接编辑 Gemini 和
-# MiMo 的 LLM 密钥,胜算云密钥的控件没有 _input 后缀。恢复备份时必须清除
-# 每一个别名,否则遗留的旧值会在下一次 rerun 覆盖刚刚恢复的密钥。
+# MiMo 的 LLM 密钥。恢复备份时必须清除每一个别名,否则遗留的旧值
+# 会在下一次 rerun 覆盖刚刚恢复的密钥。
CREDENTIAL_WIDGET_STATE_ALIASES = {
("app", "gemini_api_key"): ("gemini_tts_api_key_input",),
("app", "mimo_api_key"): ("mimo_tts_api_key_input",),
- ("app", "loomloom_api_token"): ("loomloom_user_api_token",),
}
# ui 分区只保存界面偏好,不含任何凭据,备份时整体跳过。
KEY_BACKUP_EXCLUDED_SECTIONS = frozenset({"ui"})
@@ -562,6 +569,7 @@ def _initialize_session_state():
"wavespeed_confirm_charge": False,
"volcengine_seedance_confirm_charge": False,
"ofox_confirm_charge": False,
+ "metaso_minimax_confirm_charge": False,
# AI 视频按素材段计费,默认只生成一段,用户确认效果后再主动增加数量。
"loomloom_video_scene_count": _saved_ui_number(
"loomloom_video_scene_count",
@@ -3297,15 +3305,112 @@ def _render_settings_dialog():
st.markdown(f"#### {tr('AI Video Generation APIs')}")
st.caption(tr("AI Video Generation APIs Help"))
- wavespeed_api_key = _get_material_api_keys("wavespeed_api_keys")
- st.markdown("**WaveSpeed**")
- wavespeed_api_key = st.text_input(
- tr("WaveSpeed API Key"),
- value=wavespeed_api_key,
+ # 视频生成 Provider 按赞助商优先展示,赞助商内部顺序
+ # 与商务约定保持一致:秘塔、胜算云、火山引擎。
+ st.markdown(f"**{tr('Metaso MiniMax H3')}**")
+ metaso_api_key = st.text_input(
+ tr("Metaso MiniMax API Key"),
+ value=str(
+ config.app.get("metaso_minimax_api_key", "") or ""
+ ).strip(),
type="password",
- key="wavespeed_api_keys_input",
+ help=tr("Metaso MiniMax API Key Help"),
+ key="metaso_minimax_api_key_input",
)
- _save_material_api_keys("wavespeed_api_keys", wavespeed_api_key)
+ _set_runtime_config(
+ "app", "metaso_minimax_api_key", metaso_api_key.strip()
+ )
+ configured_metaso_base_url = str(
+ config.app.get(
+ "metaso_minimax_base_url",
+ metaso_minimax.DEFAULT_BASE_URL,
+ )
+ or metaso_minimax.DEFAULT_BASE_URL
+ ).strip()
+ metaso_base_url = st.text_input(
+ tr("Metaso MiniMax Base URL"),
+ value=(
+ ""
+ if configured_metaso_base_url == metaso_minimax.DEFAULT_BASE_URL
+ else configured_metaso_base_url
+ ),
+ placeholder=metaso_minimax.DEFAULT_BASE_URL,
+ key="metaso_minimax_base_url_input",
+ )
+ _set_runtime_config(
+ "app",
+ "metaso_minimax_base_url",
+ metaso_base_url.strip() or metaso_minimax.DEFAULT_BASE_URL,
+ )
+ configured_metaso_resolution = (
+ str(
+ config.app.get(
+ "metaso_minimax_resolution",
+ metaso_minimax.DEFAULT_RESOLUTION,
+ )
+ )
+ .strip()
+ .upper()
+ )
+ metaso_resolution_options = sorted(
+ metaso_minimax.SUPPORTED_RESOLUTIONS,
+ key=lambda value: value != metaso_minimax.DEFAULT_RESOLUTION,
+ )
+ resolution_is_valid = (
+ configured_metaso_resolution
+ in metaso_minimax.SUPPORTED_RESOLUTIONS
+ )
+ if not resolution_is_valid:
+ # 分辨率直接影响计费。手工配置错误时保留原值并要求用户
+ # 主动选择,不能在打开设置弹窗时静默改成价格更高的 2K。
+ st.error(
+ tr("Metaso MiniMax Invalid Resolution").format(
+ value=configured_metaso_resolution,
+ supported=", ".join(metaso_resolution_options),
+ )
+ )
+ metaso_resolution = st.selectbox(
+ tr("Metaso MiniMax Resolution"),
+ options=metaso_resolution_options,
+ index=(
+ metaso_resolution_options.index(configured_metaso_resolution)
+ if resolution_is_valid
+ else None
+ ),
+ key="metaso_minimax_resolution_input",
+ help=tr("Metaso MiniMax Resolution Help"),
+ placeholder=tr("Select Metaso MiniMax Resolution"),
+ )
+ if metaso_resolution is not None:
+ _set_runtime_config(
+ "app", "metaso_minimax_resolution", metaso_resolution
+ )
+
+ st.divider()
+ st.markdown(f"**{tr('Shengsuan Cloud AI Video')}**")
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ if (
+ str(app_config_snapshot.get("llm_provider", "") or "").lower()
+ == "shengsuanyun"
+ ):
+ # 大模型 Provider 已选胜算云时,视频生成直接复用
+ # 同一密钥,不再展示一个容易引起歧义的独立输入框。
+ st.caption(tr("Shengsuan Cloud API Key Reused"))
+ else:
+ configured_loomloom_token = str(
+ app_config_snapshot.get("loomloom_api_token", "") or ""
+ ).strip()
+ loomloom_api_token = st.text_input(
+ tr("Shengsuan Cloud API Key"),
+ value=configured_loomloom_token,
+ type="password",
+ key="loomloom_api_token_input",
+ help=tr("Shengsuan Cloud API Key Help"),
+ placeholder=tr("Shengsuan Cloud API Key Placeholder"),
+ ).strip()
+ _set_runtime_config(
+ "app", "loomloom_api_token", loomloom_api_token
+ )
st.divider()
seedance_api_key_value = str(
@@ -3387,6 +3492,18 @@ def _render_settings_dialog():
seedance_base_url.strip() or volcengine_seedance.DEFAULT_BASE_URL,
)
+ st.divider()
+ wavespeed_api_key = _get_material_api_keys("wavespeed_api_keys")
+ st.markdown("**WaveSpeed**")
+ wavespeed_api_key = st.text_input(
+ tr("WaveSpeed API Key"),
+ value=wavespeed_api_key,
+ type="password",
+ key="wavespeed_api_keys_input",
+ )
+ _save_material_api_keys("wavespeed_api_keys", wavespeed_api_key)
+
+ st.divider()
st.markdown("**OFox**")
ofox_api_key = st.text_input(
tr("OFox API Key"),
@@ -3566,26 +3683,6 @@ def _effective_script_generation_backend():
return backend if backend in {"local", "loomloom"} else "local"
-def _render_loomloom_api_token_input():
- """仅在未选择胜算云 Provider 时显示独立 LoomLoom 密钥输入。"""
- app_config_snapshot = config.snapshot_config_with_pending(config.app)
- if str(app_config_snapshot.get("llm_provider", "") or "").lower() == "shengsuanyun":
- st.caption(tr("Shengsuan Cloud API Key Reused"))
- return loomloom.resolve_api_token(app_config_snapshot)
-
- configured_token = loomloom.resolve_api_token(app_config_snapshot)
- st.session_state.setdefault("loomloom_user_api_token", configured_token)
- api_token = st.text_input(
- tr("Shengsuan Cloud API Key"),
- type="password",
- key="loomloom_user_api_token",
- help=tr("Shengsuan Cloud API Key Help"),
- placeholder=tr("Shengsuan Cloud API Key Placeholder"),
- ).strip()
- _set_runtime_config("app", "loomloom_api_token", api_token)
- return _effective_loomloom_api_token()
-
-
def _loomloom_video_scene_prompts(video_terms, subject, scene_count):
"""按素材关键词生成有限数量的场景描述,供视频模型逐段生成素材。"""
if isinstance(video_terms, str):
@@ -3655,9 +3752,7 @@ def _current_loomloom_video_quote_context(params):
def _render_loomloom_video_settings(params):
"""渲染默认视频 SkillBot 的报价、报价失效和付费确认流程。"""
st.caption(tr("Shengsuan Cloud AI Video Help"))
- if _effective_script_generation_backend() != "loomloom":
- _render_loomloom_api_token_input()
- elif (
+ if (
str(
config.snapshot_config_with_pending(config.app).get("llm_provider", "")
or ""
@@ -3929,7 +4024,7 @@ def _render_loomloom_run_progress():
def _render_loomloom_script_generation(params):
st.caption(tr("LoomLoom Batch Script Generation Help"))
- effective_token = _render_loomloom_api_token_input()
+ effective_token = _effective_loomloom_api_token()
if not effective_token:
st.warning(tr("Shengsuan Cloud API Key Required"))
@@ -4316,6 +4411,7 @@ def _render_video_settings(panel, params):
"wavespeed": tr("WaveSpeed AI Video"),
"volcengine_seedance": tr("Volcano Engine Seedance"),
"ofox": tr("OFox AI Video"),
+ "metaso_minimax": tr("Metaso MiniMax H3"),
"loomloom": tr("Shengsuan Cloud AI Video"),
"openai_image": tr("OpenAI Compatible Text-to-Image"),
"local": tr("Local file"),
@@ -4345,6 +4441,8 @@ def _render_video_settings(panel, params):
st.caption(tr("Volcano Engine Seedance Help"))
if params.video_source == "ofox":
st.caption(tr("OFox AI Video Help"))
+ if params.video_source == "metaso_minimax":
+ st.caption(tr("Metaso MiniMax H3 Help"))
if params.video_source == "local":
# Streamlit 的文件类型校验对扩展名大小写敏感,这里同时放行大小写两种形式。
local_file_types = sorted(
@@ -4482,12 +4580,25 @@ def _render_video_settings(panel, params):
"ui", "video_fit_mode", params.video_fit_mode.value
)
- video_clip_durations = [2, 3, 4, 5, 6, 7, 8, 9, 10]
+ # MiniMax H3 的远端时长范围是 4~15 秒。选择秘塔时使用完整能力
+ # 范围,既避免 2/3 秒被按 4 秒计费,也让 WebUI 与 CLI、服务层一致。
+ 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]
+ )
params.video_clip_duration = stable_selectbox(
tr("Clip Duration"),
options=video_clip_durations,
default_value=_saved_ui_choice(
- "video_clip_duration", video_clip_durations, 3
+ "video_clip_duration",
+ video_clip_durations,
+ 5 if params.video_source == "metaso_minimax" else 3,
),
key="video_clip_duration_select",
help=tr("Clip Duration Help"),
@@ -4568,6 +4679,8 @@ def _render_video_settings(panel, params):
_render_seedance_video_settings(params)
if params.video_source == "ofox":
_render_ofox_video_settings(params)
+ if params.video_source == "metaso_minimax":
+ _render_metaso_minimax_video_settings(params)
return uploaded_files
@@ -4653,6 +4766,60 @@ def _render_ofox_video_settings(params):
)
+def _render_metaso_minimax_video_settings(params):
+ """展示预计付费任务数量,并要求用户确认秘塔 MiniMax 生成费用。"""
+ clip_duration = max(int(params.video_clip_duration or 1), 1)
+ video_count = max(int(params.video_count or 1), 1)
+ voice_mode = st.session_state.get(
+ localized_widget_key("voice_mode_control"),
+ config.ui.get("voice_mode"),
+ )
+ if voice_mode == VOICE_MODE_UPLOAD:
+ # 视频设置渲染在音频设置之前,此时无法可靠读取本轮新上传文件的实际
+ # 时长。上传模式不再展示按脚本文字推算的数字,避免用户误以为一个
+ # 5 秒音频也会按较长文案创建多个付费任务;运行时仍以文件真实时长为准。
+ st.warning(
+ tr("Metaso MiniMax Billing Notice Uploaded Audio").format(
+ resolution=str(
+ config.app.get(
+ "metaso_minimax_resolution",
+ metaso_minimax.DEFAULT_RESOLUTION,
+ )
+ or metaso_minimax.DEFAULT_RESOLUTION
+ ),
+ duration=clip_duration,
+ count=video_count,
+ )
+ )
+ elif 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("Metaso MiniMax Billing Notice").format(
+ min=min_clips,
+ max=max_clips,
+ resolution=str(
+ config.app.get(
+ "metaso_minimax_resolution",
+ metaso_minimax.DEFAULT_RESOLUTION,
+ )
+ or metaso_minimax.DEFAULT_RESOLUTION
+ ),
+ )
+ )
+ else:
+ st.warning(tr("Metaso MiniMax Billing Notice Without Script"))
+ st.checkbox(
+ tr("Confirm Metaso MiniMax Charge"),
+ key="metaso_minimax_confirm_charge",
+ help=tr("Confirm Metaso MiniMax Charge Help"),
+ )
+
+
def _estimate_voiceover_duration_range(
text: str, voice_rate: float
) -> tuple[float, float] | None:
@@ -6326,6 +6493,7 @@ def _render_generation_controls(
"wavespeed",
"volcengine_seedance",
"ofox",
+ "metaso_minimax",
"loomloom",
"openai_image",
"local",
@@ -6399,6 +6567,22 @@ def _render_generation_controls(
st.error(tr("Confirm OFox Charge Required"))
st.stop()
+ if params.video_source == "metaso_minimax" and not (
+ metaso_minimax.is_enabled(
+ config.snapshot_config_with_pending(config.app)
+ )
+ ):
+ _remove_active_generation_task(task_id)
+ st.error(tr("Please Enter the Metaso MiniMax API Key"))
+ st.stop()
+
+ if params.video_source == "metaso_minimax" and not st.session_state.get(
+ "metaso_minimax_confirm_charge", False
+ ):
+ _remove_active_generation_task(task_id)
+ st.error(tr("Confirm Metaso MiniMax 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 8a815f80..a545e4f5 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -28,7 +28,7 @@
"Shengsuan Cloud API Key": "Shengsuan Cloud API Key",
"Shengsuan Cloud API Key Help": "Create an API Key in the [Shengsuan Cloud console](https://console.shengsuanyun.com/user/keys). The key is saved to config.toml, and usage is billed to your account.",
"Shengsuan Cloud API Key Placeholder": "Enter an API Key",
- "Shengsuan Cloud API Key Required": "Enter your Shengsuan Cloud API Key before generating AI video materials.",
+ "Shengsuan Cloud API Key Required": "Configure your Shengsuan Cloud API Key in Settings before using Shengsuan Cloud script or AI video generation.",
"Shengsuan Cloud API Key Reused": "The Shengsuan Cloud API Key from Settings is reused here; no duplicate entry is needed.",
"Script Generation Method": "Script Generation Method",
"Script Generation Method Help": "Local LLM uses the Provider configured in Settings. Shengsuan Cloud generates several paid candidates after you review and confirm a quote.",
@@ -378,6 +378,22 @@
"Confirm Volcano Engine Seedance Charge": "I understand Volcano Engine Seedance generation creates paid Ark tasks",
"Confirm Volcano Engine Seedance Charge Help": "Seedance clips are submitted one at a time and stop once they cover the voiceover duration. Ark bills each submitted generation task.",
"Confirm Volcano Engine Seedance Charge Required": "Please confirm the Volcano Engine Seedance charge before generating the video.",
+ "Metaso MiniMax H3": "Metaso · MiniMax H3",
+ "Metaso MiniMax H3 Help": "Generate brand-new clips from script keywords through Metaso's MiniMax H3 V2 proxy. Each clip creates a paid asynchronous task.",
+ "Metaso MiniMax API Key": "Metaso MiniMax API Key ([Get one](https://metaso.cn/minimax-h3/?s=MPT))",
+ "Metaso MiniMax API Key Help": "Register through the MoneyPrinterTurbo referral link and enter the independent API key issued by Metaso. It cannot be shared with the MiniMax LLM API key.",
+ "Metaso MiniMax Base URL": "Metaso MiniMax Base URL",
+ "Metaso MiniMax Resolution": "Metaso MiniMax Resolution",
+ "Metaso MiniMax Resolution Help": "MiniMax H3 supports 768P and 2K. This controls the generated source material; MPT still exports on its fixed output canvas (1920×1080 for 16:9). Metaso currently lists CNY 0.09/s for 768P and CNY 0.15/s for 2K; the checkout price is authoritative.",
+ "Metaso MiniMax Invalid Resolution": "The configured Metaso MiniMax resolution `{value}` is invalid. Select one of: {supported}. The existing value has not been changed.",
+ "Select Metaso MiniMax Resolution": "Select a valid resolution",
+ "Please Enter the Metaso MiniMax API Key": "Please enter the **Metaso MiniMax API Key**",
+ "Metaso MiniMax Billing Notice": "Each generated clip is billed by Metaso. At {resolution}, the estimated voiceover and clip duration require roughly {min}-{max} paid task(s). Generation stops as soon as enough footage is collected.",
+ "Metaso MiniMax Billing Notice Uploaded Audio": "Each generated clip is billed by Metaso. The current settings use {resolution}, {duration}-second clips, and {count} output video(s). With an uploaded voiceover, the paid task count is based on the audio file's actual duration, and generation stops as soon as enough footage is collected.",
+ "Metaso MiniMax Billing Notice Without Script": "Each MiniMax H3 clip is billed by Metaso. Enter or generate the video script to see an estimated task count.",
+ "Confirm Metaso MiniMax Charge": "I understand Metaso MiniMax H3 creates paid video tasks",
+ "Confirm Metaso MiniMax Charge Help": "Clips are submitted one script segment at a time and stop once they cover the voiceover duration. Metaso bills the submitted generation tasks.",
+ "Confirm Metaso MiniMax Charge Required": "Please confirm the Metaso MiniMax H3 charge before generating the video.",
"OpenAI Compatible Text-to-Image": "OpenAI Compatible Text-to-Image",
"OpenAI Image Base URL": "OpenAI Compatible Image Base URL",
"OpenAI Image API Key": "OpenAI Compatible Image API Key",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index ece6f46f..da5d690d 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -28,7 +28,7 @@
"Shengsuan Cloud API Key": "胜算云 API Key",
"Shengsuan Cloud API Key Help": "请前往[胜算云控制台](https://console.shengsuanyun.com/user/keys)创建 API Key。密钥会保存到 config.toml,调用费用将从您的账户扣除。",
"Shengsuan Cloud API Key Placeholder": "输入 API Key",
- "Shengsuan Cloud API Key Required": "请先输入胜算云 API Key,再生成 AI 视频素材。",
+ "Shengsuan Cloud API Key Required": "请先在“设置”中配置胜算云 API Key,再使用胜算云脚本或 AI 视频生成。",
"Shengsuan Cloud API Key Reused": "已复用“设置 → 大模型提供商”中的胜算云 API Key,无需重复填写。",
"Script Generation Method": "文案生成方式",
"Script Generation Method Help": "当前大模型使用“设置”中的 Provider;胜算云批量生成会在确认报价后付费生成多个候选。",
@@ -378,6 +378,22 @@
"Confirm Volcano Engine Seedance Charge": "我已了解火山引擎 Seedance 会创建付费方舟任务",
"Confirm Volcano Engine Seedance Charge Help": "Seedance 素材按脚本片段逐段提交,凑够配音所需时长后立即停止。火山方舟按实际提交的生成任务计费。",
"Confirm Volcano Engine Seedance Charge Required": "请确认火山引擎 Seedance 生成费用后再生成视频。",
+ "Metaso MiniMax H3": "秘塔 · MiniMax H3",
+ "Metaso MiniMax H3 Help": "通过秘塔代理的 MiniMax H3 V2 接口,按脚本关键词生成全新视频素材。每段素材都会创建一个付费异步任务。",
+ "Metaso MiniMax API Key": "秘塔 MiniMax API Key([专属链接获取](https://metaso.cn/minimax-h3/?s=MPT))",
+ "Metaso MiniMax API Key Help": "请通过 MoneyPrinterTurbo 专属链接注册并获取秘塔独立 API Key。该凭据不能与 MiniMax 大模型 API Key 混用。",
+ "Metaso MiniMax Base URL": "秘塔 MiniMax Base URL",
+ "Metaso MiniMax Resolution": "秘塔 MiniMax 分辨率",
+ "Metaso MiniMax Resolution Help": "MiniMax H3 支持 768P 和 2K。该选项控制秘塔生成素材的规格;MPT 最终成片仍按当前固定画布导出(16:9 为 1920×1080)。秘塔当前页面标价为 768P 0.09 元/秒、2K 0.15 元/秒,实际费用以秘塔结算页为准。",
+ "Metaso MiniMax Invalid Resolution": "当前配置的秘塔 MiniMax 分辨率 `{value}` 无效,请选择:{supported}。原配置值尚未被修改。",
+ "Select Metaso MiniMax Resolution": "请选择有效分辨率",
+ "Please Enter the Metaso MiniMax API Key": "请输入 **秘塔 MiniMax API Key**",
+ "Metaso MiniMax Billing Notice": "每段生成视频都会由秘塔计费。当前选择 {resolution},根据预计配音时长和片段时长,将提交约 {min}-{max} 个付费任务;凑够所需素材后会立即停止。",
+ "Metaso MiniMax Billing Notice Uploaded Audio": "每段生成视频都会由秘塔计费。当前选择 {resolution}、每段 {duration} 秒、生成 {count} 条成片;上传配音时,付费任务数量按音频文件的实际时长计算,凑够所需素材后会立即停止。",
+ "Metaso MiniMax Billing Notice Without Script": "每段 MiniMax H3 视频都会由秘塔计费。填写或生成视频文案后可查看预计任务数量。",
+ "Confirm Metaso MiniMax Charge": "我已了解秘塔 MiniMax H3 会创建付费视频任务",
+ "Confirm Metaso MiniMax Charge Help": "素材按脚本片段逐段提交,凑够配音所需时长后立即停止。秘塔按实际提交的生成任务结算。",
+ "Confirm Metaso MiniMax Charge Required": "请确认秘塔 MiniMax H3 生成费用后再生成视频。",
"OpenAI Compatible Text-to-Image": "OpenAI 兼容文生图",
"OpenAI Image Base URL": "OpenAI 兼容文生图 Base URL",
"OpenAI Image API Key": "OpenAI 兼容文生图 API 密钥",
@@ -418,7 +434,7 @@
"llm_provider_tips.minimax": "##### MiniMax 配置说明\n- **API Key**: 在 [中国站](https://platform.minimaxi.com/) 或 [国际站](https://platform.minimax.io/) 创建\n- **Base Url**: 中国站使用 `https://api.minimaxi.com/v1`;国际站使用 `{default_base_url}`(默认)\n- **Model Name**: 默认 `{default_model}`;也可以填写当前账号支持的其它模型 ID\n\n请确保 API Key 与 Base Url 来自同一平台,否则可能出现鉴权失败。",
"llm_provider_tips.pollinations": "##### Pollinations AI 配置说明\n- **API Key**: 在 [Pollinations]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;也可以填写 [模型目录](https://gen.pollinations.ai/v1/models) 中支持 Chat Completions 的其它模型 ID",
"LoomLoom Video Terms Reuse Help": "LoomLoom 文案候选已包含素材关键词。选择候选或在下方编辑关键词即可,不再调用本地大模型。",
- "Shengsuan Cloud AI Video": "胜算云 AI 生成",
+ "Shengsuan Cloud AI Video": "胜算云 AI 视频",
"Shengsuan Cloud AI Video Help": "通过默认 LoomLoom SkillBot 付费生成 1~5 段 AI 视频素材。请先获取报价并确认费用,再使用现有配音、字幕和剪辑流程合成成片。",
"AI Video Scene Count": "AI 视频素材段数",
"AI Video Quote Summary": "共 {tasks} 段 AI 视频素材,预计扣费:{amount} {currency}",
diff --git a/webui/styles.css b/webui/styles.css
index 3f3f2bb2..570530be 100644
--- a/webui/styles.css
+++ b/webui/styles.css
@@ -371,8 +371,10 @@ div[class*="st-key-task_row_"] button[kind="secondary"] p {
}
-/* 中等宽度下将四个设置面板调整为 2×2,避免每列过窄导致标签和按钮频繁换行。 */
-@media (min-width: 701px) and (max-width: 1100px) {
+/* 中等宽度下将四个设置面板调整为 2×2。主内容区还会扣除页面边距,因此
+ 1200~1440px 的常见视口不足以稳定容纳四列英文标签;断点覆盖到 1500px,
+ 避免下拉内容和标题被裁切,真正的宽屏才恢复四列。 */
+@media (min-width: 701px) and (max-width: 1500px) {
.mpt-brand__name {
font-size: 2.25rem;
}