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
38 changes: 38 additions & 0 deletions tests/tools/test_tts_xai_speech_tags.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Tests for xAI TTS speech-tag handling."""

from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch

import pytest

from tools import tts_tool
from tools.tts_tool import (
_XAI_INLINE_SPEECH_TAGS,
_XAI_WRAPPING_SPEECH_TAGS,
Expand Down Expand Up @@ -326,6 +328,42 @@ def fake_post(url, headers, json, timeout):
assert captured["json"]["text"] == "Bonjour Monsieur Talbot. Ceci est un test."


def test_generate_xai_tts_transcodes_ogg_requests_to_opus(tmp_path, monkeypatch):
"""xAI only returns MP3/WAV; .ogg callers need an Opus transcode."""
captured = {}
out = tmp_path / "out.ogg"

fake_response = Mock()
fake_response.content = b"mp3"
fake_response.raise_for_status.return_value = None

def fake_post(url, headers, json, timeout):
captured["json"] = json
return fake_response

def fake_convert(path: str) -> str:
captured["convert_input"] = path
assert path.endswith(".mp3")
converted = Path(path).with_suffix(".ogg")
converted.write_bytes(b"opus")
return str(converted)

monkeypatch.setenv("XAI_API_KEY", "test-xai-key")
monkeypatch.setattr("requests.post", fake_post)
monkeypatch.setattr(tts_tool, "_convert_to_opus", fake_convert)

result = _generate_xai_tts(
"Hello world.",
str(out),
{"xai": {"voice_id": "ara", "language": "en"}},
)

assert result == str(out)
assert out.read_bytes() == b"opus"
assert captured["convert_input"] != str(out)
assert captured["json"]["text"] == "Hello world."


def test_generate_xai_tts_omits_speed_and_latency_by_default(tmp_path, monkeypatch):
"""No speed / optimize_streaming_latency in the request body unless
the user explicitly sets them. Keeps the existing minimal-payload
Expand Down
24 changes: 22 additions & 2 deletions tools/tts_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1227,9 +1227,18 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
or DEFAULT_XAI_BASE_URL
).strip().rstrip("/")

# xAI does not expose a native Opus/OGG codec. Telegram auto-voice callers
# pass an .ogg target, so synthesize MP3 first and transcode below.
needs_opus_transcode = output_path.endswith(".ogg")
if needs_opus_transcode:
output = Path(output_path)
api_output_path = str(output.with_name(f"{output.stem}-{uuid.uuid4().hex}.mp3"))
else:
api_output_path = output_path

# Match the documented minimal POST /v1/tts shape by default. Only send
# output_format when Hermes actually needs a non-default format/override.
codec = "wav" if output_path.endswith(".wav") else "mp3"
codec = "wav" if api_output_path.endswith(".wav") else "mp3"
payload: Dict[str, Any] = {
"text": text,
"voice_id": voice_id,
Expand Down Expand Up @@ -1271,9 +1280,20 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -
)
response.raise_for_status()

with open(output_path, "wb") as f:
with open(api_output_path, "wb") as f:
f.write(response.content)

if needs_opus_transcode:
opus_path = _convert_to_opus(api_output_path)
if not opus_path:

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.

When _convert_to_opus() returns None (including when ffmpeg is unavailable), this raises before the cleanup below, leaving the UUID-named temporary MP3 behind. Please clean up api_output_path in a finally block and add a failure-path regression test.

raise RuntimeError("xAI TTS could not convert MP3 output to OGG Opus")
if opus_path != output_path:
os.replace(opus_path, output_path)
try:
os.remove(api_output_path)
except OSError:
pass

return output_path


Expand Down