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

Updates to README, examples, and More PyDocs #209

Merged
merged 1 commit into from
Dec 15, 2023
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
1,010 changes: 84 additions & 926 deletions README.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions deepgram/audio/microphone/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

import logging, verboselogs

"""
constants for microphone
"""
LOGGING = logging.WARNING
CHANNELS = 1
RATE = 16000
Expand Down
5 changes: 1 addition & 4 deletions deepgram/audio/microphone/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT


# exceptions for microphone
class DeepgramMicrophoneError(Exception):
"""
Exception raised for known errors related to Microphone library.

Attributes:
message (str): The error message describing the exception.
status (str): The HTTP status associated with the API error.
original_error (str - json): The original error that was raised.
"""

def __init__(self, message: str):
super().__init__(message)
self.name = "DeepgramMicrophoneError"
Expand Down
28 changes: 20 additions & 8 deletions deepgram/audio/microphone/microphone.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from .errors import DeepgramMicrophoneError
from .constants import LOGGING, CHANNELS, RATE, CHUNK


class Microphone:
"""
This implements a microphone for local audio input. This uses PyAudio under the hood.
Expand All @@ -25,6 +24,7 @@ def __init__(
chunk=CHUNK,
channels=CHANNELS,
):
# dynamic import of pyaudio as not to force the requirements on the SDK (and users)
import pyaudio

self.logger = logging.getLogger(__name__)
Expand All @@ -40,6 +40,9 @@ def __init__(
self.stream = None

def is_active(self):
"""
returns True if the stream is active, False otherwise
"""
self.logger.debug("Microphone.is_active ENTER")
if self.stream is None:
self.logger.error("stream is None")
Expand All @@ -52,6 +55,9 @@ def is_active(self):
return

def start(self):
"""
starts the microphone stream
"""
self.logger.debug("Microphone.start ENTER")

if self.stream is not None:
Expand All @@ -76,14 +82,17 @@ def start(self):
self.lock = threading.Lock()

self.stream.start_stream()
self.thread = threading.Thread(target=self.processing)
self.thread = threading.Thread(target=self._processing)
self.thread.start()

self.logger.notice("start succeeded")
self.logger.debug("Microphone.start LEAVE")

def processing(self):
self.logger.debug("Microphone.processing ENTER")
def _processing(self):
"""
the main processing loop for the microphone
"""
self.logger.debug("Microphone._processing ENTER")

try:
while True:
Expand All @@ -106,15 +115,18 @@ def processing(self):
self.logger.verbose("regular threaded callback")
self.push_callback(data)

self.logger.notice("processing exiting...")
self.logger.debug("Microphone.processing LEAVE")
self.logger.notice("_processing exiting...")
self.logger.debug("Microphone._processing LEAVE")

except Exception as e:
self.logger.error("Error while sending: %s", str(e))
self.logger.debug("Microphone.processing LEAVE")
self.logger.debug("Microphone._processing LEAVE")
raise

def finish(self):
"""
Stops the microphone stream
"""
self.logger.debug("Microphone.finish ENTER")

self.lock.acquire()
Expand All @@ -125,7 +137,7 @@ def finish(self):
if self.thread is not None:
self.thread.join()
self.thread = None
self.logger.notice("processing/send thread joined")
self.logger.notice("_processing/send thread joined")

if self.stream is not None:
self.stream.stop_stream()
Expand Down
8 changes: 6 additions & 2 deletions deepgram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,12 @@ class DeepgramClient:

Methods:
listen: Returns a ListenClient instance for interacting with Deepgram's transcription services.
manage: Returns a ManageClient instance for managing Deepgram resources.
onprem: Returns an OnPremClient instance for interacting with Deepgram's on-premises API.

manage: (Preferred) Returns a Threaded ManageClient instance for managing Deepgram resources.
onprem: (Preferred) Returns an Threaded OnPremClient instance for interacting with Deepgram's on-premises API.

asyncmanage: Returns an (Async) ManageClient instance for managing Deepgram resources.
asynconprem: Returns an (Async) OnPremClient instance for interacting with Deepgram's on-premises API.
"""

