edge-tts 升 7.3.1 并打补丁拦坏 metadata 帧

edge_tts 7.3.1 在 ws 返回坏 metadata 帧时,父类解析抛错导致
后续音频收不到。父类流方法内部用编译期锁死的父类方法名,子
类覆写根本走不到。这次直接给父类方法打补丁,坏帧悄悄丢掉,
让音频继续流;连续太多坏帧才主动报错让上层重试。补一个集
成测试,覆盖生产流路径。
This commit is contained in:
hrz 2026-10-14 22:01:56 +08:00
parent 27399a2fb6
commit 9325f0150b
4 changed files with 360 additions and 43 deletions

View file

@ -1,23 +1,78 @@
import json
import os
import uuid
import edge_tts
import edge_tts.communicate # 显式 import,下方要给本模块的 WSS_URL 重新赋值
import edge_tts.communicate
from datetime import datetime
from config.logger import setup_logging
from core.providers.tts.base import TTSProviderBase
# 微软 2026-10 起对 legacy 消费者接口返回 403,edge-tts 7.2.8 仍走
# speech.platform.bing.com 走不通。上游 PR rany2/edge-tts#491 切到
# api.msedgeservices.com 修好,但 7.2.8 仍是 PyPI 最新版本,临时把 WSS_URL 顶住。
# TODO(7.2.9): 升 edge-tts ≥ 7.2.9 后删掉这段 monkey patch。
_NEW_WSS_URL = (
"wss://api.msedgeservices.com/tts/cognitiveservices/websocket/v1"
f"?Ocp-Apim-Subscription-Key={edge_tts.constants.TRUSTED_CLIENT_TOKEN}"
)
# communicate.py 第 35 行 `from .constants import WSS_URL` 会在 import 时把
# WSS_URL 复制成本模块局部名,只改 edge_tts.constants.WSS_URL 不会生效。
# __stream() 走 LEGB 找的是 edge_tts.communicate.WSS_URL,所以这里两个都要改。
edge_tts.constants.WSS_URL = _NEW_WSS_URL
edge_tts.communicate.WSS_URL = _NEW_WSS_URL
TAG = __name__
logger = setup_logging()
# edge_tts 7.3.1 在 ws 返回坏 metadata 帧(非 JSON 或非 utf-8 bytes)时,
# 父类 __parse_metadata 调 json.loads 抛 JSONDecodeError / UnicodeDecodeError;
# stream() 的音频收帧循环被中断,听不到声音。
#
# 父类 __stream 内部用编译期锁死的 mangled 名
# `self._Communicate__parse_metadata(data)` 调用,子类覆写根本走不到,所以
# 必须在父类 Communicate 类上做 monkey-patch:替换 mangled 方法为带兜底的
# wrapper,让坏帧悄悄丢掉,音频二进制帧继续往下走。连续坏帧超阈值主动
# raise NoAudioReceived 让 base.py 的 5 次重试接管。
#
# Communicate 类内 `__parse_metadata` 写法在类外访问必须用 mangled 名
# `_Communicate__parse_metadata`;直接用 `"__parse_metadata"` 字面访问永远拿不到。
_METADATA_FALLBACK_COUNT = 5
_PARSED_METADATA_ATTR = "_Communicate__parse_metadata"
def _install_metadata_patch():
"""模块级一次性 patch,import 时执行。
三道闸门:
1. 探测父类 mangled 方法存在;不存在则 wrapper 不写入(patch 哑火)
2. wrapper 仅捕获 json.JSONDecodeError + UnicodeDecodeError;
KeyError/UnknownResponse/UnexpectedResponse 等真协议错误冒泡给 base.py 重试
3. 连续坏帧超 _METADATA_FALLBACK_COUNT 主动 raise NoAudioReceived
"""
cls = edge_tts.communicate.Communicate
original = cls.__dict__.get(_PARSED_METADATA_ATTR)
if original is None:
logger.bind(tag=TAG).error(
f"edge-tts Communicate.{_PARSED_METADATA_ATTR} 不存在,"
"metadata patch 失效,升级 edge_tts 后清掉这段兜底"
)
return
def wrapper(self, data):
try:
return original(self, data)
except (json.JSONDecodeError, UnicodeDecodeError) as e:
count = self.state.get("bad_metadata_count", 0) + 1
self.state["bad_metadata_count"] = count
logger.bind(tag=TAG).warning(
f"edge-tts metadata 帧非 JSON,已忽略(第 {count}/{_METADATA_FALLBACK_COUNT} 次): {e}"
)
if count > _METADATA_FALLBACK_COUNT:
raise edge_tts.exceptions.NoAudioReceived(
f"edge-tts 连续 {count} 次返回非 JSON metadata 帧"
)
return {
"type": "metadata_ignored",
"offset": 0,
"duration": 0,
"text": "",
}
setattr(cls, _PARSED_METADATA_ATTR, wrapper)
logger.bind(tag=TAG).info(
f"edge-tts Communicate.{_PARSED_METADATA_ATTR} patch 安装成功"
)
_install_metadata_patch()
class TTSProvider(TTSProviderBase):
@ -44,7 +99,6 @@ class TTSProvider(TTSProviderBase):
pitch_rate = config.get("pitch", "0")
self.pitch_rate = int(pitch_rate) if pitch_rate else 0
# 应用百分比调整
self._apply_percentage_params(config)
self.edge_rate = f"{self.speech_rate:+}%"
@ -58,32 +112,26 @@ class TTSProvider(TTSProviderBase):
)
async def text_to_speak(self, text, output_file):
try:
communicate = edge_tts.Communicate(
text,
voice=self.voice,
rate=self.edge_rate,
volume=self.edge_volume,
pitch=self.edge_pitch,
)
if output_file:
# 确保目录存在并创建空文件
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, "wb") as f:
pass
communicate = edge_tts.communicate.Communicate(
text,
voice=self.voice,
rate=self.edge_rate,
volume=self.edge_volume,
pitch=self.edge_pitch,
)
if output_file:
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, "wb") as f:
pass
# 流式写入音频数据
with open(output_file, "ab") as f: # 改为追加模式避免覆盖
async for chunk in communicate.stream():
if chunk["type"] == "audio": # 只处理音频数据块
f.write(chunk["data"])
else:
# 返回音频二进制数据
audio_bytes = b""
with open(output_file, "ab") as f:
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_bytes += chunk["data"]
return audio_bytes
except Exception as e:
error_msg = f"Edge TTS请求失败: {e}"
raise Exception(error_msg) # 抛出异常,让调用方捕获
if chunk.get("type") == "audio":
f.write(chunk["data"])
else:
audio_bytes = b""
async for chunk in communicate.stream():
if chunk.get("type") == "audio":
audio_bytes += chunk["data"]
return audio_bytes
return None

