利用 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
fix(tts): stop MiniMax retries after accepted synthesis
Rudy Celeklie445e48d8a5d
diff --git a/app/services/voice.py b/app/services/voice.pyindex 40cc6a92..4d138237 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -2237,25 +2237,34 @@ def minimax_tts(text: str, voice_id: str, voice_rate: float, voice_file: str, vo}headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}for attempt in range(3):+ received_success = Falsetry:logger.info(f"start MiniMax TTS, model: {model}, voice: {voice_id}, try: {attempt + 1}")response = requests.post(url, json=payload, headers=headers, timeout=120)if response.status_code != 200:logger.error(f"MiniMax TTS failed with status {response.status_code}: {response.text[:200]}")continue+ received_success = Truebody = response.json()data = body.get("data") or {}base_resp = body.get("base_resp") or {}- if base_resp.get("status_code") != 0 or data.get("status") != 2:+ status_code = base_resp.get("status_code")+ if not isinstance(status_code, int) or isinstance(status_code, bool):+ logger.error("MiniMax returned an unknown acceptance status; stop paid retries")+ return None+ if status_code != 0:logger.error(f"MiniMax TTS returned an unsuccessful response: status_code={base_resp.get('status_code')}, audio_status={data.get('status')}")continue+ if data.get("status") != 2:+ logger.error("MiniMax accepted the request but returned incomplete audio")+ return Noneaudio_hex = data.get("audio")if not isinstance(audio_hex, str) or not audio_hex:logger.error("MiniMax TTS returned empty audio data")- continue+ return Noneif len(audio_hex) > _MINIMAX_TTS_MAX_AUDIO_HEX_CHARS:logger.error("MiniMax TTS returned audio data exceeding the supported size")- continue+ return Noneaudio_duration = _write_validated_minimax_audio(bytes.fromhex(audio_hex), voice_file)logger.success(f"MiniMax TTS succeeded: {voice_file}")return populate_legacy_submaker_with_full_text(@@ -2269,8 +2278,12 @@ def minimax_tts(text: str, voice_id: str, voice_rate: float, voice_file: str, vof"stop paid retries: {type(exc).__name__}")return None- except (OSError, ValueError) as exc:+ except (OSError, ValueError, TypeError, AttributeError) as exc:logger.error(f"MiniMax TTS failed: {str(exc)}")+ if received_success:+ # The request may already be billed, even if JSON/audio parsing+ # or local file publication failed. Never regenerate it here.+ return Nonereturn Nonediff --git a/test/services/test_minimax_success_retry.py b/test/services/test_minimax_success_retry.pynew file mode 100644index 00000000..7f8c585b--- /dev/null+++ b/test/services/test_minimax_success_retry.py@@ -0,0 +1,42 @@+import tempfile+import unittest+from pathlib import Path+from unittest.mock import Mock, patch+import requests+from app.services import voice+++class TestMinimaxAcceptedResponseRetry(unittest.TestCase):+ def test_successful_paid_response_is_never_resubmitted_for_invalid_audio(self):+ for audio, error in [("not-hex", None), ("01", ValueError("decode failed")), ("01", OSError("disk full")), ("", None)]:+ with self.subTest(audio=audio, error=error), tempfile.TemporaryDirectory() as tmp:+ response = Mock(status_code=200)+ response.json.return_value = {"base_resp": {"status_code": 0}, "data": {"status": 2, "audio": audio}}+ output = Path(tmp) / "narration.mp3"+ output.write_bytes(b"previous narration")+ with patch.dict(voice.config.minimax_tts, {"api_key": "test-key"}), patch.object(voice.requests, "post", return_value=response) as post, patch.object(voice, "_write_validated_minimax_audio", side_effect=error, return_value=1):+ result = voice.minimax_tts("Hello.", "voice-id", 1, str(output))+ self.assertIsNone(result)+ self.assertEqual(post.call_count, 1, "paid synthesis was resubmitted")+ self.assertEqual(output.read_bytes(), b"previous narration")++ def test_connect_timeout_before_acceptance_can_retry(self):+ response = Mock(status_code=200)+ response.json.return_value = {"base_resp": {"status_code": 0}, "data": {"status": 2, "audio": "01"}}+ with patch.dict(voice.config.minimax_tts, {"api_key": "test-key"}), patch.object(voice.requests, "post", side_effect=[requests.ConnectTimeout("not connected"), response]) as post, patch.object(voice, "_write_validated_minimax_audio", return_value=1):+ result = voice.minimax_tts("Hello.", "voice-id", 1, "unused.mp3")+ self.assertIsNotNone(result)+ self.assertEqual(post.call_count, 2)++ def test_unreadable_or_incomplete_success_body_is_not_resubmitted(self):+ for body in (None, [], {}, {"base_resp": {}}, {"data": {"status": 2, "audio": "01"}}, {"base_resp": {"status_code": 0}, "data": {"status": 1}}):+ with self.subTest(body=body):+ response = Mock(status_code=200)+ if body is None:+ response.json.side_effect = ValueError("invalid JSON")+ else:+ response.json.return_value = body+ with patch.dict(voice.config.minimax_tts, {"api_key": "test-key"}), patch.object(voice.requests, "post", return_value=response) as post:+ result = voice.minimax_tts("Hello.", "voice-id", 1, "unused.mp3")+ self.assertIsNone(result)+ post.assert_called_once()