generated from deepgram/oss-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathclient.py
638 lines (567 loc) · 16.3 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT
from typing import Optional
from importlib import import_module
import os
import logging
import deprecation # type: ignore
from . import __version__
from .utils import verboselogs
# common
# pylint: disable=unused-import
from .clients import (
TextSource,
BufferSource,
StreamSource,
FileSource,
UrlSource,
)
from .clients import BaseResponse
from .clients import (
Average,
Intent,
Intents,
IntentsInfo,
Segment,
SentimentInfo,
Sentiment,
Sentiments,
SummaryInfo,
Topic,
Topics,
TopicsInfo,
)
from .clients import (
ModelInfo,
Hit,
Search,
)
from .clients import (
OpenResponse,
CloseResponse,
UnhandledResponse,
ErrorResponse,
)
from .clients import (
DeepgramError,
DeepgramTypeError,
DeepgramModuleError,
DeepgramApiError,
DeepgramUnknownApiError,
)
# listen client
from .clients import ListenRouter, ReadRouter, SpeakRouter, AgentRouter
# speech-to-text
from .clients import LiveClient, AsyncLiveClient # backward compat
from .clients import (
ListenWebSocketClient,
AsyncListenWebSocketClient,
)
from .clients import (
ListenWebSocketOptions,
LiveOptions,
LiveTranscriptionEvents,
)
# live client responses
from .clients import (
#### top level
LiveResultResponse,
ListenWSMetadataResponse,
SpeechStartedResponse,
UtteranceEndResponse,
#### common websocket response
# OpenResponse,
# CloseResponse,
# ErrorResponse,
# UnhandledResponse,
#### unique
ListenWSMetadata,
ListenWSAlternative,
ListenWSChannel,
ListenWSWord,
)
# prerecorded
from .clients import (
# common
# UrlSource,
# BufferSource,
# StreamSource,
# TextSource,
# FileSource,
# unique
PreRecordedStreamSource,
PrerecordedSource,
ListenRestSource,
)
from .clients import (
PreRecordedClient,
AsyncPreRecordedClient,
) # backward compat
from .clients import (
ListenRESTClient,
AsyncListenRESTClient,
)
from .clients import (
ListenRESTOptions,
PrerecordedOptions,
)
# rest client responses
from .clients import (
#### top level
AsyncPrerecordedResponse,
PrerecordedResponse,
SyncPrerecordedResponse,
#### shared
# Average,
# Intent,
# Intents,
# IntentsInfo,
# Segment,
# SentimentInfo,
# Sentiment,
# Sentiments,
# SummaryInfo,
# Topic,
# Topics,
# TopicsInfo,
#### between rest and websocket
# ModelInfo,
# Alternative,
# Hit,
# Search,
# Channel,
# Word,
# unique
Entity,
ListenRESTMetadata,
Paragraph,
Paragraphs,
ListenRESTResults,
Sentence,
Summaries,
SummaryV1,
SummaryV2,
Translation,
Utterance,
Warning,
ListenRESTAlternative,
ListenRESTChannel,
ListenRESTWord,
)
# read
from .clients import ReadClient, AsyncReadClient
from .clients import AnalyzeClient, AsyncAnalyzeClient
from .clients import (
AnalyzeOptions,
AnalyzeStreamSource,
AnalyzeSource,
)
# read client responses
from .clients import (
#### top level
AsyncAnalyzeResponse,
SyncAnalyzeResponse,
AnalyzeResponse,
#### shared
# Average,
# Intent,
# Intents,
# IntentsInfo,
# Segment,
# SentimentInfo,
# Sentiment,
# Sentiments,
# SummaryInfo,
# Topic,
# Topics,
# TopicsInfo,
#### unique
AnalyzeMetadata,
AnalyzeResults,
AnalyzeSummary,
)
# speak
## speak REST
from .clients import (
#### top level
SpeakRESTOptions,
SpeakOptions, # backward compat
#### common
# TextSource,
# BufferSource,
# StreamSource,
# FileSource,
#### unique
SpeakSource,
SpeakRestSource,
SpeakRESTSource,
)
from .clients import (
SpeakClient, # backward compat
SpeakRESTClient,
AsyncSpeakRESTClient,
)
from .clients import (
SpeakResponse, # backward compat
SpeakRESTResponse,
)
## speak WebSocket
from .clients import SpeakWebSocketEvents, SpeakWebSocketMessage
from .clients import (
SpeakWSOptions,
)
from .clients import (
SpeakWebSocketClient,
AsyncSpeakWebSocketClient,
SpeakWSClient,
AsyncSpeakWSClient,
)
from .clients import (
#### top level
SpeakWSMetadataResponse,
FlushedResponse,
ClearedResponse,
WarningResponse,
#### common websocket response
# OpenResponse,
# CloseResponse,
# UnhandledResponse,
# ErrorResponse,
)
# manage client classes/input
from .clients import ManageClient, AsyncManageClient
from .clients import (
ProjectOptions,
KeyOptions,
ScopeOptions,
InviteOptions,
UsageRequestOptions,
UsageSummaryOptions,
UsageFieldsOptions,
)
# manage client responses
from .clients import (
#### top level
Message,
ProjectsResponse,
ModelResponse,
ModelsResponse,
MembersResponse,
KeyResponse,
KeysResponse,
ScopesResponse,
InvitesResponse,
UsageRequest,
UsageResponse,
UsageRequestsResponse,
UsageSummaryResponse,
UsageFieldsResponse,
BalancesResponse,
#### shared
Project,
STTDetails,
TTSMetadata,
TTSDetails,
Member,
Key,
Invite,
Config,
STTUsageDetails,
Callback,
TokenDetail,
SpeechSegment,
TTSUsageDetails,
STTTokens,
TTSTokens,
UsageSummaryResults,
Resolution,
UsageModel,
Balance,
)
# on-prem
from .clients import (
OnPremClient,
AsyncOnPremClient,
SelfHostedClient,
AsyncSelfHostedClient,
)
# agent
from .clients import AgentWebSocketEvents
# websocket
from .clients import (
AgentWebSocketClient,
AsyncAgentWebSocketClient,
)
from .clients import (
#### common websocket response
# OpenResponse,
# CloseResponse,
# ErrorResponse,
# UnhandledResponse,
#### unique
WelcomeResponse,
SettingsAppliedResponse,
ConversationTextResponse,
UserStartedSpeakingResponse,
AgentThinkingResponse,
FunctionCalling,
FunctionCallRequest,
AgentStartedSpeakingResponse,
AgentAudioDoneResponse,
InjectionRefusedResponse,
)
from .clients import (
# top level
SettingsConfigurationOptions,
UpdateInstructionsOptions,
UpdateSpeakOptions,
InjectAgentMessageOptions,
FunctionCallResponse,
AgentKeepAlive,
# sub level
Listen,
Speak,
Header,
Item,
Properties,
Parameters,
Function,
Provider,
Think,
Agent,
Input,
Output,
Audio,
Context,
)
# client errors and options
from .options import DeepgramClientOptions, ClientOptionsFromEnv
from .errors import DeepgramApiKeyError
# pylint: enable=unused-import
class Deepgram: # pylint: disable=broad-exception-raised
"""
The Deepgram class is no longer a class in version 3 of this SDK.
"""
def __init__(self, *anything):
raise Exception(
"""
FATAL ERROR:
You are attempting to instantiate a Deepgram object, which is no longer a class in version 3 of this SDK.
To fix this issue:
1. You need to revert to the previous version 2 of the SDK: pip install deepgram-sdk==2.12.0
2. or, update your application's code to use version 3 of this SDK. See the README for more information.
Things to consider:
- This Version 3 of the SDK requires Python 3.10 or higher.
Older versions (3.9 and lower) of Python are nearing end-of-life: https://devguide.python.org/versions/
Understand the risks of using a version of Python nearing EOL.
- Version 2 of the SDK will receive maintenance updates in the form of security fixes only.
No new features will be added to version 2 of the SDK.
"""
)
class DeepgramClient:
"""
Represents a client for interacting with the Deepgram API.
This class provides a client for making requests to the Deepgram API with various configuration options.
Attributes:
api_key (str): The Deepgram API key used for authentication.
config_options (DeepgramClientOptions): An optional configuration object specifying client options.
Raises:
DeepgramApiKeyError: If the API key is missing or invalid.
Methods:
listen: Returns a ListenClient instance for interacting with Deepgram's transcription services.
manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources.
selfhosted: (Preferred) Returns an Threaded SelfHostedClient instance for interacting with Deepgram's on-premises API.
asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources.
asyncselfhosted: Returns an (Async) SelfHostedClient instance for interacting with Deepgram's on-premises API.
"""
_config: DeepgramClientOptions
_logger: verboselogs.VerboseLogger
def __init__(
self,
api_key: str = "",
config: Optional[DeepgramClientOptions] = None,
):
self._logger = verboselogs.VerboseLogger(__name__)
self._logger.addHandler(logging.StreamHandler())
if api_key == "" and config is not None:
self._logger.info("Attempting to set API key from config object")
api_key = config.api_key
if api_key == "":
self._logger.info("Attempting to set API key from environment variable")
api_key = os.getenv("DEEPGRAM_API_KEY", "")
if api_key == "":
self._logger.warning("WARNING: API key is missing")
self.api_key = api_key
if config is None: # Use default configuration
self._config = DeepgramClientOptions(self.api_key)
else:
config.set_apikey(self.api_key)
self._config = config
@property
def listen(self):
"""
Returns a Listen dot-notation router for interacting with Deepgram's transcription services.
"""
return ListenRouter(self._config)
@property
def read(self):
"""
Returns a Read dot-notation router for interacting with Deepgram's read services.
"""
return ReadRouter(self._config)
@property
def speak(self):
"""
Returns a Speak dot-notation router for interacting with Deepgram's speak services.
"""
return SpeakRouter(self._config)
@property
@deprecation.deprecated(
deprecated_in="3.4.0",
removed_in="4.0.0",
current_version=__version__,
details="deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.",
)
def asyncspeak(self):
"""
DEPRECATED: deepgram.asyncspeak is deprecated. Use deepgram.speak.asyncrest instead.
"""
return self.Version(self._config, "asyncspeak")
@property
def manage(self):
"""
Returns a ManageClient instance for managing Deepgram resources.
"""
return self.Version(self._config, "manage")
@property
def asyncmanage(self):
"""
Returns an AsyncManageClient instance for managing Deepgram resources.
"""
return self.Version(self._config, "asyncmanage")
@property
@deprecation.deprecated(
deprecated_in="3.4.0",
removed_in="4.0.0",
current_version=__version__,
details="deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.",
)
def onprem(self):
"""
DEPRECATED: deepgram.onprem is deprecated. Use deepgram.speak.selfhosted instead.
"""
return self.Version(self._config, "selfhosted")
@property
def selfhosted(self):
"""
Returns an SelfHostedClient instance for interacting with Deepgram's on-premises API.
"""
return self.Version(self._config, "selfhosted")
@property
@deprecation.deprecated(
deprecated_in="3.4.0",
removed_in="4.0.0",
current_version=__version__,
details="deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.",
)
def asynconprem(self):
"""
DEPRECATED: deepgram.asynconprem is deprecated. Use deepgram.speak.asyncselfhosted instead.
"""
return self.Version(self._config, "asyncselfhosted")
@property
def asyncselfhosted(self):
"""
Returns an AsyncSelfHostedClient instance for interacting with Deepgram's on-premises API.
"""
return self.Version(self._config, "asyncselfhosted")
@property
def agent(self):
"""
Returns a Agent dot-notation router for interacting with Deepgram's speak services.
"""
return AgentRouter(self._config)
# INTERNAL CLASSES
class Version:
"""
Represents a version of the Deepgram API.
"""
_logger: verboselogs.VerboseLogger
_config: DeepgramClientOptions
_parent: str
def __init__(self, config, parent: str):
self._logger = verboselogs.VerboseLogger(__name__)
self._logger.addHandler(logging.StreamHandler())
self._logger.setLevel(config.verbose)
self._config = config
self._parent = parent
# FUTURE VERSIONING:
# When v2 or v1.1beta1 or etc. This allows easy access to the latest version of the API.
# @property
# def latest(self):
# match self._parent:
# case "manage":
# return ManageClient(self._config)
# case "selfhosted":
# return SelfHostedClient(self._config)
# case _:
# raise DeepgramModuleError("Invalid parent")
def v(self, version: str = ""):
# pylint: disable-msg=too-many-statements
"""
Returns a client for the specified version of the API.
"""
self._logger.debug("Version.v ENTER")
self._logger.info("version: %s", version)
if len(version) == 0:
self._logger.error("version is empty")
self._logger.debug("Version.v LEAVE")
raise DeepgramModuleError("Invalid module version")
parent = ""
filename = ""
classname = ""
match self._parent:
case "manage":
parent = "manage"
filename = "client"
classname = "ManageClient"
case "asyncmanage":
parent = "manage"
filename = "async_client"
classname = "AsyncManageClient"
case "asyncspeak":
return AsyncSpeakRESTClient(self._config)
case "selfhosted":
parent = "selfhosted"
filename = "client"
classname = "SelfHostedClient"
case "asyncselfhosted":
parent = "selfhosted"
filename = "async_client"
classname = "AsyncSelfHostedClient"
case _:
self._logger.error("parent unknown: %s", self._parent)
self._logger.debug("Version.v LEAVE")
raise DeepgramModuleError("Invalid parent type")
# create class path
path = f"deepgram.clients.{parent}.v{version}.{filename}"
self._logger.info("path: %s", path)
self._logger.info("classname: %s", classname)
# import class
mod = import_module(path)
if mod is None:
self._logger.error("module path is None")
self._logger.debug("Version.v LEAVE")
raise DeepgramModuleError("Unable to find package")
my_class = getattr(mod, classname)
if my_class is None:
self._logger.error("my_class is None")
self._logger.debug("Version.v LEAVE")
raise DeepgramModuleError("Unable to find class")
# instantiate class
my_class_instance = my_class(self._config)
self._logger.notice("Version.v succeeded")
self._logger.debug("Version.v LEAVE")
return my_class_instance
# pylint: enable-msg=too-many-statements