Skip to content
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

WebSockets: do not yield chunks unless request ID matches #94

Merged
merged 2 commits into from
Jan 29, 2025
Merged
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
31 changes: 23 additions & 8 deletions pyht/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import tempfile
import time
from typing import Any, Dict, AsyncGenerator, AsyncIterable, AsyncIterator, Coroutine, Tuple, Optional, Union
import uuid
from websockets.asyncio.client import connect, ClientConnection
from websockets.exceptions import ConnectionClosed

Expand Down Expand Up @@ -110,6 +109,8 @@ async def lease_factory() -> Lease:
self._api_key = api_key
self._inference_coordinates: Optional[Dict[str, Any]] = None
self._ws: Optional[ClientConnection] = None
self._ws_requests_sent = 0
self._ws_responses_received = 0

if self._advanced.congestion_ctrl == CongestionCtrl.STATIC_MAR_2023:
self._max_attempts = 3
Expand Down Expand Up @@ -446,34 +447,48 @@ async def _tts_ws(
assert self._inference_coordinates is not None, "No connection"
metrics.append("text", str(text)).append("endpoint",
str(self._inference_coordinates[voice_engine]["websocket_url"]))
request_id = str(uuid.uuid4())
json_data = http_prepare_dict(text, options, voice_engine)
json_data["request_id"] = request_id

for attempt in range(1, self._max_attempts + 1):
try:
assert self._inference_coordinates is not None, "No connection"
ws_address = self._inference_coordinates[voice_engine]["websocket_url"]
if self._ws is None:
self._ws = await connect(ws_address)
self._ws_requests_sent = 0
self._ws_responses_received = 0
try:
await self._ws.send(json.dumps(json_data))
self._ws_requests_sent += 1
except ConnectionClosed as e:
logging.debug(f"Reconnecting websocket which closed unexpectedly: {e}")
self._ws = await connect(ws_address)
self._ws_requests_sent = 0
self._ws_responses_received = 0
await self._ws.send(json.dumps(json_data))
self._ws_requests_sent += 1
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
chunk_idx = -1
request_id = -1
started = False
async for chunk in self._ws:
chunk_idx += 1
if isinstance(chunk, str):
msg = json.loads(chunk)
if msg["type"] == "end":
if msg["type"] == "start":
self._ws_responses_received += 1
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
if self._ws_responses_received == self._ws_requests_sent:
started = True
request_id = msg["request_id"]
elif self._ws_responses_received > self._ws_requests_sent:
raise Exception("Received more responses than requests")
elif msg["type"] == "end" and msg["request_id"] == request_id:
break
else:
continue
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
elif chunk_idx == _audio_begins_at(options.format):
metrics.set_timer("time-to-first-audio", time.perf_counter() - start)
yield chunk
elif started:
chunk_idx += 1
if chunk_idx == _audio_begins_at(options.format):
metrics.set_timer("time-to-first-audio", time.perf_counter() - start)
yield chunk
metrics.finish_ok()
break
except Exception as e:
Expand Down
30 changes: 23 additions & 7 deletions pyht/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import tempfile
import threading
import time
import uuid
from websockets.sync.client import connect, ClientConnection
from websockets.exceptions import ConnectionClosed

Expand Down Expand Up @@ -384,6 +383,8 @@ def lease_factory() -> Lease:
self._api_key = api_key
self._inference_coordinates: Optional[Dict[str, Any]] = None
self._ws: Optional[ClientConnection] = None
self._ws_requests_sent = 0
self._ws_responses_received = 0

if self._advanced.congestion_ctrl == CongestionCtrl.STATIC_MAR_2023:
self._max_attempts = 3
Expand Down Expand Up @@ -715,34 +716,49 @@ def _tts_ws(
assert self._inference_coordinates is not None, "No connection"
metrics.append("text", str(text)).append("endpoint",
str(self._inference_coordinates[voice_engine]["websocket_url"]))
request_id = str(uuid.uuid4())
json_data = http_prepare_dict(text, options, voice_engine)
json_data["request_id"] = request_id

for attempt in range(1, self._max_attempts + 1):
try:
assert self._inference_coordinates is not None, "No connection"
ws_address = self._inference_coordinates[voice_engine]["websocket_url"]
if self._ws is None:
self._ws = connect(ws_address)
self._ws_requests_sent = 0
self._ws_responses_received = 0
try:
self._ws.send(json.dumps(json_data))
self._ws_requests_sent += 1
except ConnectionClosed as e:
logging.debug(f"Reconnecting websocket which closed unexpectedly: {e}")
self._ws = connect(ws_address)
self._ws_requests_sent = 0
self._ws_responses_received = 0
self._ws.send(json.dumps(json_data))
self._ws_requests_sent += 1
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
chunk_idx = -1
request_id = -1
started = False
for chunk in self._ws:
chunk_idx += 1
if isinstance(chunk, str):
msg = json.loads(chunk)
if msg["type"] == "end":
if msg["type"] == "start":
self._ws_responses_received += 1
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
if self._ws_responses_received == self._ws_requests_sent:
started = True
request_id = msg["request_id"]
elif self._ws_responses_received > self._ws_requests_sent:
raise Exception("Received more responses than requests")
elif msg["type"] == "end" and msg["request_id"] == request_id:
break
else:
continue
bryananderson marked this conversation as resolved.
Show resolved Hide resolved
elif chunk_idx == _audio_begins_at(options.format):
metrics.set_timer("time-to-first-audio", time.perf_counter() - start)
yield chunk
elif started:
chunk_idx += 1
if chunk_idx == _audio_begins_at(options.format):
metrics.set_timer("time-to-first-audio", time.perf_counter() - start)
yield chunk
metrics.finish_ok()
break
except Exception as e:
Expand Down