利用 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: harden Windows portable update and Azure TTS compatibility
Harry400c1c3f35be
diff --git a/app/services/voice.py b/app/services/voice.pyindex 26ff8fcd..665b58b7 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -1,4 +1,5 @@import asyncio+import inspectimport mathimport osimport re@@ -1281,6 +1282,63 @@ def populate_legacy_submaker_with_full_text(return sub_maker+def create_edge_tts_communicate(+ text: str, voice_name: str, rate_str: str+) -> edge_tts.Communicate:+ """+ 按当前已安装的 edge_tts 版本构造 Communicate 对象。++ 背景:+ 1. 主线代码已经升级到 edge_tts 7.x,并使用 `boundary` 参数拿到更细的边界事件;+ 2. 但 Windows 便携包如果更新失败,现场环境可能仍然停留在旧版 edge_tts;+ 3. 旧版 `Communicate.__init__()` 不接受 `boundary`,会直接抛出+ `unexpected keyword argument 'boundary'`,导致整个 TTS 链路失败。++ 因此这里先根据构造函数签名探测当前版本支持的参数,再决定是否传入+ `boundary`,让同一份代码同时兼容旧版和新版依赖。+ """+ communicate_kwargs = {"rate": rate_str}+ communicate_signature = inspect.signature(edge_tts.Communicate)++ if "boundary" in communicate_signature.parameters:+ communicate_kwargs["boundary"] = "WordBoundary"++ return edge_tts.Communicate(text, voice_name, **communicate_kwargs)+++def stream_edge_tts_chunks(communicate, on_chunk) -> None:+ """+ 统一消费 edge_tts 的同步流和旧版异步流。++ edge_tts 7.x 提供 `stream_sync()`,可以在同步函数里直接迭代;+ 更早的版本通常只有异步 `stream()`。为了让 `azure_tts_v1()` 在+ 旧依赖残留场景下仍能继续工作,这里统一做一层流式兼容。++ Args:+ communicate: edge_tts.Communicate 实例+ on_chunk: 每拿到一个事件块时执行的回调+ """+ if hasattr(communicate, "stream_sync"):+ for chunk in communicate.stream_sync():+ on_chunk(chunk)+ return++ if not hasattr(communicate, "stream"):+ raise AttributeError("edge_tts communicate object has no stream method")++ async def _consume_async_stream():+ async for chunk in communicate.stream():+ on_chunk(chunk)++ # 这里显式创建独立事件循环,而不是复用外部上下文,目的是避免+ # 在同步调用栈里遇到“当前线程没有事件循环”或跨线程复用循环的问题。+ loop = asyncio.new_event_loop()+ try:+ loop.run_until_complete(_consume_async_stream())+ finally:+ loop.close()++def azure_tts_v1(text: str, voice_name: str, voice_rate: float, voice_file: str) -> Union[SubMaker, None]:@@ -1291,27 +1349,26 @@ def azure_tts_v1(try:logger.info(f"start, voice name: {voice_name}, try: {i + 1}")- # edge_tts 7.x 已经提供同步流接口和新的字幕聚合器实现,- # 这里直接使用同步接口,避免继续依赖旧版本的异步流事件结构。+ # 这里同时兼容 edge_tts 7.x 和旧版便携包里可能残留的老依赖:+ # 1. 新版支持 `boundary` + `stream_sync()`+ # 2. 旧版不支持 `boundary`,且通常只暴露异步 `stream()`ensure_file_path_exists(voice_file)- communicate = edge_tts.Communicate(- text,- voice_name,- rate=rate_str,- boundary="WordBoundary",- )+ communicate = create_edge_tts_communicate(text, voice_name, rate_str)sub_maker = edge_tts.SubMaker()with open(voice_file, "wb") as file:- for chunk in communicate.stream_sync():+ def _handle_chunk(chunk):chunk_type = chunk["type"]if chunk_type == "audio":file.write(chunk["data"])elif chunk_type in ["WordBoundary", "SentenceBoundary"]:- # 直接把 7.x 返回的边界事件喂给新的 SubMaker,- # 这样后续可以复用官方生成的字幕与时间轴。+ # 无论来自 7.x 的同步流,还是旧版异步流,只要事件结构+ # 里仍有边界信息,就统一喂给 SubMaker,保证后续字幕链路+ # 仍然走项目现有逻辑。sub_maker.feed(chunk)+ stream_edge_tts_chunks(communicate, _handle_chunk)+if not sub_maker.get_srt():logger.warning("failed, sub_maker.get_srt() is empty")continuediff --git a/requirements.txt b/requirements.txtindex e8ab37b2..cc8a63c5 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,4 +1,4 @@-# 兼容旧的 pip 安装方式;主依赖定义已迁移到 pyproject.toml / uv.lock。+# Keep legacy pip install support; primary deps moved to pyproject.toml / uv.lock.moviepy==2.1.2streamlit==1.45.0edge_tts==7.2.7diff --git a/test/services/test_voice.py b/test/services/test_voice.pyindex 4f2f175e..e02ee7e4 100644--- a/test/services/test_voice.py+++ b/test/services/test_voice.py@@ -86,6 +86,59 @@ class TestVoiceService(unittest.TestCase):audio_duration = vs.get_audio_duration(sub_maker)print(f"voice: {voice_name}, audio duration: {audio_duration}s")+ def test_azure_tts_v1_supports_legacy_edge_tts_without_boundary(self):+ """+ 验证 Azure TTS V1 在旧版 edge_tts 依赖残留时仍可继续工作。++ 这个回归场景对应 Windows 便携包更新失败后,现场环境还停留在旧版+ edge_tts 的情况:+ 1. `Communicate.__init__()` 不接受 `boundary`+ 2. 只有异步 `stream()`,没有 `stream_sync()`+ """++ class _LegacyCommunicate:+ def __init__(self, text, voice, rate="+0%"):+ self.text = text+ self.voice = voice+ self.rate = rate++ async def stream(self):+ yield {"type": "audio", "data": b"legacy-audio"}+ yield {+ "type": "WordBoundary",+ "offset": 0,+ "duration": 10000000,+ "text": "legacy",+ }++ class _FakeSubMaker:+ def __init__(self):+ self.events = []++ def feed(self, chunk):+ self.events.append(chunk)++ def get_srt(self):+ if not self.events:+ return ""+ return "1\n00:00:00,000 --> 00:00:01,000\nlegacy\n"++ with tempfile.TemporaryDirectory() as tmp_dir, patch.object(+ vs.edge_tts, "Communicate", _LegacyCommunicate+ ), patch.object(vs.edge_tts, "SubMaker", _FakeSubMaker):+ voice_file = str(Path(tmp_dir) / "legacy-edge-tts.mp3")+ sub_maker = vs.azure_tts_v1(+ text="legacy edge tts compatibility",+ voice_name="zh-CN-XiaoyiNeural-Female",+ voice_file=voice_file,+ voice_rate=1.0,+ )++ self.assertIsNotNone(sub_maker)+ self.assertEqual(Path(voice_file).read_bytes(), b"legacy-audio")+ self.assertEqual(len(sub_maker.events), 1)+ self.assertEqual(sub_maker.events[0]["type"], "WordBoundary")+def test_azure_tts_v2(self):voice_name = "zh-CN-XiaoxiaoMultilingualNeural-V2-Female"voice_name = vs.parse_voice_name(voice_name)