Skip to content

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

fix(tts): handle invalid voice rate values

harry0703267e441cbc55
diff --git a/app/services/voice.py b/app/services/voice.py
index 1d8072f0..5bcb3431 100644
--- a/app/services/voice.py
+++ b/app/services/voice.py
@@ -446,6 +446,15 @@ def convert_rate_to_percent(rate: float) -> str:
# Rounding can yield 0 for rates near but not equal to 1.0 (e.g. 1.004,
# 0.997); those must still be returned as "+0%", not the unsigned "0%"
# which edge-tts rejects with ValueError: Invalid rate '0%'.
+ # API 或批处理调用可能传入 0、0.0、None 或无法转换的空值;这些值不代表
+ # 合法语速,直接计算会变成 -100% 或抛异常。这里统一回退到正常语速,
+ # 避免生成极慢音频或让 TTS 流程在边界输入下失败。
+ try:
+ rate = float(rate)
+ except (TypeError, ValueError):
+ rate = 1.0
+ if rate <= 0:
+ rate = 1.0
percent = round((rate - 1.0) * 100)
if percent >= 0:
return f"+{percent}%"
diff --git a/test/services/test_voice.py b/test/services/test_voice.py
index 57128114..70a2229f 100644
--- a/test/services/test_voice.py
+++ b/test/services/test_voice.py
@@ -854,6 +854,14 @@ class TestVoiceService(unittest.TestCase):
self.assertEqual(vs.convert_rate_to_percent(1.5), "+50%")
self.assertEqual(vs.convert_rate_to_percent(0.8), "-20%")
+ def test_convert_rate_to_percent_invalid_values_default_to_normal(self):
+ # API 和批处理脚本可能把空语速传成 0、None 或空字符串;这些都不应让
+ # edge-tts 收到 -100% 或触发异常,而是按正常语速处理。
+ self.assertEqual(vs.convert_rate_to_percent(0), "+0%")
+ self.assertEqual(vs.convert_rate_to_percent(0.0), "+0%")
+ self.assertEqual(vs.convert_rate_to_percent(None), "+0%")
+ self.assertEqual(vs.convert_rate_to_percent(""), "+0%")
+
class TestElevenLabsVoice(unittest.TestCase):