Skip to content

Commit

Permalink
Restructure Python SDK Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dvonthenen committed Nov 9, 2023
1 parent 13e734f commit 74ae8a6
Show file tree
Hide file tree
Showing 14 changed files with 45 additions and 91 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/CD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ jobs:
with:
python-version: '3.10'

- name: Update Version in _version.py
run: sed -i 's/0.0.0/${{ github.event.release.tag_name }}/g' ./deepgram/_version.py
- name: Update Version in __init__.py
run: sed -i 's/0.0.0/${{ github.event.release.tag_name }}/g' ./deepgram/__init__.py

- name: Install Dependencies
run: pip install .
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
*.egg-info
*/__pycache__/
__pycache__
dist/
.venv
.env
venv/
venv.bak/
build/
38 changes: 13 additions & 25 deletions deepgram/__init__.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
from deepgram.deepgram_client import DeepgramClient
from .types.deepgram_client_options import DeepgramClientOptions

def create_client(api_key: str, config_options: DeepgramClientOptions = None) -> DeepgramClient:
"""
Create a DeepgramClient instance with the provided API key and optional configuration options.
This function initializes and returns a DeepgramClient instance, which can be used to interact with the Deepgram API. You can provide an API key for authentication and customize the client's configuration by passing a DeepgramClientOptions object.
# version
__version__ = '0.0.0'

Args:
api_key (str): The Deepgram API key used for authentication.
config_options (DeepgramClientOptions, optional): An optional configuration object specifying client options. If not provided, the default settings will be used.
Returns:
DeepgramClient: An instance of the DeepgramClient class for making requests to the Deepgram API.
Example usage:
To create a DeepgramClient instance with a custom configuration:
# entry point for the deepgram python sdk
from .deepgram_client import DeepgramClient
from .types.deepgram_client_options import DeepgramClientOptions
from .errors import DeepgramError, DeepgramApiError, DeepgramUnknownApiError, DeepgramUnknownError

>>> api_key = "your_api_key"
>>> custom_options = DeepgramClientOptions(global_options={"url": "custom_url", "headers": {"Custom-Header": "value"}})
>>> client = create_client(api_key, config_options=custom_options)
# live
from .types.transcription_options import LiveOptions
from .enums import LiveTranscriptionEvents

Example usage with default settings:
# prerecorded
from .types.transcription_options import PrerecordedOptions

>>> api_key = "your_api_key"
>>> client = create_client(api_key)
"""
return DeepgramClient(api_key, config_options)
# manage
from .clients.manage_client import ManageClient
1 change: 0 additions & 1 deletion deepgram/_version.py

This file was deleted.