View file

@ -13,7 +13,7 @@ pydub==0.25.1
funasr==1.2.7
openai==2.8.1
google-generativeai==0.8.5
edge_tts==7.2.8
edge_tts==7.3.1
httpx==0.28.1
aiohttp==3.13.2
aiohttp_cors==0.8.1

View file

@ -0,0 +1,163 @@
"""edge_tts Communicate.stream() 生产路径上 metadata patch 的集成测试。
不连 ws 服务。直接把 Communicate 实例的 mangled `__stream` 替换成 fake,
fake 内调真实的 `self.__parse_metadata(raw_bytes)` —— 这条路径正好走过
_install_metadata_patch 装在父类上的 wrapper。
之前 hotfix-3 ~ 5 的 SafeCommunicate 子类方案之所以假阳性,就是只测了
wrapper 自身,没走 stream() 入口。这层覆盖必须保留。
不依赖 pytest-asyncio(项目 conda env 没装),用 asyncio.run 在同步
测试里跑 async stream。
"""
from __future__ import annotations
import asyncio
from xml.sax.saxutils import escape
import edge_tts.communicate as ec
import edge_tts.exceptions
def _make_communicate() -> ec.Communicate:
return ec.Communicate(text="hi", voice="zh-CN-XiaoxiaoNeural")
def _ok_payload(meta_type: str = "WordBoundary", offset: int = 12345, duration: int = 678, text: str = "你好") -> bytes:
return (
b'{"Metadata":[{"Type":"' + meta_type.encode() + b'",'
b'"Data":{"Offset":' + str(offset).encode() + b','
b'"Duration":' + str(duration).encode() + b','
b'"text":{"Text":"' + escape(text).encode() + b'"}}}]}'
)
def _install_fake_stream(comm: ec.Communicate, sequence: list) -> None:
"""在实例上替换 _Communicate__stream,绕过 aiohttp ws,按 sequence yield chunks。
sequence 元素约定:
- tuple ("raw_metadata", bytes) → 调 self.__parse_metadata(bytes) 并 yield 结果
- dict → 直接 yield(audio 帧或其他)
- "turn_end" → 模拟 turn.end:调 __compensate_offset 后退出
"""
async def fake_stream(self):
for item in sequence:
if item == "turn_end":
self._Communicate__compensate_offset()
return
if isinstance(item, tuple) and item[0] == "raw_metadata":
_, raw = item
# 显式 mangled name:fake_stream 在模块作用域定义,
# `self.__parse_metadata` 不会被 Python 名字改写。
parsed = self._Communicate__parse_metadata(raw)
yield parsed
self.state["last_duration_offset"] = (
parsed["offset"] + parsed["duration"]
)
else:
yield item
comm._Communicate__stream = fake_stream.__get__(comm, ec.Communicate)
def _drain_stream(comm: ec.Communicate) -> list:
"""同步跑一次 stream(),把 yield 出的 chunks 全收集。"""
chunks: list = []
async def collect():
async for chunk in comm.stream():
chunks.append(chunk)
asyncio.run(collect())
return chunks
class TestStreamMetadataPatch:
def test_stream_skips_bad_metadata_then_yields_audio(self):
"""1 帧坏 metadata + 1 帧合法 audio → stream 不抛错,audio 拿到,坏帧计数==1。"""
comm = _make_communicate()
_install_fake_stream(comm, [
("raw_metadata", b"this is not json at all"),
{"type": "audio", "data": b"\xff\xfb\x90\x00fake-mp3-bytes"},
"turn_end",
])
chunks = _drain_stream(comm)
audio = [c for c in chunks if c.get("type") == "audio"]
assert len(audio) == 1
assert audio[0]["data"] == b"\xff\xfb\x90\x00fake-mp3-bytes"
assert comm.state["bad_metadata_count"] == 1
# 坏帧的 fallback offset=0 duration=0,last_duration_offset 走兜底 0+0
assert comm.state["last_duration_offset"] == 0
def test_stream_consecutive_bad_metadata_eventually_raises(self):
"""连续 6 帧坏 metadata → NoAudioReceived 冒泡,让 base.py 重试。"""
comm = _make_communicate()
bad = ("raw_metadata", b"not-json-again")
sequence = [bad] * 6 + [
{"type": "audio", "data": b"\xff\xfb"},
"turn_end",
]
_install_fake_stream(comm, sequence)
async def run():
async for _ in comm.stream():
pass
with pytest_raises_no_audio_received():
asyncio.run(run())
assert comm.state["bad_metadata_count"] == 6
def test_stream_real_good_metadata_passes_through_unchanged(self):
"""正常 WordBoundary JSON → 不走 wrapper fallback 分支,原样 yield。"""
comm = _make_communicate()
_install_fake_stream(comm, [
("raw_metadata", _ok_payload("WordBoundary", 12345, 678, "你好")),
{"type": "audio", "data": b"audio"},
"turn_end",
])
chunks = _drain_stream(comm)
word = [c for c in chunks if c.get("type") == "WordBoundary"]
assert len(word) == 1
assert word[0]["offset"] == 12345
assert word[0]["duration"] == 678
assert word[0]["text"] == "你好"
assert comm.state.get("bad_metadata_count", 0) == 0
def test_stream_recovers_after_single_bad_frame(self):
"""1 帧坏 metadata 后 1 帧好 metadata → stream 继续,好帧原样 yield。"""
comm = _make_communicate()
_install_fake_stream(comm, [
("raw_metadata", b"junk"),
("raw_metadata", _ok_payload("WordBoundary", 9000, 400, "复")),
{"type": "audio", "data": b"a"},
"turn_end",
])
chunks = _drain_stream(comm)
word = [c for c in chunks if c.get("type") == "WordBoundary"]
assert len(word) == 1
assert word[0]["text"] == "复"
assert comm.state["bad_metadata_count"] == 1
# pytest 没装 pytest-asyncio,pytest.raises 不认 coroutine;这里用上下文管理器
# 包一层,跟 pytest.raises 行为一致但能跑 coroutine。
import contextlib
@contextlib.contextmanager
def pytest_raises_no_audio_received():
try:
yield
except edge_tts.exceptions.NoAudioReceived:
return
except BaseException as e:
raise AssertionError(f"expected NoAudioReceived, got {type(e).__name__}: {e}")
raise AssertionError("expected NoAudioReceived but no exception raised")

