Skip to content

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

feat(bgm): add ElevenLabs video-matched music

harry0703d5f31da9a2eb
diff --git a/app/models/schema.py b/app/models/schema.py
index 58eb4959..5c3b4ce1 100644
--- a/app/models/schema.py
+++ b/app/models/schema.py
@@ -97,6 +97,9 @@ class VideoParams(BaseModel):
bgm_type: Optional[str] = "random"
bgm_file: Optional[str] = ""
bgm_volume: Optional[float] = 0.2
+ # 视频配乐供应商共用提示词,WebUI 新任务统一写入该字段。保留下面的
+ # Sonilo 专用字段以兼容旧任务记录和现有 CLI 参数。
+ video_music_prompt: str = Field(default="", max_length=2000)
sonilo_bgm_prompt: str = Field(default="", max_length=2000)
subtitle_enabled: Optional[bool] = True
diff --git a/app/services/elevenlabs_music.py b/app/services/elevenlabs_music.py
new file mode 100644
index 00000000..c88a990e
--- /dev/null
+++ b/app/services/elevenlabs_music.py
@@ -0,0 +1,384 @@
+import math
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import Any
+
+import requests
+from loguru import logger
+
+from app.config import config
+from app.services import bgm as bgm_service
+from app.utils import utils
+
+
+DEFAULT_BASE_URL = "https://api.elevenlabs.io"
+VIDEO_TO_MUSIC_PATH = "/v1/music/video-to-music"
+SUBSCRIPTION_PATH = "/v1/user/subscription"
+DEFAULT_MODEL_ID = "music_v2"
+SUPPORTED_MODEL_IDS = frozenset({"music_v1", "music_v2"})
+MAX_VIDEO_DURATION_SECONDS = 600
+MAX_PROMPT_LENGTH = 1000
+MAX_PROXY_BYTES = 200 * 1024 * 1024
+MAX_GENERATED_AUDIO_BYTES = 50 * 1024 * 1024
+
+
+class ElevenLabsMusicError(RuntimeError):
+ """表示 ElevenLabs 配乐请求、代理生成或返回音频校验失败。"""
+
+
+class ElevenLabsPaidPlanRequiredError(ElevenLabsMusicError):
+ """表示 Key 有效,但当前账号套餐不包含 ElevenLabs Music API。"""
+
+
+class ElevenLabsAuthenticationError(ElevenLabsMusicError):
+ """表示 ElevenLabs API Key 缺失或已被服务端拒绝。"""
+
+
+def get_api_key() -> str:
+ """
+ 读取 ElevenLabs 共用 API Key。
+
+ 配乐与现有 ElevenLabs TTS 使用同一个账号配置,避免用户在 WebUI 重复维护
+ 两份 Key;环境变量仅作为本机配置未填写时的后备来源。
+ """
+ configured_key = str(config.elevenlabs.get("api_key", "") or "").strip()
+ return configured_key or os.getenv("ELEVENLABS_API_KEY", "").strip()
+
+
+def is_enabled() -> bool:
+ return bool(get_api_key())
+
+
+def _base_url() -> str:
+ return str(
+ config.elevenlabs.get("music_base_url", DEFAULT_BASE_URL)
+ or DEFAULT_BASE_URL
+ ).rstrip("/")
+
+
+def _model_id() -> str:
+ """只允许官方 Video-to-Music 当前公开的模型,错误配置时安全回退。"""
+ model_id = str(
+ config.elevenlabs.get("music_model_id", DEFAULT_MODEL_ID)
+ or DEFAULT_MODEL_ID
+ ).strip()
+ return model_id if model_id in SUPPORTED_MODEL_IDS else DEFAULT_MODEL_ID
+
+
+def _request_timeout() -> tuple[int, int]:
+ """限制配乐读取超时,兼顾长视频生成耗时与错误配置的可恢复性。"""
+ raw_timeout = config.elevenlabs.get("music_timeout", 600)
+ try:
+ read_timeout = float(raw_timeout)
+ except (TypeError, ValueError):
+ read_timeout = 600
+ if not math.isfinite(read_timeout) or read_timeout <= 0:
+ read_timeout = 600
+ return 15, max(1, math.ceil(min(read_timeout, 1800)))
+
+
+def _safe_response_error(response: requests.Response) -> str:
+ """截断第三方错误正文,保留定位信息但不让 HTML 页面污染任务日志。"""
+ body = (response.text or "").strip().replace("\n", " ")[:500]
+ return body or response.reason or "request failed"
+
+
+def test_connection() -> dict[str, Any]:
+ """
+ 使用不消耗音乐生成额度的订阅接口检查 API Key 和账号套餐。
+
+ 该接口只能确认 Key 可访问订阅信息以及账号不是免费套餐,不能证明当前 Key
+ 一定拥有 Music endpoint 权限。ElevenLabs 允许按 endpoint、额度和 IP 限制
+ Key,因此 UI 成功提示必须保留这一边界,实际权限仍由生成请求最终确认。
+ 响应中的账单和用量详情不会写入日志,避免记录账号隐私。
+ """
+ api_key = get_api_key()
+ if not api_key:
+ raise ElevenLabsAuthenticationError("ElevenLabs API key is required")
+ try:
+ response = requests.get(
+ f"{_base_url()}{SUBSCRIPTION_PATH}",
+ headers={"xi-api-key": api_key},
+ timeout=(15, 30),
+ )
+ except requests.RequestException as exc:
+ raise ElevenLabsMusicError(
+ f"failed to connect to ElevenLabs: {exc}"
+ ) from exc
+ if response.status_code == 401:
+ raise ElevenLabsAuthenticationError(
+ "ElevenLabs API key was rejected (401): "
+ f"{_safe_response_error(response)}"
+ )
+ if not response.ok:
+ raise ElevenLabsMusicError(
+ f"ElevenLabs account check failed ({response.status_code}): "
+ f"{_safe_response_error(response)}"
+ )
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise ElevenLabsMusicError(
+ "ElevenLabs returned an invalid subscription response"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise ElevenLabsMusicError(
+ "ElevenLabs returned an unexpected subscription response"
+ )
+ tier = str(payload.get("tier") or "").strip().lower()
+ if not tier:
+ raise ElevenLabsMusicError(
+ "ElevenLabs subscription response does not include an account tier"
+ )
+ if tier == "free":
+ raise ElevenLabsPaidPlanRequiredError(
+ "ElevenLabs Music API requires a paid plan; "
+ "the current account is on the free tier"
+ )
+ logger.info(f"ElevenLabs account and plan check succeeded: tier={tier}")
+ return payload
+
+
+def validate_generation_access() -> None:
+ """
+ 在昂贵的视频流水线开始前排除确定无法生成配乐的账号。
+
+ 免费套餐和无效 Key 都是确定性错误,必须立即终止,避免先消耗 LLM、TTS
+ 和素材服务额度。订阅接口也可能因 Music-only endpoint scope、IP 限制或
+ 临时网络问题不可访问;这些结果不能证明 Music API 不可用,因此只记录警告,
+ 继续让真正的生成请求决定结果,避免把受限但可用的 Key 错误拦截。
+ """
+ try:
+ test_connection()
+ except (ElevenLabsPaidPlanRequiredError, ElevenLabsAuthenticationError):
+ raise
+ except ElevenLabsMusicError as exc:
+ logger.warning(
+ "ElevenLabs account preflight was inconclusive; "
+ f"generation will verify Music API access: error={exc}"
+ )
+
+
+def _remove_file(file_path: str) -> None:
+ """尽力清理 ElevenLabs 中间文件,不覆盖调用方正在处理的原始异常。"""
+ if not file_path or not os.path.exists(file_path):
+ return
+ try:
+ os.remove(file_path)
+ except OSError as exc:
+ logger.warning(
+ "failed to remove ElevenLabs temporary file: "
+ f"path={file_path}, error={exc}"
+ )
+
+
+def _create_video_proxy(video_path: str) -> str:
+ """
+ 生成无音轨、最长边 1280 像素的 H.264 代理视频。
+
+ Video-to-Music 只分析画面,上传原始高清成片既不会改善配乐,又会增加流量
+ 和等待时间。代理严格限制在官方 200 MB 上限内,并在请求结束后删除。
+ """
+ descriptor, proxy_path = tempfile.mkstemp(
+ prefix=".elevenlabs-music-proxy-",
+ suffix=".mp4",
+ dir=os.path.dirname(os.path.abspath(video_path)),
+ )
+ os.close(descriptor)
+ command = [
+ utils.get_ffmpeg_binary(),
+ "-nostdin",
+ "-v",
+ "error",
+ "-y",
+ "-i",
+ video_path,
+ "-vf",
+ (
+ "scale=w=1280:h=1280:force_original_aspect_ratio=decrease:"
+ "force_divisible_by=2"
+ ),
+ "-an",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "30",
+ "-pix_fmt",
+ "yuv420p",
+ "-movflags",
+ "+faststart",
+ proxy_path,
+ ]
+ try:
+ result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=600,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ _remove_file(proxy_path)
+ raise ElevenLabsMusicError(
+ "ElevenLabs video proxy generation timed out"
+ ) from exc
+ except OSError as exc:
+ _remove_file(proxy_path)
+ raise ElevenLabsMusicError(
+ "failed to run FFmpeg for ElevenLabs video proxy"
+ ) from exc
+ if result.returncode != 0:
+ _remove_file(proxy_path)
+ detail = (result.stderr or "").strip().replace("\n", " ")[-500:]
+ raise ElevenLabsMusicError(
+ f"failed to generate ElevenLabs video proxy: {detail}"
+ )
+ proxy_size = os.path.getsize(proxy_path) if os.path.isfile(proxy_path) else 0
+ if proxy_size <= 0 or proxy_size > MAX_PROXY_BYTES:
+ _remove_file(proxy_path)
+ raise ElevenLabsMusicError(
+ "ElevenLabs video proxy is empty or exceeds the 200 MB limit"
+ )
+ logger.info(
+ "ElevenLabs video proxy prepared: "
+ f"source={video_path}, size={proxy_size} bytes"
+ )
+ return proxy_path
+
+
+def _stream_audio(response: requests.Response, temp_audio_path: str) -> int:
+ """分块保存音频并限制最大体积,防止异常响应耗尽本机磁盘。"""
+ total_bytes = 0
+ with open(temp_audio_path, "wb") as output:
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
+ if not chunk:
+ continue
+ total_bytes += len(chunk)
+ if total_bytes > MAX_GENERATED_AUDIO_BYTES:
+ raise ElevenLabsMusicError(
+ "ElevenLabs audio exceeds the 50 MB limit"
+ )
+ output.write(chunk)
+ output.flush()
+ os.fsync(output.fileno())
+ if total_bytes <= 0:
+ raise ElevenLabsMusicError("ElevenLabs returned no audio data")
+ return total_bytes
+
+
+def _request_bgm(video_path: str, output_path: str, prompt: str) -> str:
+ """请求 ElevenLabs 配乐,完整下载并通过 FFmpeg 校验后再原子发布。"""
+ output_dir = os.path.dirname(os.path.abspath(output_path))
+ os.makedirs(output_dir, exist_ok=True)
+ descriptor, temp_audio_path = tempfile.mkstemp(
+ prefix=".elevenlabs-music-",
+ suffix=Path(output_path).suffix or ".mp3",
+ dir=output_dir,
+ )
+ os.close(descriptor)
+ try:
+ model_id = _model_id()
+ logger.info(
+ "requesting ElevenLabs background music: "
+ f"video={video_path}, model={model_id}, "
+ f"prompt_provided={bool(prompt)}"
+ )
+ request_data = {"model_id": model_id}
+ if prompt:
+ request_data["description"] = prompt
+ try:
+ with open(video_path, "rb") as video_file:
+ response = requests.post(
+ f"{_base_url()}{VIDEO_TO_MUSIC_PATH}",
+ headers={"xi-api-key": get_api_key()},
+ params={"output_format": "mp3_44100_128"},
+ files=[
+ (
+ # 官方文档把表单数组展示为 ``videos[]``,但 2026-07-18
+ # 生产接口会对该字段返回 422,实际 Starlette 参数名为
+ # ``videos``。重复上传时 requests 可继续添加同名字段。
+ "videos",
+ (Path(video_path).name, video_file, "video/mp4"),
+ )
+ ],
+ data=request_data,
+ stream=True,
+ timeout=_request_timeout(),
+ )
+ with response:
+ if not response.ok:
+ raise ElevenLabsMusicError(
+ "ElevenLabs generation failed "
+ f"({response.status_code}): "
+ f"{_safe_response_error(response)}"
+ )
+ total_bytes = _stream_audio(response, temp_audio_path)
+ except requests.RequestException as exc:
+ # 下载阶段断线也属于请求失败,必须进入任务降级逻辑,不能留下半条
+ # 音频或让已经生成的视频因为第三方网络波动整体失败。
+ raise ElevenLabsMusicError(
+ f"failed to request ElevenLabs music: {exc}"
+ ) from exc
+
+ try:
+ bgm_service.validate_audio_file(temp_audio_path, timeout_seconds=120)
+ except (bgm_service.BgmUploadError, bgm_service.BgmServiceError) as exc:
+ raise ElevenLabsMusicError(
+ "ElevenLabs returned audio that FFmpeg cannot decode"
+ ) from exc
+ os.replace(temp_audio_path, output_path)
+ temp_audio_path = ""
+ logger.info(
+ "ElevenLabs background music generated: "
+ f"output={output_path}, size={total_bytes} bytes"
+ )
+ return output_path
+ finally:
+ _remove_file(temp_audio_path)
+
+
+def generate_bgm(
+ video_path: str,
+ output_path: str,
+ video_duration: float,
+ prompt: str = "",
+) -> str:
+ """为一条已拼接视频生成时长和画面匹配的 ElevenLabs 背景音乐。"""
+ if not get_api_key():
+ raise ElevenLabsMusicError("ElevenLabs API key is required")
+ if not os.path.isfile(video_path):
+ raise ElevenLabsMusicError("ElevenLabs input video does not exist")
+ try:
+ duration = float(video_duration)
+ except (TypeError, ValueError) as exc:
+ raise ElevenLabsMusicError(
+ "ElevenLabs video duration is invalid"
+ ) from exc
+ if not math.isfinite(duration) or duration <= 0:
+ raise ElevenLabsMusicError("ElevenLabs video duration is invalid")
+ if duration > MAX_VIDEO_DURATION_SECONDS:
+ raise ElevenLabsMusicError(
+ "ElevenLabs supports videos up to 600 seconds"
+ )
+ prompt = str(prompt or "").strip()
+ if len(prompt) > MAX_PROMPT_LENGTH:
+ raise ElevenLabsMusicError(
+ "ElevenLabs music prompt exceeds 1000 characters"
+ )
+
+ proxy_path = ""
+ try:
+ proxy_path = _create_video_proxy(video_path)
+ return _request_bgm(proxy_path, output_path, prompt)
+ except ElevenLabsMusicError:
+ raise
+ except OSError as exc:
+ raise ElevenLabsMusicError(
+ f"ElevenLabs local file operation failed: {exc}"
+ ) from exc
+ finally:
+ _remove_file(proxy_path)
diff --git a/app/services/task.py b/app/services/task.py
index d1c8c569..cd08d3bc 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -15,7 +15,16 @@ from app.config import config
from app.models import const
from app.models.schema import VideoConcatMode, VideoParams
from app.services import bgm as bgm_service
-from app.services import llm, material, sonilo, subtitle, twelvelabs, video, voice
+from app.services import (
+ elevenlabs_music,
+ llm,
+ material,
+ sonilo,
+ subtitle,
+ twelvelabs,
+ video,
+ voice,
+)
from app.services import upload_post
from app.services import state as sm
from app.utils import file_security, utils
@@ -45,6 +54,38 @@ _CROSS_POST_STATE_RETRY_DELAY_SECONDS = 0.1
_INTERRUPTED_CROSS_POST_ERROR = (
"cross-posting was interrupted before the process completed"
)
+# 视频配乐服务只需实现 ``is_enabled`` 和 ``generate_bgm``。供应商差异集中在
+# 文件扩展名、领域异常和 WebUI 警告代码;任务编排、0 音量短路及失败降级
+# 全部复用同一路径,避免后续新增供应商时维护多份相似流程。
+_VIDEO_MUSIC_PROVIDERS = {
+ "sonilo": {
+ "service": sonilo,
+ "error_type": sonilo.SoniloError,
+ "suffix": ".m4a",
+ "warning_code": "sonilo_bgm_failed",
+ "display_name": "Sonilo",
+ },
+ "elevenlabs": {
+ "service": elevenlabs_music,
+ "error_type": elevenlabs_music.ElevenLabsMusicError,
+ "suffix": ".mp3",
+ "warning_code": "elevenlabs_bgm_failed",
+ "display_name": "ElevenLabs",
+ },
+}
+
+
+def _get_video_music_prompt(params: VideoParams) -> str:
+ """
+ 读取当前视频配乐供应商实际使用的提示词。
+
+ 新任务统一使用供应商无关字段;旧 Sonilo CLI 参数和历史任务仍可能只有
+ ``sonilo_bgm_prompt``,因此仅在 Sonilo 通用字段为空时读取旧字段。
+ """
+ prompt = str(params.video_music_prompt or "").strip()
+ if params.bgm_type == "sonilo" and not prompt:
+ prompt = str(params.sonilo_bgm_prompt or "").strip()
+ return prompt
def is_task_busy(task: dict | None) -> bool:
@@ -572,8 +613,9 @@ def generate_final_videos(
final_video_paths = []
combined_video_paths = []
warnings = []
- sonilo_bgm_requested = (
- params.bgm_type == "sonilo"
+ video_music_provider = _VIDEO_MUSIC_PROVIDERS.get(params.bgm_type)
+ video_music_requested = (
+ video_music_provider is not None
and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
)
# 多视频生成默认会打散素材以增加差异;但“按文案顺序匹配素材”追求的是
@@ -610,33 +652,34 @@ def generate_final_videos(
final_video_path = path.join(utils.task_dir(task_id), f"final-{index}.mp4")
- # Sonilo 模式下先明确禁用默认 BGM 解析,避免恢复旧任务时残留的
- # bgm_file 被误当成当前配乐。只有音量大于 0 才生成代理并调用付费 API;
- # 0 音量表示完整禁用背景音乐,不产生生成、下载或混音开销。
- bgm_file_override = "" if params.bgm_type == "sonilo" else None
- if sonilo_bgm_requested:
- sonilo_bgm_path = path.join(
- utils.task_dir(task_id), f"sonilo-bgm-{index}.m4a"
+ # 视频配乐模式先明确禁用默认 BGM 解析,避免旧任务残留的 bgm_file 被
+ # 误用。只有音量大于 0 才生成代理并调用付费 API;0 音量统一跳过。
+ bgm_file_override = "" if video_music_provider else None
+ if video_music_requested:
+ service = video_music_provider["service"]
+ display_name = video_music_provider["display_name"]
+ warning_code = video_music_provider["warning_code"]
+ generated_bgm_path = path.join(
+ utils.task_dir(task_id),
+ (f"{params.bgm_type}-bgm-{index}{video_music_provider['suffix']}"),
)
try:
- sonilo.generate_bgm(
+ service.generate_bgm(
video_path=combined_video_path,
- output_path=sonilo_bgm_path,
+ output_path=generated_bgm_path,
video_duration=audio_duration,
- prompt=params.sonilo_bgm_prompt,
+ prompt=_get_video_music_prompt(params),
)
- bgm_file_override = sonilo_bgm_path
- except sonilo.SoniloError as exc:
+ bgm_file_override = generated_bgm_path
+ except video_music_provider["error_type"] as exc:
# 视频、旁白和字幕都已生成时,第三方配乐临时失败不应浪费整条
# 任务。当前视频明确禁用 BGM,并把降级结果返回 WebUI 提醒用户。
logger.warning(
- f"Sonilo BGM generation failed: task_id={task_id}, "
+ f"{display_name} BGM generation failed: task_id={task_id}, "
f"video_index={index}, error={exc}"
)
bgm_file_override = ""
- warnings.append(
- {"code": "sonilo_bgm_failed", "video_index": index}
- )
+ warnings.append({"code": warning_code, "video_index": index})
logger.info(f"\n\n## generating video: {index} => {final_video_path}")
bgm_mix_succeeded = video.generate_video(
@@ -648,14 +691,19 @@ def generate_final_videos(
bgm_file_override=bgm_file_override,
)
if (
- params.bgm_type == "sonilo"
+ video_music_provider is not None
and bgm_file_override
and not bgm_mix_succeeded
):
- # Sonilo 已成功返回并通过 FFmpeg 校验,但 MoviePy 最终混音仍可能
- # 因运行环境失败。视频服务会保留无 BGM 成片,任务层复用同一结构化
- # 警告通知 WebUI;API 生成失败时 override 为空,不会重复追加警告。
- warnings.append({"code": "sonilo_bgm_failed", "video_index": index})
+ # 第三方已成功返回并通过 FFmpeg 校验,但 MoviePy 最终混音仍可能
+ # 因运行环境失败。视频服务会保留无 BGM 成片;API 生成失败时
+ # override 为空,因此不会重复追加警告。
+ warnings.append(
+ {
+ "code": video_music_provider["warning_code"],
+ "video_index": index,
+ }
+ )
_progress += 50 / params.video_count / 2
sm.state.update_task(task_id, progress=_progress)
@@ -1003,19 +1051,44 @@ def _run_pipeline(
logger.info(f"start task: {task_id}, stop_at: {stop_at}")
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=5)
- # 只有完整成片流程需要 Sonilo。尽早阻止缺少 Key 的完整任务,避免先消耗
- # LLM、TTS 和素材服务额度;各个中间产物接口仍可独立使用,不受配乐配置影响。
- if (
+ # 只有完整成片流程需要视频配乐供应商。尽早阻止缺少 Key 的完整任务,避免
+ # 先消耗 LLM、TTS 和素材服务额度;中间产物接口仍可独立使用。
+ video_music_provider = _VIDEO_MUSIC_PROVIDERS.get(params.bgm_type)
+ video_music_enabled = (
stop_at == "video"
- and params.bgm_type == "sonilo"
+ and video_music_provider is not None
and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
- and not sonilo.is_enabled()
- ):
- return _mark_task_failed(
- task_id,
- "preflight",
- "Sonilo background music requires an API key",
- )
+ )
+ if video_music_enabled:
+ service = video_music_provider["service"]
+ display_name = video_music_provider["display_name"]
+ if not service.is_enabled():
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ f"{display_name} background music requires an API key",
+ )
+
+ # WebUI 会限制输入长度,但 API、CLI 和历史任务可以绕过前端控件。
+ # 在生成脚本、配音和素材之前按供应商上限再次校验,避免完整视频合成后
+ # 才由第三方请求拒绝。服务层仍保留同一校验,作为直接调用时的最后防线。
+ music_prompt = _get_video_music_prompt(params)
+ max_prompt_length = int(getattr(service, "MAX_PROMPT_LENGTH", 0) or 0)
+ if max_prompt_length and len(music_prompt) > max_prompt_length:
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ (f"{display_name} music prompt exceeds {max_prompt_length} characters"),
+ )
+
+ # 供应商可以选择提供不计费的账号前置检查。检查函数只应抛出确定性
+ # 错误;网络波动或权限范围无法确认时由服务层记录警告并继续实际生成。
+ validate_access = getattr(service, "validate_generation_access", None)
+ if callable(validate_access):
+ try:
+ validate_access()
+ except video_music_provider["error_type"] as exc:
+ return _mark_task_failed(task_id, "preflight", str(exc))
# 1. Generate script
video_script = generate_script(task_id, params)
diff --git a/config.example.toml b/config.example.toml
index 032f2f38..eb1d6fd1 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -316,6 +316,9 @@ api_key = ""
api_key = ""
# Available models include eleven_multilingual_v2, eleven_flash_v2_5, and eleven_v3.
model_id = "eleven_multilingual_v2"
+# Video-to-Music uses a separate model family while sharing the same API key.
+music_model_id = "music_v2"
+music_timeout = 600
[chatterbox]
# OpenAI-compatible Chatterbox TTS server. The defaults target
diff --git a/test/services/test_bgm.py b/test/services/test_bgm.py
index 1ca1a0d5..477101a9 100644
--- a/test/services/test_bgm.py
+++ b/test/services/test_bgm.py
@@ -39,6 +39,7 @@ class TestBackgroundMusicService(unittest.TestCase):
("random", 0.2, True),
("custom", 0.2, True),
("sonilo", 0.2, True),
+ ("elevenlabs", 0.2, True),
("future_provider", 0.2, True),
("random", 0.0, False),
("custom", -0.1, False),
diff --git a/test/services/test_elevenlabs_music.py b/test/services/test_elevenlabs_music.py
new file mode 100644
index 00000000..f3cca22f
--- /dev/null
+++ b/test/services/test_elevenlabs_music.py
@@ -0,0 +1,503 @@
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from app.services import elevenlabs_music
+
+
+class _StreamingResponse:
+ """提供 ElevenLabs 配乐服务实际使用的最小 Response 接口。"""
+
+ def __init__(
+ self,
+ chunks=None,
+ *,
+ status_code=200,
+ payload=None,
+ iter_error=None,
+ ):
+ self.chunks = chunks or []
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 300
+ self.reason = "OK" if self.ok else "Request failed"
+ self.text = "" if self.ok else "request failed"
+ self.payload = payload if payload is not None else {"user_id": "test"}
+ self.iter_error = iter_error
+
+ def iter_content(self, chunk_size):
+ if self.iter_error:
+ raise self.iter_error
+ return iter(self.chunks)
+
+ def json(self):
+ return self.payload
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+
+class TestElevenLabsMusicService(unittest.TestCase):
+ def test_api_key_prefers_config_and_falls_back_to_environment(self):
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "config-key"},
+ ),
+ patch.dict(os.environ, {"ELEVENLABS_API_KEY": "env-key"}),
+ ):
+ self.assertEqual(elevenlabs_music.get_api_key(), "config-key")
+
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": ""},
+ ),
+ patch.dict(os.environ, {"ELEVENLABS_API_KEY": "env-key"}),
+ ):
+ self.assertEqual(elevenlabs_music.get_api_key(), "env-key")
+
+ def test_model_and_timeout_reject_invalid_configuration(self):
+ """第三方请求配置异常时必须回退安全默认值,不能让任务直接崩溃。"""
+ test_cases = [
+ ({"music_model_id": "music_v1"}, "music_v1", (15, 600)),
+ (
+ {"music_model_id": "unknown", "music_timeout": 0.2},
+ "music_v2",
+ (15, 1),
+ ),
+ (
+ {"music_model_id": "", "music_timeout": float("inf")},
+ "music_v2",
+ (15, 600),
+ ),
+ (
+ {"music_timeout": 2000},
+ "music_v2",
+ (15, 1800),
+ ),
+ ]
+ for configured, expected_model, expected_timeout in test_cases:
+ with self.subTest(configured=configured), patch.object(
+ elevenlabs_music.config, "elevenlabs", configured
+ ):
+ self.assertEqual(elevenlabs_music._model_id(), expected_model)
+ self.assertEqual(
+ elevenlabs_music._request_timeout(), expected_timeout
+ )
+
+ def test_connection_uses_non_billing_user_endpoint(self):
+ response = _StreamingResponse(payload={"tier": "creator"})
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music.requests,
+ "get",
+ return_value=response,
+ ) as request,
+ ):
+ result = elevenlabs_music.test_connection()
+
+ self.assertEqual(result, {"tier": "creator"})
+ self.assertTrue(
+ request.call_args.args[0].endswith("/v1/user/subscription")
+ )
+ self.assertEqual(
+ request.call_args.kwargs["headers"]["xi-api-key"], "test-key"
+ )
+
+ def test_connection_converts_http_network_and_payload_errors(self):
+ failure_cases = [
+ (_StreamingResponse(status_code=401), None, "401"),
+ (
+ None,
+ elevenlabs_music.requests.Timeout("timed out"),
+ "failed to connect",
+ ),
+ (
+ _StreamingResponse(payload=[]),
+ None,
+ "unexpected subscription response",
+ ),
+ (
+ _StreamingResponse(payload={"user_id": "test"}),
+ None,
+ "does not include an account tier",
+ ),
+ ]
+ for response, request_error, expected_message in failure_cases:
+ with (
+ self.subTest(expected_message=expected_message),
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music.requests,
+ "get",
+ return_value=response,
+ side_effect=request_error,
+ ),
+ ):
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError,
+ expected_message,
+ ):
+ elevenlabs_music.test_connection()
+
+ def test_generation_access_only_blocks_deterministic_account_errors(self):
+ """
+ 免费套餐和无效 Key 必须阻止昂贵任务;订阅接口范围或网络问题无法证明
+ Music API 不可用,只能记录警告并交给实际生成请求确认。
+ """
+ deterministic_errors = [
+ elevenlabs_music.ElevenLabsPaidPlanRequiredError("paid plan"),
+ elevenlabs_music.ElevenLabsAuthenticationError("invalid key"),
+ ]
+ for error in deterministic_errors:
+ with (
+ self.subTest(error=type(error).__name__),
+ patch.object(
+ elevenlabs_music,
+ "test_connection",
+ side_effect=error,
+ ),
+ self.assertRaises(type(error)),
+ ):
+ elevenlabs_music.validate_generation_access()
+
+ with (
+ patch.object(
+ elevenlabs_music,
+ "test_connection",
+ side_effect=elevenlabs_music.ElevenLabsMusicError(
+ "subscription endpoint is restricted"
+ ),
+ ),
+ patch.object(elevenlabs_music.logger, "warning") as warning,
+ ):
+ self.assertIsNone(elevenlabs_music.validate_generation_access())
+
+ self.assertIn("inconclusive", str(warning.call_args))
+
+ def test_connection_rejects_free_plan_before_music_generation(self):
+ """免费套餐不支持 Music API,应在上传视频前给出明确错误。"""
+ response = _StreamingResponse(payload={"tier": "free"})
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music.requests,
+ "get",
+ return_value=response,
+ ),
+ ):
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError,
+ "requires a paid plan",
+ ):
+ elevenlabs_music.test_connection()
+
+ def test_create_video_proxy_removes_audio_and_limits_dimensions(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ source = Path(temp_dir) / "source.mp4"
+ source.write_bytes(b"source-video")
+
+ def create_proxy(command, **_kwargs):
+ Path(command[-1]).write_bytes(b"proxy-video")
+ return elevenlabs_music.subprocess.CompletedProcess(
+ command, 0, "", ""
+ )
+
+ with (
+ patch.object(
+ elevenlabs_music.utils,
+ "get_ffmpeg_binary",
+ return_value="test-ffmpeg",
+ ),
+ patch.object(
+ elevenlabs_music.subprocess,
+ "run",
+ side_effect=create_proxy,
+ ) as run,
+ ):
+ proxy_path = elevenlabs_music._create_video_proxy(str(source))
+
+ command = run.call_args.args[0]
+ self.assertEqual(command[0], "test-ffmpeg")
+ self.assertIn("-an", command)
+ self.assertIn(
+ "force_original_aspect_ratio=decrease",
+ command[command.index("-vf") + 1],
+ )
+ self.assertEqual(Path(proxy_path).read_bytes(), b"proxy-video")
+ Path(proxy_path).unlink()
+
+ def test_create_video_proxy_cleans_partial_files_on_failures(self):
+ failures = [
+ (
+ elevenlabs_music.subprocess.TimeoutExpired("ffmpeg", 600),
+ "timed out",
+ ),
+ (OSError("ffmpeg missing"), "failed to run FFmpeg"),
+ (
+ elevenlabs_music.subprocess.CompletedProcess(
+ ["ffmpeg"], 1, "", "encoder unavailable"
+ ),
+ "encoder unavailable",
+ ),
+ ]
+ for result_or_error, expected_message in failures:
+ with (
+ self.subTest(expected_message=expected_message),
+ tempfile.TemporaryDirectory() as temp_dir,
+ ):
+ source = Path(temp_dir) / "source.mp4"
+ source.write_bytes(b"source-video")
+ run_kwargs = (
+ {"return_value": result_or_error}
+ if isinstance(
+ result_or_error,
+ elevenlabs_music.subprocess.CompletedProcess,
+ )
+ else {"side_effect": result_or_error}
+ )
+ with patch.object(
+ elevenlabs_music.subprocess, "run", **run_kwargs
+ ):
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError,
+ expected_message,
+ ):
+ elevenlabs_music._create_video_proxy(str(source))
+
+ self.assertEqual(
+ list(
+ Path(temp_dir).glob(
+ ".elevenlabs-music-proxy-*"
+ )
+ ),
+ [],
+ )
+
+ def test_stream_audio_rejects_empty_and_oversized_responses(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ output_path = Path(temp_dir) / "music.mp3"
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError, "no audio"
+ ):
+ elevenlabs_music._stream_audio(
+ _StreamingResponse([]), str(output_path)
+ )
+
+ with (
+ patch.object(
+ elevenlabs_music,
+ "MAX_GENERATED_AUDIO_BYTES",
+ 3,
+ ),
+ self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError, "50 MB"
+ ),
+ ):
+ elevenlabs_music._stream_audio(
+ _StreamingResponse([b"four"]), str(output_path)
+ )
+
+ def test_request_bgm_sends_official_multipart_and_publishes_atomically(self):
+ audio_bytes = b"generated-mp3"
+ response = _StreamingResponse([audio_bytes])
+ with tempfile.TemporaryDirectory() as temp_dir:
+ video_path = Path(temp_dir) / "proxy.mp4"
+ output_path = Path(temp_dir) / "music.mp3"
+ video_path.write_bytes(b"video")
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {
+ "api_key": "test-key",
+ "music_model_id": "music_v2",
+ },
+ ),
+ patch.object(
+ elevenlabs_music.requests,
+ "post",
+ return_value=response,
+ ) as post,
+ patch.object(
+ elevenlabs_music.bgm_service,
+ "validate_audio_file",
+ ) as validate_audio,
+ ):
+ result = elevenlabs_music._request_bgm(
+ str(video_path), str(output_path), "warm cinematic"
+ )
+
+ self.assertEqual(result, str(output_path))
+ self.assertEqual(output_path.read_bytes(), audio_bytes)
+ validate_audio.assert_called_once()
+ self.assertEqual(
+ post.call_args.kwargs["data"],
+ {
+ "model_id": "music_v2",
+ "description": "warm cinematic",
+ },
+ )
+ self.assertEqual(
+ post.call_args.kwargs["params"]["output_format"],
+ "mp3_44100_128",
+ )
+ # 生产接口实际接收 ``videos``;使用文档示例中的 ``videos[]`` 会
+ # 返回 422 Field required,因此测试固定真实可用的协议字段。
+ self.assertEqual(post.call_args.kwargs["files"][0][0], "videos")
+ self.assertEqual(post.call_args.kwargs["stream"], True)
+ self.assertEqual(
+ list(Path(temp_dir).glob(".elevenlabs-music-*")), []
+ )
+
+ def test_request_bgm_preserves_existing_output_after_failures(self):
+ failure_cases = [
+ (_StreamingResponse(status_code=403), None, "403"),
+ (
+ _StreamingResponse(
+ iter_error=elevenlabs_music.requests.ConnectionError(
+ "stream lost"
+ )
+ ),
+ None,
+ "failed to request",
+ ),
+ (
+ _StreamingResponse([b"invalid-audio"]),
+ elevenlabs_music.bgm_service.BgmUploadError("invalid"),
+ "cannot decode",
+ ),
+ ]
+ for response, validation_error, expected_message in failure_cases:
+ with (
+ self.subTest(expected_message=expected_message),
+ tempfile.TemporaryDirectory() as temp_dir,
+ ):
+ video_path = Path(temp_dir) / "proxy.mp4"
+ output_path = Path(temp_dir) / "music.mp3"
+ video_path.write_bytes(b"video")
+ output_path.write_bytes(b"existing-music")
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music.requests,
+ "post",
+ return_value=response,
+ ),
+ patch.object(
+ elevenlabs_music.bgm_service,
+ "validate_audio_file",
+ side_effect=validation_error,
+ ),
+ ):
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError,
+ expected_message,
+ ):
+ elevenlabs_music._request_bgm(
+ str(video_path), str(output_path), ""
+ )
+
+ self.assertEqual(output_path.read_bytes(), b"existing-music")
+ self.assertEqual(
+ list(Path(temp_dir).glob(".elevenlabs-music-*")), []
+ )
+
+ def test_generate_bgm_validates_boundaries_before_proxy_work(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ source = Path(temp_dir) / "source.mp4"
+ source.write_bytes(b"video")
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music, "_create_video_proxy"
+ ) as create_proxy,
+ ):
+ for duration in (0, -1, float("nan"), 601):
+ with self.subTest(duration=duration):
+ with self.assertRaises(
+ elevenlabs_music.ElevenLabsMusicError
+ ):
+ elevenlabs_music.generate_bgm(
+ str(source),
+ str(Path(temp_dir) / "music.mp3"),
+ duration,
+ )
+ with self.assertRaisesRegex(
+ elevenlabs_music.ElevenLabsMusicError, "1000"
+ ):
+ elevenlabs_music.generate_bgm(
+ str(source),
+ str(Path(temp_dir) / "music.mp3"),
+ 5,
+ "x" * 1001,
+ )
+ create_proxy.assert_not_called()
+
+ def test_generate_bgm_cleans_proxy_when_request_fails(self):
+ with tempfile.TemporaryDirectory() as temp_dir:
+ source = Path(temp_dir) / "source.mp4"
+ proxy = Path(temp_dir) / "proxy.mp4"
+ source.write_bytes(b"video")
+ proxy.write_bytes(b"proxy")
+ with (
+ patch.object(
+ elevenlabs_music.config,
+ "elevenlabs",
+ {"api_key": "test-key"},
+ ),
+ patch.object(
+ elevenlabs_music,
+ "_create_video_proxy",
+ return_value=str(proxy),
+ ),
+ patch.object(
+ elevenlabs_music,
+ "_request_bgm",
+ side_effect=elevenlabs_music.ElevenLabsMusicError(
+ "network failed"
+ ),
+ ),
+ ):
+ with self.assertRaises(
+ elevenlabs_music.ElevenLabsMusicError
+ ):
+ elevenlabs_music.generate_bgm(
+ str(source),
+ str(Path(temp_dir) / "music.mp3"),
+ 5,
+ )
+
+ self.assertFalse(proxy.exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/services/test_task.py b/test/services/test_task.py
index 364d46b1..bb4f4e5f 100644
--- a/test/services/test_task.py
+++ b/test/services/test_task.py
@@ -148,6 +148,77 @@ class TestTaskService(unittest.TestCase):
)
)
+ def test_generate_final_videos_uses_generated_elevenlabs_music(self):
+ """ElevenLabs 应复用视频配乐编排,并使用通用风格提示词。"""
+ params = VideoParams(
+ video_subject="test",
+ video_count=1,
+ bgm_type="elevenlabs",
+ video_music_prompt="gentle documentary",
+ )
+
+ with (
+ patch.object(tm.video, "combine_videos"),
+ patch.object(
+ tm.elevenlabs_music,
+ "generate_bgm",
+ side_effect=lambda **kwargs: kwargs["output_path"],
+ ) as generate_bgm,
+ patch.object(tm.video, "generate_video") as generate_video,
+ patch.object(tm.sm.state, "update_task"),
+ ):
+ _, _, warnings = tm.generate_final_videos(
+ task_id="elevenlabs-task",
+ params=params,
+ downloaded_videos=["material.mp4"],
+ audio_file="audio.mp3",
+ subtitle_path="",
+ audio_duration=5,
+ )
+
+ self.assertEqual(warnings, [])
+ self.assertEqual(generate_bgm.call_args.kwargs["video_duration"], 5)
+ self.assertEqual(
+ generate_bgm.call_args.kwargs["prompt"], "gentle documentary"
+ )
+ self.assertTrue(
+ generate_video.call_args.kwargs["bgm_file_override"].endswith(
+ "elevenlabs-bgm-1.mp3"
+ )
+ )
+
+ def test_generate_final_videos_falls_back_on_elevenlabs_failure(self):
+ """ElevenLabs 暂时失败时必须保留无配乐视频和结构化警告。"""
+ params = VideoParams(video_subject="test", bgm_type="elevenlabs")
+
+ with (
+ patch.object(tm.video, "combine_videos"),
+ patch.object(
+ tm.elevenlabs_music,
+ "generate_bgm",
+ side_effect=tm.elevenlabs_music.ElevenLabsMusicError(
+ "temporary outage"
+ ),
+ ),
+ patch.object(tm.video, "generate_video") as generate_video,
+ patch.object(tm.sm.state, "update_task"),
+ ):
+ final_paths, _, warnings = tm.generate_final_videos(
+ task_id="elevenlabs-fallback",
+ params=params,
+ downloaded_videos=["material.mp4"],
+ audio_file="audio.mp3",
+ subtitle_path="",
+ audio_duration=5,
+ )
+
+ self.assertEqual(len(final_paths), 1)
+ self.assertEqual(
+ warnings,
+ [{"code": "elevenlabs_bgm_failed", "video_index": 1}],
+ )
+ self.assertEqual(generate_video.call_args.kwargs["bgm_file_override"], "")
+
def test_generate_final_videos_falls_back_without_bgm_on_sonilo_failure(self):
"""第三方配乐失败时应完成视频并返回可见警告,而不是丢弃所有产物。"""
params = VideoParams(video_subject="test", bgm_type="sonilo")
@@ -277,6 +348,80 @@ class TestTaskService(unittest.TestCase):
generate_script.assert_called_once_with("zero-volume-without-key", params)
self.assertEqual(result["failed_stage"], "script")
+ def test_start_rejects_missing_elevenlabs_key_before_pipeline_steps(self):
+ """完整任务缺少 ElevenLabs Key 时必须在任何付费步骤前失败。"""
+ params = VideoParams(video_subject="test", bgm_type="elevenlabs")
+ state = MemoryState()
+ with (
+ patch.object(
+ tm.elevenlabs_music, "is_enabled", return_value=False
+ ),
+ patch.object(tm, "generate_script") as generate_script,
+ patch.object(tm, "generate_audio") as generate_audio,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("missing-elevenlabs-key", params)
+
+ generate_script.assert_not_called()
+ generate_audio.assert_not_called()
+ self.assertEqual(result["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(result["failed_stage"], "preflight")
+ self.assertIn("ElevenLabs", result["error"])
+
+ def test_start_rejects_free_elevenlabs_plan_before_pipeline_steps(self):
+ """已确认的免费套餐不能先消耗 LLM、TTS 或素材服务额度。"""
+ params = VideoParams(video_subject="test", bgm_type="elevenlabs")
+ state = MemoryState()
+ with (
+ patch.object(
+ tm.elevenlabs_music, "is_enabled", return_value=True
+ ),
+ patch.object(
+ tm.elevenlabs_music,
+ "validate_generation_access",
+ side_effect=(
+ tm.elevenlabs_music.ElevenLabsPaidPlanRequiredError(
+ "ElevenLabs Music API requires a paid plan"
+ )
+ ),
+ ) as validate_access,
+ patch.object(tm, "generate_script") as generate_script,
+ patch.object(tm, "generate_audio") as generate_audio,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("free-elevenlabs-plan", params)
+
+ validate_access.assert_called_once_with()
+ generate_script.assert_not_called()
+ generate_audio.assert_not_called()
+ self.assertEqual(result["failed_stage"], "preflight")
+ self.assertIn("paid plan", result["error"])
+
+ def test_start_rejects_oversized_elevenlabs_prompt_before_account_check(self):
+ """API/CLI 绕过 WebUI 时,超长提示词也必须在昂贵步骤前被拒绝。"""
+ params = VideoParams(
+ video_subject="test",
+ bgm_type="elevenlabs",
+ video_music_prompt="x" * 1001,
+ )
+ state = MemoryState()
+ with (
+ patch.object(
+ tm.elevenlabs_music, "is_enabled", return_value=True
+ ),
+ patch.object(
+ tm.elevenlabs_music, "validate_generation_access"
+ ) as validate_access,
+ patch.object(tm, "generate_script") as generate_script,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("oversized-elevenlabs-prompt", params)
+
+ validate_access.assert_not_called()
+ generate_script.assert_not_called()
+ self.assertEqual(result["failed_stage"], "preflight")
+ self.assertIn("1000", result["error"])
+
def test_generate_terms_uses_script_order_mode_when_enabled(self):
"""
默认模式不受影响;只有用户显式开启素材按文案顺序匹配时,任务层才
diff --git a/test/services/test_webui_bgm.py b/test/services/test_webui_bgm.py
index cbe25c0b..b507f9f1 100644
--- a/test/services/test_webui_bgm.py
+++ b/test/services/test_webui_bgm.py
@@ -12,7 +12,7 @@ from streamlit.testing.v1 import AppTest
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from app.config import config
-from app.services import bgm, sonilo
+from app.services import bgm, elevenlabs_music, sonilo, voice
ROOT_DIR = Path(__file__).parent.parent.parent
@@ -74,6 +74,14 @@ class TestWebuiBackgroundMusic(unittest.TestCase):
source_select.set_value("sonilo").run()
return app
+ def _open_elevenlabs_bgm_panel(self, locale):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = locale
+ app.run()
+ source_select = self._widget_by_key(app.selectbox, "bgm_type_select")
+ source_select.set_value("elevenlabs").run()
+ return app
+
def _uploader(self, app):
return self._widget_by_key(app.file_uploader, "custom_bgm_uploader")
@@ -194,7 +202,7 @@ class TestWebuiBackgroundMusic(unittest.TestCase):
self.assertEqual(len(app.get("audio")), 0)
def test_sonilo_source_shows_masked_prefilled_key_and_optional_prompt(self):
- """选择 Sonilo 后应回填本机 Key,但控件必须保持密码显示模式。"""
+ """选择 Sonilo 后应回填本机 Key,且保持密码显示模式。"""
for locale in TEST_LOCALES:
with self.subTest(locale=locale):
test_config = dict(config.app, sonilo_api_key="saved-test-key")
@@ -215,14 +223,13 @@ class TestWebuiBackgroundMusic(unittest.TestCase):
api_key_input.label,
self._translation(locale, "Sonilo API Key"),
)
- self.assertIn(
- "https://platform.sonilo.com/", api_key_input.label
- )
+ self.assertIn("platform.sonilo.com", api_key_input.label)
# AppTest 的 element.type 表示控件种类(text_input);密码模式
# 保存在底层 protobuf 枚举中,必须检查该字段才能验证真实渲染。
self.assertEqual(
api_key_input.proto.type, api_key_input.proto.PASSWORD
)
+ self.assertFalse(getattr(api_key_input.proto, "help", ""))
self.assertEqual(prompt_input.value, "")
self.assertEqual([str(item.value) for item in app.exception], [])
@@ -261,6 +268,171 @@ class TestWebuiBackgroundMusic(unittest.TestCase):
self.assertNotIn(required_warning, [item.value for item in app.warning])
self.assertEqual([str(item.value) for item in app.exception], [])
+ def test_elevenlabs_source_reuses_masked_tts_key_and_shows_prompt(self):
+ """配乐和 TTS 应共用 Key,并保持密码输入和独立音乐模型配置。"""
+ for locale in TEST_LOCALES:
+ with self.subTest(locale=locale):
+ test_config = dict(
+ config.elevenlabs,
+ api_key="saved-elevenlabs-key",
+ model_id="eleven_multilingual_v2",
+ music_model_id="music_v2",
+ )
+ with (
+ patch.object(config, "elevenlabs", test_config),
+ patch.object(config, "save_config"),
+ ):
+ app = self._open_elevenlabs_bgm_panel(locale)
+
+ api_key_input = self._widget_by_key(
+ app.text_input, "elevenlabs_api_key_input"
+ )
+ prompt_input = self._widget_by_key(
+ app.text_input, "elevenlabs_music_prompt_input"
+ )
+ self.assertEqual(api_key_input.value, "saved-elevenlabs-key")
+ self.assertEqual(
+ api_key_input.label,
+ self._translation(locale, "ElevenLabs Music API Key"),
+ )
+ self.assertIn(
+ "elevenlabs.io/app/settings/api-keys",
+ api_key_input.label,
+ )
+ self.assertEqual(
+ api_key_input.proto.type, api_key_input.proto.PASSWORD
+ )
+ self.assertFalse(getattr(api_key_input.proto, "help", ""))
+ self.assertEqual(prompt_input.value, "")
+ self.assertEqual(
+ test_config["model_id"], "eleven_multilingual_v2"
+ )
+ self.assertEqual([str(item.value) for item in app.exception], [])
+
+ def test_elevenlabs_tts_and_music_share_one_api_key_widget(self):
+ """同时启用配音和配乐时只能存在一个 Key 状态,修改后不能被旧值覆盖。"""
+ test_config = dict(config.elevenlabs, api_key="key-A")
+ test_ui = dict(config.ui, voice_mode="tts")
+ with (
+ patch.object(config, "elevenlabs", test_config),
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ patch.object(voice, "get_elevenlabs_voices", return_value=[]),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "en"
+ app.run()
+ self._widget_by_key(
+ app.selectbox, "tts_server_select"
+ ).set_value("elevenlabs").run()
+ self._widget_by_key(
+ app.selectbox, "bgm_type_select"
+ ).set_value("elevenlabs").run()
+
+ shared_inputs = [
+ item
+ for item in app.text_input
+ if str(getattr(item, "key", "")).startswith(
+ "elevenlabs_api_key_input"
+ )
+ ]
+ self.assertEqual(len(shared_inputs), 1)
+ self.assertEqual(shared_inputs[0].value, "key-A")
+ self.assertFalse(
+ any(
+ str(getattr(item, "key", "")).startswith(
+ "elevenlabs_music_api_key_input"
+ )
+ for item in app.text_input
+ )
+ )
+
+ shared_inputs[0].set_value("key-B").run()
+ updated_input = self._widget_by_key(
+ app.text_input, "elevenlabs_api_key_input"
+ )
+ self.assertEqual(updated_input.value, "key-B")
+ self.assertEqual(test_config["api_key"], "key-B")
+
+ self.assertEqual([str(item.value) for item in app.exception], [])
+
+ def test_elevenlabs_connection_button_reports_success(self):
+ test_config = dict(config.elevenlabs, api_key="saved-test-key")
+ with (
+ patch.object(config, "elevenlabs", test_config),
+ patch.object(config, "save_config"),
+ patch.object(
+ elevenlabs_music, "test_connection", return_value={}
+ ) as connection,
+ ):
+ app = self._open_elevenlabs_bgm_panel("en")
+ button = self._widget_by_key(
+ app.button, "test_elevenlabs_music_connection_button"
+ )
+ button.click().run()
+
+ connection.assert_called_once_with()
+ self.assertIn(
+ self._translation(
+ "en", "ElevenLabs Connection Test Succeeded"
+ ),
+ [item.value for item in app.success],
+ )
+
+ def test_elevenlabs_connection_reports_paid_plan_requirement(self):
+ """免费套餐错误应使用当前界面的自然语言,而不是直接展示英文异常。"""
+ for locale in TEST_LOCALES:
+ with self.subTest(locale=locale):
+ test_config = dict(
+ config.elevenlabs, api_key="saved-test-key"
+ )
+ with (
+ patch.object(config, "elevenlabs", test_config),
+ patch.object(config, "save_config"),
+ patch.object(
+ elevenlabs_music,
+ "test_connection",
+ side_effect=(
+ elevenlabs_music.ElevenLabsPaidPlanRequiredError(
+ "paid plan required"
+ )
+ ),
+ ),
+ ):
+ app = self._open_elevenlabs_bgm_panel(locale)
+ button = self._widget_by_key(
+ app.button,
+ "test_elevenlabs_music_connection_button",
+ )
+ button.click().run()
+
+ self.assertIn(
+ self._translation(
+ locale, "ElevenLabs Paid Plan Required"
+ ),
+ [item.value for item in app.error],
+ )
+
+ def test_zero_volume_does_not_require_elevenlabs_key(self):
+ """ElevenLabs 音量为 0 时同样不应要求 Key 或调用付费服务。"""
+ test_config = dict(config.elevenlabs, api_key="")
+ required_warning = self._translation(
+ "en", "ElevenLabs API Key Required"
+ )
+ with (
+ patch.object(config, "elevenlabs", test_config),
+ patch.object(config, "save_config"),
+ patch.object(
+ elevenlabs_music, "is_enabled", return_value=False
+ ),
+ ):
+ app = self._open_elevenlabs_bgm_panel("en")
+ self.assertIn(required_warning, [item.value for item in app.warning])
+ self._volume_select(app).set_value(0.0).run()
+
+ self.assertNotIn(required_warning, [item.value for item in app.warning])
+ self.assertEqual([str(item.value) for item in app.exception], [])
+
if __name__ == "__main__":
unittest.main()
diff --git a/webui/Main.py b/webui/Main.py
index ff2666e1..b47d817e 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -41,6 +41,7 @@ from app.models.schema import (
)
from app.services import bgm as bgm_service
from app.services import cache_manager, llm, video, voice, webui_task
+from app.services import elevenlabs_music as elevenlabs_music_service
from app.services import sonilo as sonilo_service
from app.services import state as sm
from app.services import task as tm
@@ -943,7 +944,10 @@ def _apply_pending_task_restore():
_set_stable_widget_value("bgm_volume_select", params.get("bgm_volume", 0.2))
st.session_state["custom_bgm_file_input"] = params.get("bgm_file") or ""
st.session_state["sonilo_bgm_prompt_input"] = (
- params.get("sonilo_bgm_prompt") or ""
+ params.get("video_music_prompt") or params.get("sonilo_bgm_prompt") or ""
+ )
+ st.session_state["elevenlabs_music_prompt_input"] = (
+ params.get("video_music_prompt") or ""
)
# 字幕设置。对旧任务中的越界数值做最小限幅,避免 Slider 无法初始化。
@@ -1352,6 +1356,15 @@ def _render_generation_task_snapshot(task_id, task):
index=warning.get("video_index", "")
)
)
+ elif (
+ isinstance(warning, Mapping)
+ and warning.get("code") == "elevenlabs_bgm_failed"
+ ):
+ st.warning(
+ tr("ElevenLabs BGM Fallback Warning").format(
+ index=warning.get("video_index", "")
+ )
+ )
else:
st.warning(str(warning))
@@ -2761,7 +2774,36 @@ def _get_reusable_full_voice_preview(params, voice_mode: str) -> dict | None:
}
-def _render_background_music_settings(params):
+def _render_elevenlabs_api_key_input(label_key):
+ """
+ 渲染 ElevenLabs TTS 与配乐共用的唯一 API Key 输入状态。
+
+ 同一页面若为 TTS 和配乐分别使用两个 widget key,Streamlit 会各自保留旧值,
+ 后渲染的输入框还会覆盖共享配置。这里统一使用一个 key,并集中处理环境变量
+ 回填、配置更新和音色缓存失效,确保界面显示与后台任务始终读取同一个值。
+ """
+ configured_key = str(config.elevenlabs.get("api_key", "") or "").strip()
+ effective_key = configured_key or os.getenv("ELEVENLABS_API_KEY", "").strip()
+ entered_key = st.text_input(
+ tr(label_key),
+ value=effective_key,
+ type="password",
+ key="elevenlabs_api_key_input",
+ ).strip()
+
+ if entered_key != effective_key:
+ for cache_key in list(st.session_state.keys()):
+ if str(cache_key).startswith("elevenlabs_voices_"):
+ del st.session_state[cache_key]
+
+ # 环境变量仅用于当前进程,不在用户未修改时自动复制到 config.toml。
+ # 已有配置或用户主动修改输入时才更新本机配置,与 Sonilo 行为保持一致。
+ if configured_key or entered_key != effective_key:
+ config.elevenlabs["api_key"] = entered_key
+ return entered_key
+
+
+def _render_background_music_settings(params, elevenlabs_api_key_rendered=False):
"""渲染背景音乐来源与音量设置,并返回本次待保存的上传文件。"""
uploaded_bgm_file = None
st.divider()
@@ -2770,6 +2812,7 @@ def _render_background_music_settings(params):
(tr("Random Background Music"), "random"),
(tr("Custom Background Music"), "custom"),
(tr("Sonilo Background Music"), "sonilo"),
+ (tr("ElevenLabs Background Music"), "elevenlabs"),
]
selected_bgm_type = stable_selectbox(
tr("Background Music Source"),
@@ -2779,6 +2822,28 @@ def _render_background_music_settings(params):
format_func=lambda value: dict((v, label) for label, v in bgm_options)[value],
)
params.bgm_type = selected_bgm_type
+ if params.bgm_type == "sonilo":
+ configured_key = str(config.app.get("sonilo_api_key", "") or "").strip()
+ effective_key = configured_key or os.getenv("SONILO_API_KEY", "").strip()
+ entered_key = st.text_input(
+ tr("Sonilo API Key"),
+ value=effective_key,
+ type="password",
+ key="sonilo_api_key_input",
+ ).strip()
+ # 用户要求已配置的 Key 直接回填到密码输入框。配置值优先于环境变量;
+ # 仅当用户确实修改输入或本来就使用配置时写回,避免把环境变量中的 Key
+ # 在无操作的情况下复制进 config.toml。
+ if configured_key or entered_key != effective_key:
+ config.app["sonilo_api_key"] = entered_key
+ elif params.bgm_type == "elevenlabs":
+ if elevenlabs_api_key_rendered:
+ # TTS 区域已经渲染共享输入框时不再创建第二个 widget,避免两个独立
+ # session_state 值互相覆盖。说明文字帮助用户定位上方的共用配置。
+ st.caption(tr("ElevenLabs API Key Help"))
+ else:
+ _render_elevenlabs_api_key_input("ElevenLabs Music API Key")
+
params.bgm_volume = stable_selectbox(
tr("Background Music Volume"),
options=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
@@ -2902,22 +2967,7 @@ def _render_background_music_settings(params):
params.bgm_file = ""
if params.bgm_type == "sonilo":
- configured_key = str(config.app.get("sonilo_api_key", "") or "").strip()
- effective_key = configured_key or os.getenv("SONILO_API_KEY", "").strip()
- entered_key = st.text_input(
- tr("Sonilo API Key"),
- value=effective_key,
- type="password",
- key="sonilo_api_key_input",
- help=tr("Sonilo API Key Help"),
- ).strip()
- # 用户要求已配置的 Key 直接回填到密码输入框。配置值优先于环境变量;
- # 仅当用户确实修改输入或本来就使用配置时写回,避免把环境变量中的 Key
- # 在无操作的情况下复制进 config.toml。
- if configured_key or entered_key != effective_key:
- config.app["sonilo_api_key"] = entered_key
-
- params.sonilo_bgm_prompt = st.text_input(
+ params.video_music_prompt = st.text_input(
tr("Sonilo Music Prompt"),
key="sonilo_bgm_prompt_input",
max_chars=sonilo_service.MAX_PROMPT_LENGTH,
@@ -2937,14 +2987,39 @@ def _render_background_music_settings(params):
st.error(tr("Sonilo Connection Test Failed").format(error=str(exc)))
else:
st.success(tr("Sonilo Connection Test Succeeded"))
- if (
- params.bgm_type == "sonilo"
- and bgm_enabled
- and not sonilo_service.is_enabled()
- ):
+ elif params.bgm_type == "elevenlabs":
+ params.video_music_prompt = st.text_input(
+ tr("ElevenLabs Music Prompt"),
+ key="elevenlabs_music_prompt_input",
+ max_chars=elevenlabs_music_service.MAX_PROMPT_LENGTH,
+ help=tr("ElevenLabs Music Prompt Help"),
+ ).strip()
+ if params.video_count > 1:
+ st.warning(tr("ElevenLabs Multiple Videos Warning"))
+ if st.button(
+ tr("Test ElevenLabs Connection"),
+ key="test_elevenlabs_music_connection_button",
+ use_container_width=True,
+ ):
+ try:
+ elevenlabs_music_service.test_connection()
+ except elevenlabs_music_service.ElevenLabsPaidPlanRequiredError:
+ st.error(tr("ElevenLabs Paid Plan Required"))
+ except elevenlabs_music_service.ElevenLabsMusicError as exc:
+ logger.warning(f"ElevenLabs connection test failed: {exc}")
+ st.error(tr("ElevenLabs Connection Test Failed").format(error=str(exc)))
+ else:
+ st.success(tr("ElevenLabs Connection Test Succeeded"))
+ if params.bgm_type == "sonilo" and bgm_enabled and not sonilo_service.is_enabled():
# 音量为 0 时任务层不会生成或混合 Sonilo 配乐,因此无需提示 Key;
# 该判断与任务入口共用服务层规则,避免界面提示和实际执行条件分叉。
st.warning(tr("Sonilo API Key Required"))
+ elif (
+ params.bgm_type == "elevenlabs"
+ and bgm_enabled
+ and not elevenlabs_music_service.is_enabled()
+ ):
+ st.warning(tr("ElevenLabs API Key Required"))
return uploaded_bgm_file
@@ -3027,6 +3102,7 @@ def _render_audio_settings(panel, params):
# 根据选择的TTS服务器获取声音列表
filtered_voices = []
saved_voice_name = config.ui.get("voice_name", "")
+ elevenlabs_api_key_rendered = False
if not tts_mode_enabled:
# 上传音频和无配音模式不加载远程音色,减少无意义的网络请求和界面噪音。
@@ -3210,14 +3286,10 @@ def _render_audio_settings(panel, params):
selected_tts_server == "elevenlabs"
or (voice_name and voice.is_elevenlabs_voice(voice_name))
):
- saved_elevenlabs_api_key = config.elevenlabs.get("api_key", "")
-
- elevenlabs_api_key = st.text_input(
- tr("ElevenLabs API Key"),
- value=saved_elevenlabs_api_key,
- type="password",
- key="elevenlabs_api_key_input",
+ _render_elevenlabs_api_key_input(
+ "ElevenLabs API Key",
)
+ elevenlabs_api_key_rendered = True
_elevenlabs_models = [
"eleven_multilingual_v2",
@@ -3237,13 +3309,6 @@ def _render_audio_settings(panel, params):
)
config.elevenlabs["model_id"] = elevenlabs_model
- if elevenlabs_api_key != saved_elevenlabs_api_key:
- for k in list(st.session_state.keys()):
- if k.startswith("elevenlabs_voices_"):
- del st.session_state[k]
-
- config.elevenlabs["api_key"] = elevenlabs_api_key
-
# Chatterbox API settings section (self-hosted, OpenAI-compatible)
if tts_mode_enabled and (
selected_tts_server == "chatterbox"
@@ -3356,7 +3421,10 @@ def _render_audio_settings(panel, params):
"Custom audio will be used directly. TTS synthesis will be skipped for this task."
)
)
- uploaded_bgm_file = _render_background_music_settings(params)
+ uploaded_bgm_file = _render_background_music_settings(
+ params,
+ elevenlabs_api_key_rendered=elevenlabs_api_key_rendered,
+ )
return uploaded_audio_file, uploaded_bgm_file, voice_mode
@@ -3677,6 +3745,15 @@ def _render_generation_controls(
st.error(tr("Sonilo API Key Required"))
st.stop()
+ if (
+ params.bgm_type == "elevenlabs"
+ and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
+ and not elevenlabs_music_service.is_enabled()
+ ):
+ _remove_active_generation_task(task_id)
+ st.error(tr("ElevenLabs API Key Required"))
+ st.stop()
+
if params.video_source == "local" and not has_local_materials:
# 本地素材为空时继续执行会先产生 TTS/字幕,最后才在素材预处理阶段失败。
# 在任务启动前拦截,可以避免无意义的 API 调用和中间文件。
diff --git a/webui/i18n/de.json b/webui/i18n/de.json
index e1181366..3d3fa61c 100644
--- a/webui/i18n/de.json
+++ b/webui/i18n/de.json
@@ -113,9 +113,8 @@
"No Background Music": "Ohne Hintergrundmusik",
"Random Background Music": "Zufällige Hintergrundmusik",
"Custom Background Music": "Benutzerdefinierte Hintergrundmusik",
- "Sonilo Background Music": "Sonilo videobasierte Musik",
+ "Sonilo Background Music": "Automatische Musik zum Video (Sonilo AI)",
"Sonilo API Key": "Sonilo API-Schlüssel ([Schlüssel abrufen](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Erstellen Sie einen Schlüssel auf platform.sonilo.com. Der Wert wird maskiert und lokal in config.toml gespeichert.",
"Sonilo Music Prompt": "Musikstil (optional)",
"Sonilo Music Prompt Help": "Optionale Stil- oder Stimmungsvorgabe mit bis zu 2000 Zeichen. Leer lassen, damit Sonilo das Video automatisch abstimmt.",
"Sonilo Multiple Videos Warning": "Sonilo erzeugt für jedes Ausgabevideo separate Musik; mehrere Videos verbrauchen mehrere Generierungen.",
@@ -124,7 +123,19 @@
"Sonilo Connection Test Succeeded": "Sonilo-Verbindung erfolgreich.",
"Sonilo Connection Test Failed": "Sonilo-Verbindung fehlgeschlagen: {error}",
"Sonilo BGM Fallback Warning": "Video {index} wurde ohne Sonilo-Hintergrundmusik erstellt, weil die Musikanfrage fehlgeschlagen ist.",
- "Custom Background Music File": "Pfad der eigenen Musik",
+ "ElevenLabs Background Music": "Automatische Musik zum Video (ElevenLabs)",
+ "ElevenLabs Music API Key": "ElevenLabs API-Schlüssel ([Schlüssel abrufen](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Dieser Schlüssel wird auch für ElevenLabs TTS verwendet, maskiert und lokal in config.toml gespeichert.",
+ "ElevenLabs Music Prompt": "Musikstil (optional)",
+ "ElevenLabs Music Prompt Help": "Optionale Stil- oder Stimmungsvorgabe mit bis zu 1000 Zeichen. Leer lassen, damit ElevenLabs das Video automatisch abstimmt.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs erzeugt für jedes Ausgabevideo separate Musik; mehrere Videos verbrauchen mehrere Generierungen.",
+ "ElevenLabs API Key Required": "Geben Sie einen ElevenLabs API-Schlüssel ein, um ElevenLabs-Hintergrundmusik zu verwenden.",
+ "Test ElevenLabs Connection": "ElevenLabs-Konto prüfen",
+ "ElevenLabs Connection Test Succeeded": "ElevenLabs-Konto und Tarif wurden geprüft. Der Music-API-Zugriff wird bei der Generierung bestätigt.",
+ "ElevenLabs Connection Test Failed": "ElevenLabs-Kontoprüfung fehlgeschlagen: {error}",
+ "ElevenLabs Paid Plan Required": "Der API-Schlüssel ist gültig, aber die ElevenLabs Music API erfordert ein kostenpflichtiges Abo. Aktualisieren Sie das Konto, bevor Sie Musik erzeugen.",
+ "ElevenLabs BGM Fallback Warning": "Video {index} wurde ohne ElevenLabs-Hintergrundmusik erstellt, weil die Musikanfrage fehlgeschlagen ist.",
+ "Custom Background Music File": "Oder Pfad zur eigenen Musik eingeben",
"Upload Background Music": "Hintergrundmusik hochladen",
"Upload Background Music Help": "Laden Sie eine MP3-, M4A-, AAC-, WAV-, FLAC-, OGG-, OPUS- oder WMA-Datei bis 30 MB hoch. Sie wird beim Start der Videoerstellung dauerhaft gespeichert.",
"Background Music Ready": "Hintergrundmusik ist bereit",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index b4483280..f6978935 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -110,9 +110,8 @@
"No Background Music": "No Background Music",
"Random Background Music": "Random Background Music",
"Custom Background Music": "Custom Background Music",
- "Sonilo Background Music": "Sonilo Video-Matched Music",
+ "Sonilo Background Music": "Automatic Video-Matched Music (Sonilo AI)",
"Sonilo API Key": "Sonilo API Key ([Get API Key](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Create a key at platform.sonilo.com. The value is masked and saved in your local config.toml.",
"Sonilo Music Prompt": "Music Style (Optional)",
"Sonilo Music Prompt Help": "Optional style or mood guidance, up to 2000 characters. Leave empty to let Sonilo match the video automatically.",
"Sonilo Multiple Videos Warning": "Sonilo generates music separately for each output video, so multiple videos consume multiple generations.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Sonilo connection succeeded.",
"Sonilo Connection Test Failed": "Sonilo connection failed: {error}",
"Sonilo BGM Fallback Warning": "Video {index} was generated without Sonilo background music because the music request failed.",
- "Custom Background Music File": "Custom Music Path",
+ "ElevenLabs Background Music": "Automatic Video-Matched Music (ElevenLabs AI)",
+ "ElevenLabs Music API Key": "ElevenLabs API Key ([Get API Key](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "This key is shared with ElevenLabs TTS. It is masked and saved in your local config.toml.",
+ "ElevenLabs Music Prompt": "Music Style (Optional)",
+ "ElevenLabs Music Prompt Help": "Optional style or mood guidance, up to 1000 characters. Leave empty to let ElevenLabs match the video automatically.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs generates music separately for each output video, so multiple videos consume multiple generations.",
+ "ElevenLabs API Key Required": "Enter an ElevenLabs API Key to use ElevenLabs background music.",
+ "Test ElevenLabs Connection": "Check ElevenLabs Account",
+ "ElevenLabs Connection Test Succeeded": "ElevenLabs account and plan check passed. Music API access will be confirmed during generation.",
+ "ElevenLabs Connection Test Failed": "ElevenLabs account check failed: {error}",
+ "ElevenLabs Paid Plan Required": "The API Key is valid, but the ElevenLabs Music API requires a paid plan. Upgrade the account before generating music.",
+ "ElevenLabs BGM Fallback Warning": "Video {index} was generated without ElevenLabs background music because the music request failed.",
+ "Custom Background Music File": "Or Enter a Custom Music Path",
"Upload Background Music": "Upload Background Music",
"Upload Background Music Help": "Upload an MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, or WMA file up to 30 MB. It will be stored persistently when video generation starts.",
"Background Music Ready": "Background music ready",
diff --git a/webui/i18n/es.json b/webui/i18n/es.json
index 30c5de4b..3348d064 100644
--- a/webui/i18n/es.json
+++ b/webui/i18n/es.json
@@ -110,9 +110,8 @@
"No Background Music": "Sin música de fondo",
"Random Background Music": "Música de fondo aleatoria",
"Custom Background Music": "Música de fondo personalizada",
- "Sonilo Background Music": "Música Sonilo adaptada al video",
+ "Sonilo Background Music": "Música automática adaptada al video (Sonilo AI)",
"Sonilo API Key": "Clave API de Sonilo ([Obtener clave](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Crea una clave en platform.sonilo.com. El valor se oculta y se guarda en tu config.toml local.",
"Sonilo Music Prompt": "Estilo musical (opcional)",
"Sonilo Music Prompt Help": "Indicación opcional de estilo o emoción, hasta 2000 caracteres. Déjalo vacío para que Sonilo se adapte al video.",
"Sonilo Multiple Videos Warning": "Sonilo genera música por separado para cada video, por lo que varios videos consumen varias generaciones.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Conexión con Sonilo correcta.",
"Sonilo Connection Test Failed": "Falló la conexión con Sonilo: {error}",
"Sonilo BGM Fallback Warning": "El video {index} se generó sin música de Sonilo porque falló la solicitud de música.",
- "Custom Background Music File": "Ruta de música personalizada",
+ "ElevenLabs Background Music": "Música automática adaptada al video (ElevenLabs)",
+ "ElevenLabs Music API Key": "Clave API de ElevenLabs ([Obtener clave](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Esta clave se comparte con ElevenLabs TTS, se oculta y se guarda en tu config.toml local.",
+ "ElevenLabs Music Prompt": "Estilo musical (opcional)",
+ "ElevenLabs Music Prompt Help": "Indicación opcional de estilo o emoción, hasta 1000 caracteres. Déjalo vacío para que ElevenLabs se adapte al video.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs genera música por separado para cada video, por lo que varios videos consumen varias generaciones.",
+ "ElevenLabs API Key Required": "Introduce una clave API de ElevenLabs para usar su música de fondo.",
+ "Test ElevenLabs Connection": "Comprobar cuenta de ElevenLabs",
+ "ElevenLabs Connection Test Succeeded": "La cuenta y el plan de ElevenLabs son válidos. El acceso a Music API se confirmará durante la generación.",
+ "ElevenLabs Connection Test Failed": "Falló la comprobación de la cuenta de ElevenLabs: {error}",
+ "ElevenLabs Paid Plan Required": "La clave API es válida, pero la API de música de ElevenLabs requiere un plan de pago. Actualiza la cuenta antes de generar música.",
+ "ElevenLabs BGM Fallback Warning": "El video {index} se generó sin música de ElevenLabs porque falló la solicitud de música.",
+ "Custom Background Music File": "O introduce una ruta de música personalizada",
"Upload Background Music": "Subir música de fondo",
"Upload Background Music Help": "Sube un archivo MP3, M4A, AAC, WAV, FLAC, OGG, OPUS o WMA de hasta 30 MB. Se guardará de forma permanente al iniciar la generación del vídeo.",
"Background Music Ready": "La música de fondo está lista",
diff --git a/webui/i18n/id.json b/webui/i18n/id.json
index 60662287..b7ace153 100644
--- a/webui/i18n/id.json
+++ b/webui/i18n/id.json
@@ -110,9 +110,8 @@
"No Background Music": "Tidak Ada Musik Latar",
"Random Background Music": "Musik Latar Acak",
"Custom Background Music": "Musik Latar Kustom",
- "Sonilo Background Music": "Musik Sonilo yang sesuai video",
+ "Sonilo Background Music": "Musik otomatis yang sesuai video (Sonilo AI)",
"Sonilo API Key": "Kunci API Sonilo ([Dapatkan kunci](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Buat kunci di platform.sonilo.com. Nilai disamarkan dan disimpan di config.toml lokal.",
"Sonilo Music Prompt": "Gaya musik (opsional)",
"Sonilo Music Prompt Help": "Panduan gaya atau suasana opsional, maksimal 2000 karakter. Kosongkan agar Sonilo menyesuaikan video otomatis.",
"Sonilo Multiple Videos Warning": "Sonilo membuat musik terpisah untuk tiap video, sehingga beberapa video memakai beberapa generasi.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Koneksi Sonilo berhasil.",
"Sonilo Connection Test Failed": "Koneksi Sonilo gagal: {error}",
"Sonilo BGM Fallback Warning": "Video {index} dibuat tanpa musik Sonilo karena permintaan musik gagal.",
- "Custom Background Music File": "Jalur Musik Kustom",
+ "ElevenLabs Background Music": "Musik otomatis yang sesuai video (ElevenLabs)",
+ "ElevenLabs Music API Key": "Kunci API ElevenLabs ([Dapatkan kunci](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Kunci ini juga dipakai untuk ElevenLabs TTS, disamarkan, dan disimpan di config.toml lokal.",
+ "ElevenLabs Music Prompt": "Gaya musik (opsional)",
+ "ElevenLabs Music Prompt Help": "Panduan gaya atau suasana opsional, maksimal 1000 karakter. Kosongkan agar ElevenLabs menyesuaikan video otomatis.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs membuat musik terpisah untuk tiap video, sehingga beberapa video memakai beberapa generasi.",
+ "ElevenLabs API Key Required": "Masukkan Kunci API ElevenLabs untuk menggunakan musik latar ElevenLabs.",
+ "Test ElevenLabs Connection": "Periksa akun ElevenLabs",
+ "ElevenLabs Connection Test Succeeded": "Pemeriksaan akun dan paket ElevenLabs berhasil. Akses Music API akan dikonfirmasi saat pembuatan.",
+ "ElevenLabs Connection Test Failed": "Pemeriksaan akun ElevenLabs gagal: {error}",
+ "ElevenLabs Paid Plan Required": "Kunci API valid, tetapi ElevenLabs Music API memerlukan paket berbayar. Tingkatkan akun sebelum membuat musik.",
+ "ElevenLabs BGM Fallback Warning": "Video {index} dibuat tanpa musik ElevenLabs karena permintaan musik gagal.",
+ "Custom Background Music File": "Atau masukkan jalur musik kustom",
"Upload Background Music": "Unggah Musik Latar",
"Upload Background Music Help": "Unggah file MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, atau WMA hingga 30 MB. File akan disimpan secara permanen saat pembuatan video dimulai.",
"Background Music Ready": "Musik latar siap",
diff --git a/webui/i18n/pt.json b/webui/i18n/pt.json
index dc95a318..948deb76 100644
--- a/webui/i18n/pt.json
+++ b/webui/i18n/pt.json
@@ -110,9 +110,8 @@
"No Background Music": "Sem Música de Fundo",
"Random Background Music": "Música de Fundo Aleatória",
"Custom Background Music": "Música de Fundo Personalizada",
- "Sonilo Background Music": "Música Sonilo adaptada ao vídeo",
+ "Sonilo Background Music": "Música automática adaptada ao vídeo (Sonilo AI)",
"Sonilo API Key": "Chave de API Sonilo ([Obter chave](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Crie uma chave em platform.sonilo.com. O valor fica oculto e é salvo no config.toml local.",
"Sonilo Music Prompt": "Estilo musical (opcional)",
"Sonilo Music Prompt Help": "Orientação opcional de estilo ou clima, até 2000 caracteres. Deixe vazio para o Sonilo combinar automaticamente com o vídeo.",
"Sonilo Multiple Videos Warning": "O Sonilo gera música separada para cada vídeo; vários vídeos consomem várias gerações.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Conexão Sonilo bem-sucedida.",
"Sonilo Connection Test Failed": "Falha na conexão Sonilo: {error}",
"Sonilo BGM Fallback Warning": "O vídeo {index} foi gerado sem música Sonilo porque a solicitação de música falhou.",
- "Custom Background Music File": "Caminho da música personalizada",
+ "ElevenLabs Background Music": "Música automática adaptada ao vídeo (ElevenLabs)",
+ "ElevenLabs Music API Key": "Chave API do ElevenLabs ([Obter chave](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Esta chave também é usada pelo ElevenLabs TTS, fica oculta e é salva no config.toml local.",
+ "ElevenLabs Music Prompt": "Estilo musical (opcional)",
+ "ElevenLabs Music Prompt Help": "Orientação opcional de estilo ou clima, até 1000 caracteres. Deixe vazio para o ElevenLabs combinar automaticamente com o vídeo.",
+ "ElevenLabs Multiple Videos Warning": "O ElevenLabs gera música separada para cada vídeo; vários vídeos consomem várias gerações.",
+ "ElevenLabs API Key Required": "Insira uma chave de API ElevenLabs para usar a música de fundo ElevenLabs.",
+ "Test ElevenLabs Connection": "Verificar conta ElevenLabs",
+ "ElevenLabs Connection Test Succeeded": "A conta e o plano ElevenLabs foram verificados. O acesso à Music API será confirmado durante a geração.",
+ "ElevenLabs Connection Test Failed": "Falha ao verificar a conta ElevenLabs: {error}",
+ "ElevenLabs Paid Plan Required": "A chave de API é válida, mas a API de música ElevenLabs exige um plano pago. Atualize a conta antes de gerar música.",
+ "ElevenLabs BGM Fallback Warning": "O vídeo {index} foi gerado sem música ElevenLabs porque a solicitação de música falhou.",
+ "Custom Background Music File": "Ou insira o caminho da música personalizada",
"Upload Background Music": "Enviar música de fundo",
"Upload Background Music Help": "Envie um arquivo MP3, M4A, AAC, WAV, FLAC, OGG, OPUS ou WMA de até 30 MB. Ele será salvo permanentemente quando a geração do vídeo começar.",
"Background Music Ready": "A música de fundo está pronta",
diff --git a/webui/i18n/ru.json b/webui/i18n/ru.json
index 31099f12..5582ea3e 100644
--- a/webui/i18n/ru.json
+++ b/webui/i18n/ru.json
@@ -110,9 +110,8 @@
"No Background Music": "Без фоновой музыки",
"Random Background Music": "Случайная фоновая музыка",
"Custom Background Music": "Своя фоновая музыка",
- "Sonilo Background Music": "Музыка Sonilo под видео",
+ "Sonilo Background Music": "Автоматическая музыка под видео (Sonilo AI)",
"Sonilo API Key": "API-ключ Sonilo ([Получить ключ](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Создайте ключ на platform.sonilo.com. Значение скрывается и сохраняется в локальном config.toml.",
"Sonilo Music Prompt": "Стиль музыки (необязательно)",
"Sonilo Music Prompt Help": "Необязательное описание стиля или настроения, до 2000 символов. Оставьте пустым для автоматического подбора.",
"Sonilo Multiple Videos Warning": "Sonilo создаёт музыку отдельно для каждого видео, поэтому несколько видео расходуют несколько генераций.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Подключение Sonilo успешно.",
"Sonilo Connection Test Failed": "Ошибка подключения Sonilo: {error}",
"Sonilo BGM Fallback Warning": "Видео {index} создано без музыки Sonilo из-за ошибки запроса музыки.",
- "Custom Background Music File": "Путь к своей музыке",
+ "ElevenLabs Background Music": "Автоматическая музыка под видео (ElevenLabs)",
+ "ElevenLabs Music API Key": "API-ключ ElevenLabs ([получить ключ](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Этот ключ также используется для ElevenLabs TTS, скрывается и сохраняется в локальном config.toml.",
+ "ElevenLabs Music Prompt": "Стиль музыки (необязательно)",
+ "ElevenLabs Music Prompt Help": "Необязательное описание стиля или настроения, до 1000 символов. Оставьте пустым для автоматического подбора.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs создаёт музыку отдельно для каждого видео, поэтому несколько видео расходуют несколько генераций.",
+ "ElevenLabs API Key Required": "Введите API-ключ ElevenLabs для использования фоновой музыки ElevenLabs.",
+ "Test ElevenLabs Connection": "Проверить аккаунт ElevenLabs",
+ "ElevenLabs Connection Test Succeeded": "Аккаунт и тариф ElevenLabs проверены. Доступ к Music API будет подтверждён при генерации.",
+ "ElevenLabs Connection Test Failed": "Не удалось проверить аккаунт ElevenLabs: {error}",
+ "ElevenLabs Paid Plan Required": "API-ключ действителен, но для ElevenLabs Music API нужен платный тариф. Обновите тариф перед созданием музыки.",
+ "ElevenLabs BGM Fallback Warning": "Видео {index} создано без музыки ElevenLabs из-за ошибки запроса музыки.",
+ "Custom Background Music File": "Или укажите путь к своей музыке",
"Upload Background Music": "Загрузить фоновую музыку",
"Upload Background Music Help": "Загрузите файл MP3, M4A, AAC, WAV, FLAC, OGG, OPUS или WMA размером до 30 МБ. Он будет сохранён при запуске создания видео.",
"Background Music Ready": "Фоновая музыка готова",
diff --git a/webui/i18n/tr.json b/webui/i18n/tr.json
index 773c6a30..e4ab6926 100644
--- a/webui/i18n/tr.json
+++ b/webui/i18n/tr.json
@@ -108,9 +108,8 @@
"No Background Music": "Arka Plan Müziği Yok",
"Random Background Music": "Rastgele Arka Plan Müziği",
"Custom Background Music": "Özel Arka Plan Müziği",
- "Sonilo Background Music": "Videoya uyumlu Sonilo müziği",
+ "Sonilo Background Music": "Videoya uyumlu otomatik müzik (Sonilo AI)",
"Sonilo API Key": "Sonilo API Anahtarı ([Anahtar al](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "platform.sonilo.com adresinden bir anahtar oluşturun. Değer maskelenir ve yerel config.toml dosyasına kaydedilir.",
"Sonilo Music Prompt": "Müzik stili (isteğe bağlı)",
"Sonilo Music Prompt Help": "En fazla 2000 karakterlik isteğe bağlı stil veya duygu açıklaması. Otomatik eşleştirme için boş bırakın.",
"Sonilo Multiple Videos Warning": "Sonilo her çıktı videosu için ayrı müzik üretir; birden fazla video birden fazla üretim harcar.",
@@ -119,7 +118,19 @@
"Sonilo Connection Test Succeeded": "Sonilo bağlantısı başarılı.",
"Sonilo Connection Test Failed": "Sonilo bağlantısı başarısız: {error}",
"Sonilo BGM Fallback Warning": "Müzik isteği başarısız olduğu için {index}. video Sonilo arka plan müziği olmadan oluşturuldu.",
- "Custom Background Music File": "Özel Müzik Yolu",
+ "ElevenLabs Background Music": "Videoya uyumlu otomatik müzik (ElevenLabs)",
+ "ElevenLabs Music API Key": "ElevenLabs API Anahtarı ([Anahtar al](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Bu anahtar ElevenLabs TTS ile ortaktır, maskelenir ve yerel config.toml dosyasına kaydedilir.",
+ "ElevenLabs Music Prompt": "Müzik stili (isteğe bağlı)",
+ "ElevenLabs Music Prompt Help": "En fazla 1000 karakterlik isteğe bağlı stil veya duygu açıklaması. Otomatik eşleştirme için boş bırakın.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs her çıktı videosu için ayrı müzik üretir; birden fazla video birden fazla üretim harcar.",
+ "ElevenLabs API Key Required": "ElevenLabs arka plan müziğini kullanmak için API anahtarını girin.",
+ "Test ElevenLabs Connection": "ElevenLabs hesabını kontrol et",
+ "ElevenLabs Connection Test Succeeded": "ElevenLabs hesabı ve planı doğrulandı. Music API erişimi oluşturma sırasında onaylanacak.",
+ "ElevenLabs Connection Test Failed": "ElevenLabs hesap kontrolü başarısız: {error}",
+ "ElevenLabs Paid Plan Required": "API anahtarı geçerli, ancak ElevenLabs Music API ücretli bir plan gerektirir. Müzik oluşturmadan önce hesabı yükseltin.",
+ "ElevenLabs BGM Fallback Warning": "Müzik isteği başarısız olduğu için {index}. video ElevenLabs arka plan müziği olmadan oluşturuldu.",
+ "Custom Background Music File": "Veya özel müzik yolunu girin",
"Upload Background Music": "Arka Plan Müziği Yükle",
"Upload Background Music Help": "En fazla 30 MB boyutunda MP3, M4A, AAC, WAV, FLAC, OGG, OPUS veya WMA dosyası yükleyin. Video oluşturma başladığında kalıcı olarak saklanır.",
"Background Music Ready": "Arka plan müziği hazır",
diff --git a/webui/i18n/vi.json b/webui/i18n/vi.json
index 8a3e77f7..f4e3f2fb 100644
--- a/webui/i18n/vi.json
+++ b/webui/i18n/vi.json
@@ -110,9 +110,8 @@
"No Background Music": "Không Có Âm Nhạc Nền",
"Random Background Music": "Âm Nhạc Nền Ngẫu Nhiên",
"Custom Background Music": "Âm Nhạc Nền Tùy Chỉnh",
- "Sonilo Background Music": "Nhạc Sonilo phù hợp video",
+ "Sonilo Background Music": "Nhạc tự động phù hợp với video (Sonilo AI)",
"Sonilo API Key": "Khóa API Sonilo ([Lấy khóa](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "Tạo khóa tại platform.sonilo.com. Giá trị được che và lưu trong config.toml cục bộ.",
"Sonilo Music Prompt": "Phong cách nhạc (không bắt buộc)",
"Sonilo Music Prompt Help": "Mô tả phong cách hoặc cảm xúc, tối đa 2000 ký tự. Để trống để Sonilo tự động khớp video.",
"Sonilo Multiple Videos Warning": "Sonilo tạo nhạc riêng cho từng video, vì vậy nhiều video sẽ dùng nhiều lượt tạo.",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Kết nối Sonilo thành công.",
"Sonilo Connection Test Failed": "Kết nối Sonilo thất bại: {error}",
"Sonilo BGM Fallback Warning": "Video {index} được tạo không có nhạc Sonilo vì yêu cầu tạo nhạc thất bại.",
- "Custom Background Music File": "Đường dẫn nhạc tùy chỉnh",
+ "ElevenLabs Background Music": "Nhạc tự động phù hợp với video (ElevenLabs)",
+ "ElevenLabs Music API Key": "Khóa API ElevenLabs ([Lấy khóa](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "Khóa này được dùng chung với ElevenLabs TTS, được che và lưu trong config.toml cục bộ.",
+ "ElevenLabs Music Prompt": "Phong cách nhạc (không bắt buộc)",
+ "ElevenLabs Music Prompt Help": "Mô tả phong cách hoặc cảm xúc, tối đa 1000 ký tự. Để trống để ElevenLabs tự động khớp video.",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs tạo nhạc riêng cho từng video, vì vậy nhiều video sẽ dùng nhiều lượt tạo.",
+ "ElevenLabs API Key Required": "Nhập Khóa API ElevenLabs để dùng nhạc nền ElevenLabs.",
+ "Test ElevenLabs Connection": "Kiểm tra tài khoản ElevenLabs",
+ "ElevenLabs Connection Test Succeeded": "Tài khoản và gói ElevenLabs đã được kiểm tra. Quyền truy cập Music API sẽ được xác nhận khi tạo nhạc.",
+ "ElevenLabs Connection Test Failed": "Kiểm tra tài khoản ElevenLabs thất bại: {error}",
+ "ElevenLabs Paid Plan Required": "Khóa API hợp lệ, nhưng ElevenLabs Music API yêu cầu gói trả phí. Hãy nâng cấp tài khoản trước khi tạo nhạc.",
+ "ElevenLabs BGM Fallback Warning": "Video {index} được tạo không có nhạc ElevenLabs vì yêu cầu tạo nhạc thất bại.",
+ "Custom Background Music File": "Hoặc nhập đường dẫn nhạc tùy chỉnh",
"Upload Background Music": "Tải nhạc nền lên",
"Upload Background Music Help": "Tải lên tệp MP3, M4A, AAC, WAV, FLAC, OGG, OPUS hoặc WMA tối đa 30 MB. Tệp sẽ được lưu lâu dài khi bắt đầu tạo video.",
"Background Music Ready": "Nhạc nền đã sẵn sàng",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index b112327c..1ff8b2cb 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -110,9 +110,8 @@
"No Background Music": "无背景音乐",
"Random Background Music": "随机背景音乐",
"Custom Background Music": "自定义背景音乐",
- "Sonilo Background Music": "Sonilo 视频匹配配乐",
+ "Sonilo Background Music": "根据画面自动配乐(Sonilo AI)",
"Sonilo API Key": "Sonilo API Key([点击获取](https://platform.sonilo.com/))",
- "Sonilo API Key Help": "请前往 platform.sonilo.com 创建 Key。输入内容会以密码形式显示,并保存到本机 config.toml。",
"Sonilo Music Prompt": "音乐风格(可选)",
"Sonilo Music Prompt Help": "可以填写风格或情绪要求,最多 2000 个字符;留空时由 Sonilo 自动匹配视频。",
"Sonilo Multiple Videos Warning": "Sonilo 会为每条输出视频分别生成配乐,生成多条视频会消耗多次额度。",
@@ -121,7 +120,19 @@
"Sonilo Connection Test Succeeded": "Sonilo 连接成功。",
"Sonilo Connection Test Failed": "Sonilo 连接失败:{error}",
"Sonilo BGM Fallback Warning": "第 {index} 条视频的 Sonilo 配乐生成失败,已降级生成无背景音乐的视频。",
- "Custom Background Music File": "请输入自定义背景音乐的文件路径",
+ "ElevenLabs Background Music": "根据画面自动配乐(ElevenLabs AI)",
+ "ElevenLabs Music API Key": "ElevenLabs API 密钥([点击获取](https://elevenlabs.io/app/settings/api-keys))",
+ "ElevenLabs API Key Help": "该 Key 与 ElevenLabs 配音共用,输入内容会以密码形式显示,并保存到本机 config.toml。",
+ "ElevenLabs Music Prompt": "音乐风格(可选)",
+ "ElevenLabs Music Prompt Help": "可以填写风格或情绪要求,最多 1000 个字符;留空时由 ElevenLabs 自动匹配视频。",
+ "ElevenLabs Multiple Videos Warning": "ElevenLabs 会为每条输出视频分别生成配乐,生成多条视频会消耗多次额度。",
+ "ElevenLabs API Key Required": "使用 ElevenLabs 背景音乐前,请填写 ElevenLabs API Key。",
+ "Test ElevenLabs Connection": "检查 ElevenLabs 账号",
+ "ElevenLabs Connection Test Succeeded": "ElevenLabs 账号和套餐检查通过,Music API 权限将在生成配乐时确认。",
+ "ElevenLabs Connection Test Failed": "ElevenLabs 账号检查失败:{error}",
+ "ElevenLabs Paid Plan Required": "API Key 有效,但 ElevenLabs Music API 需要付费套餐,请升级账号后再生成配乐。",
+ "ElevenLabs BGM Fallback Warning": "第 {index} 条视频的 ElevenLabs 配乐生成失败,已降级生成无背景音乐的视频。",
+ "Custom Background Music File": "或者输入自定义背景音乐的文件路径",
"Upload Background Music": "上传背景音乐",
"Upload Background Music Help": "请上传不超过 30 MB 的 MP3、M4A、AAC、WAV、FLAC、OGG、OPUS 或 WMA 文件,点击生成视频时会持久化保存。",
"Background Music Ready": "背景音乐已就绪",