from __future__ import annotations import asyncio import json from collections import deque from types import SimpleNamespace from urllib.parse import parse_qs, urlparse import aiohttp import pytest from livekit.agents import APIConnectOptions, http, utils pytestmark = pytest.mark.plugin("deepgram") def _text(payload: dict) -> http.WebSocketMessage: return http.WebSocketMessage(http.WebSocketMessageType.TEXT, json.dumps(payload)) def _binary(data: bytes) -> http.WebSocketMessage: return http.WebSocketMessage(http.WebSocketMessageType.BINARY, data) class _FakeWS: """Minimal http.WebSocket stand-in for the receive loop.""" def __init__(self, incoming: list[http.WebSocketMessage]) -> None: self._incoming: deque[http.WebSocketMessage] = deque(incoming) self.sent: list[str] = [] async def send_str(self, data: str) -> None: self.sent.append(data) async def receive(self, timeout: float | None = None) -> http.WebSocketMessage: if self._incoming: return self._incoming.popleft() # Nothing left to hand out: emulate a closed socket so a runaway loop # surfaces instead of hanging. return http.WebSocketMessage(http.WebSocketMessageType.CLOSE, "") @property def unconsumed(self) -> list[http.WebSocketMessage]: return list(self._incoming) class _FakePool: def __init__(self, ws: _FakeWS) -> None: self._ws = ws self.last_acquire_time = 0.0 self.last_connection_reused = False def connection(self, *, conn_options: APIConnectOptions): # noqa: ANN201 ws = self._ws class _Ctx: async def __aenter__(self_): # noqa: N805 return ws async def __aexit__(self_, *exc): # noqa: N805 return False return _Ctx() class _FakeEmitter: def __init__(self) -> None: self.segments_started = 0 self.segments_ended = 0 self.pushed: list[bytes] = [] self.billed: list[tuple[int | None, int]] = [] def start_segment(self, *, segment_id: str) -> None: self.segments_started += 1 def end_segment(self) -> None: self.segments_ended += 1 def report_usage(self, usage: object = None, *, characters_count: int | None = None) -> None: # the segment it is reported in: billing belongs to the segment it ends self.billed.append((characters_count, self.segments_ended)) def push(self, data: bytes) -> None: self.pushed.append(data) def _segment(chunks: list[str]) -> utils.aio.Chan[str]: segment = utils.aio.Chan[str]() for chunk in chunks: segment.send_nowait(chunk) segment.close() return segment def _make_stream(ws: _FakeWS): # noqa: ANN201 # Exercise SynthesizeStreamv2._run_ws without constructing the full stream (whose # base __init__ wires up channels and telemetry we don't need here). from livekit.plugins.deepgram.tts_v2 import SynthesizeStreamv2 stream = SimpleNamespace( _pool=_FakePool(ws), _conn_options=APIConnectOptions(read_timeout=5.0), mark_started=lambda: None, ) stream._run_ws = SynthesizeStreamv2._run_ws.__get__(stream) return stream # --- update_options / pool invalidation (DG-4b) -------------------------------------- async def test_update_options_invalidates_pool_on_change(): from livekit.plugins.deepgram import TTSv2 tts = TTSv2(api_key="test-key") calls: list[bool] = [] tts._pool.invalidate = lambda: calls.append(True) # type: ignore[method-assign] tts.update_options(sample_rate=48000) assert calls == [True] assert tts._opts.sample_rate == 48000 # base-class property is kept in sync so downstream sizing stays correct assert tts.sample_rate == 48000 # --- receive loop (DG-4a, DG-6) ------------------------------------------------------ async def test_recv_ends_segment_on_speech_metadata_and_leaves_flushed(): ws = _FakeWS( [ _text({"type": "SpeechStarted"}), _binary(b"\x00\x01\x02\x03"), _text( { "type": "SpeechMetadata", "audio_duration_ms": 120, "input_character_count": 12, "billable_character_count": 11, } ), # server emits Flushed after SpeechMetadata; the loop must not depend on it _text({"type": "Flushed"}), ] ) stream = _make_stream(ws) emitter = _FakeEmitter() await asyncio.wait_for(stream._run_ws(_segment(["hello", "world"]), emitter), timeout=5.0) assert [json.loads(m) for m in ws.sent] == [ {"type": "Speak", "text": "hello "}, {"type": "Speak", "text": "world "}, {"type": "Flush"}, ] assert emitter.segments_started == 1 assert emitter.segments_ended == 1 assert emitter.pushed == [b"\x00\x01\x02\x03"] # the turn's billed characters are reported before its segment ends assert emitter.billed == [(11, 0)] # SpeechMetadata is the authoritative end-of-turn marker; the trailing Flushed is # intentionally left in the buffer (absorbed as a no-op on the next pooled reuse). remaining = ws.unconsumed assert len(remaining) == 1 assert json.loads(remaining[0].data)["type"] == "Flushed" async def test_flushed_is_a_noop_before_speech_metadata(): # A Flushed seen mid-turn must not end the segment early. ws = _FakeWS( [ _text({"type": "Flushed"}), _binary(b"\xaa\xbb"), _text({"type": "SpeechMetadata"}), ] ) stream = _make_stream(ws) emitter = _FakeEmitter() await asyncio.wait_for(stream._run_ws(_segment(["hi"]), emitter), timeout=5.0) assert emitter.segments_ended == 1 assert emitter.pushed == [b"\xaa\xbb"] # --- warning logging (DG-4c, DG-5) --------------------------------------------------- # --- encoding / mime type (DG-2, DG-3) ----------------------------------------------- def test_encoding_to_mimetype_rejects_unsupported(): from livekit.plugins.deepgram.tts_v2 import _encoding_to_mimetype # mulaw/alaw aren't playable through the pipeline yet, so they're not mapped for enc in ("mulaw", "alaw", "bogus"): with pytest.raises(ValueError): _encoding_to_mimetype(enc) async def test_stream_run_rejects_non_linear16_encoding(): # The streaming path validates encoding up front (before any connection), so a # compressed encoding fails fast with a clear message rather than at connect time. from livekit.plugins.deepgram.tts_v2 import SynthesizeStreamv2 stream = SimpleNamespace(_opts=SimpleNamespace(encoding="mp3")) stream._run = SynthesizeStreamv2._run.__get__(stream) with pytest.raises(ValueError, match="linear16"): await stream._run(_FakeEmitter()) # type: ignore[arg-type] # --- speed (v1 / Aura-2) ------------------------------------------------------------- async def _request_urls(**options) -> list[str]: """Observe streaming and batch request URLs at a real local HTTP boundary.""" from aiohttp import web from aiohttp.test_utils import TestServer from livekit.plugins.deepgram import TTS urls: list[str] = [] async def speak(request: web.Request) -> web.StreamResponse: urls.append(str(request.rel_url)) if request.method == "GET": ws = web.WebSocketResponse() await ws.prepare(request) async for message in ws: if ( message.type == aiohttp.WSMsgType.TEXT and json.loads(message.data)["type"] == "Flush" ): await ws.send_bytes(bytes(4800)) await ws.send_json({"type": "Flushed"}) return ws assert await request.json() == {"text": "hello"} return web.Response(body=bytes(4800), content_type="audio/pcm") app = web.Application() app.router.add_route("*", "/speak", speak) async with TestServer(app) as server, http.open() as session: provider = TTS( api_key="test-key", base_url=str(server.make_url("/speak")), http_session=session, **options, ) try: async with provider.stream(conn_options=APIConnectOptions(max_retry=0)) as stream: stream.push_text("hello") stream.end_input() async with asyncio.timeout(2): assert [chunk async for chunk in stream] async with provider.synthesize( "hello", conn_options=APIConnectOptions(max_retry=0) ) as stream: async with asyncio.timeout(2): assert [chunk async for chunk in stream] finally: await provider.aclose() return urls async def test_speed_is_sent_on_websocket_and_http(): ws_url, http_url = await _request_urls(speed=1.2) assert parse_qs(urlparse(ws_url).query)["speed"] == ["1.2"] assert parse_qs(urlparse(http_url).query)["speed"] == ["1.2"] async def test_speed_is_left_out_unless_set(): # Aura-1 and some Aura-2 languages reject even speed=1.0. for url in await _request_urls(model="aura-asteria-en"): assert "speed" not in parse_qs(urlparse(url).query) @pytest.mark.parametrize("speed", [0.69, 1.51]) async def test_speed_out_of_range_is_rejected(speed: float): from livekit.plugins.deepgram import TTS with pytest.raises(ValueError, match="speed"): TTS(api_key="test-key", speed=speed) tts = TTS(api_key="test-key") with pytest.raises(ValueError, match="speed"): tts.update_options(speed=speed) assert tts._opts.speed is None async def test_update_options_speed_invalidates_pool(): from livekit.plugins.deepgram import TTS tts = TTS(api_key="test-key") calls: list[bool] = [] tts._pool.invalidate = lambda: calls.append(True) # type: ignore[method-assign] tts.update_options(speed=0.9) assert tts._opts.speed == 0.9 # None goes back to the model's normal rate by leaving `speed` out again tts.update_options(speed=None) assert tts._opts.speed is None assert calls == [True, True] # Catches: the REST response's billed characters (`dg-char-count`, sent before the audio) # dropped instead of riding on the synthesis' final frame. async def test_rest_billed_characters_reach_the_final_frame(): from aiohttp import web from aiohttp.test_utils import TestServer from livekit.plugins.deepgram import TTS async def speak(request: web.Request) -> web.StreamResponse: return web.Response( body=bytes(4800), content_type="audio/pcm", headers={"dg-char-count": "5"} ) app = web.Application() app.router.add_post("/speak", speak) async with TestServer(app) as server, http.open() as session: provider = TTS( api_key="test-key", base_url=str(server.make_url("/speak")), http_session=session ) try: async with provider.synthesize( "hello", conn_options=APIConnectOptions(max_retry=0) ) as stream: frames = [audio async for audio in stream] finally: await provider.aclose() assert frames[-1].is_final and frames[-1].characters_count == 5 assert all(f.characters_count is None for f in frames[:-1])