利用 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 existing narration when Edge TTS streams fail
Rudy Celekli96d8c889b61f
diff --git a/app/services/voice.py b/app/services/voice.pyindex 30e171ce..78744e70 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -1393,6 +1393,7 @@ def azure_tts_v1(text = text.strip()rate_str = convert_rate_to_percent(voice_rate)for i in range(3):+ temp_path = Nonetry:logger.info(f"start, voice name: {voice_name}, try: {i + 1}")@@ -1404,7 +1405,12 @@ def azure_tts_v1(sub_maker = edge_tts.SubMaker()timeout_seconds = get_edge_tts_timeout_seconds()- with open(voice_file, "wb") as file:+ descriptor, temp_path = tempfile.mkstemp(+ prefix=".edge-tts-",+ suffix=os.path.splitext(voice_file)[1] or ".mp3",+ dir=os.path.dirname(os.path.abspath(voice_file)),+ )+ with os.fdopen(descriptor, "wb") as file:def _handle_chunk(chunk):chunk_type = chunk["type"]if chunk_type == "audio":@@ -1421,29 +1427,30 @@ def azure_tts_v1(# Edge can finish a stream with timing events but no audio payload.# Those events produce a nonempty SRT, yet the MP3 is unplayable.- if os.path.getsize(voice_file) == 0:+ if os.path.getsize(temp_path) == 0:logger.warning("failed, edge tts stream contained no audio")- os.remove(voice_file)continueif not sub_maker.get_srt():logger.warning("failed, sub_maker.get_srt() is empty")continue+ # Audio and its timing belong to this same completed attempt.+ # Failed retries must not replace previously successful narration.+ os.replace(temp_path, voice_file)+ temp_path = Nonelogger.info(f"completed, output file: {voice_file}")return sub_makerexcept Exception as e:logger.error(f"failed, error: {str(e)}")- # TTS 流式写入如果在首包前超时或网络异常,会留下 0 字节音频文件。- # 这种文件既不可播放,也可能误导后续排查,因此失败后只清理空文件;- # 如果已经写入了部分数据,则保留现场文件,便于分析服务端返回内容。- if os.path.exists(voice_file) and os.path.getsize(voice_file) == 0:+ finally:+ if temp_path is not None:try:- os.remove(voice_file)- except Exception as remove_error:+ os.remove(temp_path)+ except OSError as remove_error:logger.warning(- "failed to remove empty tts file: "- f"{voice_file}, error: {str(remove_error)}"+ "failed to remove temporary Edge TTS audio: "+ f"{temp_path}, error: {remove_error}")return Nonediff --git a/test/services/test_edge_atomic_audio.py b/test/services/test_edge_atomic_audio.pynew file mode 100644index 00000000..1b1f63df--- /dev/null+++ b/test/services/test_edge_atomic_audio.py@@ -0,0 +1,47 @@+import tempfile+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from app.services import voice++[email protected]("failure", ["no-audio", "no-timing", "interrupted"])+def test_edge_failure_preserves_previous_narration_and_cleans_staging(failure):+ def stream(_communicate, on_chunk, **_kwargs):+ if failure != "no-audio":+ on_chunk({"type": "audio", "data": b"partial-new-audio"})+ if failure == "interrupted":+ raise TimeoutError("lost stream")++ submaker = SimpleNamespace(get_srt=lambda: "" if failure == "no-timing" else "timing")+ with (+ tempfile.TemporaryDirectory() as temp_dir,+ patch.object(voice, "create_edge_tts_communicate"),+ patch.object(voice.edge_tts, "SubMaker", return_value=submaker),+ patch.object(voice, "stream_edge_tts_chunks", side_effect=stream),+ ):+ target = Path(temp_dir) / "voice.mp3"+ target.write_bytes(b"previous-good-audio")+ assert voice.azure_tts_v1("Hello", "en-US-AriaNeural-Female", 1.0, str(target)) is None+ assert target.read_bytes() == b"previous-good-audio"+ assert sorted(item.name for item in Path(temp_dir).iterdir()) == ["voice.mp3"]+++def test_edge_success_replaces_narration_with_matching_submaker():+ submaker = SimpleNamespace(get_srt=lambda: "matching-new-timing")+ def stream(_communicate, on_chunk, **_kwargs):+ on_chunk({"type": "audio", "data": b"complete-new-audio"})+ with (+ tempfile.TemporaryDirectory() as temp_dir,+ patch.object(voice, "create_edge_tts_communicate"),+ patch.object(voice.edge_tts, "SubMaker", return_value=submaker),+ patch.object(voice, "stream_edge_tts_chunks", side_effect=stream),+ ):+ target = Path(temp_dir) / "voice.mp3"+ target.write_bytes(b"previous-good-audio")+ assert voice.azure_tts_v1("Hello", "en-US-AriaNeural-Female", 1.0, str(target)) is submaker+ assert target.read_bytes() == b"complete-new-audio"+ assert sorted(item.name for item in Path(temp_dir).iterdir()) == ["voice.mp3"]