Skip to content

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

fix(tts): address VoxCPM review feedback

lottshinefc86c7071fe
diff --git a/app/services/voice.py b/app/services/voice.py
index c317f732..95770747 100644
--- a/app/services/voice.py
+++ b/app/services/voice.py
@@ -77,6 +77,8 @@ GEMINI_TTS_VOICES = (
_MINIMAX_TTS_MAX_AUDIO_HEX_CHARS = 100 * 1024 * 1024
VOXCPM_DEFAULT_BASE_URL = "https://api.modelbest.cn/v1"
VOXCPM_DEFAULT_VOICE = "default"
+_VOXCPM_NON_RETRYABLE_STATUS_CODES = {400, 401, 403, 404, 422}
+_VOXCPM_RETRY_DELAY_SECONDS = (1.0, 2.0)
NO_VOICE_NAME = "no-voice"
# `none` 是 PR #981 里曾使用过的无配音标识。这里短期兼容这个值,避免
# 已经手动调用过该分支的 API 用户升级后立即失效;WebUI 和新代码统一使用
@@ -2525,6 +2527,10 @@ def voxcpm_tts(
f"VoxCPM TTS failed with status {response.status_code}: "
f"{response.text[:200]}"
)
+ if response.status_code in _VOXCPM_NON_RETRYABLE_STATUS_CODES:
+ return None
+ if attempt < 2:
+ time.sleep(_VOXCPM_RETRY_DELAY_SECONDS[attempt])
continue
audio_chunks = []
@@ -2579,8 +2585,15 @@ def voxcpm_tts(
text=text,
audio_duration_seconds=audio_duration,
)
+ except requests.RequestException as exc:
+ logger.error(f"VoxCPM TTS request failed: {exc}")
+ if attempt < 2:
+ time.sleep(_VOXCPM_RETRY_DELAY_SECONDS[attempt])
except Exception as exc:
+ # Invalid SSE/WAV data and local conversion failures are deterministic;
+ # retrying the same response cannot repair them.
logger.error(f"VoxCPM TTS failed: {exc}")
+ return None
finally:
close_response = getattr(response, "close", None)
if callable(close_response):
diff --git a/test/services/test_voxcpm.py b/test/services/test_voxcpm.py
index 7c66d0d9..acf26ea1 100644
--- a/test/services/test_voxcpm.py
+++ b/test/services/test_voxcpm.py
@@ -138,7 +138,7 @@ def test_voxcpm_tts_failure_never_overwrites_existing_audio(
assert voice.voxcpm_tts("Hello", "default", str(output)) is None
assert output.read_bytes() == b"previous-audio"
- assert post.call_count == 3
+ assert post.call_count == 1
def test_voxcpm_requires_key_and_model_without_making_requests(monkeypatch, tmp_path):
@@ -162,9 +162,35 @@ def test_voxcpm_http_error_is_retried_and_preserves_output(
)
post = Mock(return_value=response)
monkeypatch.setattr(voice.requests, "post", post)
+ sleep = Mock()
+ monkeypatch.setattr(voice.time, "sleep", sleep)
output = tmp_path / "existing.mp3"
output.write_bytes(b"previous-audio")
assert voice.voxcpm_tts("Hello", "default", str(output)) is None
assert output.read_bytes() == b"previous-audio"
assert post.call_count == 3
+ assert sleep.call_args_list == [((1.0,),), ((2.0,),)]
+
+
[email protected]("status_code", [400, 401, 403, 404, 422])
+def test_voxcpm_auth_and_invalid_parameter_errors_fail_without_retry(
+ monkeypatch, tmp_path, voxcpm_config, status_code
+):
+ response = SimpleNamespace(
+ status_code=status_code,
+ text="invalid request",
+ close=lambda: None,
+ )
+ post = Mock(return_value=response)
+ monkeypatch.setattr(voice.requests, "post", post)
+ sleep = Mock()
+ monkeypatch.setattr(voice.time, "sleep", sleep)
+
+ output = tmp_path / "existing.mp3"
+ output.write_bytes(b"previous-audio")
+
+ assert voice.voxcpm_tts("Hello", "default", str(output)) is None
+ assert output.read_bytes() == b"previous-audio"
+ post.assert_called_once()
+ sleep.assert_not_called()
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index b7cf2c06..08c2c236 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -87,6 +87,7 @@ ENGLISH_FALLBACK_KEYS = frozenset(
"Stop Tracking LoomLoom Run",
"Stop Tracking LoomLoom Run Help",
"Unavailable AI Video Model",
+ "VoxCPM Speed Not Supported",
}
)
FORMAT_PLACEHOLDER_PATTERN = re.compile(r"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})")
diff --git a/test/services/test_webui_tts_settings.py b/test/services/test_webui_tts_settings.py
index 76239b64..3cd51fdd 100644
--- a/test/services/test_webui_tts_settings.py
+++ b/test/services/test_webui_tts_settings.py
@@ -132,6 +132,34 @@ def test_voxcpm_settings_render_model_and_endpoint_fields():
_widget_by_key(app.text_input, "voxcpm_base_url_input").value
== voice.VOXCPM_DEFAULT_BASE_URL
)
+ speed_input = _widget_by_key(app.selectbox, "voice_rate_select")
+ assert speed_input.disabled
+ assert "does not support numeric speed" in speed_input.help
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_voxcpm_reconnect_restores_saved_key_instead_of_clearing_it():
+ """Streamlit 重连重放空密码状态时,VoxCPM Key 仍应保留。"""
+ test_config = dict(config.voxcpm, api_key="saved-voxcpm-key")
+ test_ui = dict(
+ config.ui,
+ voice_mode="tts",
+ tts_server="voxcpm",
+ voice_name="voxcpm:default",
+ )
+
+ with (
+ patch.object(config, "voxcpm", test_config),
+ patch.object(config, "ui", test_ui),
+ patch.object(config, "try_save_config", return_value=True),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "en"
+ app.session_state["voxcpm_api_key_input"] = ""
+ app.run()
+
+ assert test_config["api_key"] == "saved-voxcpm-key"
+ assert app.session_state["voxcpm_api_key_input"] == "saved-voxcpm-key"
assert [str(item.value) for item in app.exception] == []
diff --git a/webui/Main.py b/webui/Main.py
index fb677e49..232e4a12 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -5968,6 +5968,26 @@ def _sync_elevenlabs_api_key_input():
return entered_key
+def _sync_voxcpm_api_key_input():
+ """恢复 VoxCPM 密码控件在重连时被 Streamlit 重放的空状态。"""
+ widget_key = "voxcpm_api_key_input"
+ configured_key = str(config.voxcpm.get("api_key", "") or "").strip()
+ had_widget_state = widget_key in st.session_state
+ entered_key = str(st.session_state.get(widget_key, "") or "").strip()
+
+ if not entered_key and configured_key:
+ # 浏览器重连可能重放空密码状态。保留已保存凭据,避免本次 rerun
+ # 通过 _set_runtime_config 把 config.toml 中的有效 Key 覆盖为空。
+ st.session_state[widget_key] = configured_key
+ entered_key = configured_key
+ if had_widget_state:
+ logger.debug("restored VoxCPM API key after empty session replay")
+ elif not had_widget_state:
+ st.session_state[widget_key] = entered_key
+
+ return entered_key
+
+
def _render_elevenlabs_api_key_input(label_key):
"""
渲染 ElevenLabs TTS 与配乐共用的唯一 API Key 输入状态。
@@ -6683,9 +6703,9 @@ def _render_audio_settings(panel, params):
selected_tts_server == "voxcpm"
or (voice_name and voice.is_voxcpm_voice(voice_name))
):
+ _sync_voxcpm_api_key_input()
voxcpm_api_key = st.text_input(
tr("VoxCPM API Key"),
- value=config.voxcpm.get("api_key", ""),
type="password",
key="voxcpm_api_key_input",
)
@@ -6843,6 +6863,10 @@ def _render_audio_settings(panel, params):
)
with voice_control_cols[1]:
+ is_voxcpm = bool(
+ selected_tts_server == "voxcpm"
+ or (voice_name and voice.is_voxcpm_voice(voice_name))
+ )
params.voice_rate = stable_selectbox(
tr("Voiceover Speed"),
options=voice_rate_options,
@@ -6851,7 +6875,12 @@ def _render_audio_settings(panel, params):
),
key="voice_rate_select",
format_func=lambda value: f"{value:.1f}×",
- help=tr("Voiceover Speed Help"),
+ help=(
+ tr("VoxCPM Speed Not Supported")
+ if is_voxcpm
+ else tr("Voiceover Speed Help")
+ ),
+ disabled=is_voxcpm,
)
_set_runtime_config("ui", "voice_volume", params.voice_volume)
_set_runtime_config("ui", "voice_rate", params.voice_rate)
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index b47fbdfe..bf7cd248 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -125,6 +125,7 @@
"Voiceover Volume Help": "Adjusts automatic or uploaded voiceover volume. 100% keeps the original level.",
"Voiceover Speed": "Voiceover Speed",
"Voiceover Speed Help": "Applies only to automatic voiceover. 1.0× is the normal speed.",
+ "VoxCPM Speed Not Supported": "VoxCPM does not support numeric speed adjustment.",
"Upload Voiceover File": "Upload Voiceover File",
"Upload Voiceover File Help": "The uploaded audio is used directly instead of generating a voiceover.",
"Please Upload Voiceover File First": "Please upload a voiceover file first",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index 7f4794ec..05063758 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -125,6 +125,7 @@
"Voiceover Volume Help": "调整自动配音或上传音频的音量,100% 为原始音量。",
"Voiceover Speed": "配音语速",
"Voiceover Speed Help": "仅对自动配音生效,1.0× 为正常语速。",
+ "VoxCPM Speed Not Supported": "VoxCPM 暂不支持数值语速调节。",
"Upload Voiceover File": "上传配音文件",
"Upload Voiceover File Help": "上传后直接使用该音频,不再生成自动配音。",
"Please Upload Voiceover File First": "请先上传配音文件",