View file

@ -0,0 +1,106 @@
"""edge_tts 父类 metadata 解析 monkey-patch 行为测试。
不连 edge_tts 服务,只验证 `_install_metadata_patch` 装在父类 mangled
方法上的 wrapper 自身行为契约。生产路径 stream() 上的兜底由
test_edge_metadata_patch_integration.py 单独覆盖。
"""
from __future__ import annotations
from xml.sax.saxutils import escape
import edge_tts.communicate as ec
import edge_tts.exceptions
import pytest
from core.providers.tts.edge import _PARSED_METADATA_ATTR, _METADATA_FALLBACK_COUNT
def _make_communicate() -> ec.Communicate:
return ec.Communicate(text="hi", voice="zh-CN-XiaoxiaoNeural")
def _ok_payload(meta_type: str = "WordBoundary", offset: int = 8000, duration: int = 2500) -> bytes:
return (
b'{"Metadata":[{"Type":"' + meta_type.encode() + b'",'
b'"Data":{"Offset":' + str(offset).encode() + b','
b'"Duration":' + str(duration).encode() + b','
b'"text":{"Text":"' + escape("hi").encode() + b'"}}}]}'
)
class TestSafeParseMetadata:
def test_a_normal_word_boundary_returns_full_metadata(self):
"""正常 WordBoundary JSON → 返回原 metadata dict,不增加 bad_metadata_count。"""
comm = _make_communicate()
result = comm._Communicate__parse_metadata(_ok_payload("WordBoundary", 8000, 2500))
assert result["type"] == "WordBoundary"
assert result["offset"] == 8000
assert result["duration"] == 2500
assert result["text"] == "hi"
assert comm.state.get("bad_metadata_count", 0) == 0
def test_a_sentence_boundary(self):
comm = _make_communicate()
result = comm._Communicate__parse_metadata(_ok_payload("SentenceBoundary", 1000, 500))
assert result["type"] == "SentenceBoundary"
assert result["offset"] == 1000
assert result["duration"] == 500
def test_b_bad_bytes_returns_safe_fallback_and_increments(self):
"""非 JSON bytes → 返回 safe fallback + bad_metadata_count==1。"""
comm = _make_communicate()
result = comm._Communicate__parse_metadata(b"this is not json {")
assert result == {
"type": "metadata_ignored",
"offset": 0,
"duration": 0,
"text": "",
}
assert comm.state["bad_metadata_count"] == 1
def test_b_empty_bytes(self):
comm = _make_communicate()
result = comm._Communicate__parse_metadata(b"")
assert result["type"] == "metadata_ignored"
assert comm.state["bad_metadata_count"] == 1
def test_c_six_consecutive_bad_bytes_raises_no_audio(self):
"""连续 6 次非 JSON bytes → 第 6 次 raise NoAudioReceived。"""
comm = _make_communicate()
for _ in range(_METADATA_FALLBACK_COUNT):
r = comm._Communicate__parse_metadata(b"bad")
assert r["type"] == "metadata_ignored"
assert comm.state["bad_metadata_count"] == _METADATA_FALLBACK_COUNT
with pytest.raises(edge_tts.exceptions.NoAudioReceived):
comm._Communicate__parse_metadata(b"bad again")
def test_f_non_utf8_bytes_returns_safe_fallback(self):
"""非 utf-8 bytes → 走 safe fallback + bad_metadata_count+=1。"""
comm = _make_communicate()
result = comm._Communicate__parse_metadata(b"\x00\xff\xfe")
assert result == {
"type": "metadata_ignored",
"offset": 0,
"duration": 0,
"text": "",
}
assert comm.state["bad_metadata_count"] == 1
def test_g_missing_metadata_key_raises_keyerror(self):
"""合法 JSON 缺 Metadata 字段 → KeyError 透出,不被吞。"""
comm = _make_communicate()
with pytest.raises(KeyError):
comm._Communicate__parse_metadata(b'{"type": "test"}')
assert comm.state.get("bad_metadata_count", 0) == 0
class TestPatchInstallation:
def test_install_replaces_mangled_attr_on_communicate_class(self):
"""_install_metadata_patch 跑过之后,父类 mangled attr 已被替换成 wrapper。"""
cls = ec.Communicate
current = cls.__dict__.get(_PARSED_METADATA_ATTR)
assert callable(current)
# wrapper 内层捕获 json.JSONDecodeError,可由坏字节验证它已装上
comm = _make_communicate()
result = comm._Communicate__parse_metadata(b"definitely-not-json")
assert result["type"] == "metadata_ignored"