Files
livekit-agents/tests/test_plugin_speechify.py

340 lines
12 KiB
Python

from __future__ import annotations
import asyncio
import base64
import httpx2 as httpx
import pytest
from speechify.core.pagination import AsyncPager
from speechify.types.error_detail import ErrorDetail
from speechify.types.get_voice import GetVoice
from speechify.types.get_voices_model import GetVoicesModel
from speechify.types.list_voices_response import ListVoicesResponse
from speechify.types.nested_chunk import NestedChunk
from speechify.types.speech_stream_event import (
SpeechStreamEvent_SpeechChunk,
SpeechStreamEvent_SpeechDone,
SpeechStreamEvent_SpeechError,
)
from livekit.agents import (
APIConnectionError,
APIConnectOptions,
APIStatusError,
APITimeoutError,
)
from livekit.agents.types import NOT_GIVEN, USERDATA_TIMED_TRANSCRIPT
from livekit.plugins.speechify import tts as sfy_tts
pytestmark = pytest.mark.unit
_PCM = b"\x00\x7f" * (24000 * 2) # 0.5s of 24 kHz mono PCM silence
class _FakeAudio:
def __init__(self) -> None:
self.stream_calls: list[dict] = []
self.speech_calls: list[dict] = []
self.streams_read_to_end = 0
async def stream_with_timestamps(self, **kwargs: object) -> object:
self.stream_calls.append(kwargs)
yield SpeechStreamEvent_SpeechChunk(
type="speech.chunk",
audio=base64.b64encode(_PCM).decode("ascii"),
speech_marks=[
NestedChunk(
type="word", value="Hello", start=0, end=5, start_time=0, end_time=320.0
)
],
)
yield SpeechStreamEvent_SpeechChunk(
type="speech.chunk",
audio=None,
speech_marks=[
NestedChunk(
type="word", value="world", start=6, end=11, start_time=340.0, end_time=700.0
)
],
)
yield SpeechStreamEvent_SpeechDone(
type="speech.done", billable_characters_count=11, audio_duration_ms=700
)
# only reached when the caller keeps reading after speech.done
self.streams_read_to_end += 1
async def speech(self, **kwargs: object) -> _FakeSpeechResponse:
self.speech_calls.append(kwargs)
return _FakeSpeechResponse()
async def stream(self, **kwargs: object) -> object:
raise AssertionError("raw /v1/audio/stream should not be called")
class _FakeSpeechResponse:
audio_data: str = base64.b64encode(_PCM).decode("ascii")
speech_marks = type("Marks", (), {"chunks": []})
def _sdk_voice(voice_id: str, gender: str, *models: str) -> GetVoice:
return GetVoice(
id=voice_id,
display_name=voice_id,
gender=gender,
locale="en-US",
models=[GetVoicesModel(name=m, languages=[]) for m in models],
type="shared",
)
class _FakeVoices:
# Two pages chained by get_next, the way the SDK pages GET /v1/voices.
pages = [
[_sdk_voice("dominic_32", "male", "simba-3.2", "simba-3.5")],
[_sdk_voice("sam", "not_specified", "simba-3.0")],
]
async def list(self, **kwargs: object) -> AsyncPager[GetVoice, ListVoicesResponse]:
return self._page(0)
def _page(self, i: int) -> AsyncPager[GetVoice, ListVoicesResponse]:
has_next = i + 1 < len(self.pages)
async def get_next() -> AsyncPager[GetVoice, ListVoicesResponse]:
return self._page(i + 1)
return AsyncPager(
has_next=has_next,
items=self.pages[i],
get_next=get_next if has_next else None,
response=ListVoicesResponse(voices=self.pages[i], has_more=has_next),
)
class _ErrorAudio(_FakeAudio):
async def stream_with_timestamps(self, **kwargs: object) -> object:
self.stream_calls.append(kwargs)
yield SpeechStreamEvent_SpeechError(
type="speech.error",
error=ErrorDetail(code="speech_failed", message="boom"),
request_id="rid-1",
)
class _FakeClient:
def __init__(self) -> None:
self.audio = _FakeAudio()
self.voices = _FakeVoices()
_NO_RETRY = APIConnectOptions(max_retry=0)
def _make_tts(model: str, client: _FakeClient) -> sfy_tts.TTS:
return sfy_tts.TTS(model=model, client=client) # type: ignore[arg-type]
async def _run(t: sfy_tts.TTS, mode: str, conn_options: APIConnectOptions = _NO_RETRY) -> list:
if mode == "synthesize":
async with t.synthesize("Hello world.", conn_options=conn_options) as s:
return [f async for f in s]
stream = t.stream(conn_options=conn_options)
stream.push_text("Hello world.")
stream.end_input()
return [f async for f in stream]
@pytest.mark.parametrize("mode", ["stream", "synthesize"])
async def test_streaming_model_uses_sse_with_timestamps(mode: str) -> None:
client = _FakeClient()
frames = await _run(_make_tts("simba-3.2", client), mode)
assert len(client.audio.stream_calls) == 1
kwargs = client.audio.stream_calls[0]
assert kwargs["input"] == "Hello world."
assert kwargs["voice_id"] == sfy_tts.DEFAULT_VOICE_ID
assert kwargs["output_format"] == "pcm_24000"
assert kwargs.get("model") == "simba-3.2"
assert client.audio.speech_calls == []
assert sum(f.frame.duration for f in frames) > 0.4
transcripts = [t for f in frames for t in f.frame.userdata.get(USERDATA_TIMED_TRANSCRIPT, [])]
words = {str(t): t for t in transcripts}
assert set(words) == {"Hello", "world"}
assert words["Hello"].start_time == pytest.approx(0.0)
assert words["Hello"].end_time == pytest.approx(0.32)
assert words["world"].start_time == pytest.approx(0.34)
# the body is read past speech.done, so its connection can go back to the pool
assert client.audio.streams_read_to_end == 1
@pytest.mark.parametrize("mode", ["stream", "synthesize"])
async def test_legacy_model_uses_speech_endpoint(mode: str) -> None:
client = _FakeClient()
frames = await _run(_make_tts("simba-english", client), mode)
assert client.audio.stream_calls == []
assert len(client.audio.speech_calls) == 1
assert client.audio.speech_calls[0]["audio_format"] == "pcm"
assert sum(f.frame.duration for f in frames) > 0.4
async def test_not_given_model_streams_without_model_param() -> None:
client = _FakeClient()
await _run(sfy_tts.TTS(model=NOT_GIVEN, client=client), "stream") # type: ignore[arg-type]
# the server defaults to simba-3.0, which streams
assert len(client.audio.stream_calls) == 1
assert "model" not in client.audio.stream_calls[0]
@pytest.mark.parametrize("mode", ["stream", "synthesize"])
async def test_speech_error_raises(mode: str) -> None:
client = _FakeClient()
client.audio = _ErrorAudio()
with pytest.raises(APIStatusError, match="boom"):
await _run(_make_tts("simba-3.2", client), mode)
def _mock_http(monkeypatch: pytest.MonkeyPatch, handler: object) -> None:
real_init = httpx.AsyncClient.__init__
def init(self: httpx.AsyncClient, *args: object, **kwargs: object) -> None:
kwargs["transport"] = httpx.MockTransport(handler) # type: ignore[arg-type]
real_init(self, *args, **kwargs) # type: ignore[arg-type]
monkeypatch.setattr(httpx.AsyncClient, "__init__", init)
@pytest.mark.virtual_time
@pytest.mark.parametrize(
("exc", "expected"),
[(httpx.ConnectError, APIConnectionError), (httpx.ReadTimeout, APITimeoutError)],
)
async def test_owned_client_transport_error_is_retried(
monkeypatch: pytest.MonkeyPatch, exc: type[Exception], expected: type[Exception]
) -> None:
attempts = 0
def handler(request: httpx.Request) -> httpx.Response:
nonlocal attempts
attempts += 1
raise exc("failed", request=request) # type: ignore[call-arg]
_mock_http(monkeypatch, handler)
t = sfy_tts.TTS(api_key="sk-test", base_url="https://api.example.test/")
try:
with pytest.raises(expected):
await _run(t, "synthesize", APIConnectOptions(max_retry=2, retry_interval=0))
finally:
await t.aclose()
assert attempts == 3
async def test_prewarm_opens_connection_without_credentials(
monkeypatch: pytest.MonkeyPatch,
) -> None:
requests: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
return httpx.Response(200, json={"status": "ok"})
_mock_http(monkeypatch, handler)
t = sfy_tts.TTS(api_key="sk-test", base_url="https://api.example.test/")
t.prewarm()
t.prewarm() # a second call while the first is in flight is a no-op
assert t._prewarm_task is not None
await t._prewarm_task
assert [(r.method, str(r.url)) for r in requests] == [
("GET", "https://api.example.test/health")
]
assert "authorization" not in requests[0].headers
assert requests[0].headers[sfy_tts.CALLER_HEADER] == "livekit"
await t.aclose()
async def test_aclose_cancels_pending_prewarm(monkeypatch: pytest.MonkeyPatch) -> None:
async def handler(request: httpx.Request) -> httpx.Response:
await asyncio.Event().wait()
raise AssertionError("unreachable")
_mock_http(monkeypatch, handler)
t = sfy_tts.TTS(api_key="sk-test")
t.prewarm()
task = t._prewarm_task
assert task is not None
await asyncio.wait_for(t.aclose(), timeout=1)
assert task.cancelled()
def test_prewarm_is_noop_with_injected_client() -> None:
t = _make_tts("simba-3.2", _FakeClient())
t.prewarm()
assert t._prewarm_task is None
async def test_list_voices_reads_every_page() -> None:
voices = await _make_tts("simba-3.2", _FakeClient()).list_voices()
assert [v.id for v in voices] == ["dominic_32", "sam"]
assert voices[0].models == ["simba-3.2", "simba-3.5"]
assert voices[0].gender == "male"
assert voices[1].gender == "neutral"
def test_supports_streaming_marks() -> None:
assert sfy_tts._supports_streaming_marks(NOT_GIVEN)
assert sfy_tts._supports_streaming_marks("simba-3.0")
assert sfy_tts._supports_streaming_marks("simba-3.2")
assert sfy_tts._supports_streaming_marks("simba-3.5")
# a model released after this plugin streams without a plugin update
assert sfy_tts._supports_streaming_marks("simba-9.9")
assert not sfy_tts._supports_streaming_marks("simba-english")
assert not sfy_tts._supports_streaming_marks("simba-multilingual")
def test_marks_to_timed_uses_start_end_time() -> None:
marks = [
NestedChunk(type="word", value="a", start=0, end=1, start_time=0.0, end_time=100.0),
# character-offset-only mark (no times) must be skipped, as in the batch path
NestedChunk(type="word", value="b", start=5, end=6, start_time=None, end_time=None),
]
timed = sfy_tts._marks_to_timed(marks, offset=0.5)
assert len(timed) == 1
assert timed[0] == "a"
assert timed[0].start_time == pytest.approx(0.5)
assert timed[0].end_time == pytest.approx(0.6)
def test_warn_voice_model_compat(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level("WARNING", "livekit.plugins.speechify"):
# curated simba-3.2 voices (id suffix "_32") warn on models older than simba-3.2
for model in ("simba-english", "simba-multilingual", "simba-3.0"):
caplog.clear()
sfy_tts._warn_voice_model_compat("dominic_32", model)
assert any("dominic_32" in r.message for r in caplog.records), model
caplog.clear()
# NOT_GIVEN defaults the server to simba-3.0 -> still a mismatch
sfy_tts._warn_voice_model_compat("dominic_32", NOT_GIVEN)
assert any("dominic_32" in r.message for r in caplog.records)
caplog.clear()
# simba-3.2 and every later model, including unreleased ones, are silent
sfy_tts._warn_voice_model_compat("dominic_32", "simba-3.2")
sfy_tts._warn_voice_model_compat("dominic_32", "simba-3.5")
sfy_tts._warn_voice_model_compat("dominic_32", "simba-9.9")
assert not caplog.records
caplog.clear()
# non "_32" voices never warn regardless of model
sfy_tts._warn_voice_model_compat("henry", "simba-english")
sfy_tts._warn_voice_model_compat("henry", "simba-3.2")
assert not caplog.records