diff --git a/README.md b/README.md index bacf2295..c68d042c 100644 --- a/README.md +++ b/README.md @@ -10,44 +10,12 @@ Official Python SDK for [Deepgram](https://www.deepgram.com/). Power your apps w - [Deepgram Python SDK](#deepgram-python-sdk) - [Documentation](#documentation) - [Getting an API Key](#getting-an-api-key) +- [Requirements](#requirements) - [Installation](#installation) +- [Quickstarts](#quickstarts) + - [PreRecorded Audio Transcription Quickstart](#prerecorded-audio-transcription-quickstart) + - [Live Audio Transcription Quickstart](#live-audio-transcription-quickstart) - [Examples](#examples) -- [Testing](#testing) -- [Configuration](#configuration) - - [Custom API Endpoint] [#custom-api-endpoint] -- [Transcription](#transcription) - - [Remote Files](#remote-files) - - [Local Files](#local-files) - - [Live Audio](#live-audio) - - [Parameters](#parameters) -- [Transcribing to captions](#transcribing-to-captions) -- [Projects](#projects) - - [Get Projects](#get-projects) - - [Get Project](#get-project) - - [Update Project](#update-project) -- [Keys](#keys) - - [List Keys](#list-keys) - - [Get Key](#get-key) - - [Create Key](#create-key) - - [Delete Key](#delete-key) -- [Members](#members) - - [Get Members](#get-members) - - [Remove Member](#remove-member) -- [Scopes](#scopes) - - [Get Member Scopes](#get-member-scopes) - - [Update Scope](#update-scope) -- [Invitations](#invitations) - - [List Invites](#list-invites) - - [Send Invite](#send-invite) - - [Delete Invite](#delete-invite) - - [Leave Project](#leave-project) -- [Usage](#usage) - - [Get All Requests](#get-all-requests) - - [Get Request](#get-request) - - [Get Fields](#get-fields) -- [Billing](#billing) - - [Get All Balances](#get-all-balances) - - [Get Balance](#get-balance) - [Development and Contributing](#development-and-contributing) - [Getting Help](#getting-help) @@ -59,941 +27,131 @@ You can learn more about the Deepgram API at [developers.deepgram.com](https://d 🔑 To access the Deepgram API you will need a [free Deepgram API Key](https://console.deepgram.com/signup?jump=keys). -# Installation - -```sh -pip install deepgram-sdk -``` - -# Examples - -To quickly get started with examples for prerecorded and streaming, run the files in the example folder. See the README in that folder for more information on getting started. - -# Testing - -## Setup - -Run the following command to install `pytest` and `pytest-cov` as dev dependencies. - -```sh -pip install -r requirements.txt -``` - -## Run All Tests - -## Setup - -```sh -pip install pytest -pip install pytest-cov -``` +# Requirements -## Run All Tests +[Python](https://www.python.org/downloads/) (version ^3.10) -```sh -pytest --api-key tests/ -``` +> **_NOTE:_** Althought many older versions should work. -## Test Coverage Report +# Installation ```sh -pytest --cov=deepgram --api-key tests/ -``` - -# Configuration - -To setup the configuration of the Deepgram Client, do the following: - -- Import the Deepgram client -- Create a Deepgram Client instance and pass in credentials to the constructor. - -```python -from deepgram import Deepgram - -DEEPGRAM_API_KEY = 'YOUR_API_KEY' -deepgram = Deepgram(DEEPGRAM_API_KEY) -``` - -## Custom API Endpoint - -In order to point the SDK at a different API environment (e.g., for on-prem deployments), you can pass in an object setting the `api_url` when initializing the Deepgram client. - -```python -dg_client = Deepgram({ - "api_key": DEEPGRAM_API_KEY, - "api_url": "http://localhost:8080/v1/listen" -}) -``` - -# Transcription - -## Remote Files - -```python -from deepgram import Deepgram -import asyncio, json - -DEEPGRAM_API_KEY = 'YOUR_API_KEY' -FILE_URL = 'https://static.deepgram.com/examples/interview_speech-analytics.wav' - -async def main(): - # Initializes the Deepgram SDK - deepgram = Deepgram(DEEPGRAM_API_KEY) - source = {'url': FILE_URL} - response = await asyncio.create_task( - deepgram.transcription.prerecorded(source, { - 'smart_format': True, - 'model': 'nova', - })) - print(json.dumps(response, indent=4)) - -asyncio.run(main()) -``` - -## Local Files - -```python -from deepgram import Deepgram -import json - -DEEPGRAM_API_KEY = 'YOUR_API_KEY' -PATH_TO_FILE = 'some/file.wav' - -def main(): - # Initializes the Deepgram SDK - deepgram = Deepgram(DEEPGRAM_API_KEY) - # Open the audio file - with open(PATH_TO_FILE, 'rb') as audio: - # ...or replace mimetype as appropriate - source = {'buffer': audio, 'mimetype': 'audio/wav'} - response = deepgram.transcription.sync_prerecorded(source, {'punctuate': True}) - print(json.dumps(response, indent=4)) - -main() -``` - -## Live Audio - -```python -from deepgram import Deepgram -import asyncio -import aiohttp - -# Your Deepgram API Key -DEEPGRAM_API_KEY = 'YOUR_API_KEY' - -# URL for the audio you would like to stream -URL = 'http://stream.live.vc.bbcmedia.co.uk/bbc_world_service' - -async def main(): - # Initialize the Deepgram SDK - deepgram = Deepgram(DEEPGRAM_API_KEY) - - # Create a websocket connection to Deepgram - # In this example, punctuation is turned on, interim results are turned off, and language is set to US English. - try: - deepgramLive = await deepgram.transcription.live({ 'punctuate': True, 'interim_results': False, 'language': 'en-US' }) - except Exception as e: - print(f'Could not open socket: {e}') - return - -# Listen for the connection to close - deepgramLive.registerHandler(deepgramLive.event.CLOSE, lambda c: print(f'Connection closed with code {c}.')) - - # Listen for any transcripts received from Deepgram and write them to the console - deepgramLive.registerHandler(deepgramLive.event.TRANSCRIPT_RECEIVED, print) - - # Listen for the connection to open and send streaming audio from the URL to Deepgram - async with aiohttp.ClientSession() as session: - async with session.get(URL) as audio: - while True: - data = await audio.content.readany() - deepgramLive.send(data) - - # If there's no data coming from the livestream then break out of the loop - if not data: - break - - # Indicate that we've finished sending data by sending the customary zero-byte message to the Deepgram streaming endpoint, and wait until we get back the final summary metadata object - await deepgramLive.finish() - -asyncio.run(main()) -``` - -## Parameters - -Query parameters like `punctuate` are added as part of the `TranscriptionOptions` `dict` in the `.prerecorded`/`.live` transcription call. -Multiple query parameters can be added similarly, and any dict will do - the types are provided for reference/convenience. - -```python -response = await dg_client.transcription.prerecorded(source, {'punctuate': True, 'keywords': ['first:5', 'second']}) -``` - -Depending on your preference, you can also add parameters as named arguments, instead. - -```python -response = await dg_client.transcription.prerecorded(source, punctuate=True, keywords=['first:5', 'second']) -``` - -# Transcribing to captions - -```python -from deepgram_captions import DeepgramConverter, webvtt, srt - -transcription = DeepgramConverter(dg_response) -captions = webvtt(transcription) -# captions = srt(transcription) -``` - -[See our standalone captions library for more information](https://github.com/deepgram/deepgram-python-captions). - -# Projects - -The `Deepgram.projects` object provides access to manage projects associated with the API key you provided when instantiating the Deepgram client. - -## Get Projects - -### Get Projects Example Request - -```python -projects = await deepgram.projects.list() -``` - -### Get Projects Response - -```ts -{ - projects: [ - { - project_id: String, - name: String, - }, - ], -} -``` - -## Get Project - -Retrieves a project based on the provided project id. - -### Get a Project Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ----------------------------------------------- | -| project_id | String | A unique identifier for the project to retrieve | - -### Get a Project Example Request - -```python -project = await deepgram.projects.get(PROJECT_ID) -``` - -### Get a Project Response - -```ts -{ - project_id: String, - name: String, -} -``` - -## Update Project - -Updates a project based on a provided project object. - -### Update Project Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------------------------------------- | -| project | Object | Object representing a project. Must contain `project_id` and `name` properties. | - -### Update a Project Example Request - -```python -updateResponse = await deepgram.projects.update(project) -``` - -### Update a Project Response - -```ts -{ - message: String; -} -``` - -# Keys - -The `Deepgram.keys` object provides access to manage keys associated with your projects. Every function provided will required a `PROJECT_ID` that your current has access to manage. - -## List Keys - -You can retrieve all keys for a given project using the `keys.list` function. - -### List Project API Keys Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project the API key will be created for | - -### List Project Keys Example Request - -```python -response = await deepgram.keys.list(PROJECT_ID) -``` - -### List Keys Response - -```ts -{ - api_keys: [ - { - api_key_id: string, - comment: string, - created: string, - scopes: Array, - }, - ]; -} -``` - -## Create Key - -Create a new API key for a project using the `keys.create` function with a name for the key. - -### Create API Key Parameters - -| Parameter | Type | Description | -| --------------- | ------ | ------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project the API key will be created for | -| comment_for_key | String | A comment to denote what the API key is for | -| scopes | Array | A permissions scopes of the key to create | - -### Create API Key Example Request - -```python -response = await deepgram.keys.create(PROJECT_ID, COMMENT_FOR_KEY, SCOPES) -``` - -### Create API Key Response - -```ts -{ - api_key_id: string, - key: string, - comment: string, - created: string, - scopes: string[] -} -``` - -## Delete Key - -Delete an existing API key using the `keys.delete` method with project id and key id to delete. - -### Delete Key Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project the API key will be delete from | -| key_id | String | A unique identifier for the API key to delete | - -### Delete Key Example Request - -```python -await deepgram.keys.delete(PROJECT_ID, KEY_ID) -``` - -### Delete Key Response - -The `keys.delete` function returns a void. - -# Members - -The `deepgram.members` object provides access to the members endpoints of the Deepgram API. Each request is project based and will require a `project_id`. - -## Get Members - -You can retrieve all members on a given project using the `members.list_members` function. - -### Get Members Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------ | -| project_id | String | A unique identifier for the project you wish to see the members of | - -### Get Members Example Request - -```python -response = await deepgram.members.list_members(PROJECT_ID) -``` - -### Get Members Response - -```ts -{ - members: [ - { - member_id: string, - scopes: Array - email: string, - first_name: string, - last_name: string, - }, - ]; -} -``` - -## Remove Member - -You can remove a member from a given project using the `members.remove_member` function. - -### Remove Member Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------ | -| project_id | String | A unique identifier for the project you wish to see the members of | -| member_id | String | A unique identifier for the member you wish to remove | - -### Remove Member Example Request - -```python -response = await deepgram.members.remove_member(PROJECT_ID, MEMBER_ID) -``` - -### Remove Member Response - -```ts -{ - message: string; -} -``` - -# Scopes - -The `deepgram.scopes` object provides access to the scopes endpoints of the Deepgram API. Each request is project based and will require a `project_id`. - -## Get Member Scopes - -You can retrieve all scopes of a member on a given project using the `scopes.get_scope` function. - -### Get Member Scopes Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ------------------------------------------------------------------------ | -| project_id | String | A unique identifier for the project you wish to see the member scopes of | -| member_id | String | A unique identifier for the member you wish to see member scopes of | - -### Get Member Scopes Example Request - -```python -response = await deepgram.scopes.get_scope(PROJECT_ID, MEMBER_ID) -``` - -### Get Member Scopes Response - -```ts -{ - scopes: string[] -} -``` - -## Update Scope - -You can update the scope of a member on a given project using the `scopes.update_scope` function. - -### Update Scope Parameters - -| Parameter | Type | Description | -| ---------- | ------ | --------------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to update the member scopes of | -| member_id | String | A unique identifier for the member you wish to update member scopes of | -| scopes | String | The scope you wish to update the member to | - -### Update Scope Example Request - -```python -response = await deepgram.scopes.update_scope(PROJECT_ID, MEMBER_ID, 'member') -``` - -### Update Scope Response - -```ts -{ - message: string; -} -``` - -# Invitations - -The `deepgram.invitations` object provides access to the invites endpoints of the Deepgram API. Each request is project based and will require a `project_id`. - -## List Invites - -You can retrieve all active invitations on a given project using the `invitations.list_invitations` function. - -### List Invites Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ---------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to see the invitations of | - -### List Invites Example Request - -```python -response = await deepgram.invitations.list_invitations(PROJECT_ID) -``` - -### List Invites Response - -```ts -{ - members: [ - { - email: string, - scope: string, - }, - ]; -} +pip install deepgram-sdk ``` -## Send Invite - -You can send an invitation to a given email address to join a given project using the `invitations.send_invitation` function. +# Quickstarts -### Send Invite Parameters +This SDK aims to reduce complexity and abtract/hide some internal Deepgram details that clients shouldn't need to know about. However you can still tweak options and settings if you need. -| Parameter | Type | Description | -| ---------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to send an invitation from | -| option | Object | An object containing the email address of the person you wish to send an invite to, and the scope you want them to have in the project | +## PreRecorded Audio Transcription Quickstart -### Send Invite Example Request +You can find a [walkthrough](https://developers.deepgram.com/docs/pre-recorded-audio-transcription) on our documentation site. Transcribing Pre-Recorded Audio can be done using the following sample code: ```python -response = await deepgram.invitations.send_invitation(PROJECT_ID, { - email: 'example@email.com', - scope: 'member', -}) -``` - -### Send Invite Response - -```ts -{ - message: string; +AUDIO_URL = { + "url": "https://static.deepgram.com/examples/Bueller-Life-moves-pretty-fast.wav" } -``` - -## Delete Invite - -Removes the invitation of the specified email from the specified project. - -### Delete Invite Parameters -| Parameter | Type | Description | -| ---------- | ------ | ---------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to remove the invite from | -| email | String | The email address of the invitee | +# STEP 1 Create a Deepgram client using the API key from environment variables +deepgram = DeepgramClient() -### Delete Invite Example Request - -```python -response = await deepgram.invitations.remove_invitation( - PROJECT_ID, - 'example@email.com' +# STEP 2 Call the transcribe_url method on the prerecorded class +options = PrerecordedOptions( + model="nova", + smart_format=True, + summarize="v2", ) +url_response = deepgram.listen.prerecorded.v("1").transcribe_url(AUDIO_URL, options) +print(url_response) ``` -### Delete Invite Response - -```ts -{ - message: string; -} -``` - -## Leave Project - -Removes the authenticated account from the specified project. - -### Leave Project Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ----------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to leave | - -### Leave Project Example Request - -```python -response = await deepgram.invitations.leave_project(PROJECT_ID) -``` - -### Leave Project Response - -```ts -{ - message: string; -} -``` - -# Usage - -The `deepgram.usage` object provides access to the usage endpoints of the Deepgram API. Each request is project based and will require a `project_id`. - -## Get All Requests - -Retrieves transcription requests for a project based on the provided options. - -### Get All Requests Parameters - -| Parameter | Type | Description | -| ---------- | ------ | --------------------------------------------------------- | -| project_id | String | A unique identifier for the project to retrieve usage for | -| options | Object | Parameters to filter requests. See below. | - -#### Get All Requests Options - -```python -{ - // The time to retrieve requests made since - // Example: "2020-01-01T00:00:00+00:00" - start?: String, - // The time to retrieve requests made until - // Example: "2021-01-01T00:00:00+00:00" - end?: String, - // Page of requests to return - // Defaults to 0 - page?: Number, - // Number of requests to return per page - // Defaults to 10. Maximum of 100 - limit?: Number, - // Filter by succeeded or failed requests - // By default, all requests are returned - status?: 'succeeded' | 'failed' -} -``` - -### Get All Requests Example Request - -```python -response = await deepgram.usage.list_requests(PROJECT_ID, { - 'limit': 10, - # other options are available -}) -``` - -### Get All Requests Response - -```ts -{ - page: Number, - limit: Number, - requests?: [ - { - request_id: String; - created: String; - path: String; - accessor: String; - response?: { - details: { - usd: Number; - duration: Number; - total_audio: Number; - channels: Number; - streams: Number; - model: String; - method: String; - tags: String[]; - features: String[]; - config: { - multichannel?: Boolean; - interim_results?: Boolean; - punctuate?: Boolean; - ner?: Boolean; - utterances?: Boolean; - replace?: Boolean; - profanity_filter?: Boolean; - keywords?: Boolean; - diarize?: Boolean; - search?: Boolean; - redact?: Boolean; - alternatives?: Boolean; - numerals?: Boolean; - }; - } - }, || - { - message?: String; - }, - callback?: { - code: Number; - completed: String; - }, - }, - ]; -} -``` - -## Get Request +## Live Audio Transcription Quickstart -Retrieves a specific transcription request for a project based on the provided `projectId` and `requestId`. - -### Get Request Parameters - -| Parameter | Type | Description | -| ---------- | ------ | --------------------------------------------------------- | -| project_id | String | A unique identifier for the project to retrieve usage for | -| request_id | String | Unique identifier of the request to retrieve | - -### Get Request Example Request +You can find a [walkthrough](https://developers.deepgram.com/docs/live-streaming-audio-transcription) on our documentation site. Transcribing Live Audio can be done using the following sample code: ```python -response = await deepgram.usage.get_request(PROJECT_ID, REQUEST_ID) -``` - -### Get Request Response - -```ts -{ - request_id: String; - created: String; - path: String; - accessor: String; - response?: { - details: { - usd: Number; - duration: Number; - total_audio: Number; - channels: Number; - streams: Number; - model: String; - method: String; - tags: String[]; - features: String[]; - config: { - multichannel?: Boolean; - interim_results?: Boolean; - punctuate?: Boolean; - ner?: Boolean; - utterances?: Boolean; - replace?: Boolean; - profanity_filter?: Boolean; - keywords?: Boolean; - diarize?: Boolean; - search?: Boolean; - redact?: Boolean; - alternatives?: Boolean; - numerals?: Boolean; - }; - } - }, || - { - message?: String; - }, - callback?: { - code: Number; - completed: String; - } -} -``` - -## Get Usage - -Retrieves aggregated usage data for a project based on the provided options. - -### Get Usage Parameters - -| Parameter | Type | Description | -| ---------- | ------ | --------------------------------------------------------- | -| project_id | String | A unique identifier for the project to retrieve usage for | -| options | Object | Parameters to filter requests. See below. | - -#### Get Usage Options - -```ts -{ - // The time to retrieve requests made since - // Example: "2020-01-01T00:00:00+00:00" - start?: String, - // The time to retrieve requests made until - // Example: "2021-01-01T00:00:00+00:00" - end?: String, - // Specific identifer for a request - accessor?: String, - // Array of tags used in requests - tag?: String[], - // Filter requests by method - method?: "sync" | "async" | "streaming", - // Filter requests by model used - model?: String, - // Filter only requests using multichannel feature - multichannel?: Boolean, - // Filter only requests using interim results feature - interim_results?: Boolean, - // Filter only requests using the punctuation feature - punctuate?: Boolean, - // Filter only requests using ner feature - ner?: Boolean, - // Filter only requests using utterances feature - utterances?: Boolean, - // Filter only requests using replace feature - replace?: Boolean, - // Filter only requests using profanity_filter feature - profanity_filter?: Boolean, - // Filter only requests using keywords feature - keywords?: Boolean, - // Filter only requests using diarization feature - diarize?: Boolean, - // Filter only requests using search feature - search?: Boolean, - // Filter only requests using redact feature - redact?: Boolean, - // Filter only requests using alternatives feature - alternatives?: Boolean, - // Filter only requests using numerals feature - numerals?: Boolean -} -``` +deepgram = DeepgramClient() -### Get Usage Example Request +# Create a websocket connection to Deepgram +options = LiveOptions( + punctuate=True, + language="en-US", + encoding="linear16", + channels=1, + sample_rate=16000, +) -```python -response = await deepgram.usage.get_usage(PROJECT_ID, { - 'start': '2020-01-01T00:00:00+00:00', - # other options are available -}) -``` +def on_message(result=None): + if result is None: + return + sentence = result.channel.alternatives[0].transcript + if len(sentence) == 0: + return + print(f"speaker: {sentence}") -### Get Usage Response - -```ts -{ - start: String, - end: String, - resolution: { - units: String, - amount: Number - }; - results: [ - { - start: String, - end: String, - hours: Number, - requests: Number - } - ]; -} -``` +def on_metadata(metadata=None): + if metadata is None: + return + print(f"\n{metadata}\n") -## Get Fields -Retrieves features used by the provided project_id based on the provided options. +def on_error(error=None): + if error is None: + return + print(f"\n{error}\n") -### Get Fields Parameters +dg_connection = deepgram.listen.live.v("1") +dg_connection.start(options) -| Parameter | Type | Description | -| ---------- | ------ | --------------------------------------------------------------- | -| project_id | String | A unique identifier for the project to retrieve fields used for | -| options | Object | Parameters to filter requests. See below. | +dg_connection.on(LiveTranscriptionEvents.Transcript, on_message) +dg_connection.on(LiveTranscriptionEvents.Metadata, on_metadata) +dg_connection.on(LiveTranscriptionEvents.Error, on_error) -#### Get Fields Options +# create microphone +microphone = Microphone(dg_connection.send) -```ts -{ - // The time to retrieve requests made since - // Example: "2020-01-01T00:00:00+00:00" - start?: String, - // The time to retrieve requests made until - // Example: "2021-01-01T00:00:00+00:00" - end?: String -} -``` +# start microphone +microphone.start() -### Get Fields Example Request +# wait until finished +input("Press Enter to stop recording...\n\n") -```python -response = await deepgram.usage.get_fields(PROJECT_ID, { - 'start': '2020-01-01T00:00:00+00:00', - # other options are available -}) -``` +# Wait for the microphone to close +microphone.finish() -#### Get Fields Response +# Indicate that we've finished +dg_connection.finish() -```ts -{ - tags: String[], - models: String[], - processing_methods: String[], - languages: String[], - features: String[] -} +print("Finished") ``` -# Billing - -The `deepgram.billing` object provides access to the balances endpoints of the Deepgram API. Each request is project based and will require a `project_id`. - -## Get All Balances - -You can retrieve all balances on a given project using the `billing.list_balance` function. - -### Get All Balances Parameters - -| Parameter | Type | Description | -| ---------- | ------ | ----------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to see the balance info of | - -### Get All Balances Example Request - -```python -response = await deepgram.billing.list_balance(PROJECT_ID) -``` +# Examples -### Get All Balances Response - -```ts -{ - balances: [ - { - balance_id: string - amount: number - units: string - purchase: string - } - ] -} -``` +There are examples for **every** API call in this SDK. You can find all of these examples in the [examples folder](https://github.com/deepgram/deepgram-python-sdk/tree/main/examples) at the root of this repo. -## Get Balance +These examples provide: -You can retrieve all balances on a given project using the `billing.get_balance` function. +- PreRecorded Audio Transcription: -### Get Balance Parameters + - From an Audio File - [examples/prerecorded/file](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/prerecorded/file/main.py) + - From an URL - [examples/prerecorded/url](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/prerecorded/url/main.py) -| Parameter | Type | Description | -| ---------- | ------ | ----------------------------------------------------------------------- | -| project_id | String | A unique identifier for the project you wish to see the balance info of | -| balance_id | String | A unique identifier for the balance you wish to see the balance info of | +- Live Audio Transcription: -### Get Balance Example Request + - From a Microphone - [examples/streaming/microphone](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/streaming/microphone/main.py) + - From an HTTP Endpoint - [examples/streaming/http](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/streaming/http/main.py) -```python -const response = deepgram.billing.get_balance(PROJECT_ID, BALANCE_ID) -``` +- Management API exercise the full [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations for: -### Get Balance Response + - Balances - [examples/manage/balances](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/balances/main.py) + - Invitations - [examples/manage/invitations](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/invitations/main.py) + - Keys - [examples/manage/keys](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/keys/main.py) + - Members - [examples/manage/members](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/members/main.py) + - Projects - [examples/manage/projects](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/projects/main.py) + - Scopes - [examples/manage/scopes](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/scopes/main.py) + - Usage - [examples/manage/usage](https://github.com/deepgram/deepgram-python-sdk/blob/main/examples/manage/usage/main.py) -```ts -{ - balance: { - balance_id: string; - amount: number; - units: string; - purchase: string; - } -} -``` +To run each example set the `DEEPGRAM_API_KEY` as an environment variable, then `cd` into each example folder and execute the example: `go run main.py`. # Development and Contributing diff --git a/deepgram/audio/microphone/constants.py b/deepgram/audio/microphone/constants.py index 74585855..c8198ff8 100644 --- a/deepgram/audio/microphone/constants.py +++ b/deepgram/audio/microphone/constants.py @@ -4,6 +4,9 @@ import logging, verboselogs +""" +constants for microphone +""" LOGGING = logging.WARNING CHANNELS = 1 RATE = 16000 diff --git a/deepgram/audio/microphone/errors.py b/deepgram/audio/microphone/errors.py index cfd729fa..5b6eeff5 100644 --- a/deepgram/audio/microphone/errors.py +++ b/deepgram/audio/microphone/errors.py @@ -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" diff --git a/deepgram/audio/microphone/microphone.py b/deepgram/audio/microphone/microphone.py index 42d9af7e..f4b9209c 100644 --- a/deepgram/audio/microphone/microphone.py +++ b/deepgram/audio/microphone/microphone.py @@ -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. @@ -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__) @@ -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") @@ -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: @@ -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: @@ -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() @@ -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() diff --git a/deepgram/client.py b/deepgram/client.py index 670672e5..653946b0 100644 --- a/deepgram/client.py +++ b/deepgram/client.py @@ -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__( diff --git a/deepgram/clients/abstract_async_client.py b/deepgram/clients/abstract_async_client.py index 6b278bda..90f59c9c 100644 --- a/deepgram/clients/abstract_async_client.py +++ b/deepgram/clients/abstract_async_client.py @@ -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. diff --git a/deepgram/clients/abstract_sync_client.py b/deepgram/clients/abstract_sync_client.py index 56178f1f..4425727e 100644 --- a/deepgram/clients/abstract_sync_client.py +++ b/deepgram/clients/abstract_sync_client.py @@ -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. diff --git a/deepgram/clients/errors.py b/deepgram/clients/errors.py index 6fffb4b9..29e63b54 100644 --- a/deepgram/clients/errors.py +++ b/deepgram/clients/errors.py @@ -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" @@ -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" @@ -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" @@ -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" diff --git a/deepgram/clients/listen.py b/deepgram/clients/listen.py index b0ad987e..ab16bff8 100644 --- a/deepgram/clients/listen.py +++ b/deepgram/clients/listen.py @@ -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()) diff --git a/deepgram/clients/live/client.py b/deepgram/clients/live/client.py index 782f5119..e362c098 100644 --- a/deepgram/clients/live/client.py +++ b/deepgram/clients/live/client.py @@ -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) diff --git a/deepgram/clients/live/enums.py b/deepgram/clients/live/enums.py index 40324ab6..fdf67796 100644 --- a/deepgram/clients/live/enums.py +++ b/deepgram/clients/live/enums.py @@ -4,7 +4,9 @@ from enum import Enum - +""" +Constants mapping to events from the Deepgram API +""" class LiveTranscriptionEvents(Enum): Open = "open" Close = "close" diff --git a/deepgram/clients/live/errors.py b/deepgram/clients/live/errors.py index 30c3a57f..931b0bbd 100644 --- a/deepgram/clients/live/errors.py +++ b/deepgram/clients/live/errors.py @@ -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" @@ -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): diff --git a/deepgram/clients/live/v1/async_client.py b/deepgram/clients/live/v1/async_client.py index f574a8ba..6fcc445c 100644 --- a/deepgram/clients/live/v1/async_client.py +++ b/deepgram/clients/live/v1/async_client.py @@ -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): @@ -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) @@ -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) @@ -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) @@ -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: diff --git a/deepgram/clients/live/v1/client.py b/deepgram/clients/live/v1/client.py index 9e0705b7..daf97e06 100644 --- a/deepgram/clients/live/v1/client.py +++ b/deepgram/clients/live/v1/client.py @@ -26,18 +26,6 @@ class LiveClient: 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): @@ -56,6 +44,9 @@ def __init__(self, config: DeepgramClientOptions): self.websocket_url = convert_to_websocket_url(self.config.url, self.endpoint) def start(self, options: LiveOptions = None): + """ + Starts the WebSocket connection for live transcription. + """ self.logger.debug("LiveClient.start ENTER") self.logger.info("options: %s", options) @@ -90,14 +81,17 @@ def start(self, options: LiveOptions = None): self.logger.notice("start succeeded") self.logger.debug("LiveClient.start LEAVE") - def on(self, event, handler): # registers event handlers for specific events + def on(self, event, handler): + """ + Registers event handlers for specific events. + """ self.logger.info("event fired: %s", event) if event in LiveTranscriptionEvents and callable(handler): self._event_handlers[event].append(handler) def _emit( self, event, *args, **kwargs - ): # triggers the registered event handlers for a specific event + ): for handler in self._event_handlers[event]: handler(*args, **kwargs) @@ -196,6 +190,9 @@ def _processing(self) -> None: self.logger.debug("LiveClient._processing LEAVE") def send(self, data) -> int: + """ + Sends data over the WebSocket connection. + """ self.logger.spam("LiveClient.send ENTER") self.logger.spam("data: %s", data) @@ -213,6 +210,9 @@ def send(self, data) -> int: return 0 def finish(self): + """ + Closes the WebSocket connection gracefully. + """ self.logger.spam("LiveClient.finish ENTER") if self._socket: diff --git a/deepgram/clients/live/v1/options.py b/deepgram/clients/live/v1/options.py index c783aff4..d4cae539 100644 --- a/deepgram/clients/live/v1/options.py +++ b/deepgram/clients/live/v1/options.py @@ -10,6 +10,12 @@ @dataclass_json @dataclass class LiveOptions: + """ + Live Transcription Options for the Deepgram Platform. + + Please see the documentation for more information on each option: + https://developers.deepgram.com/reference/streaming + """ callback: Optional[str] = None channels: Optional[int] = None diarize: Optional[bool] = None diff --git a/deepgram/clients/live/v1/response.py b/deepgram/clients/live/v1/response.py index e55f0b4c..7f58a499 100644 --- a/deepgram/clients/live/v1/response.py +++ b/deepgram/clients/live/v1/response.py @@ -9,7 +9,6 @@ # Result Message - @dataclass_json @dataclass class Word: @@ -83,6 +82,9 @@ def __getitem__(self, key): @dataclass_json @dataclass class LiveResultResponse: + """ + Result Message from the Deepgram Platform + """ type: Optional[str] = "" channel_index: Optional[List[int]] = None duration: Optional[float] = 0 @@ -107,7 +109,6 @@ def __getitem__(self, key): # Metadata Message - @dataclass_json @dataclass class ModelInfo: @@ -123,6 +124,9 @@ def __getitem__(self, key): @dataclass_json @dataclass class MetadataResponse: + """ + Metadata Message from the Deepgram Platform + """ type: Optional[str] = "" transaction_key: Optional[str] = "" request_id: Optional[str] = "" @@ -142,14 +146,15 @@ def __getitem__(self, key): ModelInfo.from_dict(value) for value in _dict["model_info"] ] return _dict[key] - - + # Error Message - @dataclass_json @dataclass class ErrorResponse: + """ + Error Message from the Deepgram Platform + """ description: Optional[str] = "" message: Optional[str] = "" type: Optional[str] = "" diff --git a/deepgram/clients/manage/client.py b/deepgram/clients/manage/client.py index 5e4f1eba..b899858b 100644 --- a/deepgram/clients/manage/client.py +++ b/deepgram/clients/manage/client.py @@ -21,30 +21,51 @@ class ProjectOptions(ProjectOptionsLatest): + """ + pass through for ProjectOptions based on API version + """ pass class KeyOptions(KeyOptionsLatest): + """ + pass through for KeyOptions based on API version + """ pass class ScopeOptions(ScopeOptionsLatest): + """ + pass through for ScopeOptions based on API version + """ pass class InviteOptions(InviteOptionsLatest): + """ + pass through for InviteOptions based on API version + """ pass class UsageRequestOptions(UsageRequestOptionsLatest): + """ + pass through for UsageRequestOptions based on API version + """ pass class UsageSummaryOptions(UsageSummaryOptionsLatest): + """ + pass through for UsageSummaryOptions based on API version + """ pass class UsageFieldsOptions(UsageFieldsOptionsLatest): + """ + pass through for UsageFieldsOptions based on API version + """ pass @@ -52,7 +73,6 @@ class ManageClient(ManageClientLatest): """ Please see ManageClientLatest for details """ - def __init__(self, config): super().__init__(config) @@ -61,6 +81,5 @@ class AsyncManageClient(AsyncManageClientLatest): """ Please see AsyncManageClientLatest for details """ - def __init__(self, config): super().__init__(config) diff --git a/deepgram/clients/manage/v1/async_client.py b/deepgram/clients/manage/v1/async_client.py index 3e5c4726..fffd2a5f 100644 --- a/deepgram/clients/manage/v1/async_client.py +++ b/deepgram/clients/manage/v1/async_client.py @@ -48,16 +48,6 @@ class AsyncManageClient(AbstractAsyncRestClient): Args: config (DeepgramClientOptions): all the options for the client. - - Attributes: - url (str): The base URL of the Deepgram API. - headers (dict): Optional HTTP headers to include in requests. - endpoint (str): The API endpoint for managing projects. - - Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. """ def __init__(self, config: DeepgramClientOptions): @@ -70,9 +60,18 @@ def __init__(self, config: DeepgramClientOptions): # projects async def list_projects(self): + """ + Please see get_projects for more information. + """ return self.get_projects() async def get_projects(self): + """ + Gets a list of projects for the authenticated user. + + Reference: + https://developers.deepgram.com/reference/get-projects + """ self.logger.debug("ManageClient.get_projects ENTER") url = f"{self.config.url}/{self.endpoint}" self.logger.info("url: %s", url) @@ -85,6 +84,12 @@ async def get_projects(self): return res async def get_project(self, project_id: str): + """ + Gets details for a specific project. + + Reference: + https://developers.deepgram.com/reference/get-project + """ self.logger.debug("ManageClient.get_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" self.logger.info("url: %s", url) @@ -98,6 +103,12 @@ async def get_project(self, project_id: str): return res async def update_project_option(self, project_id: str, options: ProjectOptions): + """ + Updates a project's settings. + + Reference: + https://developers.deepgram.com/reference/update-project + """ self.logger.debug("ManageClient.update_project_option ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" self.logger.info("url: %s", url) @@ -112,6 +123,12 @@ async def update_project_option(self, project_id: str, options: ProjectOptions): return res async def update_project(self, project_id: str, name=""): + """ + Updates a project's settings. + + Reference: + https://developers.deepgram.com/reference/update-project + """ self.logger.debug("ManageClient.update_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" options: ProjectOptions = { @@ -129,6 +146,12 @@ async def update_project(self, project_id: str, name=""): return res async def delete_project(self, project_id: str) -> None: + """ + Deletes a project. + + Reference: + https://developers.deepgram.com/reference/delete-project + """ self.logger.debug("ManageClient.delete_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" json = await self.delete(url) @@ -141,9 +164,18 @@ async def delete_project(self, project_id: str) -> None: # keys async def list_keys(self, project_id: str): + """ + Please see get_keys for more information. + """ return self.get_keys(project_id) async def get_keys(self, project_id: str): + """ + Gets a list of keys for a project. + + Reference: + https://developers.deepgram.com/reference/list-keys + """ self.logger.debug("ManageClient.get_keys ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys" self.logger.info("url: %s", url) @@ -157,6 +189,12 @@ async def get_keys(self, project_id: str): return res async def get_key(self, project_id: str, key_id: str): + """ + Gets details for a specific key. + + Reference: + https://developers.deepgram.com/reference/get-key + """ self.logger.debug("ManageClient.get_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys/{key_id}" self.logger.info("url: %s", url) @@ -171,6 +209,12 @@ async def get_key(self, project_id: str, key_id: str): return res async def create_key(self, project_id: str, options: KeyOptions): + """ + Creates a new key. + + Reference: + https://developers.deepgram.com/reference/create-key + """ self.logger.debug("ManageClient.create_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys" self.logger.info("url: %s", url) @@ -185,6 +229,12 @@ async def create_key(self, project_id: str, options: KeyOptions): return res async def delete_key(self, project_id: str, key_id: str) -> None: + """ + Deletes a key. + + Reference: + https://developers.deepgram.com/reference/delete-key + """ self.logger.debug("ManageClient.delete_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys/{key_id}" self.logger.info("url: %s", url) @@ -200,9 +250,18 @@ async def delete_key(self, project_id: str, key_id: str) -> None: # members async def list_members(self, project_id: str): + """ + Please see get_members for more information. + """ return self.get_members(project_id) async def get_members(self, project_id: str): + """ + Gets a list of members for a project. + + Reference: + https://developers.deepgram.com/reference/get-members + """ self.logger.debug("ManageClient.get_members ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/members" self.logger.info("url: %s", url) @@ -216,6 +275,12 @@ async def get_members(self, project_id: str): return res async def remove_member(self, project_id: str, member_id: str) -> None: + """ + Removes a member from a project. + + Reference: + https://developers.deepgram.com/reference/remove-member + """ self.logger.debug("ManageClient.remove_member ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}" self.logger.info("url: %s", url) @@ -231,6 +296,12 @@ async def remove_member(self, project_id: str, member_id: str) -> None: # scopes async def get_member_scopes(self, project_id: str, member_id: str): + """ + Gets a list of scopes for a member. + + Reference: + https://developers.deepgram.com/reference/get-member-scopes + """ self.logger.debug("ManageClient.get_member_scopes ENTER") url = ( f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}/scopes" @@ -249,6 +320,12 @@ async def get_member_scopes(self, project_id: str, member_id: str): async def update_member_scope( self, project_id: str, member_id: str, options: ScopeOptions ): + """ + Updates a member's scopes. + + Reference: + https://developers.deepgram.com/reference/update-scope + """ self.logger.debug("ManageClient.update_member_scope ENTER") url = ( f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}/scopes" @@ -266,9 +343,18 @@ async def update_member_scope( # invites async def list_invites(self, project_id: str): + """ + Please see get_invites for more information. + """ return self.get_invites(project_id) async def get_invites(self, project_id: str): + """ + Gets a list of invites for a project. + + Reference: + https://developers.deepgram.com/reference/list-invites + """ self.logger.debug("ManageClient.get_invites ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" self.logger.info("url: %s", url) @@ -282,6 +368,12 @@ async def get_invites(self, project_id: str): return res async def send_invite_options(self, project_id: str, options: InviteOptions): + """ + Sends an invite to a project. + + Reference: + https://developers.deepgram.com/reference/send-invite + """ self.logger.debug("ManageClient.send_invite_options ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" self.logger.info("url: %s", url) @@ -296,6 +388,12 @@ async def send_invite_options(self, project_id: str, options: InviteOptions): return res async def send_invite(self, project_id: str, email: str, scope="member"): + """ + Sends an invite to a project. + + Reference: + https://developers.deepgram.com/reference/send-invite + """ self.logger.debug("ManageClient.send_invite ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" options: InviteOptions = { @@ -314,6 +412,12 @@ async def send_invite(self, project_id: str, email: str, scope="member"): return res async def delete_invite(self, project_id: str, email: str): + """ + Deletes an invite from a project. + + Reference: + https://developers.deepgram.com/reference/delete-invite + """ self.logger.debug("ManageClient.delete_invite ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites/{email}" self.logger.info("url: %s", url) @@ -328,6 +432,12 @@ async def delete_invite(self, project_id: str, email: str): return res async def leave_project(self, project_id: str): + """ + Leaves a project. + + Reference: + https://developers.deepgram.com/reference/leave-project + """ self.logger.debug("ManageClient.leave_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/leave" self.logger.info("url: %s", url) @@ -342,6 +452,12 @@ async def leave_project(self, project_id: str): # usage async def get_usage_requests(self, project_id: str, options: UsageRequestOptions): + """ + Gets a list of usage requests for a project. + + Reference: + https://developers.deepgram.com/reference/get-all-requests + """ self.logger.debug("ManageClient.get_usage_requests ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/requests" self.logger.info("url: %s", url) @@ -356,6 +472,12 @@ async def get_usage_requests(self, project_id: str, options: UsageRequestOptions return res async def get_usage_request(self, project_id: str, request_id: str): + """ + Gets details for a specific usage request. + + Reference: + https://developers.deepgram.com/reference/get-request + """ self.logger.debug("ManageClient.get_usage_request ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/requests/{request_id}" self.logger.info("url: %s", url) @@ -370,6 +492,12 @@ async def get_usage_request(self, project_id: str, request_id: str): return res async def get_usage_summary(self, project_id: str, options: UsageSummaryOptions): + """ + Gets a summary of usage for a project. + + Reference: + https://developers.deepgram.com/reference/summarize-usage + """ self.logger.debug("ManageClient.get_usage_summary ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/usage" self.logger.info("url: %s", url) @@ -384,6 +512,12 @@ async def get_usage_summary(self, project_id: str, options: UsageSummaryOptions) return res async def get_usage_fields(self, project_id: str, options: UsageFieldsOptions): + """ + Gets a list of usage fields for a project. + + Reference: + https://developers.deepgram.com/reference/get-fields + """ self.logger.debug("ManageClient.get_usage_fields ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/usage/fields" self.logger.info("url: %s", url) @@ -399,9 +533,18 @@ async def get_usage_fields(self, project_id: str, options: UsageFieldsOptions): # balances async def list_balances(self, project_id: str): + """ + Please see get_balances for more information. + """ return self.get_balances(project_id) async def get_balances(self, project_id: str): + """ + Gets a list of balances for a project. + + Reference: + https://developers.deepgram.com/reference/get-all-balances + """ self.logger.debug("ManageClient.get_balances ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/balances" self.logger.info("url: %s", url) @@ -415,6 +558,12 @@ async def get_balances(self, project_id: str): return res async def get_balance(self, project_id: str, balance_id: str): + """ + Gets details for a specific balance. + + Reference: + https://developers.deepgram.com/reference/get-balance + """ self.logger.debug("ManageClient.get_balance ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/balances/{balance_id}" self.logger.info("url: %s", url) diff --git a/deepgram/clients/manage/v1/client.py b/deepgram/clients/manage/v1/client.py index 5a1c495d..966c8a90 100644 --- a/deepgram/clients/manage/v1/client.py +++ b/deepgram/clients/manage/v1/client.py @@ -50,18 +50,7 @@ class ManageClient(AbstractSyncRestClient): Args: config (DeepgramClientOptions): all the options for the client. - - Attributes: - url (str): The base URL of the Deepgram API. - headers (dict): Optional HTTP headers to include in requests. - endpoint (str): The API endpoint for managing projects. - - Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. """ - def __init__(self, config: DeepgramClientOptions): self.logger = logging.getLogger(__name__) self.logger.addHandler(logging.StreamHandler()) @@ -73,9 +62,18 @@ def __init__(self, config: DeepgramClientOptions): # projects def list_projects(self, timeout: httpx.Timeout = None): + """ + List all projects for the current user. + """ return self.get_projects() def get_projects(self, timeout: httpx.Timeout = None): + """ + Gets a list of projects for the authenticated user. + + Reference: + https://developers.deepgram.com/reference/get-projects + """ self.logger.debug("ManageClient.get_projects ENTER") url = f"{self.config.url}/{self.endpoint}" self.logger.info("url: %s", url) @@ -88,6 +86,12 @@ def get_projects(self, timeout: httpx.Timeout = None): return res def get_project(self, project_id: str, timeout: httpx.Timeout = None): + """ + Gets details for a specific project. + + Reference: + https://developers.deepgram.com/reference/get-project + """ self.logger.debug("ManageClient.get_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" self.logger.info("url: %s", url) @@ -101,6 +105,12 @@ def get_project(self, project_id: str, timeout: httpx.Timeout = None): return res def update_project_option(self, project_id: str, options: ProjectOptions, timeout: httpx.Timeout = None): + """ + Updates a project's settings. + + Reference: + https://developers.deepgram.com/reference/update-project + """ self.logger.debug("ManageClient.update_project_option ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" self.logger.info("url: %s", url) @@ -118,6 +128,12 @@ def update_project_option(self, project_id: str, options: ProjectOptions, timeou return res def update_project(self, project_id: str, name="", timeout: httpx.Timeout = None): + """ + Updates a project's settings. + + Reference: + https://developers.deepgram.com/reference/update-project + """ self.logger.debug("ManageClient.update_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" options: ProjectOptions = { @@ -135,6 +151,12 @@ def update_project(self, project_id: str, name="", timeout: httpx.Timeout = None return res def delete_project(self, project_id: str, timeout: httpx.Timeout = None) -> None: + """ + Deletes a project. + + Reference: + https://developers.deepgram.com/reference/delete-project + """ self.logger.debug("ManageClient.delete_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}" result = self.delete(url, timeout=timeout) @@ -147,9 +169,18 @@ def delete_project(self, project_id: str, timeout: httpx.Timeout = None) -> None # keys def list_keys(self, project_id: str, timeout: httpx.Timeout = None): + """ + Please see get_keys for more information. + """ return self.get_keys(project_id) def get_keys(self, project_id: str, timeout: httpx.Timeout = None): + """ + Gets a list of keys for a project. + + Reference: + https://developers.deepgram.com/reference/list-keys + """ self.logger.debug("ManageClient.get_keys ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys" self.logger.info("url: %s", url) @@ -163,6 +194,12 @@ def get_keys(self, project_id: str, timeout: httpx.Timeout = None): return res def get_key(self, project_id: str, key_id: str, timeout: httpx.Timeout = None): + """ + Gets details for a specific key. + + Reference: + https://developers.deepgram.com/reference/get-key + """ self.logger.debug("ManageClient.get_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys/{key_id}" self.logger.info("url: %s", url) @@ -177,6 +214,12 @@ def get_key(self, project_id: str, key_id: str, timeout: httpx.Timeout = None): return res def create_key(self, project_id: str, options: KeyOptions, timeout: httpx.Timeout = None): + """ + Creates a new key. + + Reference: + https://developers.deepgram.com/reference/create-key + """ self.logger.debug("ManageClient.create_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys" self.logger.info("url: %s", url) @@ -194,6 +237,12 @@ def create_key(self, project_id: str, options: KeyOptions, timeout: httpx.Timeou return res def delete_key(self, project_id: str, key_id: str, timeout: httpx.Timeout = None) -> None: + """ + Deletes a key. + + Reference: + https://developers.deepgram.com/reference/delete-key + """ self.logger.debug("ManageClient.delete_key ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/keys/{key_id}" self.logger.info("url: %s", url) @@ -209,9 +258,18 @@ def delete_key(self, project_id: str, key_id: str, timeout: httpx.Timeout = None # members def list_members(self, project_id: str, timeout: httpx.Timeout = None): + """ + Please see get_members for more information. + """ return self.get_members(project_id) def get_members(self, project_id: str, timeout: httpx.Timeout = None): + """ + Gets a list of members for a project. + + Reference: + https://developers.deepgram.com/reference/get-members + """ self.logger.debug("ManageClient.get_members ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/members" self.logger.info("url: %s", url) @@ -225,6 +283,12 @@ def get_members(self, project_id: str, timeout: httpx.Timeout = None): return res def remove_member(self, project_id: str, member_id: str, timeout: httpx.Timeout = None) -> None: + """ + Removes a member from a project. + + Reference: + https://developers.deepgram.com/reference/remove-member + """ self.logger.debug("ManageClient.remove_member ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}" self.logger.info("url: %s", url) @@ -240,6 +304,12 @@ def remove_member(self, project_id: str, member_id: str, timeout: httpx.Timeout # scopes def get_member_scopes(self, project_id: str, member_id: str, timeout: httpx.Timeout = None): + """ + Gets a list of scopes for a member. + + Reference: + https://developers.deepgram.com/reference/get-member-scopes + """ self.logger.debug("ManageClient.get_member_scopes ENTER") url = ( f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}/scopes" @@ -258,6 +328,12 @@ def get_member_scopes(self, project_id: str, member_id: str, timeout: httpx.Time def update_member_scope( self, project_id: str, member_id: str, options: ScopeOptions, timeout: httpx.Timeout = None ): + """ + Updates a member's scopes. + + Reference: + https://developers.deepgram.com/reference/update-scope + """ self.logger.debug("ManageClient.update_member_scope ENTER") url = ( f"{self.config.url}/{self.endpoint}/{project_id}/members/{member_id}/scopes" @@ -278,9 +354,18 @@ def update_member_scope( # invites def list_invites(self, project_id: str, timeout: httpx.Timeout = None): + """ + Please see get_invites for more information. + """ return self.get_invites(project_id) def get_invites(self, project_id: str, timeout: httpx.Timeout = None): + """ + Gets a list of invites for a project. + + Reference: + https://developers.deepgram.com/reference/list-invites + """ self.logger.debug("ManageClient.get_invites ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" self.logger.info("url: %s", url) @@ -294,6 +379,12 @@ def get_invites(self, project_id: str, timeout: httpx.Timeout = None): return res def send_invite_options(self, project_id: str, options: InviteOptions, timeout: httpx.Timeout = None): + """ + Sends an invite to a project. + + Reference: + https://developers.deepgram.com/reference/send-invite + """ self.logger.debug("ManageClient.send_invite_options ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" self.logger.info("url: %s", url) @@ -311,6 +402,12 @@ def send_invite_options(self, project_id: str, options: InviteOptions, timeout: return res def send_invite(self, project_id: str, email: str, scope="member", timeout: httpx.Timeout = None): + """ + Sends an invite to a project. + + Reference: + https://developers.deepgram.com/reference/send-invite + """ self.logger.debug("ManageClient.send_invite ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites" options: InviteOptions = { @@ -329,6 +426,12 @@ def send_invite(self, project_id: str, email: str, scope="member", timeout: http return res def delete_invite(self, project_id: str, email: str, timeout: httpx.Timeout = None): + """ + Deletes an invite from a project. + + Reference: + https://developers.deepgram.com/reference/delete-invite + """ self.logger.debug("ManageClient.delete_invite ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/invites/{email}" self.logger.info("url: %s", url) @@ -343,6 +446,12 @@ def delete_invite(self, project_id: str, email: str, timeout: httpx.Timeout = No return res def leave_project(self, project_id: str, timeout: httpx.Timeout = None): + """ + Leaves a project. + + Reference: + https://developers.deepgram.com/reference/leave-project + """ self.logger.debug("ManageClient.leave_project ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/leave" self.logger.info("url: %s", url) @@ -357,6 +466,12 @@ def leave_project(self, project_id: str, timeout: httpx.Timeout = None): # usage def get_usage_requests(self, project_id: str, options: UsageRequestOptions, timeout: httpx.Timeout = None): + """ + Gets a list of usage requests for a project. + + Reference: + https://developers.deepgram.com/reference/get-all-requests + """ self.logger.debug("ManageClient.get_usage_requests ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/requests" self.logger.info("url: %s", url) @@ -374,6 +489,12 @@ def get_usage_requests(self, project_id: str, options: UsageRequestOptions, time return res def get_usage_request(self, project_id: str, request_id: str, timeout: httpx.Timeout = None): + """ + Gets details for a specific usage request. + + Reference: + https://developers.deepgram.com/reference/get-request + """ self.logger.debug("ManageClient.get_usage_request ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/requests/{request_id}" self.logger.info("url: %s", url) @@ -388,6 +509,12 @@ def get_usage_request(self, project_id: str, request_id: str, timeout: httpx.Tim return res def get_usage_summary(self, project_id: str, options: UsageSummaryOptions, timeout: httpx.Timeout = None): + """ + Gets a summary of usage for a project. + + Reference: + https://developers.deepgram.com/reference/summarize-usage + """ self.logger.debug("ManageClient.get_usage_summary ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/usage" self.logger.info("url: %s", url) @@ -405,6 +532,12 @@ def get_usage_summary(self, project_id: str, options: UsageSummaryOptions, timeo return res def get_usage_fields(self, project_id: str, options: UsageFieldsOptions, timeout: httpx.Timeout = None): + """ + Gets a list of usage fields for a project. + + Reference: + https://developers.deepgram.com/reference/get-fields + """ self.logger.debug("ManageClient.get_usage_fields ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/usage/fields" self.logger.info("url: %s", url) @@ -423,9 +556,18 @@ def get_usage_fields(self, project_id: str, options: UsageFieldsOptions, timeout # balances def list_balances(self, project_id: str, timeout: httpx.Timeout = None): + """ + Please see get_balances for more information. + """ return self.get_balances(project_id) def get_balances(self, project_id: str, timeout: httpx.Timeout = None): + """ + Gets a list of balances for a project. + + Reference: + https://developers.deepgram.com/reference/get-all-balances + """ self.logger.debug("ManageClient.get_balances ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/balances" self.logger.info("url: %s", url) @@ -439,6 +581,12 @@ def get_balances(self, project_id: str, timeout: httpx.Timeout = None): return res def get_balance(self, project_id: str, balance_id: str, timeout: httpx.Timeout = None): + """ + Gets details for a specific balance. + + Reference: + https://developers.deepgram.com/reference/get-balance + """ self.logger.debug("ManageClient.get_balance ENTER") url = f"{self.config.url}/{self.endpoint}/{project_id}/balances/{balance_id}" self.logger.info("url: %s", url) diff --git a/deepgram/clients/onprem/client.py b/deepgram/clients/onprem/client.py index 6001b374..7c6621c8 100644 --- a/deepgram/clients/onprem/client.py +++ b/deepgram/clients/onprem/client.py @@ -15,7 +15,6 @@ class OnPremClient(OnPremClientLatest): """ Please see OnPremClientLatest for details """ - def __init__(self, config): super().__init__(config) @@ -24,6 +23,5 @@ class AsyncOnPremClient(AsyncOnPremClientLatest): """ Please see AsyncOnPremClientLatest for details """ - def __init__(self, config): super().__init__(config) diff --git a/deepgram/clients/onprem/v1/async_client.py b/deepgram/clients/onprem/v1/async_client.py index e241be9a..09e01e50 100644 --- a/deepgram/clients/onprem/v1/async_client.py +++ b/deepgram/clients/onprem/v1/async_client.py @@ -15,18 +15,7 @@ class AsyncOnPremClient(AbstractAsyncRestClient): Args: config (DeepgramClientOptions): all the options for the client. - - Attributes: - endpoint (str): The API endpoint for on-premises projects. - - Methods: - list_onprem_credentials: Lists on-premises distribution credentials for a specific project. - get_onprem_credentials: Retrieves details of a specific on-premises distribution credential for a project. - create_onprem_credentials: Creates a new on-premises distribution credential for a project. - delete_onprem_credentials: Deletes an on-premises distribution credential for a project. - """ - def __init__(self, config): self.logger = logging.getLogger(__name__) self.logger.addHandler(logging.StreamHandler()) diff --git a/deepgram/clients/onprem/v1/client.py b/deepgram/clients/onprem/v1/client.py index da4ea323..307188c2 100644 --- a/deepgram/clients/onprem/v1/client.py +++ b/deepgram/clients/onprem/v1/client.py @@ -16,18 +16,7 @@ class OnPremClient(AbstractSyncRestClient): Args: config (DeepgramClientOptions): all the options for the client. - - Attributes: - endpoint (str): The API endpoint for on-premises projects. - - Methods: - list_onprem_credentials: Lists on-premises distribution credentials for a specific project. - get_onprem_credentials: Retrieves details of a specific on-premises distribution credential for a project. - create_onprem_credentials: Creates a new on-premises distribution credential for a project. - delete_onprem_credentials: Deletes an on-premises distribution credential for a project. - """ - def __init__(self, config): self.logger = logging.getLogger(__name__) self.logger.addHandler(logging.StreamHandler()) diff --git a/deepgram/clients/prerecorded/client.py b/deepgram/clients/prerecorded/client.py index e4235719..a4a40a90 100644 --- a/deepgram/clients/prerecorded/client.py +++ b/deepgram/clients/prerecorded/client.py @@ -14,6 +14,9 @@ class PrerecordedOptions(PrerecordedOptionsLatest): + """ + Please see PrerecordedOptionsLatest for details + """ pass @@ -21,7 +24,6 @@ class PreRecordedClient(PreRecordedClientLatest): """ Please see PreRecordedClientLatest for details """ - def __init__(self, config): self.config = config super().__init__(config) @@ -31,6 +33,5 @@ class AsyncPreRecordedClient(AsyncPreRecordedClientLatest): """ Please see AsyncPreRecordedClientLatest for details """ - def __init__(self, config): super().__init__(config) diff --git a/deepgram/clients/prerecorded/errors.py b/deepgram/clients/prerecorded/errors.py index fc0d4d4c..392abe29 100644 --- a/deepgram/clients/prerecorded/errors.py +++ b/deepgram/clients/prerecorded/errors.py @@ -9,9 +9,7 @@ class DeepgramTypeError(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 = "DeepgramTypeError" diff --git a/deepgram/clients/prerecorded/source.py b/deepgram/clients/prerecorded/source.py index b498cebd..2afd4648 100644 --- a/deepgram/clients/prerecorded/source.py +++ b/deepgram/clients/prerecorded/source.py @@ -16,11 +16,8 @@ class ReadStreamSource(TypedDict): Attributes: stream (BufferedReader): A BufferedReader object for reading binary data. - mimetype (str): The MIME type or content type associated with the data. """ - stream: BufferedReader - mimetype: str class UrlSource(TypedDict): @@ -33,7 +30,6 @@ class UrlSource(TypedDict): Attributes: url (str): The URL pointing to the hosted file. """ - url: str @@ -46,11 +42,8 @@ class BufferSource(TypedDict): Attributes: buffer (bytes): The binary data. - mimetype (str): The MIME type or content type associated with the data. """ - buffer: bytes - mimetype: str PrerecordedSource = Union[UrlSource, BufferSource, ReadStreamSource] diff --git a/deepgram/clients/prerecorded/v1/async_client.py b/deepgram/clients/prerecorded/v1/async_client.py index 7a0364f4..3ed61bb2 100644 --- a/deepgram/clients/prerecorded/v1/async_client.py +++ b/deepgram/clients/prerecorded/v1/async_client.py @@ -36,12 +36,10 @@ def __init__(self, config): endpoint (str): The API endpoint for the transcription (default is "v1/listen"). Returns: - SyncPrerecordedResponse: An object containing the transcription result. + PrerecordedResponse: An object containing the transcription result. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ async def transcribe_url( @@ -93,9 +91,7 @@ async def transcribe_url( AsyncPrerecordedResponse: An object containing the request_id or an error message. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ async def transcribe_url_callback( @@ -141,13 +137,10 @@ async def transcribe_url_callback( endpoint (str): The API endpoint for the transcription (default is "v1/listen"). Returns: - SyncPrerecordedResponse: An object containing the transcription result or an error message. + PrerecordedResponse: An object containing the transcription result or an error message. Raises: - - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ async def transcribe_file( @@ -200,9 +193,7 @@ async def transcribe_file( AsyncPrerecordedResponse: An object containing the request_id or an error message. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ async def transcribe_file_callback( diff --git a/deepgram/clients/prerecorded/v1/client.py b/deepgram/clients/prerecorded/v1/client.py index 9380d91f..3d867590 100644 --- a/deepgram/clients/prerecorded/v1/client.py +++ b/deepgram/clients/prerecorded/v1/client.py @@ -37,12 +37,10 @@ def __init__(self, config): endpoint (str): The API endpoint for the transcription (default is "v1/listen"). Returns: - SyncPrerecordedResponse: An object containing the transcription result. + PrerecordedResponse: An object containing the transcription result. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ def transcribe_url( @@ -95,9 +93,7 @@ def transcribe_url( AsyncPrerecordedResponse: An object containing the request_id or an error message. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ def transcribe_url_callback( @@ -144,13 +140,10 @@ def transcribe_url_callback( endpoint (str): The API endpoint for the transcription (default is "v1/listen"). Returns: - SyncPrerecordedResponse: An object containing the transcription result or an error message. + PrerecordedResponse: An object containing the transcription result or an error message. Raises: - - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ def transcribe_file( @@ -204,9 +197,7 @@ def transcribe_file( AsyncPrerecordedResponse: An object containing the request_id or an error message. Raises: - DeepgramApiError: Raised for known API errors. - DeepgramUnknownApiError: Raised for unknown API errors. - Exception: For any other unexpected exceptions. + DeepgramTypeError: Raised for known API errors. """ def transcribe_file_callback( diff --git a/deepgram/clients/prerecorded/v1/options.py b/deepgram/clients/prerecorded/v1/options.py index eb23bb7a..932fff94 100644 --- a/deepgram/clients/prerecorded/v1/options.py +++ b/deepgram/clients/prerecorded/v1/options.py @@ -10,6 +10,12 @@ @dataclass_json @dataclass class PrerecordedOptions: + """ + Contains all the options for the PrerecordedClient. + + Reference: + https://developers.deepgram.com/reference/pre-recorded + """ alternatives: Optional[int] = None callback: Optional[str] = None detect_entities: Optional[bool] = None diff --git a/deepgram/errors.py b/deepgram/errors.py index 23439e8b..025de8a0 100644 --- a/deepgram/errors.py +++ b/deepgram/errors.py @@ -10,7 +10,6 @@ class DeepgramApiKeyError(Exception): Attributes: message (str): The error message describing the exception. """ - def __init__(self, message: str): super().__init__(message) self.name = "DeepgramApiKeyError" @@ -23,7 +22,6 @@ class DeepgramModuleError(Exception): Attributes: message (str): The error message describing the exception. """ - def __init__(self, message: str): super().__init__(message) self.name = "DeepgramModuleError" diff --git a/deepgram/options.py b/deepgram/options.py index 5218f544..15b169e7 100644 --- a/deepgram/options.py +++ b/deepgram/options.py @@ -8,18 +8,18 @@ class DeepgramClientOptions: - """ Represents options for configuring a Deepgram client. This class allows you to customize various options for interacting with the Deepgram API. Attributes: - api_key (str): A Deepgram API key used for authentication. - global_options (dict): A dictionary containing global configuration options. - - headers (dict): Optional headers for initializing the client. - - url (str): The URL used to interact with production, On-prem, and other Deepgram environments. Defaults to `api.deepgram.com`. - """ + api_key: (Optional) A Deepgram API key used for authentication. Default uses the `DEEPGRAM_API_KEY` environment variable. + verbose: (Optional) The logging level for the client. Defaults to `logging.WARNING`. + url: (Optional) The URL used to interact with production, On-prem, and other Deepgram environments. Defaults to `api.deepgram.com`. + headers: (Optional) Headers for initializing the client. + options: (Optional) Additional options for initializing the client. + """ def __init__( self, diff --git a/examples/manage/balances/main.py b/examples/manage/balances/main.py index 8dbe08cf..13dcf691 100644 --- a/examples/manage/balances/main.py +++ b/examples/manage/balances/main.py @@ -11,16 +11,15 @@ load_dotenv() -# Create a Deepgram client using the API key -config = DeepgramClientOptions( - verbose=logging.SPAM, -) - -deepgram = DeepgramClient("", config) - - def main(): try: + # Create a Deepgram client using the API key + config = DeepgramClientOptions( + verbose=logging.SPAM, + ) + + deepgram = DeepgramClient("", config) + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: diff --git a/examples/manage/invitations/main.py b/examples/manage/invitations/main.py index 97d673ae..25d0118f 100644 --- a/examples/manage/invitations/main.py +++ b/examples/manage/invitations/main.py @@ -10,12 +10,11 @@ load_dotenv() -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: diff --git a/examples/manage/keys/main.py b/examples/manage/keys/main.py index 9ac68c15..952ce98c 100644 --- a/examples/manage/keys/main.py +++ b/examples/manage/keys/main.py @@ -10,12 +10,11 @@ load_dotenv() -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: diff --git a/examples/manage/members/main.py b/examples/manage/members/main.py index 8a4b1bd3..fbf8634c 100644 --- a/examples/manage/members/main.py +++ b/examples/manage/members/main.py @@ -13,12 +13,11 @@ # environment variables DELETE_MEMBER_BY_EMAIL = "enter-your-email@gmail.com" -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: diff --git a/examples/manage/projects/main.py b/examples/manage/projects/main.py index 4bdeb200..8ffe6c37 100644 --- a/examples/manage/projects/main.py +++ b/examples/manage/projects/main.py @@ -13,12 +13,11 @@ # environment variables DELETE_PROJECT_BY_NAME = os.getenv("DG_DELETE_PROJECT_BY_NAME") -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects listResp = deepgram.manage.v("1").get_projects() if listResp is None: diff --git a/examples/manage/scopes/main.py b/examples/manage/scopes/main.py index 51f70931..b43dcabb 100644 --- a/examples/manage/scopes/main.py +++ b/examples/manage/scopes/main.py @@ -13,12 +13,11 @@ # environment variables MEMBER_BY_EMAIL = "enter-your-email@gmail.com" -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: diff --git a/examples/manage/usage/main.py b/examples/manage/usage/main.py index 4632a48b..e5ee1403 100644 --- a/examples/manage/usage/main.py +++ b/examples/manage/usage/main.py @@ -15,12 +15,11 @@ load_dotenv() -# Create a Deepgram client using the API key -deepgram = DeepgramClient() - - def main(): try: + # Create a Deepgram client using the API key + deepgram = DeepgramClient() + # get projects projectResp = deepgram.manage.v("1").get_projects() if projectResp is None: @@ -73,7 +72,7 @@ def main(): print(f"GetUsageFields Methods: {method}") print("") - # list members + # list usage options: UsageSummaryOptions = {} listResp = deepgram.manage.v("1").get_usage_summary(myId, options) if listResp is None: diff --git a/examples/prerecorded/file/main.py b/examples/prerecorded/file/main.py index ff863d69..af67c7eb 100644 --- a/examples/prerecorded/file/main.py +++ b/examples/prerecorded/file/main.py @@ -17,45 +17,36 @@ AUDIO_FILE = "preamble.wav" -# Create a Deepgram client using the API key -config: DeepgramClientOptions = DeepgramClientOptions( - verbose=logging.SPAM, -) - -options = PrerecordedOptions( - model="nova", - smart_format=True, - utterances=True, - punctuate=True, - diarize=True, -) - -# STEP 1 Create a Deepgram client using the API key (optional - add config options) -deepgram: DeepgramClient = DeepgramClient("", config) - - -# STEP 2 Call the transcribe_file method on the prerecorded class -def transcribe_file(): - # Logic to read the file - with open(AUDIO_FILE, "rb") as file: - buffer_data = file.read() - - payload: FileSource = { - "buffer": buffer_data, - } - - file_response = deepgram.listen.prerecorded.v("1").transcribe_file(payload, options) - return file_response - - def main(): try: - response = transcribe_file() - print(response) - print("") - json = response.to_json() - print("") - print(json) + # STEP 1 Create a Deepgram client using the API key in the environment variables + config: DeepgramClientOptions = DeepgramClientOptions( + verbose=logging.SPAM, + ) + + deepgram: DeepgramClient = DeepgramClient("", config) + + # STEP 2 Call the transcribe_file method on the prerecorded class + with open(AUDIO_FILE, "rb") as file: + buffer_data = file.read() + + payload: FileSource = { + "buffer": buffer_data, + } + + options = PrerecordedOptions( + model="nova", + smart_format=True, + utterances=True, + punctuate=True, + diarize=True, + ) + file_response = deepgram.listen.prerecorded.v("1").transcribe_file(payload, options) + + print(f"\n\n{file_response}\n\n") + json = file_response.to_json() + print(f"{json}\n") + except Exception as e: print(f"Exception: {e}") diff --git a/examples/prerecorded/url/main.py b/examples/prerecorded/url/main.py index d82382d6..b9ec12f0 100644 --- a/examples/prerecorded/url/main.py +++ b/examples/prerecorded/url/main.py @@ -14,30 +14,20 @@ "url": "https://static.deepgram.com/examples/Bueller-Life-moves-pretty-fast.wav" } -options = PrerecordedOptions( - model="nova", - smart_format=True, - summarize="v2", -) - -# STEP 1 Create a Deepgram client using the API key (optional - add config options) -config = DeepgramClientOptions( - verbose=logging.SPAM, -) - -deepgram = DeepgramClient("", config) - - -# STEP 2 Call the transcribe_url method on the prerecorded class -def transcribe_url(): - url_response = deepgram.listen.prerecorded.v("1").transcribe_url(AUDIO_URL, options) - return url_response - - def main(): try: - response = transcribe_url() - print(response) + # STEP 1 Create a Deepgram client using the API key from environment variables + deepgram = DeepgramClient() + + # STEP 2 Call the transcribe_url method on the prerecorded class + options = PrerecordedOptions( + model="nova", + smart_format=True, + summarize="v2", + ) + url_response = deepgram.listen.prerecorded.v("1").transcribe_url(AUDIO_URL, options) + print(url_response) + except Exception as e: print(f"Exception: {e}") diff --git a/examples/streaming/http/main.py b/examples/streaming/http/main.py index 5ffc9cbb..81e8550c 100644 --- a/examples/streaming/http/main.py +++ b/examples/streaming/http/main.py @@ -16,37 +16,28 @@ # URL for the realtime streaming audio you would like to transcribe URL = "http://stream.live.vc.bbcmedia.co.uk/bbc_world_service" - -def on_message(result=None): - if result is None: - return - sentence = result.channel.alternatives[0].transcript - if len(sentence) == 0: - return - print(f"speaker: {sentence}") - - -def on_metadata(metadata=None): - if metadata is None: - return - print("") - print(metadata) - print("") - - -def on_error(error=None): - if error is None: - return - print("") - print(error) - print("") - - def main(): - # config: DeepgramClientOptions = DeepgramClientOptions(options={'keepalive': 'true'}) - deepgram = DeepgramClient() - try: + deepgram = DeepgramClient() + + def on_message(result=None): + if result is None: + return + sentence = result.channel.alternatives[0].transcript + if len(sentence) == 0: + return + print(f"speaker: {sentence}") + + def on_metadata(metadata=None): + if metadata is None: + return + print(f"\n{metadata}\n") + + def on_error(error=None): + if error is None: + return + print(f"\n{error}\n") + # Create a websocket connection to Deepgram dg_connection = deepgram.listen.live.v("1") dg_connection.start(options) @@ -82,7 +73,7 @@ def myThread(): # Wait for the HTTP thread to close and join myHttp.join() - # Indicate that we've finished sending data by sending the {"type": "CloseStream"} + # Indicate that we've finished dg_connection.finish() print("Finished") diff --git a/examples/streaming/microphone/main.py b/examples/streaming/microphone/main.py index 8a3aba90..adb5adad 100644 --- a/examples/streaming/microphone/main.py +++ b/examples/streaming/microphone/main.py @@ -16,54 +16,44 @@ load_dotenv() -# example of setting up a client config -# config = DeepgramClientOptions( -# verbose=logging.SPAM, -# options={'keepalive': 'true'} -# ) - -options = LiveOptions( - punctuate=True, - language="en-US", - encoding="linear16", - channels=1, - sample_rate=16000, -) - - -def on_message(result=None): - if result is None: - return - sentence = result.channel.alternatives[0].transcript - if len(sentence) == 0: - return - print(f"speaker: {sentence}") - - -def on_metadata(metadata=None): - if metadata is None: - return - print("") - print(metadata) - print("") - - -def on_error(error=None): - if error is None: - return - print("") - print(error) - print("") - - def main(): - # to specify a client config - # deepgram: DeepgramClient = DeepgramClient("", config) - # otherwise, use default config - deepgram = DeepgramClient() - try: + # example of setting up a client config + # config = DeepgramClientOptions( + # verbose=logging.SPAM, + # options={'keepalive': 'true'} + # ) + # deepgram: DeepgramClient = DeepgramClient("", config) + # otherwise, use default config + deepgram = DeepgramClient() + # Create a websocket connection to Deepgram + options = LiveOptions( + punctuate=True, + language="en-US", + encoding="linear16", + channels=1, + sample_rate=16000, + ) + + def on_message(result=None): + if result is None: + return + sentence = result.channel.alternatives[0].transcript + if len(sentence) == 0: + return + print(f"speaker: {sentence}") + + def on_metadata(metadata=None): + if metadata is None: + return + print(f"\n{metadata}\n") + + def on_error(error=None): + if error is None: + return + print(f"\n{error}\n") + dg_connection = deepgram.listen.live.v("1") dg_connection.start(options) @@ -71,7 +61,7 @@ def main(): dg_connection.on(LiveTranscriptionEvents.Metadata, on_metadata) dg_connection.on(LiveTranscriptionEvents.Error, on_error) - # Open a microphone stream + # create microphone microphone = Microphone(dg_connection.send) # start microphone @@ -80,10 +70,10 @@ def main(): # wait until finished input("Press Enter to stop recording...\n\n") - # Wait for the connection to close + # Wait for the microphone to close microphone.finish() - # Indicate that we've finished sending data by sending the {"type": "CloseStream"} + # Indicate that we've finished dg_connection.finish() print("Finished")