Skip to content

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

Keep Fish Audio narration intact on invalid provider responses

Rudy Celekli414abd4c724d
diff --git a/app/services/voice.py b/app/services/voice.py
index 046bee0f..b5253755 100644
--- a/app/services/voice.py
+++ b/app/services/voice.py
@@ -2527,6 +2527,8 @@ def fish_audio_tts(
payload["reference_id"] = reference_id
for i in range(3):
+ temporary_audio = None
+ received_success = False
try:
logger.info(
f"start fish audio tts, model: {model_name}, "
@@ -2559,24 +2561,33 @@ def fish_audio_tts(
f"{response.status_code}: {response.text[:200]}"
)
continue
+ received_success = True
# Validate response contains audio data
if not response.content or len(response.content) < 100:
logger.error(
"Fish Audio TTS returned empty or invalid audio data"
)
- continue
+ return None
- with open(voice_file, "wb") as f:
+ with tempfile.NamedTemporaryFile(
+ dir=os.path.dirname(os.path.abspath(voice_file)),
+ suffix=".mp3",
+ delete=False,
+ ) as f:
+ temporary_audio = f.name
f.write(response.content)
- audio_clip = AudioFileClip(voice_file)
+ audio_clip = AudioFileClip(temporary_audio)
try:
audio_duration = audio_clip.duration
finally:
audio_clip.close()
+ if not math.isfinite(audio_duration) or audio_duration <= 0:
+ raise ValueError("Fish Audio returned an invalid audio duration")
sub_maker = ensure_legacy_submaker_fields(SubMaker())
+ os.replace(temporary_audio, voice_file)
logger.success(f"fish audio tts succeeded: {voice_file}")
return populate_legacy_submaker_with_full_text(
sub_maker=sub_maker,
@@ -2593,6 +2604,17 @@ def fish_audio_tts(
return None
except Exception as e:
logger.error(f"fish audio tts failed: {str(e)}")
+ if received_success:
+ # A successful provider response may already have been billed.
+ return None
+ 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 Fish Audio file: {cleanup_error}"
+ )
return None
diff --git a/test/services/test_fish_audio.py b/test/services/test_fish_audio.py
index 56496c5b..414489fc 100644
--- a/test/services/test_fish_audio.py
+++ b/test/services/test_fish_audio.py
@@ -255,6 +255,46 @@ class TestFishAudioErrorHandling(unittest.TestCase):
result = vs.fish_audio_tts("Test.", voice_file)
self.assertIsNone(result)
+ def test_invalid_success_preserves_existing_audio_without_repeat_charge(self):
+ response = _FakeResponse(content=b"invalid audio" * 20)
+ with (
+ tempfile.TemporaryDirectory() as tmp_dir,
+ patch.object(vs.config, "fish_audio", {"api_key": "test-key"}),
+ patch.object(vs.requests, "post", return_value=response) as post,
+ patch.object(vs, "AudioFileClip", side_effect=OSError("bad mp3")),
+ ):
+ voice_file = Path(tmp_dir) / "fish.mp3"
+ voice_file.write_bytes(b"previous valid audio")
+ result = vs.fish_audio_tts("Test.", str(voice_file))
+
+ self.assertIsNone(result)
+ self.assertEqual(voice_file.read_bytes(), b"previous valid audio")
+ self.assertEqual(list(Path(tmp_dir).iterdir()), [voice_file])
+ post.assert_called_once()
+
+ def test_valid_audio_replaces_existing_file_after_decoding(self):
+ response = _FakeResponse(content=b"new mp3" * 30)
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ voice_file = Path(tmp_dir) / "fish.mp3"
+ voice_file.write_bytes(b"previous valid audio")
+
+ def validate(candidate):
+ self.assertNotEqual(Path(candidate), voice_file)
+ self.assertEqual(voice_file.read_bytes(), b"previous valid audio")
+ self.assertEqual(Path(candidate).read_bytes(), response.content)
+ return _FakeClip()
+
+ with (
+ patch.object(vs.config, "fish_audio", {"api_key": "test-key"}),
+ patch.object(vs.requests, "post", return_value=response),
+ patch.object(vs, "AudioFileClip", side_effect=validate),
+ ):
+ result = vs.fish_audio_tts("Test.", str(voice_file))
+
+ self.assertIsNotNone(result)
+ self.assertEqual(voice_file.read_bytes(), response.content)
+ self.assertEqual(list(Path(tmp_dir).iterdir()), [voice_file])
+
def test_missing_api_key_returns_none(self):
with patch.object(vs.config, "fish_audio", {"api_key": ""}), \
patch.dict(os.environ, {"FISH_API_KEY": ""}, clear=False):