Skip to content

Commit d330f61

Browse files
author
dvonthenen
committed
Make All Async/Await Deprecated
1 parent 3fbf383 commit d330f61

File tree

31 files changed

+1355
-219
lines changed

31 files changed

+1355
-219
lines changed

deepgram/__init__.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,18 @@
1111

1212
# live
1313
from .clients.live.enums import LiveTranscriptionEvents
14-
from .clients.live.client import LiveClient, LegacyLiveClient, LiveOptions
14+
from .clients.live.client import LiveClient, AsyncLiveClient, LiveOptions
15+
16+
# onprem
17+
from .clients.onprem.client import (
18+
OnPremClient,
19+
AsyncOnPremClient,
20+
)
1521

1622
# prerecorded
1723
from .clients.prerecorded.client import (
1824
PreRecordedClient,
25+
AsyncPreRecordedClient,
1926
PrerecordedOptions,
2027
PrerecordedSource,
2128
FileSource,
@@ -25,6 +32,7 @@
2532
# manage
2633
from .clients.manage.client import (
2734
ManageClient,
35+
AsyncManageClient,
2836
ProjectOptions,
2937
KeyOptions,
3038
ScopeOptions,

deepgram/client.py

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,18 @@
77
import logging, verboselogs
88
import os
99

10-
from .clients.live.client import LiveOptions
11-
from .clients.prerecorded.client import PrerecordedOptions
12-
from .clients.listen import ListenClient, PreRecordedClient
13-
from .clients.manage.client import ManageClient
10+
from .clients.listen import (
11+
ListenClient,
12+
PreRecordedClient,
13+
AsyncLiveClient,
14+
AsyncPreRecordedClient,
15+
PrerecordedOptions,
16+
LiveOptions,
17+
)
1418
from .clients.onprem.client import OnPremClient
19+
from .clients.onprem.v1.async_client import AsyncOnPremClient
20+
from .clients.manage.client import ManageClient
21+
from .clients.manage.v1.async_client import AsyncManageClient
1522

1623
from .options import DeepgramClientOptions
1724
from .errors import DeepgramApiKeyError, DeepgramModuleError
@@ -66,10 +73,18 @@ def listen(self):
6673
def manage(self):
6774
return self.Version(self.config, "manage")
6875

76+
@property
77+
def asyncmanage(self):
78+
return self.Version(self.config, "asyncmanage")
79+
6980
@property
7081
def onprem(self):
7182
return self.Version(self.config, "onprem")
7283

84+
@property
85+
def asynconprem(self):
86+
return self.Version(self.config, "asynconprem")
87+
7388
# INTERNAL CLASSES
7489
class Version:
7590
def __init__(self, config, parent: str):
@@ -99,19 +114,33 @@ def v(self, version: str = ""):
99114
self.logger.debug("Version.v LEAVE")
100115
raise DeepgramModuleError("Invalid module version")
101116

117+
parent = ""
118+
fileName = ""
102119
className = ""
103120
match self.parent:
104121
case "manage":
122+
parent = "manage"
123+
fileName = "client"
105124
className = "ManageClient"
125+
case "asyncmanage":
126+
parent = "manage"
127+
fileName = "async_client"
128+
className = "AsyncManageClient"
106129
case "onprem":
130+
parent = "onprem"
131+
fileName = "client"
107132
className = "OnPremClient"
133+
case "asynconprem":
134+
parent = "onprem"
135+
fileName = "async_client"
136+
className = "AsyncOnPremClient"
108137
case _:
109138
self.logger.error("parent unknown: %s", self.parent)
110139
self.logger.debug("Version.v LEAVE")
111140
raise DeepgramModuleError("Invalid parent type")
112141

113142
# create class path
114-
path = f"deepgram.clients.{self.parent}.v{version}.client"
143+
path = f"deepgram.clients.{parent}.v{version}.{fileName}"
115144
self.logger.info("path: %s", path)
116145
self.logger.info("className: %s", className)
117146

deepgram/clients/abstract_client.py renamed to deepgram/clients/abstract_async_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from .errors import DeepgramError, DeepgramApiError, DeepgramUnknownApiError
1010

1111

12-
class AbstractRestfulClient:
12+
class AbstractAsyncRestClient:
1313
"""
1414
An abstract base class for a RESTful HTTP client.
1515
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copyright 2023 Deepgram SDK contributors. All Rights Reserved.
2+
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
3+
# SPDX-License-Identifier: MIT
4+
5+
import httpx
6+
import json
7+
8+
from ..options import DeepgramClientOptions
9+
from .errors import DeepgramError, DeepgramApiError, DeepgramUnknownApiError
10+
11+
12+
class AbstractSyncRestClient:
13+
"""
14+
An abstract base class for a RESTful HTTP client.
15+
16+
This class provides common HTTP methods (GET, POST, PUT, PATCH, DELETE) for making asynchronous HTTP requests.
17+
It handles error responses and provides basic JSON parsing.
18+
19+
Args:
20+
url (Dict[str, str]): The base URL for the RESTful API, including any path segments.
21+
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.
22+
23+
Attributes:
24+
url (Dict[str, str]): The base URL for the RESTful API.
25+
client (httpx.AsyncClient): An asynchronous HTTP client for making requests.
26+
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.
27+
28+
Exceptions:
29+
DeepgramApiError: Raised for known API errors.
30+
DeepgramUnknownApiError: Raised for unknown API errors.
31+
"""
32+
33+
def __init__(self, config: DeepgramClientOptions):
34+
if config is None:
35+
raise DeepgramError("Config are required")
36+
37+
self.config = config
38+
39+
def get(self, url: str, options=None):
40+
return self._handle_request(
41+
"GET", url, params=options, headers=self.config.headers
42+
)
43+
44+
def post(self, url: str, options=None, **kwargs):
45+
return self._handle_request(
46+
"POST", url, params=options, headers=self.config.headers, **kwargs
47+
)
48+
49+
def put(self, url: str, options=None, **kwargs):
50+
return self._handle_request(
51+
"PUT", url, params=options, headers=self.config.headers, **kwargs
52+
)
53+
54+
def patch(self, url: str, options=None, **kwargs):
55+
return self._handle_request(
56+
"PATCH", url, params=options, headers=self.config.headers, **kwargs
57+
)
58+
59+
def delete(self, url: str):
60+
return self._handle_request("DELETE", url, headers=self.config.headers)
61+
62+
def _handle_request(self, method, url, **kwargs):
63+
try:
64+
with httpx.Client() as client:
65+
response = client.request(method, url, **kwargs)
66+
response.raise_for_status()
67+
return response.text
68+
except httpx._exceptions.HTTPError as e:
69+
if isinstance(e, httpx.HTTPStatusError):
70+
status_code = e.response.status_code or 500
71+
try:
72+
json_object = json.loads(e.response.text)
73+
raise DeepgramApiError(
74+
json_object.get("message"), status_code, json.dumps(json_object)
75+
) from e
76+
except json.decoder.JSONDecodeError:
77+
raise DeepgramUnknownApiError(e.response.text, status_code) from e
78+
except ValueError as e:
79+
raise DeepgramUnknownApiError(e.response.text, status_code) from e
80+
else:
81+
raise
82+
except Exception as e:
83+
raise

deepgram/clients/listen.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,37 @@
77

88
from ..options import DeepgramClientOptions
99

10-
from .prerecorded.client import PreRecordedClient
11-
from .live.client import LiveClient, LegacyLiveClient
10+
from .prerecorded.client import (
11+
PreRecordedClient,
12+
AsyncPreRecordedClient,
13+
PrerecordedOptions,
14+
)
15+
from .live.client import LiveClient, AsyncLiveClient, LiveOptions
1216
from .errors import DeepgramModuleError
1317

1418

1519
class ListenClient:
1620
def __init__(self, config: DeepgramClientOptions):
21+
self.logger = logging.getLogger(__name__)
22+
self.logger.addHandler(logging.StreamHandler())
23+
self.logger.setLevel(config.verbose)
1724
self.config = config
1825

1926
@property
2027
def prerecorded(self):
2128
return self.Version(self.config, "prerecorded")
2229

30+
@property
31+
def asyncprerecorded(self):
32+
return self.Version(self.config, "asyncprerecorded")
33+
2334
@property
2435
def live(self):
2536
return self.Version(self.config, "live")
2637

2738
@property
28-
def legacylive(self):
29-
return LegacyLiveClient(self.config)
39+
def asynclive(self):
40+
return self.Version(self.config, "asynclive")
3041

3142
# INTERNAL CLASSES
3243
class Version:
@@ -57,19 +68,33 @@ def v(self, version: str = ""):
5768
self.logger.debug("Version.v LEAVE")
5869
raise DeepgramModuleError("Invalid module version")
5970

71+
parent = ""
72+
fileName = ""
6073
className = ""
6174
match self.parent:
6275
case "live":
76+
parent = "live"
77+
fileName = "client"
6378
className = "LiveClient"
79+
case "asynclive":
80+
parent = "live"
81+
fileName = "async_client"
82+
className = "AsyncLiveClient"
6483
case "prerecorded":
84+
parent = "prerecorded"
85+
fileName = "client"
6586
className = "PreRecordedClient"
87+
case "asyncprerecorded":
88+
parent = "prerecorded"
89+
fileName = "async_client"
90+
className = "AsyncPreRecordedClient"
6691
case _:
6792
self.logger.error("parent unknown: %s", self.parent)
6893
self.logger.debug("Version.v LEAVE")
6994
raise DeepgramModuleError("Invalid parent type")
7095

7196
# create class path
72-
path = f"deepgram.clients.{self.parent}.v{version}.client"
97+
path = f"deepgram.clients.{parent}.v{version}.{fileName}"
7398
self.logger.info("path: %s", path)
7499
self.logger.info("className: %s", className)
75100

deepgram/clients/live/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# SPDX-License-Identifier: MIT
44

55
from .v1.client import LiveClient as LiveClientLatest
6-
from .v1.legacy_client import LegacyLiveClient as LegacyLiveClientLatest
6+
from .v1.async_client import AsyncLiveClient as AsyncLiveClientLatest
77
from .v1.options import LiveOptions as LiveOptionsLatest
88

99
"""
@@ -25,7 +25,7 @@ def __init__(self, config):
2525
super().__init__(config)
2626

2727

28-
class LegacyLiveClient(LegacyLiveClientLatest):
28+
class AsyncLiveClient(AsyncLiveClientLatest):
2929
"""
3030
Please see LiveClientLatest for details
3131
"""

deepgram/clients/live/helpers.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33
# SPDX-License-Identifier: MIT
44

55
from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
6-
from typing import Dict
7-
8-
from .errors import DeepgramError
96

107

118
def append_query_params(url, params):

deepgram/clients/live/v1/legacy_client.py renamed to deepgram/clients/live/v1/async_client.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from .options import LiveOptions
1515

1616

17-
class LegacyLiveClient:
17+
class AsyncLiveClient:
1818
"""
1919
Client for interacting with Deepgram's live transcription services over WebSockets.
2020
@@ -51,7 +51,7 @@ def __init__(self, config: DeepgramClientOptions):
5151
self.websocket_url = convert_to_websocket_url(self.config.url, self.endpoint)
5252

5353
async def __call__(self, options: LiveOptions = None):
54-
self.logger.debug("LegacyLiveClient.__call__ ENTER")
54+
self.logger.debug("AsyncLiveClient.__call__ ENTER")
5555
self.logger.info("options: %s", options)
5656

5757
self.options = options
@@ -65,12 +65,12 @@ async def __call__(self, options: LiveOptions = None):
6565
asyncio.create_task(self._start())
6666

6767
self.logger.notice("__call__ succeeded")
68-
self.logger.debug("LegacyLiveClient.__call__ LEAVE")
68+
self.logger.debug("AsyncLiveClient.__call__ LEAVE")
6969
return self
7070
except websockets.ConnectionClosed as e:
7171
await self._emit(LiveTranscriptionEvents.Close, e.code)
7272
self.logger.notice("exception: websockets.ConnectionClosed")
73-
self.logger.debug("LegacyLiveClient.__call__ LEAVE")
73+
self.logger.debug("AsyncLiveClient.__call__ LEAVE")
7474

7575
def on(self, event, handler): # registers event handlers for specific events
7676
if event in LiveTranscriptionEvents and callable(handler):
@@ -83,7 +83,7 @@ async def _emit(
8383
handler(*args, **kwargs)
8484

8585
async def _start(self) -> None:
86-
self.logger.debug("LegacyLiveClient._start ENTER")
86+
self.logger.debug("AsyncLiveClient._start ENTER")
8787

8888
async for message in self._socket:
8989
try:
@@ -113,20 +113,20 @@ async def _start(self) -> None:
113113
except json.JSONDecodeError as e:
114114
await self._emit(LiveTranscriptionEvents.Error, e.code)
115115
self.logger.error("exception: json.JSONDecodeError: %s", str(e))
116-
self.logger.debug("LegacyLiveClient._start LEAVE")
116+
self.logger.debug("AsyncLiveClient._start LEAVE")
117117

118118
async def send(self, data):
119-
self.logger.spam("LegacyLiveClient.send ENTER")
119+
self.logger.spam("AsyncLiveClient.send ENTER")
120120
self.logger.spam("data: %s", data)
121121

122122
if self._socket:
123123
await self._socket.send(data)
124124
self.logger.spam("data sent")
125125

126-
self.logger.spam("LegacyLiveClient.send LEAVE")
126+
self.logger.spam("AsyncLiveClient.send LEAVE")
127127

128128
async def finish(self):
129-
self.logger.debug("LegacyLiveClient.finish LEAVE")
129+
self.logger.debug("AsyncLiveClient.finish LEAVE")
130130

131131
if self._socket:
132132
self.logger.notice("send CloseStream...")
@@ -136,7 +136,7 @@ async def finish(self):
136136
self.logger.notice("socket.wait_closed succeeded")
137137

138138
self.logger.notice("finish succeeded")
139-
self.logger.debug("LegacyLiveClient.finish LEAVE")
139+
self.logger.debug("AsyncLiveClient.finish LEAVE")
140140

141141

142142
async def _socket_connect(websocket_url, headers):

deepgram/clients/manage/client.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# SPDX-License-Identifier: MIT
44

55
from .v1.client import ManageClient as ManageClientLatest
6+
from .v1.async_client import AsyncManageClient as AsyncManageClientLatest
67
from .v1.options import (
78
ProjectOptions as ProjectOptionsLatest,
89
KeyOptions as KeyOptionsLatest,
@@ -54,3 +55,12 @@ class ManageClient(ManageClientLatest):
5455

5556
def __init__(self, config):
5657
super().__init__(config)
58+
59+
60+
class AsyncManageClient(AsyncManageClientLatest):
61+
"""
62+
Please see AsyncManageClientLatest for details
63+
"""
64+
65+
def __init__(self, config):
66+
super().__init__(config)

0 commit comments

Comments
 (0)