Skip to content

Commit

Permalink
Fix support for Python WebSocket >=14 while preserving backward compa…
Browse files Browse the repository at this point in the history
…tibility

Python websockets did a breaking change with version 14.
"extra_headers" was renamed to "additionnal_headers".
  • Loading branch information
fviard committed Jan 27, 2025
1 parent ad276e1 commit fe44f8a
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions deepgram/clients/common/v1/abstract_async_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from abc import ABC, abstractmethod

import websockets
from websockets.client import WebSocketClientProtocol

from ....audio import Speaker
from ....utils import verboselogs
Expand All @@ -25,6 +24,8 @@
)
from .websocket_events import WebSocketEvents

WEBSOCKETS_CURRENT_MAJOR_VERSION = int(websockets.version.version.split(".", 1)[0])

ONE_SECOND = 1
HALF_SECOND = 0.5
DEEPGRAM_INTERVAL = 5
Expand All @@ -44,7 +45,7 @@ class AbstractAsyncWebSocketClient(ABC): # pylint: disable=too-many-instance-at
_endpoint: str
_websocket_url: str

_socket: Optional[WebSocketClientProtocol] = None
_socket: Optional[websockets.connect] = None

_listen_thread: Union[asyncio.Task, None]
_delegate: Optional[Speaker] = None
Expand Down Expand Up @@ -134,10 +135,20 @@ async def start(
url_with_params = append_query_params(self._websocket_url, combined_options)

try:
ws_connect_kwargs: Dict = {
"ping_interval": PING_INTERVAL,
}

# Backward compatibility support with older versions of websockets.
# "extra_headers" was renamed to "additional_headers" in Python Websockets version 14
if WEBSOCKETS_CURRENT_MAJOR_VERSION < 14:
ws_connect_kwargs["extra_headers"] = combined_headers
else:
ws_connect_kwargs["additional_headers"] = combined_headers

self._socket = await websockets.connect(
url_with_params,
extra_headers=combined_headers,
ping_interval=PING_INTERVAL,
**ws_connect_kwargs,
)
self._exit_event.clear()

Expand Down

0 comments on commit fe44f8a

Please sign in to comment.