Skip to content

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

feat(webui): add full voiceover preview

harry0703af0069a10c4f
diff --git a/app/config/config.py b/app/config/config.py
index d7faab40..f87c4637 100644
--- a/app/config/config.py
+++ b/app/config/config.py
@@ -87,6 +87,23 @@ def runtime_config_lock():
yield
+@contextmanager
+def try_runtime_config_lock():
+ """
+ 尝试获取运行期配置锁,并立即返回是否成功。
+
+ WebUI 试听属于用户主动触发的短操作,不应在后台视频任务持锁时等待数分钟。
+ 调用方可以在未获取锁时就近提示用户稍后重试;成功获取后仍能保证试听期间
+ Provider、密钥和模型配置不会被其它会话修改。
+ """
+ acquired = _config_save_lock.acquire(blocking=False)
+ try:
+ yield acquired
+ finally:
+ if acquired:
+ _config_save_lock.release()
+
+
def is_running_in_container(
dockerenv_path: str = "/.dockerenv",
containerenv_path: str = "/run/.containerenv",
diff --git a/app/services/task.py b/app/services/task.py
index 8a066241..d1c8c569 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -337,8 +337,68 @@ def resolve_custom_audio_file(task_id: str, custom_audio_file: str | None) -> st
return server_audio_file
-def generate_audio(task_id, params, video_script):
- '''
+def _resolve_reusable_voice_preview(
+ task_id: str,
+ params,
+ video_script: str,
+ voice_preview: dict | None,
+) -> tuple[str, float, object] | None:
+ """
+ 校验并解析 WebUI 提交的完整试听缓存。
+
+ 该载荷不是公开 API 参数,只能来自当前进程的 WebUI。即便如此,后台任务
+ 仍重新核对文案和全部配音参数,并限制音频位于当前任务目录;任何不一致都
+ 回退普通 TTS,不让过期试听污染正式成片。
+ """
+ if not voice_preview:
+ return None
+
+ expected_values = {
+ "script": str(video_script or "").strip(),
+ "voice_name": params.voice_name,
+ "voice_rate": float(params.voice_rate),
+ "voice_volume": float(params.voice_volume),
+ }
+ if not math.isclose(float(params.voice_volume), 1.0) or any(
+ voice_preview.get(key) != value for key, value in expected_values.items()
+ ):
+ logger.info(
+ f"skip stale voice preview cache, task_id: {task_id}, "
+ "reason: voice parameters changed"
+ )
+ return None
+
+ preview_file = path.realpath(str(voice_preview.get("audio_file") or ""))
+ task_root = path.realpath(utils.task_dir(task_id))
+ try:
+ preview_is_task_local = path.commonpath([task_root, preview_file]) == task_root
+ except ValueError:
+ preview_is_task_local = False
+
+ duration = voice_preview.get("duration")
+ sub_maker = voice_preview.get("sub_maker")
+ if (
+ not preview_is_task_local
+ or not path.isfile(preview_file)
+ or not isinstance(duration, (int, float))
+ or not math.isfinite(duration)
+ or duration <= 0
+ or sub_maker is None
+ ):
+ logger.warning(
+ f"skip invalid voice preview cache, task_id: {task_id}, "
+ f"audio_file: {preview_file or '<empty>'}"
+ )
+ return None
+
+ logger.info(
+ f"using full voice preview audio, task_id: {task_id}, duration: {duration:.2f}s"
+ )
+ return preview_file, math.ceil(duration), sub_maker
+
+
+def generate_audio(task_id, params, video_script, voice_preview=None):
+ """
Generate audio for the video script.
If a custom audio file is provided, it will be used directly.
There will be no subtitle maker object returned in this case.
@@ -347,7 +407,7 @@ def generate_audio(task_id, params, video_script):
- audio_file: path to the generated or provided audio file
- audio_duration: duration of the audio in seconds
- sub_maker: subtitle maker object if TTS is used, None otherwise
- '''
+ """
logger.info("\n\n## generating audio")
# /audio 和 /subtitle 请求模型不包含 custom_audio_file,
# 这里统一做兼容读取,避免直调接口时抛属性错误。
@@ -365,6 +425,15 @@ def generate_audio(task_id, params, video_script):
return None, None, None
if not custom_audio_file:
+ reusable_preview = _resolve_reusable_voice_preview(
+ task_id,
+ params,
+ video_script,
+ voice_preview,
+ )
+ if reusable_preview:
+ return reusable_preview
+
logger.info("no custom audio file provided, using TTS to generate audio.")
audio_file = path.join(utils.task_dir(task_id), "audio.mp3")
sub_maker = voice.tts(
@@ -925,7 +994,12 @@ def _schedule_cross_post(
return None
-def _run_pipeline(task_id, params: VideoParams, stop_at: str = "video"):
+def _run_pipeline(
+ task_id,
+ params: VideoParams,
+ stop_at: str = "video",
+ voice_preview: dict | None = None,
+):
logger.info(f"start task: {task_id}, stop_at: {stop_at}")
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=5)
@@ -984,7 +1058,10 @@ def _run_pipeline(task_id, params: VideoParams, stop_at: str = "video"):
# 3. Generate audio
audio_file, audio_duration, sub_maker = generate_audio(
- task_id, params, video_script
+ task_id,
+ params,
+ video_script,
+ voice_preview=voice_preview,
)
if not audio_file:
return _mark_task_failed(
@@ -1126,10 +1203,20 @@ def _run_pipeline(task_id, params: VideoParams, stop_at: str = "video"):
return kwargs
-def start(task_id, params: VideoParams, stop_at: str = "video"):
+def start(
+ task_id,
+ params: VideoParams,
+ stop_at: str = "video",
+ voice_preview: dict | None = None,
+):
"""执行任务流水线,并确保未预期异常也会转换成可查询的失败状态。"""
try:
- return _run_pipeline(task_id, params, stop_at=stop_at)
+ return _run_pipeline(
+ task_id,
+ params,
+ stop_at=stop_at,
+ voice_preview=voice_preview,
+ )
except Exception as exc:
logger.exception(
f"unexpected task pipeline failure, task_id: {task_id}, error: {exc}"
diff --git a/app/services/webui_task.py b/app/services/webui_task.py
index 837450a9..8cec972e 100644
--- a/app/services/webui_task.py
+++ b/app/services/webui_task.py
@@ -53,6 +53,7 @@ def _run_generation(
task_id: str,
params: VideoParams,
capture_logs: bool,
+ voice_preview: dict | None = None,
) -> dict:
"""
在后台线程中执行现有视频流水线。
@@ -76,7 +77,11 @@ def _run_generation(
# 完整任务仍使用原来的配置锁,防止另一个 WebUI 会话在生成中途修改
# Provider、密钥等进程级配置,造成同一条视频前后使用不同设置。
with config.runtime_config_lock():
- return tm.start(task_id=task_id, params=params)
+ return tm.start(
+ task_id=task_id,
+ params=params,
+ voice_preview=voice_preview,
+ )
except Exception as exc:
# tm.start 已负责把流水线异常转换成失败状态;这里额外保护日志 sink、
# 配置锁等 WebUI 包装层。任何后台线程异常都必须留下终态,不能让任务
@@ -115,6 +120,7 @@ def submit_generation(
task_id: str,
params: VideoParams,
capture_logs: bool = True,
+ voice_preview: dict | None = None,
) -> None:
"""
登记并提交 WebUI 视频生成任务,调用后立即返回。
@@ -123,6 +129,9 @@ def submit_generation(
浏览器刷新或 WebSocket 重连也不依赖旧页面内存中的占位符。
"""
task_params = params.model_copy(deep=True)
+ # 预览载荷只包含不可变音频路径、参数快照和只读字幕时间轴。复制外层字典,
+ # 避免页面后续 rerun 替换缓存字段时影响已经提交到后台队列的任务。
+ voice_preview_snapshot = dict(voice_preview) if voice_preview else None
sm.state.update_task(
task_id,
state=const.TASK_STATE_PROCESSING,
@@ -135,6 +144,7 @@ def submit_generation(
task_id=task_id,
params=task_params,
capture_logs=capture_logs,
+ voice_preview=voice_preview_snapshot,
)
except Exception as exc:
# 调度失败与流水线失败一样必须成为可查询状态,避免任务管理器永久显示
diff --git a/test/services/test_config.py b/test/services/test_config.py
index 17141ba4..fc0cbf7e 100644
--- a/test/services/test_config.py
+++ b/test/services/test_config.py
@@ -124,3 +124,24 @@ class TestConfigPersistence:
worker.join(timeout=1)
assert config.app[key] == "unchanged"
config.app.pop(key, None)
+
+ def test_try_runtime_config_lock_returns_immediately_when_busy(self):
+ """试听锁不能等待长任务释放全局配置,忙碌时应立即让 UI 提示重试。"""
+ attempted = threading.Event()
+ result = []
+
+ def try_lock():
+ with config.try_runtime_config_lock() as acquired:
+ result.append(acquired)
+ attempted.set()
+
+ with config.runtime_config_lock():
+ worker = threading.Thread(target=try_lock)
+ worker.start()
+ assert attempted.wait(timeout=0.2)
+
+ worker.join(timeout=1)
+ assert result == [False]
+
+ with config.try_runtime_config_lock() as acquired:
+ assert acquired is True
diff --git a/test/services/test_webui_voice_preview.py b/test/services/test_webui_voice_preview.py
new file mode 100644
index 00000000..eecb9e3d
--- /dev/null
+++ b/test/services/test_webui_voice_preview.py
@@ -0,0 +1,449 @@
+import ast
+import hashlib
+import re
+import shutil
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from streamlit.testing.v1 import AppTest
+
+from app.config import config
+from app.models.schema import VideoParams
+from app.services import task as tm
+from app.services import voice
+from app.services import webui_task
+from app.utils import utils
+
+
+ROOT_DIR = Path(__file__).parent.parent.parent
+WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"
+
+
+def _load_duration_estimator():
+ """只加载纯估算函数,避免单元测试导入并执行完整 Streamlit 页面。"""
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ function = next(
+ node
+ for node in tree.body
+ if isinstance(node, ast.FunctionDef)
+ and node.name == "_estimate_voiceover_duration_range"
+ )
+ module = ast.Module(body=[function], type_ignores=[])
+ namespace = {"re": re}
+ exec(compile(module, str(WEBUI_MAIN), "exec"), namespace)
+ return namespace["_estimate_voiceover_duration_range"]
+
+
+def _load_provider_signature(test_config):
+ """加载凭证摘要和 Provider 指纹函数,独立验证缓存失效规则。"""
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ functions = [
+ node
+ for node in tree.body
+ if isinstance(node, ast.FunctionDef)
+ and node.name
+ in {
+ "_credential_signature",
+ "_get_voice_preview_provider_signature",
+ }
+ ]
+ module = ast.Module(body=functions, type_ignores=[])
+ namespace = {"hashlib": hashlib, "config": test_config}
+ exec(compile(module, str(WEBUI_MAIN), "exec"), namespace)
+ return namespace["_get_voice_preview_provider_signature"]
+
+
+def _button_by_key(app, key):
+ return next(
+ button
+ for button in app.button
+ if str(getattr(button, "key", "")).startswith(key)
+ )
+
+
+def test_duration_estimator_is_local_and_respects_voice_rate():
+ """本地估算应覆盖中英文,并随用户选择的语速合理缩短。"""
+ estimate = _load_duration_estimator()
+ script = "人工智能正在改变日常生活。它可以帮助我们整理信息,也能提高效率。"
+
+ normal_range = estimate(script, 1.0)
+ fast_range = estimate(script, 2.0)
+
+ assert normal_range is not None
+ assert fast_range is not None
+ assert normal_range[0] < normal_range[1]
+ assert fast_range[0] < normal_range[0]
+ assert estimate("", 1.0) is None
+ assert estimate("AI tools can simplify repetitive work.", 1.0) is not None
+
+
+def test_provider_signature_changes_when_api_key_changes():
+ """只修改 API Key 也必须让试听缓存失效,不能伪装成新凭证验证成功。"""
+ test_config = SimpleNamespace(
+ app={"gemini_api_key": "old-gemini", "mimo_api_key": "old-mimo"},
+ azure={"speech_region": "eastasia", "speech_key": "old-azure"},
+ siliconflow={"api_key": "old-siliconflow"},
+ elevenlabs={"api_key": "old-elevenlabs", "model_id": "eleven_v3"},
+ chatterbox={
+ "api_key": "old-chatterbox",
+ "base_url": "http://127.0.0.1:4123/v1",
+ "model_id": "chatterbox",
+ },
+ )
+ provider_signature = _load_provider_signature(test_config)
+
+ old_signature = provider_signature("elevenlabs")
+ test_config.elevenlabs["api_key"] = "new-elevenlabs"
+ new_signature = provider_signature("elevenlabs")
+
+ assert old_signature != new_signature
+ assert "old-elevenlabs" not in str(old_signature)
+ assert "new-elevenlabs" not in str(new_signature)
+
+
+def test_full_voiceover_preview_is_disabled_until_script_exists():
+ """完整预览必须由用户主动触发,文案为空时不能误调用商业 TTS。"""
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.run()
+
+ full_preview = _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ )
+ assert full_preview.disabled
+ assert any("填写视频文案后" in item.value for item in app.caption)
+
+
+def test_script_shows_estimate_and_enables_full_voiceover_preview():
+ """填写文案后展示免费估算,并明确完整预览可能产生 API 成本。"""
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["video_script"] = (
+ "人工智能正在改变日常生活。合理使用工具,可以帮助我们提高工作效率。"
+ )
+ app.run()
+
+ full_preview = _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ )
+ assert not full_preview.disabled
+ assert any("本地估算,不调用 API" in item.value for item in app.caption)
+ assert "可能消耗 API 额度" in full_preview.help
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_full_preview_uses_script_and_reuses_identical_cached_audio():
+ """完整试听使用当前文案,相同参数重复点击时不得再次调用 TTS。"""
+ script = "这是一段用于验证完整配音预览缓存的测试文案。"
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+
+ def fake_tts(**kwargs):
+ # 文件扩展名虽然是 mp3,但真实 TTS 可能返回 WAV;这个最小文件头同时
+ # 验证 WebUI 会按内容识别播放器 MIME,而不是盲信扩展名。
+ Path(kwargs["voice_file"]).write_bytes(
+ b"RIFF\x24\x00\x00\x00WAVEfmt " + b"\x00" * 32
+ )
+ return object()
+
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ patch.object(voice, "tts", side_effect=fake_tts) as synthesize,
+ patch.object(voice, "get_audio_duration", return_value=12.3),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["video_script"] = script
+ app.run()
+
+ _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ ).click().run()
+ _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ ).click().run()
+
+ synthesize.assert_called_once()
+ assert synthesize.call_args.kwargs["text"] == script
+ assert len(app.get("audio")) == 1
+ assert any("实际配音时长:12.3 秒" in item.value for item in app.caption)
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_full_preview_reports_when_tts_returns_no_audio():
+ """TTS 返回空结果时必须给出可操作提示,不能让按钮点击后无任何反馈。"""
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ patch.object(voice, "tts", return_value=None),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["video_script"] = "验证配音服务空响应。"
+ app.run()
+ _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ ).click().run()
+
+ assert [item.value for item in app.error] == [
+ "配音服务未返回试听音频,请检查相关设置和应用日志。"
+ ]
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_full_preview_returns_immediately_when_runtime_config_is_busy():
+ """后台任务持有配置锁时,试听应提示稍后重试而不是阻塞页面。"""
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ patch.object(
+ config,
+ "try_runtime_config_lock",
+ return_value=nullcontext(False),
+ ),
+ patch.object(voice, "tts") as synthesize,
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["video_script"] = "验证忙碌状态不会阻塞页面。"
+ app.run()
+ _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ ).click().run()
+
+ synthesize.assert_not_called()
+ warning_messages = [item.value for item in app.warning]
+ assert "当前有视频任务正在使用配音配置,请稍后重试。" in warning_messages
+
+
+def test_full_preview_warns_when_audio_duration_is_unavailable():
+ """音频可播放但无法解码时长时,不能把 0.0 秒展示为真实结果。"""
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="azure-tts-v1",
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ )
+
+ def fake_tts(**kwargs):
+ Path(kwargs["voice_file"]).write_bytes(
+ b"RIFF\x24\x00\x00\x00WAVEfmt " + b"\x00" * 32
+ )
+ return object()
+
+ with (
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "save_config"),
+ patch.object(voice, "tts", side_effect=fake_tts),
+ patch.object(voice, "get_audio_duration", return_value=0),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "zh"
+ app.session_state["video_script"] = "验证无法读取试听音频时长的提示。"
+ app.run()
+ _button_by_key(
+ app,
+ "generate_full_voiceover_preview_button",
+ ).click().run()
+
+ assert len(app.get("audio")) == 1
+ warning_messages = [item.value for item in app.warning]
+ assert "试听音频已生成,但无法读取准确时长,请检查应用日志。" in warning_messages
+
+
+def test_task_reuses_matching_full_preview_without_calling_tts():
+ """参数完全一致时,正式任务应复用试听音频和字幕时间轴。"""
+ task_id = "reuse-full-voice-preview"
+ task_dir = Path(utils.task_dir(task_id))
+ audio_file = task_dir / "audio.mp3"
+ audio_file.write_bytes(b"preview audio")
+ sub_maker = object()
+ script = "完整试听和正式任务使用同一段文案。"
+ params = VideoParams(
+ video_subject="preview reuse",
+ video_script=script,
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ voice_rate=1.2,
+ voice_volume=1.0,
+ )
+ preview = {
+ "audio_file": str(audio_file),
+ "duration": 8.2,
+ "sub_maker": sub_maker,
+ "script": script,
+ "voice_name": params.voice_name,
+ "voice_rate": params.voice_rate,
+ "voice_volume": params.voice_volume,
+ }
+
+ try:
+ with patch.object(tm.voice, "tts") as synthesize:
+ result = tm.generate_audio(
+ task_id,
+ params,
+ script,
+ voice_preview=preview,
+ )
+ finally:
+ shutil.rmtree(task_dir, ignore_errors=True)
+
+ assert result == (str(audio_file.resolve()), 9, sub_maker)
+ synthesize.assert_not_called()
+
+
+def test_task_regenerates_audio_when_preview_parameters_changed():
+ """文案或配音参数变化后必须回退 TTS,不能复用已经过期的完整试听。"""
+ task_id = "stale-full-voice-preview"
+ task_dir = Path(utils.task_dir(task_id))
+ audio_file = task_dir / "audio.mp3"
+ audio_file.write_bytes(b"stale preview audio")
+ script = "正式任务需要使用新的语速重新生成配音。"
+ params = VideoParams(
+ video_subject="stale preview",
+ video_script=script,
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ voice_rate=1.5,
+ voice_volume=1.0,
+ )
+ preview = {
+ "audio_file": str(audio_file),
+ "duration": 8.2,
+ "sub_maker": object(),
+ "script": script,
+ "voice_name": params.voice_name,
+ "voice_rate": 1.0,
+ "voice_volume": params.voice_volume,
+ }
+ regenerated_sub_maker = object()
+
+ try:
+ with (
+ patch.object(
+ tm.voice,
+ "tts",
+ return_value=regenerated_sub_maker,
+ ) as synthesize,
+ patch.object(tm.voice, "get_audio_duration", return_value=6),
+ ):
+ result = tm.generate_audio(
+ task_id,
+ params,
+ script,
+ voice_preview=preview,
+ )
+ finally:
+ shutil.rmtree(task_dir, ignore_errors=True)
+
+ assert result[1:] == (6, regenerated_sub_maker)
+ synthesize.assert_called_once()
+ assert synthesize.call_args.kwargs["voice_rate"] == 1.5
+
+
+def test_non_default_volume_regenerates_audio_without_double_gain():
+ """非默认音量必须回退原流程,避免 TTS 与视频合成阶段重复应用增益。"""
+ task_id = "voice-volume-forwarding"
+ task_dir = Path(utils.task_dir(task_id))
+ audio_file = task_dir / "audio.mp3"
+ audio_file.write_bytes(b"preview with provider-side volume")
+ script = "非默认音量需要按原流程生成配音。"
+ params = VideoParams(
+ video_subject="voice volume",
+ video_script=script,
+ voice_name="zh-CN-XiaoxiaoNeural-Female",
+ voice_rate=1.2,
+ voice_volume=1.5,
+ )
+ sub_maker = object()
+ preview = {
+ "audio_file": str(audio_file),
+ "duration": 5.0,
+ "sub_maker": object(),
+ "script": script,
+ "voice_name": params.voice_name,
+ "voice_rate": params.voice_rate,
+ "voice_volume": params.voice_volume,
+ }
+
+ try:
+ with (
+ patch.object(tm.voice, "tts", return_value=sub_maker) as synthesize,
+ patch.object(tm.voice, "get_audio_duration", return_value=5),
+ ):
+ result = tm.generate_audio(
+ task_id,
+ params,
+ script,
+ voice_preview=preview,
+ )
+ finally:
+ shutil.rmtree(task_dir, ignore_errors=True)
+
+ assert result[1:] == (5, sub_maker)
+ synthesize.assert_called_once()
+ assert "voice_volume" not in synthesize.call_args.kwargs
+
+
+def test_webui_worker_forwards_voice_preview_to_pipeline():
+ """后台任务包装层不能丢失提交时已经校验过的试听缓存。"""
+ preview = {"audio_file": "audio.mp3", "duration": 5.0}
+ with (
+ patch.object(webui_task.tm, "start", return_value={"videos": []}) as start,
+ patch.object(
+ webui_task.config,
+ "runtime_config_lock",
+ return_value=nullcontext(),
+ ),
+ ):
+ webui_task._run_generation(
+ "preview-forwarding",
+ VideoParams(video_subject="preview forwarding"),
+ capture_logs=False,
+ voice_preview=preview,
+ )
+
+ assert start.call_args.kwargs["voice_preview"] == preview
diff --git a/webui/Main.py b/webui/Main.py
index 225b7758..80b82343 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -1,6 +1,7 @@
import hashlib
import html
import json
+import math
import mimetypes
import os
import re
@@ -2373,76 +2374,391 @@ def _render_video_settings(panel, params):
return uploaded_files
-def _render_voice_preview(params, friendly_names, selected_tts_server, voice_name):
- """使用当前音色、音量和语速生成一段试听音频。"""
- if not friendly_names or not st.button(
- tr("Play Voice"),
- key="play_voice_button",
- icon=":material/graphic_eq:",
- ):
- return
+def _estimate_voiceover_duration_range(
+ text: str, voice_rate: float
+) -> tuple[float, float] | None:
+ """
+ 在本地估算完整配音时长,返回保守的上下界秒数。
+
+ 该估算只用于帮助用户在调用付费 TTS 前判断文案量级,不参与任务执行。
+ 中文、日文和韩文按字符速度估算,其它使用空格分词的语言按单词速度估算,
+ 再计入常见标点停顿。不同 Provider、音色和语气会造成实际偏差,因此界面
+ 必须展示区间而不是伪精确的单一结果。
+ """
+ normalized_text = re.sub(r"\s+", " ", str(text or "")).strip()
+ if not normalized_text:
+ return None
+
+ script_chars = re.findall(
+ r"[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]",
+ normalized_text,
+ )
+ remaining_text = re.sub(
+ r"[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]",
+ " ",
+ normalized_text,
+ )
+ words = re.findall(r"\b[\w]+(?:[-'’][\w]+)*\b", remaining_text, re.UNICODE)
+ punctuation_count = len(re.findall(r"[,,.。!?!?;;::]", normalized_text))
+
+ # 4.2 字/秒和 2.6 词/秒接近日常解说语速;标点按 0.12 秒加入轻微停顿。
+ # voice_rate 只作为估算修正项。部分生成式 TTS 不严格执行倍率,所以最终
+ # 仍保留 ±15% 区间,避免让用户误以为该值等同于服务端真实结果。
+ base_seconds = len(script_chars) / 4.2 + len(words) / 2.6 + punctuation_count * 0.12
+ if base_seconds <= 0:
+ return None
+
+ normalized_rate = max(float(voice_rate or 1.0), 0.1)
+ estimated_seconds = base_seconds / normalized_rate
+ return (
+ round(max(estimated_seconds * 0.85, 1.0), 1),
+ round(max(estimated_seconds * 1.15, 1.0), 1),
+ )
+
+
+def _get_voice_preview_sample(voice_name: str) -> str:
+ """返回适合当前音色的短试听文案,不使用用户的完整视频文案。"""
+ # ElevenLabs 音色缺少明确语言字段时,根据展示名称中的越南语字符选择
+ # 试听文案,避免用明显不匹配的语言判断音色效果。
+ if voice.is_elevenlabs_voice(voice_name):
+ parts = voice_name.split(":", 2)
+ display = parts[2] if len(parts) >= 3 else ""
+ vietnamese_chars = set("àáâãèéêìíòóôõùúýăđơưÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚÝĂĐƠƯ")
+ if any(char in vietnamese_chars for char in display):
+ return "Xin chào, đây là đoạn âm thanh thử nghiệm giọng nói."
+ return tr("Voice Example")
+
+
+def _voice_preview_fingerprint(
+ *,
+ preview_type: str,
+ content: str,
+ tts_server: str,
+ voice_name: str,
+ voice_rate: float,
+ voice_volume: float,
+ provider_signature: dict,
+) -> str:
+ """生成试听缓存指纹,任一配音参数变化后自动让旧试听结果失效。"""
+ payload = {
+ "preview_type": preview_type,
+ "content": content,
+ "tts_server": tts_server,
+ "voice_name": voice_name,
+ "voice_rate": voice_rate,
+ "voice_volume": voice_volume,
+ "provider_signature": provider_signature,
+ }
+ encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
+ return hashlib.sha256(encoded).hexdigest()
+
+
+def _credential_signature(value: str) -> str:
+ """
+ 生成只用于缓存失效判断的凭证摘要。
+
+ 摘要不会写入配置、日志或任务文件。用户修改 API Key 后摘要会变化,从而
+ 强制重新调用当前配音服务,避免旧试听缓存让无效的新凭证看起来可用。
+ """
+ normalized_value = str(value or "")
+ if not normalized_value:
+ return ""
+ return hashlib.sha256(normalized_value.encode("utf-8")).hexdigest()
+
+
+def _get_voice_preview_provider_signature(tts_server: str) -> dict:
+ """
+ 返回会影响试听结果的非敏感 Provider 配置。
+ API Key 只以单向摘要参与缓存指纹,原始凭证不会进入缓存或日志。模型、
+ 服务地址、区域或凭证发生变化时都必须重新生成试听,否则界面可能继续播放
+ 旧 Provider 配置下的音频,让用户误判当前设置已经生效。
+ """
+ if tts_server == "azure-tts-v2":
+ return {
+ "speech_region": config.azure.get("speech_region", ""),
+ "credential": _credential_signature(config.azure.get("speech_key", "")),
+ }
+ if tts_server == "siliconflow":
+ return {
+ "credential": _credential_signature(config.siliconflow.get("api_key", ""))
+ }
+ if tts_server == "gemini-tts":
+ return {
+ "credential": _credential_signature(config.app.get("gemini_api_key", ""))
+ }
+ if tts_server == "mimo-tts":
+ return {"credential": _credential_signature(config.app.get("mimo_api_key", ""))}
+ if tts_server == "elevenlabs":
+ return {
+ "model_id": config.elevenlabs.get("model_id", ""),
+ "credential": _credential_signature(config.elevenlabs.get("api_key", "")),
+ }
+ if tts_server == "chatterbox":
+ return {
+ "base_url": config.chatterbox.get("base_url", ""),
+ "model_id": config.chatterbox.get("model_id", ""),
+ "credential": _credential_signature(config.chatterbox.get("api_key", "")),
+ }
+ return {}
+
+
+def _synthesize_voice_preview(
+ *,
+ content: str,
+ preview_type: str,
+ selected_tts_server: str,
+ voice_name: str,
+ voice_rate: float,
+ voice_volume: float,
+) -> dict | None:
+ """生成一次试听并转为内存缓存,临时文件不会跨会话长期保留。"""
if selected_tts_server == "chatterbox":
_sync_chatterbox_config_from_session_state()
- play_content = params.video_subject or params.video_script
- if not play_content:
- # ElevenLabs 音色缺少明确语言字段时,根据展示名称中的越南语字符
- # 选择试听文案,避免用不匹配的语言判断音色效果。
- if voice.is_elevenlabs_voice(voice_name):
- parts = voice_name.split(":", 2)
- display = parts[2] if len(parts) >= 3 else ""
- vietnamese_chars = set("àáâãèéêìíòóôõùúýăđơưÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚÝĂĐƠƯ")
- if any(char in vietnamese_chars for char in display):
- play_content = "Xin chào, đây là đoạn âm thanh thử nghiệm giọng nói."
- else:
- play_content = tr("Voice Example")
- else:
- play_content = tr("Voice Example")
-
- with st.spinner(tr("Synthesizing Voice")):
- temp_dir = utils.storage_dir("temp", create=True)
- audio_file = os.path.join(temp_dir, f"tmp-voice-{str(uuid4())}.mp3")
- logger.info(
- "generating voice preview: "
- f"voice={voice_name}, rate={params.voice_rate}, "
- f"volume={params.voice_volume}"
- )
- with config.runtime_config_lock():
+
+ temp_dir = utils.storage_dir("temp", create=True)
+ audio_file = os.path.join(temp_dir, f"tmp-voice-{str(uuid4())}.mp3")
+ logger.info(
+ f"generating {preview_type} voice preview: "
+ f"voice={voice_name}, rate={voice_rate}, volume={voice_volume}, "
+ f"text_length={len(content)}"
+ )
+ try:
+ with config.try_runtime_config_lock() as lock_acquired:
+ if not lock_acquired:
+ return {"busy": True}
sub_maker = voice.tts(
- text=play_content,
+ text=content,
voice_name=voice_name,
- voice_rate=params.voice_rate,
+ voice_rate=voice_rate,
voice_file=audio_file,
- voice_volume=params.voice_volume,
+ voice_volume=voice_volume,
)
- # 首次试听失败后仍在同一个配置锁中重试,避免两个请求之间
- # 被其它标签页切换 TTS Provider 或 API Key。
- if not sub_maker:
- play_content = "This is an example voice."
- sub_maker = voice.tts(
- text=play_content,
- voice_name=voice_name,
- voice_rate=params.voice_rate,
- voice_file=audio_file,
- voice_volume=params.voice_volume,
- )
-
if not sub_maker or not os.path.exists(audio_file):
- return
+ logger.error(f"{preview_type} voice preview did not produce an audio file")
+ return None
+
+ with open(audio_file, "rb") as file:
+ audio_bytes = file.read()
+ if not audio_bytes:
+ logger.error(f"voice preview audio file is empty: {audio_file}")
+ return None
+
+ duration = voice.get_audio_duration(audio_file)
+ if (
+ not isinstance(duration, (int, float))
+ or not math.isfinite(duration)
+ or duration <= 0
+ ):
+ logger.warning(
+ f"voice preview duration is unavailable: "
+ f"preview_type={preview_type}, voice={voice_name}"
+ )
+ duration = None
+
+ return {
+ "audio_bytes": audio_bytes,
+ "mime_type": _detect_audio_mime(audio_file, audio_bytes),
+ "duration": duration,
+ "preview_type": preview_type,
+ "sub_maker": sub_maker,
+ }
+ finally:
+ # 浏览器播放器使用内存字节,文件读取完即可清理,避免频繁试听积累临时文件。
try:
- with open(audio_file, "rb") as file:
- audio_bytes = file.read()
- if audio_bytes:
- st.audio(
- audio_bytes,
- format=_detect_audio_mime(audio_file, audio_bytes),
+ os.remove(audio_file)
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ # 清理失败不应覆盖真正的 TTS 响应或异常,但需要保留路径和系统错误,
+ # 方便排查权限、只读文件系统等环境问题。
+ logger.warning(
+ f"failed to delete voice preview file {audio_file}: {str(exc)}"
+ )
+
+
+def _render_voice_preview(params, friendly_names, selected_tts_server, voice_name):
+ """渲染低成本短试听、完整文案时长估算和按需完整配音预览。"""
+ if not friendly_names:
+ return
+
+ script_content = str(params.video_script or "").strip()
+ estimated_range = _estimate_voiceover_duration_range(
+ script_content,
+ params.voice_rate,
+ )
+ if estimated_range:
+ st.caption(
+ tr("Estimated Voiceover Duration").format(
+ min=estimated_range[0],
+ max=estimated_range[1],
+ )
+ )
+ else:
+ st.caption(tr("Voiceover Script Required"))
+
+ sample_content = _get_voice_preview_sample(voice_name)
+ provider_signature = _get_voice_preview_provider_signature(selected_tts_server)
+ preview_columns = st.columns(2)
+ short_preview_requested = preview_columns[0].button(
+ tr("Play Voice"),
+ key="play_voice_button",
+ icon=":material/graphic_eq:",
+ use_container_width=True,
+ )
+ full_preview_requested = preview_columns[1].button(
+ tr("Generate Full Voiceover Preview"),
+ key="generate_full_voiceover_preview_button",
+ icon=":material/article:",
+ help=tr("Full Voiceover Preview Cost Hint"),
+ use_container_width=True,
+ disabled=not bool(script_content),
+ )
+
+ preview_type = ""
+ preview_content = ""
+ if short_preview_requested:
+ preview_type = "sample"
+ preview_content = sample_content
+ elif full_preview_requested:
+ preview_type = "full"
+ preview_content = script_content
+
+ sample_fingerprint = _voice_preview_fingerprint(
+ preview_type="sample",
+ content=sample_content,
+ tts_server=selected_tts_server,
+ voice_name=voice_name,
+ voice_rate=params.voice_rate,
+ voice_volume=params.voice_volume,
+ provider_signature=provider_signature,
+ )
+ full_fingerprint = (
+ _voice_preview_fingerprint(
+ preview_type="full",
+ content=script_content,
+ tts_server=selected_tts_server,
+ voice_name=voice_name,
+ voice_rate=params.voice_rate,
+ voice_volume=params.voice_volume,
+ provider_signature=provider_signature,
+ )
+ if script_content
+ else ""
+ )
+
+ if preview_type:
+ requested_fingerprint = (
+ sample_fingerprint if preview_type == "sample" else full_fingerprint
+ )
+ cached_preview = st.session_state.get("voice_preview_audio")
+ if (
+ not cached_preview
+ or cached_preview.get("fingerprint") != requested_fingerprint
+ ):
+ try:
+ with st.spinner(tr("Synthesizing Voice")):
+ preview_result = _synthesize_voice_preview(
+ content=preview_content,
+ preview_type=preview_type,
+ selected_tts_server=selected_tts_server,
+ voice_name=voice_name,
+ voice_rate=params.voice_rate,
+ voice_volume=params.voice_volume,
+ )
+ except Exception as exc:
+ logger.exception(f"failed to generate {preview_type} voice preview")
+ st.error(tr("Voice Preview Failed").format(error=str(exc)))
+ else:
+ if preview_result and preview_result.get("busy"):
+ st.warning(tr("Voice Preview Busy"))
+ elif preview_result:
+ preview_result["fingerprint"] = requested_fingerprint
+ st.session_state["voice_preview_audio"] = preview_result
+ else:
+ st.error(tr("Voice Preview No Audio"))
+
+ cached_preview = st.session_state.get("voice_preview_audio")
+ valid_fingerprints = {sample_fingerprint, full_fingerprint}
+ if (
+ cached_preview
+ and cached_preview.get("fingerprint") in valid_fingerprints
+ and cached_preview.get("audio_bytes")
+ ):
+ st.audio(
+ cached_preview["audio_bytes"],
+ format=cached_preview.get("mime_type", "audio/mp3"),
+ )
+ if cached_preview.get("preview_type") == "full":
+ duration = cached_preview.get("duration")
+ if isinstance(duration, (int, float)) and duration > 0:
+ st.caption(
+ tr("Actual Voiceover Duration").format(duration=f"{duration:.1f}")
)
else:
- logger.error(f"voice preview audio file is empty: {audio_file}")
- finally:
- # 试听文件只服务当前 rerun,渲染为内存数据后立即清理。
- if os.path.exists(audio_file):
- os.remove(audio_file)
+ st.warning(tr("Voice Preview Duration Unavailable"))
+
+
+def _get_reusable_full_voice_preview(params, voice_mode: str) -> dict | None:
+ """
+ 返回与当前生成参数完全匹配的完整试听缓存。
+
+ 只复用完整文案试听,短音色样例永远不能进入正式任务。指纹统一覆盖文案、
+ Provider、音色、语速、音量和非敏感配置摘要;任何参数变化都会自然回退到
+ 正常 TTS 流程。字幕时间轴和有效时长同样是必需条件,避免只复用音频后让
+ Edge 字幕链路失去 SubMaker。
+ """
+ if voice_mode != VOICE_MODE_TTS:
+ return None
+
+ script_content = str(params.video_script or "").strip()
+ selected_tts_server = config.ui.get("tts_server", "azure-tts-v1")
+ if (
+ not script_content
+ or not params.voice_name
+ # 正式视频会在 MoviePy 合成阶段统一应用配音音量;部分 Provider 又会
+ # 在 TTS 阶段直接写入音量增益。非默认音量下复用试听可能造成二次增益,
+ # 因此先保守回退原流程,避免为少量场景引入 Provider 特判。
+ or not math.isclose(float(params.voice_volume), 1.0)
+ ):
+ return None
+
+ expected_fingerprint = _voice_preview_fingerprint(
+ preview_type="full",
+ content=script_content,
+ tts_server=selected_tts_server,
+ voice_name=params.voice_name,
+ voice_rate=params.voice_rate,
+ voice_volume=params.voice_volume,
+ provider_signature=_get_voice_preview_provider_signature(selected_tts_server),
+ )
+ cached_preview = st.session_state.get("voice_preview_audio")
+ if (
+ not cached_preview
+ or cached_preview.get("fingerprint") != expected_fingerprint
+ or cached_preview.get("preview_type") != "full"
+ or not cached_preview.get("audio_bytes")
+ or cached_preview.get("sub_maker") is None
+ ):
+ return None
+
+ duration = cached_preview.get("duration")
+ if (
+ not isinstance(duration, (int, float))
+ or not math.isfinite(duration)
+ or duration <= 0
+ ):
+ return None
+
+ return {
+ "audio_bytes": bytes(cached_preview["audio_bytes"]),
+ "duration": float(duration),
+ "sub_maker": cached_preview["sub_maker"],
+ "script": script_content,
+ "voice_name": params.voice_name,
+ "voice_rate": float(params.voice_rate),
+ "voice_volume": float(params.voice_volume),
+ }
def _render_background_music_settings(params):
@@ -3469,6 +3785,26 @@ def _render_generation_controls(
if m.url:
params.video_materials.append(m)
+ reusable_voice_preview = _get_reusable_full_voice_preview(
+ params,
+ voice_mode,
+ )
+ if reusable_voice_preview:
+ # 试听缓存只存在当前 Streamlit 会话。提交前把音频写入目标任务目录,
+ # 后台线程随后只读取任务自己的文件;即使页面 rerun、浏览器关闭或
+ # 用户试听其它音色,也不会影响已经入队的生成任务。
+ preview_audio_file = os.path.join(
+ utils.task_dir(task_id),
+ "audio.mp3",
+ )
+ with open(preview_audio_file, "wb") as file:
+ file.write(reusable_voice_preview.pop("audio_bytes"))
+ reusable_voice_preview["audio_file"] = preview_audio_file
+ logger.info(
+ f"reuse full voice preview for task: "
+ f"task_id={task_id}, duration={reusable_voice_preview['duration']:.2f}s"
+ )
+
try:
st.toast(tr("Generating Video"))
logger.info(tr("Start Generating Video"))
@@ -3477,6 +3813,7 @@ def _render_generation_controls(
task_id=task_id,
params=params,
capture_logs=not config.ui.get("hide_log", False),
+ voice_preview=reusable_voice_preview,
)
except Exception:
_remove_active_generation_task(task_id)
diff --git a/webui/i18n/de.json b/webui/i18n/de.json
index 9300832b..3ee1f9e2 100644
--- a/webui/i18n/de.json
+++ b/webui/i18n/de.json
@@ -187,9 +187,18 @@
"Upload Local Files": "Lokale Dateien hochladen",
"Please Upload Local Materials First": "Bitte laden Sie zuerst mindestens eine lokale Mediendatei hoch.",
"Unsupported Upload File Type": "Der hochgeladene Dateityp wird nicht unterstützt.",
- "Play Voice": "Stimme testen",
+ "Play Voice": "Stimmprobe",
"Voice Example": "Dies ist ein Beispieltext zum Testen der Sprachsynthese",
"Synthesizing Voice": "Sprachsynthese läuft, bitte warten...",
+ "Generate Full Voiceover Preview": "Ganz anhören",
+ "Estimated Voiceover Duration": "Geschätzte Gesamtdauer: ca. {min}–{max} Sek. (lokal, ohne API-Aufruf)",
+ "Voiceover Script Required": "Fügen Sie ein Videoskript hinzu, um die vollständige Vertonung zu schätzen und zu testen.",
+ "Full Voiceover Preview Cost Hint": "Die vollständige Vorschau ruft den TTS-Dienst auf und kann API-Guthaben verbrauchen.",
+ "Actual Voiceover Duration": "Tatsächliche Dauer: {duration} Sek.",
+ "Voice Preview Failed": "Stimmvorschau fehlgeschlagen: {error}",
+ "Voice Preview No Audio": "Der TTS-Dienst hat kein Audio geliefert. Prüfen Sie Einstellungen und Protokolle.",
+ "Voice Preview Busy": "Ein Videoauftrag verwendet gerade die Spracheinstellungen. Versuchen Sie es gleich erneut.",
+ "Voice Preview Duration Unavailable": "Das Vorschau-Audio wurde erstellt, aber seine Dauer konnte nicht gelesen werden. Prüfen Sie die Protokolle.",
"TTS Provider": "Sprachsynthese-Anbieter auswählen",
"TTS Servers": "TTS-Server",
"No voices available for the selected TTS server. Please select another server.": "Keine Stimmen für den ausgewählten TTS-Server verfügbar. Bitte wählen Sie einen anderen Server.",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index 75ce24ee..f97bcfa7 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -184,9 +184,18 @@
"Upload Local Files": "Upload Local Files",
"Please Upload Local Materials First": "Please upload at least one local material file first.",
"Unsupported Upload File Type": "The uploaded file type is not supported.",
- "Play Voice": "Preview Voice",
+ "Play Voice": "Voice Sample",
"Voice Example": "This is an example text for testing speech synthesis",
"Synthesizing Voice": "Synthesizing voice, please wait...",
+ "Generate Full Voiceover Preview": "Full Preview",
+ "Estimated Voiceover Duration": "Estimated full voiceover: about {min}–{max} sec (local estimate, no API call)",
+ "Voiceover Script Required": "Add a video script to estimate and preview the full voiceover.",
+ "Full Voiceover Preview Cost Hint": "A full preview calls the selected TTS service and may use API credits.",
+ "Actual Voiceover Duration": "Actual voiceover duration: {duration} sec",
+ "Voice Preview Failed": "Voice preview failed: {error}",
+ "Voice Preview No Audio": "The TTS service did not return preview audio. Check its settings and the application logs.",
+ "Voice Preview Busy": "A video task is currently using the voice settings. Try again shortly.",
+ "Voice Preview Duration Unavailable": "The preview audio was generated, but its duration could not be read. Check the application logs.",
"TTS Provider": "Select the voice synthesis provider",
"TTS Servers": "TTS Servers",
"No voices available for the selected TTS server. Please select another server.": "No voices available for the selected TTS server. Please select another server.",
diff --git a/webui/i18n/es.json b/webui/i18n/es.json
index 6fc9077d..02c401c0 100644
--- a/webui/i18n/es.json
+++ b/webui/i18n/es.json
@@ -184,9 +184,18 @@
"Upload Local Files": "Subir archivos locales",
"Please Upload Local Materials First": "Sube primero al menos un archivo multimedia local.",
"Unsupported Upload File Type": "El tipo de archivo subido no es compatible.",
- "Play Voice": "Probar voz",
+ "Play Voice": "Muestra de voz",
"Voice Example": "Este es un texto de ejemplo para probar la síntesis de voz",
"Synthesizing Voice": "Sintetizando voz, por favor espera...",
+ "Generate Full Voiceover Preview": "Audio completo",
+ "Estimated Voiceover Duration": "Duración estimada: {min}–{max} s (cálculo local, sin llamar a la API)",
+ "Voiceover Script Required": "Añade un guion para estimar y previsualizar la locución completa.",
+ "Full Voiceover Preview Cost Hint": "La vista completa llama al servicio TTS y puede consumir créditos de API.",
+ "Actual Voiceover Duration": "Duración real: {duration} s",
+ "Voice Preview Failed": "Error al previsualizar la voz: {error}",
+ "Voice Preview No Audio": "El servicio TTS no devolvió audio. Revisa la configuración y los registros.",
+ "Voice Preview Busy": "Una tarea de vídeo está usando la configuración de voz. Inténtalo de nuevo en breve.",
+ "Voice Preview Duration Unavailable": "El audio se generó, pero no se pudo leer su duración. Revisa los registros.",
"TTS Provider": "Selecciona el proveedor de síntesis de voz",
"TTS Servers": "Servidores TTS",
"No voices available for the selected TTS server. Please select another server.": "No hay voces disponibles para el servidor TTS seleccionado. Selecciona otro servidor.",
diff --git a/webui/i18n/id.json b/webui/i18n/id.json
index 8e47a042..f3004ec6 100644
--- a/webui/i18n/id.json
+++ b/webui/i18n/id.json
@@ -184,9 +184,18 @@
"Upload Local Files": "Unggah File Lokal",
"Please Upload Local Materials First": "Unggah setidaknya satu file materi lokal terlebih dahulu.",
"Unsupported Upload File Type": "Jenis file yang diunggah tidak didukung.",
- "Play Voice": "Uji Suara",
+ "Play Voice": "Contoh Suara",
"Voice Example": "Ini adalah teks contoh untuk menguji sintesis suara",
"Synthesizing Voice": "Mensintesis suara, harap tunggu...",
+ "Generate Full Voiceover Preview": "Pratinjau Penuh",
+ "Estimated Voiceover Duration": "Perkiraan durasi penuh: {min}–{max} dtk (lokal, tanpa panggilan API)",
+ "Voiceover Script Required": "Tambahkan skrip video untuk memperkirakan dan meninjau sulih suara penuh.",
+ "Full Voiceover Preview Cost Hint": "Pratinjau penuh memanggil layanan TTS dan dapat memakai kredit API.",
+ "Actual Voiceover Duration": "Durasi sebenarnya: {duration} dtk",
+ "Voice Preview Failed": "Pratinjau suara gagal: {error}",
+ "Voice Preview No Audio": "Layanan TTS tidak mengembalikan audio. Periksa pengaturan dan log aplikasi.",
+ "Voice Preview Busy": "Tugas video sedang memakai pengaturan suara. Coba lagi sebentar.",
+ "Voice Preview Duration Unavailable": "Audio pratinjau dibuat, tetapi durasinya tidak dapat dibaca. Periksa log aplikasi.",
"TTS Provider": "Pilih penyedia sintesis suara",
"TTS Servers": "Server TTS",
"No voices available for the selected TTS server. Please select another server.": "Tidak ada suara yang tersedia untuk server TTS yang dipilih. Silakan pilih server lain.",
diff --git a/webui/i18n/pt.json b/webui/i18n/pt.json
index c9c3d2c5..84f95227 100644
--- a/webui/i18n/pt.json
+++ b/webui/i18n/pt.json
@@ -184,9 +184,18 @@
"Upload Local Files": "Carregar arquivos locais",
"Please Upload Local Materials First": "Envie primeiro pelo menos um arquivo de mídia local.",
"Unsupported Upload File Type": "O tipo de arquivo enviado não é compatível.",
- "Play Voice": "Testar voz",
+ "Play Voice": "Amostra de voz",
"Voice Example": "Este é um exemplo de texto para testar a síntese de fala",
"Synthesizing Voice": "Sintetizando voz, por favor aguarde...",
+ "Generate Full Voiceover Preview": "Prévia completa",
+ "Estimated Voiceover Duration": "Duração estimada: {min}–{max} s (cálculo local, sem chamada de API)",
+ "Voiceover Script Required": "Adicione um roteiro para estimar e ouvir a narração completa.",
+ "Full Voiceover Preview Cost Hint": "A prévia completa chama o serviço TTS e pode consumir créditos da API.",
+ "Actual Voiceover Duration": "Duração real: {duration} s",
+ "Voice Preview Failed": "Falha na prévia da voz: {error}",
+ "Voice Preview No Audio": "O serviço TTS não retornou áudio. Verifique as configurações e os registros.",
+ "Voice Preview Busy": "Uma tarefa de vídeo está usando as configurações de voz. Tente novamente em instantes.",
+ "Voice Preview Duration Unavailable": "O áudio foi gerado, mas não foi possível ler sua duração. Verifique os registros.",
"TTS Provider": "Selecione o provedor de síntese de voz",
"TTS Servers": "Servidores TTS",
"No voices available for the selected TTS server. Please select another server.": "Não há vozes disponíveis para o servidor TTS selecionado. Por favor, selecione outro servidor.",
diff --git a/webui/i18n/ru.json b/webui/i18n/ru.json
index 3af4470b..24282ae2 100644
--- a/webui/i18n/ru.json
+++ b/webui/i18n/ru.json
@@ -180,9 +180,18 @@
"Upload Local Files": "Загрузите локальные файлы",
"Please Upload Local Materials First": "Сначала загрузите хотя бы один локальный медиафайл.",
"Unsupported Upload File Type": "Тип загруженного файла не поддерживается.",
- "Play Voice": "Прослушать",
+ "Play Voice": "Пример голоса",
"Voice Example": "Пример текста для проверки озвучки",
"Synthesizing Voice": "Генерируется голос, подождите...",
+ "Generate Full Voiceover Preview": "Вся озвучка",
+ "Estimated Voiceover Duration": "Примерная длительность: {min}–{max} сек. (локально, без API)",
+ "Voiceover Script Required": "Добавьте сценарий, чтобы оценить и прослушать полную озвучку.",
+ "Full Voiceover Preview Cost Hint": "Полная проверка вызывает TTS и может расходовать API-кредиты.",
+ "Actual Voiceover Duration": "Фактическая длительность: {duration} сек.",
+ "Voice Preview Failed": "Не удалось создать озвучку: {error}",
+ "Voice Preview No Audio": "Сервис TTS не вернул аудио. Проверьте настройки и журналы приложения.",
+ "Voice Preview Busy": "Настройки озвучки сейчас используются видеозадачей. Повторите попытку позже.",
+ "Voice Preview Duration Unavailable": "Аудио создано, но его длительность не удалось определить. Проверьте журналы приложения.",
"TTS Provider": "Провайдер синтеза речи",
"TTS Servers": "Сервис озвучки",
"No voices available for the selected TTS server. Please select another server.": "В выбранном сервисе озвучки нет доступных голосов. Выберите другой сервис.",
diff --git a/webui/i18n/tr.json b/webui/i18n/tr.json
index 12e5d9c6..562c8d03 100644
--- a/webui/i18n/tr.json
+++ b/webui/i18n/tr.json
@@ -182,9 +182,18 @@
"Upload Local Files": "Yerel Dosyaları Yükle",
"Please Upload Local Materials First": "Önce en az bir yerel medya dosyası yükleyin.",
"Unsupported Upload File Type": "Yüklenen dosya türü desteklenmiyor.",
- "Play Voice": "Sesi Önizle",
+ "Play Voice": "Ses Örneği",
"Voice Example": "Bu, konuşma sentezini test etmek için örnek bir metindir",
"Synthesizing Voice": "Ses sentezleniyor, lütfen bekleyin...",
+ "Generate Full Voiceover Preview": "Tam Önizleme",
+ "Estimated Voiceover Duration": "Tahmini tam süre: {min}–{max} sn (yerel, API çağrısı yok)",
+ "Voiceover Script Required": "Tam seslendirmeyi tahmin etmek ve dinlemek için video senaryosu ekleyin.",
+ "Full Voiceover Preview Cost Hint": "Tam önizleme TTS hizmetini çağırır ve API kredisi kullanabilir.",
+ "Actual Voiceover Duration": "Gerçek süre: {duration} sn",
+ "Voice Preview Failed": "Ses önizlemesi başarısız: {error}",
+ "Voice Preview No Audio": "TTS hizmeti ses döndürmedi. Ayarları ve uygulama günlüklerini kontrol edin.",
+ "Voice Preview Busy": "Bir video görevi ses ayarlarını kullanıyor. Kısa süre sonra tekrar deneyin.",
+ "Voice Preview Duration Unavailable": "Önizleme sesi oluşturuldu ancak süresi okunamadı. Uygulama günlüklerini kontrol edin.",
"TTS Provider": "Ses sentezi sağlayıcısını seçin",
"TTS Servers": "TTS Sunucuları",
"No voices available for the selected TTS server. Please select another server.": "Seçilen TTS sunucusu için uygun ses bulunamadı. Lütfen başka bir sunucu seçin.",
diff --git a/webui/i18n/vi.json b/webui/i18n/vi.json
index b0c14f54..d6096c22 100644
--- a/webui/i18n/vi.json
+++ b/webui/i18n/vi.json
@@ -184,9 +184,18 @@
"Upload Local Files": "Tải tệp cục bộ lên",
"Please Upload Local Materials First": "Vui lòng tải lên ít nhất một tệp tư liệu cục bộ trước.",
"Unsupported Upload File Type": "Loại tệp đã tải lên không được hỗ trợ.",
- "Play Voice": "Nghe Thử",
+ "Play Voice": "Mẫu Giọng",
"Voice Example": "Đây là văn bản mẫu để kiểm tra tổng hợp giọng nói",
"Synthesizing Voice": "Đang tổng hợp giọng nói, vui lòng đợi...",
+ "Generate Full Voiceover Preview": "Nghe Toàn Bộ",
+ "Estimated Voiceover Duration": "Thời lượng ước tính: {min}–{max} giây (tính cục bộ, không gọi API)",
+ "Voiceover Script Required": "Thêm kịch bản để ước tính và nghe toàn bộ lời thoại.",
+ "Full Voiceover Preview Cost Hint": "Bản nghe đầy đủ gọi dịch vụ TTS và có thể dùng tín dụng API.",
+ "Actual Voiceover Duration": "Thời lượng thực tế: {duration} giây",
+ "Voice Preview Failed": "Không thể tạo bản nghe thử: {error}",
+ "Voice Preview No Audio": "Dịch vụ TTS không trả về âm thanh. Hãy kiểm tra cài đặt và nhật ký ứng dụng.",
+ "Voice Preview Busy": "Một tác vụ video đang dùng cài đặt giọng nói. Hãy thử lại sau.",
+ "Voice Preview Duration Unavailable": "Âm thanh đã được tạo nhưng không đọc được thời lượng. Hãy kiểm tra nhật ký ứng dụng.",
"TTS Provider": "Chọn nhà cung cấp tổng hợp giọng nói",
"TTS Servers": "Máy chủ TTS",
"No voices available for the selected TTS server. Please select another server.": "Không có giọng nói nào cho máy chủ TTS đã chọn. Vui lòng chọn máy chủ khác.",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index 112c64c5..11a876ee 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -184,9 +184,18 @@
"Upload Local Files": "上传本地文件",
"Please Upload Local Materials First": "请先上传至少一个本地素材文件。",
"Unsupported Upload File Type": "上传的文件类型不受支持。",
- "Play Voice": "试听配音",
+ "Play Voice": "试听音色",
"Voice Example": "这是一段测试语音合成的示例文本",
"Synthesizing Voice": "语音合成中,请稍候...",
+ "Generate Full Voiceover Preview": "完整试听",
+ "Estimated Voiceover Duration": "预计完整配音时长:约 {min}–{max} 秒(本地估算,不调用 API)",
+ "Voiceover Script Required": "填写视频文案后,可估算并预览完整配音。",
+ "Full Voiceover Preview Cost Hint": "完整预览会调用当前配音服务,并可能消耗 API 额度。",
+ "Actual Voiceover Duration": "实际配音时长:{duration} 秒",
+ "Voice Preview Failed": "配音预览失败:{error}",
+ "Voice Preview No Audio": "配音服务未返回试听音频,请检查相关设置和应用日志。",
+ "Voice Preview Busy": "当前有视频任务正在使用配音配置,请稍后重试。",
+ "Voice Preview Duration Unavailable": "试听音频已生成,但无法读取准确时长,请检查应用日志。",
"TTS Provider": "语音合成提供商",
"TTS Servers": "TTS服务器",
"No voices available for the selected TTS server. Please select another server.": "当前选择的TTS服务器没有可用的声音,请选择其他服务器。",