Repository navigation
fix(tools): transcode to OGG/Opus for OpenAI-compatible TTS backends without opus (#54589) #54597
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
PRATHAMESH75
wants to merge
1
commit into
NousResearch:main
from
PRATHAMESH75:fix/openai-tts-opus-fallback
+131
−9
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)), \ | ||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
|
@@ -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: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This catches failures from both the API request and |
||
| # 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): | ||
|
|
@@ -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...") | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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_ttsdestructures 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.