def __init__(
Expand Down
5 changes: 0 additions & 5 deletions deepgram/clients/abstract_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ class AbstractAsyncRestClient:
url (Dict[str, str]): The base URL for the RESTful API, including any path segments.
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.

Attributes:
url (Dict[str, str]): The base URL for the RESTful API.
client (httpx.AsyncClient): An asynchronous HTTP client for making requests.
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.

Exceptions:
DeepgramApiError: Raised for known API errors.
DeepgramUnknownApiError: Raised for unknown API errors.
Expand Down
7 changes: 2 additions & 5 deletions deepgram/clients/abstract_sync_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,8 @@ class AbstractSyncRestClient:
Args:
url (Dict[str, str]): The base URL for the RESTful API, including any path segments.
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.

Attributes:
url (Dict[str, str]): The base URL for the RESTful API.
client (httpx.AsyncClient): An asynchronous HTTP client for making requests.
headers (Optional[Dict[str, Any]]): Optional HTTP headers to include in requests.
params (Optional[Dict[str, Any]]): Optional query parameters to include in requests.
timeout (Optional[httpx.Timeout]): Optional timeout configuration for requests.

Exceptions:
DeepgramApiError: Raised for known API errors.
Expand Down
5 changes: 0 additions & 5 deletions deepgram/clients/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ class DeepgramError(Exception):

Attributes:
message (str): The error message describing the exception.
status (str): The HTTP status associated with the API error.
"""

def __init__(self, message: str):
super().__init__(message)
self.name = "DeepgramError"
Expand All @@ -28,7 +26,6 @@ class DeepgramModuleError(Exception):
Attributes:
message (str): The error message describing the exception.
"""

def __init__(self, message: str):
super().__init__(message)
self.name = "DeepgramModuleError"
Expand All @@ -43,7 +40,6 @@ class DeepgramApiError(Exception):
status (str): The HTTP status associated with the API error.
original_error (str - json): The original error that was raised.
"""

def __init__(self, message: str, status: str, original_error=None):
super().__init__(message)
self.name = "DeepgramApiError"
Expand All @@ -63,7 +59,6 @@ class DeepgramUnknownApiError(Exception):
message (str): The error message describing the exception.
status (str): The HTTP status associated with the API error.
"""

def __init__(self, message: str, status: str):
super().__init__(message, status)
self.name = "DeepgramUnknownApiError"
Expand Down
19 changes: 19 additions & 0 deletions deepgram/clients/listen.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,25 @@


class ListenClient:
"""
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:
live: (Preferred) Returns a Threaded LiveClient instance for interacting with Deepgram's transcription services.
prerecorded: (Preferred) Returns an Threaded PreRecordedClient instance for interacting with Deepgram's prerecorded transcription services.

asynclive: Returns an (Async) LiveClient instance for interacting with Deepgram's transcription services.
asyncprerecorded: Returns an (Async) PreRecordedClient instance for interacting with Deepgram's prerecorded transcription services.
"""
def __init__(self, config: DeepgramClientOptions):
self.logger = logging.getLogger(__name__)
self.logger.addHandler(logging.StreamHandler())
Expand Down
10 changes: 4 additions & 6 deletions deepgram/clients/live/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,26 @@
from .v1.options import LiveOptions as LiveOptionsLatest

"""
The client.py points to the current supported version in the SDK.
The vX/client.py points to the current supported version in the SDK.
Older versions are supported in the SDK for backwards compatibility.
"""


class LiveOptions(LiveOptionsLatest):
"""
pass through for LiveOptions based on API version
"""
pass


class LiveClient(LiveClientLatest):
"""
Please see LiveClientLatest for details
"""

def __init__(self, config):
super().__init__(config)


class AsyncLiveClient(AsyncLiveClientLatest):
"""
Please see LiveClientLatest for details
"""

def __init__(self, config):
super().__init__(config)
4 changes: 3 additions & 1 deletion deepgram/clients/live/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

from enum import Enum


"""
Constants mapping to events from the Deepgram API
"""
class LiveTranscriptionEvents(Enum):
Open = "open"
Close = "close"
Expand Down
4 changes: 0 additions & 4 deletions deepgram/clients/live/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ class DeepgramError(Exception):

Attributes:
message (str): The error message describing the exception.
status (str): The HTTP status associated with the API error.
"""

def __init__(self, message: str):
super().__init__(message)
self.name = "DeepgramError"
Expand All @@ -27,8 +25,6 @@ class DeepgramWebsocketError(Exception):

Attributes:
message (str): The error message describing the exception.
status (str): The HTTP status associated with the API error.
original_error (str - json): The original error that was raised.
"""

def __init__(self, message: str):
Expand Down
26 changes: 13 additions & 13 deletions deepgram/clients/live/v1/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,6 @@ class AsyncLiveClient:

Args:
config (DeepgramClientOptions): all the options for the client.

Attributes:
endpoint (str): The API endpoint for live transcription.
_socket (websockets.WebSocketClientProtocol): The WebSocket connection object.
_event_handlers (dict): Dictionary of event handlers for specific events.
websocket_url (str): The WebSocket URL used for connection.

Methods:
__call__: Establishes a WebSocket connection for live transcription.
on: Registers event handlers for specific events.
send: Sends data over the WebSocket connection.
finish: Closes the WebSocket connection gracefully.
"""

def __init__(self, config: DeepgramClientOptions):
Expand All @@ -51,6 +39,9 @@ def __init__(self, config: DeepgramClientOptions):
self.websocket_url = convert_to_websocket_url(self.config.url, self.endpoint)

async def __call__(self, options: LiveOptions = None):
"""
Establishes a WebSocket connection for live transcription.
"""
self.logger.debug("AsyncLiveClient.__call__ ENTER")
self.logger.info("options: %s", options)

Expand All @@ -72,7 +63,10 @@ async def __call__(self, options: LiveOptions = None):
self.logger.notice("exception: websockets.ConnectionClosed")
self.logger.debug("AsyncLiveClient.__call__ LEAVE")

def on(self, event, handler): # registers event handlers for specific events
def on(self, event, handler):
"""
Registers event handlers for specific events.
"""
if event in LiveTranscriptionEvents and callable(handler):
self._event_handlers[event].append(handler)

Expand Down Expand Up @@ -116,6 +110,9 @@ async def _start(self) -> None:
self.logger.debug("AsyncLiveClient._start LEAVE")

async def send(self, data):
"""
Sends data over the WebSocket connection.
"""
self.logger.spam("AsyncLiveClient.send ENTER")
self.logger.spam("data: %s", data)

Expand All @@ -126,6 +123,9 @@ async def send(self, data):
self.logger.spam("AsyncLiveClient.send LEAVE")

async def finish(self):
"""
Closes the WebSocket connection gracefully.
"""
self.logger.debug("AsyncLiveClient.finish LEAVE")

if self._socket:
Expand Down
Loading