利用 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): preserve MiMo narration through export failures
RudyCelekli1a692cac02a9
diff --git a/app/services/voice.py b/app/services/voice.pyindex a8e25d2a..45aaeab9 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -1965,6 +1965,7 @@ def mimo_tts(_configure_pydub_ffmpeg(AudioSegment)+ temporary_audio = Nonetry:logger.info(f"start mimo tts, model: {model_name}, voice: {voice_name}"@@ -2006,26 +2007,44 @@ def mimo_tts(audio_segment = AudioSegment.from_file(io.BytesIO(audio_bytes), format="wav")output_format = utils.parse_extension(voice_file) or "mp3"+ descriptor, temporary_audio = tempfile.mkstemp(+ prefix=".mimo-tts-", suffix=f".{output_format}",+ dir=os.path.dirname(os.path.abspath(voice_file)),+ )+ os.close(descriptor)if output_format == "wav":- with open(voice_file, "wb") as f:+ with open(temporary_audio, "wb") as f:f.write(audio_bytes)else:- audio_segment.export(voice_file, format=output_format)+ exported_audio = audio_segment.export(temporary_audio, format=output_format)+ if exported_audio is not None:+ exported_audio.close()audio_duration = len(audio_segment) / 1000.0+ if audio_duration <= 0:+ raise ValueError("MiMo TTS returned empty audio")sub_maker = ensure_legacy_submaker_fields(SubMaker())+ populated_sub_maker = populate_legacy_submaker_with_full_text(+ sub_maker=sub_maker,+ text=text,+ audio_duration_seconds=audio_duration,+ )+ os.replace(temporary_audio, voice_file)+ temporary_audio = Nonelogger.success(f"mimo tts succeeded: {voice_file}")logger.debug("mimo subtitle timeline generated, "f"duration: {audio_duration:.3f}s, output_format: {output_format}")- return populate_legacy_submaker_with_full_text(- sub_maker=sub_maker,- text=text,- audio_duration_seconds=audio_duration,- )+ return populated_sub_makerexcept Exception as e:logger.error(f"mimo tts failed: {str(e)}")+ finally:+ if temporary_audio and os.path.exists(temporary_audio):+ try:+ os.remove(temporary_audio)+ except OSError as cleanup_error:+ logger.warning(f"failed to remove temporary MiMo audio: {cleanup_error}")return Nonediff --git a/test/services/test_media_mimo_publication.py b/test/services/test_media_mimo_publication.pynew file mode 100644index 00000000..52e0104c--- /dev/null+++ b/test/services/test_media_mimo_publication.py@@ -0,0 +1,94 @@+import base64+import io+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock+import wave++from pydub import AudioSegment+import pytest++from app.services import voice+++def mock_provider(monkeypatch):+ buffer = io.BytesIO()+ with wave.open(buffer, "wb") as wav:+ wav.setnchannels(1)+ wav.setsampwidth(2)+ wav.setframerate(8000)+ wav.writeframes(b"\x01\x00" * 1600)+ completion = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(+ audio={"data": base64.b64encode(buffer.getvalue()).decode("ascii")}+ ))])+ client = MagicMock()+ client.__enter__.return_value = client+ client.chat.completions.create.return_value = completion+ monkeypatch.setattr(voice, "OpenAI", lambda **kwargs: client)+ monkeypatch.setitem(voice.config.app, "mimo_api_key", "test-local-key")+ return client++[email protected]("previous", [None, b"previous complete narration"])+def test_mimo_export_failure_preserves_destination(tmp_path, monkeypatch, previous):+ client = mock_provider(monkeypatch)+ output = tmp_path / "voice.mp3"+ if previous is not None:+ output.write_bytes(previous)++ def failed_export(self, filename, **kwargs):+ Path(filename).write_bytes(b"partial mp3")+ raise OSError("encoder failed")++ monkeypatch.setattr(AudioSegment, "export", failed_export)+ assert voice.mimo_tts("Hello world.", "mimo_default", 1.0, str(output)) is None+ if previous is None:+ assert not output.exists()+ else:+ assert output.read_bytes() == previous+ assert sorted(p.name for p in tmp_path.iterdir()) == ([output.name] if previous is not None else [])+ client.chat.completions.create.assert_called_once()+++def test_mimo_success_closes_real_export_before_publication(tmp_path, monkeypatch):+ client = mock_provider(monkeypatch)+ output = tmp_path / "voice.mp3"+ handles = []+ original = AudioSegment.export++ def export(self, *args, **kwargs):+ handle = original(self, *args, **kwargs)+ handles.append(handle)+ return handle++ monkeypatch.setattr(AudioSegment, "export", export)+ maker = voice.mimo_tts("Hello world.", "mimo_default", 1.0, str(output))+ assert maker is not None+ assert len(handles) == 1 and handles[0].closed+ assert voice.get_audio_duration(str(output)) > 0+ assert voice.get_audio_duration(maker) == pytest.approx(0.2)+ assert list(tmp_path.iterdir()) == [output]+ client.chat.completions.create.assert_called_once()+++def test_mimo_cleanup_failure_keeps_failed_publication_contract(tmp_path, monkeypatch):+ client = mock_provider(monkeypatch)+ output = tmp_path / "voice.mp3"+ output.write_bytes(b"previous complete narration")+ successes = []++ def cannot_publish(*args):+ raise OSError("destination unavailable")++ def cannot_cleanup(*args):+ raise PermissionError("temporary audio is busy")++ monkeypatch.setattr(voice.os, "replace", cannot_publish)+ monkeypatch.setattr(voice.os, "remove", cannot_cleanup)+ monkeypatch.setattr(voice.logger, "success", successes.append)+ assert voice.mimo_tts("Hello world.", "mimo_default", 1.0, str(output)) is None+ assert output.read_bytes() == b"previous complete narration"+ assert successes == []+ staged = [path for path in tmp_path.iterdir() if path != output]+ assert len(staged) == 1 and staged[0].name.startswith(".mimo-tts-")+ client.chat.completions.create.assert_called_once()