9 changes: 1 addition & 8 deletions deepgram/clients/prerecorded_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ async def transcribe_file(self, source: FileSource, options: PrerecordedOptions=
Exception: For any other unexpected exceptions.
"""

url = f"{self.url}/{endpoint}"
await self._set_file_mimetype_headers(source)
url = f"{self.url}/{endpoint}"
if is_buffer_source(source):
body = source["buffer"]
elif is_readstream_source(source):
Expand Down Expand Up @@ -139,16 +138,10 @@ async def transcribe_file_callback(self, source: FileSource, callback:str, optio
if options is None:
options = {}
options['callback'] = callback
await self._set_file_mimetype_headers(source)
if is_buffer_source(source):
body = source["buffer"]
elif is_readstream_source(source):
body = source["stream"]
else:
raise DeepgramError("Unknown transcription source type")
return await self.post(url, options, content=body)

async def _set_file_mimetype_headers(self, source: FileSource) -> None:
if "mimetype" not in source or not source["mimetype"]:
raise DeepgramError("Mimetype must be provided if the source is a Buffer or a Readable")
self.headers["Content-Type"] = source["mimetype"]
2 changes: 1 addition & 1 deletion deepgram/deepgram_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class DeepgramClient:
onprem: Returns an OnPremClient instance for interacting with Deepgram's on-premises API.
"""
def __init__(self, api_key: str, config_options: Optional[DeepgramClientOptions]):
def __init__(self, api_key: str, config_options: Optional[DeepgramClientOptions] = None):
if not api_key:
raise DeepgramError("Deepgram API key is required")

Expand Down
1 change: 0 additions & 1 deletion deepgram/errors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@


class DeepgramError(Exception):
"""
Base class for exceptions raised by the Deepgram API client.
Expand Down
19 changes: 0 additions & 19 deletions deepgram/types/transcription_options.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,5 @@
from typing import Union, List, TypedDict

class TranscriptionOptions(TypedDict, total=False):
callback: str
diarize: bool
keywords: Union[List[str], str]
language: str
model: str
multichannel: bool
numerals: bool
punctuate: bool
profanity_filter: bool
redact: Union[List[str], List[bool], bool]
replace: Union[List[str], str]
search: Union[List[str], str]
smart_format: bool
tag: List[str]
tier: str
version: str


class PrerecordedOptions(TypedDict, total=False):
alternatives: int
callback: str
Expand Down
8 changes: 3 additions & 5 deletions examples/demo_live.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from deepgram import create_client, DeepgramClient
from deepgram.enums import LiveTranscriptionEvents
from deepgram import DeepgramClient, LiveTranscriptionEvents, LiveOptions
from dotenv import load_dotenv
import asyncio
import aiohttp
Expand All @@ -21,7 +20,7 @@
}
}

options = {
options: LiveOptions = {
'model': 'nova',
'interim_results': False,
'language': 'en-US'
Expand All @@ -34,8 +33,7 @@


async def main():
deepgram: DeepgramClient = create_client(deepgram_api_key)
# deepgram: DeepgramClient = create_client(deepgram_api_key, config_options)
deepgram: DeepgramClient = DeepgramClient(deepgram_api_key)

# Create a websocket connection to Deepgram
try:
Expand Down
4 changes: 2 additions & 2 deletions examples/demo_manage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncio
import os
from deepgram import create_client, DeepgramClient
from deepgram import DeepgramClient
from dotenv import load_dotenv
load_dotenv()

Expand All @@ -19,7 +19,7 @@
}

# Create a Deepgram client using the API key
deepgram: DeepgramClient = create_client(API_KEY)
deepgram: DeepgramClient = DeepgramClient(API_KEY)

async def main():
response = await deepgram.manage.get_projects()
Expand Down
28 changes: 12 additions & 16 deletions examples/demo_prerecorded.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,46 @@
from deepgram import DeepgramClient, PrerecordedOptions
import asyncio
import os
from deepgram import create_client
from deepgram.deepgram_client import DeepgramClient
from dotenv import load_dotenv
load_dotenv()

API_KEY = os.getenv('DG_API_KEY')
AUDIO_FILE = "preamble.wav"
AUDIO_URL = {"url":"https://static.deepgram.com/examples/Bueller-Life-moves-pretty-fast.wav"}
OPTIONS = {
"model": "nova",
"smart_format": "true",
"summarize": "v2",
}
CALLBACK = "https://example.com/callback"

# STEP 1 Create a Deepgram client using the API key (optional - add config options)
deepgram: DeepgramClient = create_client(API_KEY)
options: PrerecordedOptions = {
"model": "nova",
"smart_format": "true",
"summarize": "v2",
}

# STEP 1 Create a Deepgram client using the API key (optional - add config options)
deepgram = DeepgramClient(API_KEY)

###### TRANSCRIBE A LOCAL FILE #####

# Logic to read the file
async def transcribe_file():
# Logic to read the file
with open(AUDIO_FILE, 'rb') as file:
buffer_data = file.read()

PAYLOAD = {
"buffer": buffer_data,
"mimetype": "audio/wav",
}

# STEP 2 Call the transcribe_file method on the prerecorded class
file_response = await deepgram.listen.prerecorded.transcribe_file(PAYLOAD, OPTIONS)
file_response = await deepgram.listen.prerecorded.transcribe_file(PAYLOAD, options)
return file_response


###### TRANSCRIBE A HOSTED FILE #####
async def transcribe_url():
# STEP 2 Call the transcribe_url method on the prerecorded class
url_response = await deepgram.listen.prerecorded.transcribe_url(AUDIO_URL, OPTIONS)
# url_response = await deepgram.listen.prerecorded.transcribe_url_callback(AUDIO_URL,CALLBACK, OPTIONS)
url_response = await deepgram.listen.prerecorded.transcribe_url(AUDIO_URL, options)
# url_response = await deepgram.listen.prerecorded.transcribe_url_callback(AUDIO_URL,CALLBACK, options)
return url_response



async def main():
# response = await transcribe_file()
response = await transcribe_url()
Expand Down
2 changes: 1 addition & 1 deletion examples/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
-e ../../
-e ../
httpx
typing_extensions
python-dotenv
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
build-backend = "setuptools.build_meta"

[project]
name = "deepgram-sdk"
dynamic = ["version"]

[tool.setuptools.dynamic]
version = {attr = "deepgram.__version__"}
8 changes: 0 additions & 8 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
import setuptools
import os.path

# from official Python version-detection recommendations: https://packaging.python.org/guides/single-sourcing-package-version/

with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'deepgram', '_version.py'), encoding="utf8") as file:
exec(file.read())
# imports as __version__

with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md'), encoding="utf8") as file:
long_description = file.read()

setuptools.setup(
name='deepgram-sdk',
version=__version__, # type: ignore
description='The official Python SDK for the Deepgram automated speech recognition platform.',
long_description=long_description,
long_description_content_type='text/markdown',
Expand Down

0 comments on commit 74ae8a6

Please sign in to comment.