Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions tests/tools/test_tts_openai_opus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""OpenAI TTS opus handling for Telegram voice bubbles.

Real OpenAI encodes opus natively, but many OpenAI-*compatible* backends
(e.g. a self-hosted Speaches/Kokoro endpoint) only support mp3/flac/wav/pcm
and reject ``response_format="opus"``. ``_generate_openai_tts`` must try
native opus first and fall back to mp3 + local ffmpeg transcode so those
backends still deliver a playable OGG/Opus voice bubble.
"""
from unittest.mock import MagicMock, patch


def _client():
mock_response = MagicMock()
mock_client = MagicMock()
mock_client.audio.speech.create.return_value = mock_response
return mock_client, MagicMock(return_value=mock_client)


def _formats(create):
"""response_format passed to each create() call, in order."""
return [c.kwargs["response_format"] for c in create.call_args_list]


class TestOpenaiOpusFallback:
def test_native_opus_no_transcode(self, tmp_path, monkeypatch):
"""An opus-capable backend gets a single opus request, no ffmpeg."""
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
mock_client, mock_cls = _client()
out = str(tmp_path / "out.ogg")

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)), \

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main's resolver now returns (api_key, base_url, is_managed) and _generate_openai_tts destructures all three values (tools/tts_tool.py:1027). Update this and the other new mocks to return a three-tuple so the salvaged tests exercise the current contract.

patch("tools.tts_tool._convert_to_opus") as convert:
from tools.tts_tool import _generate_openai_tts
result = _generate_openai_tts("Hello", out, {})

assert _formats(mock_client.audio.speech.create) == ["opus"]
convert.assert_not_called()
assert result == out

def test_falls_back_to_mp3_and_transcodes(self, tmp_path, monkeypatch):
"""A backend that rejects opus is retried as mp3 then transcoded."""
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
mock_client, mock_cls = _client()
# First call (opus) fails; second call (mp3) succeeds.
mock_client.audio.speech.create.side_effect = [
Exception("Unsupported response_format 'opus'"),
MagicMock(),
]
out = str(tmp_path / "out.ogg")
converted = str(tmp_path / "out.ogg")

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)), \
patch("tools.tts_tool._convert_to_opus", return_value=converted) as convert:
from tools.tts_tool import _generate_openai_tts
result = _generate_openai_tts("Hello", out, {})

assert _formats(mock_client.audio.speech.create) == ["opus", "mp3"]
convert.assert_called_once_with(str(tmp_path / "out.mp3"))
assert result == converted

def test_fallback_without_ffmpeg_keeps_mp3(self, tmp_path, monkeypatch):
"""No ffmpeg => return the mp3 so the caller still has audio."""
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
mock_client, mock_cls = _client()
mock_client.audio.speech.create.side_effect = [
Exception("Unsupported response_format 'opus'"),
MagicMock(),
]
out = str(tmp_path / "out.ogg")

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)), \
patch("tools.tts_tool._convert_to_opus", return_value=None):
from tools.tts_tool import _generate_openai_tts
result = _generate_openai_tts("Hello", out, {})

assert result == str(tmp_path / "out.mp3")

def test_non_ogg_target_uses_mp3_directly(self, tmp_path, monkeypatch):
"""A plain .mp3 target never asks for opus."""
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
mock_client, mock_cls = _client()
out = str(tmp_path / "out.mp3")

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)), \
patch("tools.tts_tool._convert_to_opus") as convert:
from tools.tts_tool import _generate_openai_tts
result = _generate_openai_tts("Hello", out, {})

assert _formats(mock_client.audio.speech.create) == ["mp3"]
convert.assert_not_called()
assert result == out
41 changes: 32 additions & 9 deletions tools/tts_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,15 +1027,18 @@ def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]
base_url = oai_config.get("base_url", base_url)
speed = float(oai_config.get("speed", tts_config.get("speed", 1.0)))

# Determine response format from extension
if output_path.endswith(".ogg"):
response_format = "opus"
else:
response_format = "mp3"
# Telegram voice bubbles need OGG/Opus. Real OpenAI encodes opus natively
# (no ffmpeg needed), but many OpenAI-*compatible* backends (e.g. a
# self-hosted Speaches/Kokoro endpoint) only support mp3/flac/wav/pcm and
# reject ``response_format="opus"``. Try native opus first, then fall back
# to mp3 + local ffmpeg transcode -- mirroring the Edge provider path so a
# non-opus backend still delivers a playable voice bubble.
wants_opus = output_path.endswith(".ogg")

OpenAIClient = _import_openai_client()
client = OpenAIClient(api_key=api_key, base_url=base_url)
try:

def _synthesize(response_format: str, target_path: str) -> None:
create_kwargs = {
"model": model,
"voice": voice,
Expand All @@ -1046,9 +1049,29 @@ def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]
if speed != 1.0:
create_kwargs["speed"] = max(0.25, min(4.0, speed))
response = client.audio.speech.create(**create_kwargs)
response.stream_to_file(target_path)

response.stream_to_file(output_path)
return output_path
try:
if not wants_opus:
_synthesize("mp3", output_path)
return output_path

try:
_synthesize("opus", output_path)
return output_path
except Exception as e:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This catches failures from both the API request and stream_to_file, then issues a second synthesis request even for auth, transport, or local-write errors. Restrict the fallback to a confirmed unsupported-opus format response and propagate unrelated exceptions.

# Backend likely can't encode opus. Re-synthesize as mp3 and
# transcode to OGG/Opus locally.
logger.info(
"OpenAI TTS opus request failed (%s); retrying as mp3 + ffmpeg transcode",
e,
)
mp3_path = output_path[:-4] + ".mp3"
_synthesize("mp3", mp3_path)
converted = _convert_to_opus(mp3_path)
# If ffmpeg is unavailable, keep the mp3 so the caller still has
# playable audio (delivered as a document rather than a voice bubble).
return converted or mp3_path
finally:
close = getattr(client, "close", None)
if callable(close):
Expand Down Expand Up @@ -2272,7 +2295,7 @@ def text_to_speech_tool(
"error": "OpenAI provider selected but 'openai' package not installed."
}, ensure_ascii=False)
logger.info("Generating speech with OpenAI TTS...")
_generate_openai_tts(text, file_str, tts_config)
file_str = _generate_openai_tts(text, file_str, tts_config)

elif provider == "minimax":
logger.info("Generating speech with MiniMax TTS...")
Expand Down
Loading