利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
Preserve narration when SiliconFlow returns invalid audio
Rudy Celekli783b35975578
diff --git a/app/services/voice.py b/app/services/voice.pyindex 8dd04c52..046bee0f 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -1442,6 +1442,7 @@ def siliconflow_tts(headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}for i in range(3): # 尝试3次+ temporary_audio = Nonetry:logger.info(f"start siliconflow tts, model: {model}, voice: {voice}, try: {i + 1}"@@ -1458,14 +1459,22 @@ def siliconflow_tts(if not response.content:logger.error("siliconflow tts returned empty audio")return None- # 保存音频文件- with open(voice_file, "wb") as f:+ # Decode a temporary file before publishing it. A 200 response+ # may contain invalid audio, and must not destroy a previous+ # successful narration at the same path.+ ensure_file_path_exists(voice_file)+ with tempfile.NamedTemporaryFile(+ dir=os.path.dirname(os.path.abspath(voice_file)),+ suffix=".mp3",+ delete=False,+ ) as f:+ temporary_audio = f.namef.write(response.content)sub_maker = ensure_legacy_submaker_fields(SubMaker())try:- audio_clip = AudioFileClip(voice_file)+ audio_clip = AudioFileClip(temporary_audio)try:audio_duration = audio_clip.durationfinally:@@ -1481,14 +1490,9 @@ def siliconflow_tts(# narration. Returning a fabricated duration lets an invalid# file advance into the costly video pipeline.logger.error(f"siliconflow tts returned invalid audio: {e}")- try:- os.remove(voice_file)- except OSError as cleanup_error:- logger.warning(- f"failed to remove invalid siliconflow audio: {cleanup_error}"- )return None+ os.replace(temporary_audio, voice_file)logger.success(f"siliconflow tts succeeded: {voice_file}")return populate_legacy_submaker_with_full_text(sub_maker=sub_maker,@@ -1511,6 +1515,14 @@ def siliconflow_tts(return Noneexcept Exception as e:logger.error(f"siliconflow tts failed: {str(e)}")+ finally:+ if temporary_audio and os.path.exists(temporary_audio):+ try:+ os.unlink(temporary_audio)+ except OSError as cleanup_error:+ logger.warning(+ f"failed to remove temporary siliconflow audio: {cleanup_error}"+ )return Nonediff --git a/test/services/test_voice.py b/test/services/test_voice.pyindex 669754c0..6655b83d 100644--- a/test/services/test_voice.py+++ b/test/services/test_voice.py@@ -1725,6 +1725,57 @@ class TestElevenLabsVoice(unittest.TestCase):self.assertIsNone(result)post.assert_called_once()+ def test_siliconflow_tts_invalid_audio_preserves_existing_narration(self):+ fake_response = SimpleNamespace(status_code=200, content=b"invalid mp3")+ with (+ tempfile.TemporaryDirectory() as temp_dir,+ patch.object(vs.requests, "post", return_value=fake_response),+ patch.object(vs, "AudioFileClip", side_effect=OSError("invalid audio")),+ patch.object(vs.config, "siliconflow", {"api_key": "test-key"}),+ ):+ voice_file = Path(temp_dir) / "narration.mp3"+ voice_file.write_bytes(b"previous valid narration")+ result = vs.siliconflow_tts(+ text="An example narration",+ model="FunAudioLLM/CosyVoice2-0.5B",+ voice="FunAudioLLM/CosyVoice2-0.5B:alex",+ voice_rate=1.0,+ voice_file=str(voice_file),+ )++ self.assertIsNone(result)+ self.assertEqual(voice_file.read_bytes(), b"previous valid narration")+ self.assertEqual(list(Path(temp_dir).iterdir()), [voice_file])++ def test_siliconflow_tts_publishes_only_after_audio_validation(self):+ fake_response = SimpleNamespace(status_code=200, content=b"new mp3")+ with tempfile.TemporaryDirectory() as temp_dir:+ voice_file = Path(temp_dir) / "narration.mp3"+ voice_file.write_bytes(b"previous valid narration")++ def validate_audio(candidate):+ self.assertNotEqual(Path(candidate), voice_file)+ self.assertEqual(voice_file.read_bytes(), b"previous valid narration")+ self.assertEqual(Path(candidate).read_bytes(), b"new mp3")+ return SimpleNamespace(duration=2.5, close=lambda: None)++ with (+ patch.object(vs.requests, "post", return_value=fake_response),+ patch.object(vs, "AudioFileClip", side_effect=validate_audio),+ patch.object(vs.config, "siliconflow", {"api_key": "test-key"}),+ ):+ result = vs.siliconflow_tts(+ text="An example narration",+ model="FunAudioLLM/CosyVoice2-0.5B",+ voice="FunAudioLLM/CosyVoice2-0.5B:alex",+ voice_rate=1.0,+ voice_file=str(voice_file),+ )++ self.assertIsNotNone(result)+ self.assertEqual(voice_file.read_bytes(), b"new mp3")+ self.assertEqual(list(Path(temp_dir).iterdir()), [voice_file])+def test_pause_tag_detection_and_parsing(self):"""测试多语言停顿标签的检测、解析与清洗。"""sample_script = (