Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,20 +131,17 @@ Depending on your preference, you can also add parameters as named arguments, in
response = await dg_client.transcription.prerecorded(source, punctuate=True, keywords=['first:5', 'second'])
```

## Code Samples

To run the sample code, you may want to create a virtual environment to isolate your Python projects, but it's not required. You can learn how to make and activate these virtual environments in [this article](https://blog.deepgram.com/python-virtual-environments/) on our Deepgram blog.
## Testing

#### Streaming Audio Code Samples
### Setup

In the `sample-projects` folder, there are examples from four different Python web frameworks of how to do live streaming audio transcription with Deepgram. These include:
Run the following command to install `pytest` and `pytest-cov` as dev dependencies.

- Flask 2.0
- FastAPI
- Django
- Quart
```
pip install -r requirements-dev.txt
```

## Testing
### Run All Tests

### Setup

Expand All @@ -165,6 +162,17 @@ pytest --api-key <key> tests/
pytest --cov=deepgram --api-key <key> tests/
```

### Using Example Projects to test new features

Contributors to the SDK can test their changes locally by running the projects in the `examples` folder. This can be done when making changes without adding a unit test, but of course it is recommended that you add unit tests for any feature additions made to the SDK.

Go to the folder `examples` and look for these two projects, which can be used to test out features in the Deepgram Python SDK:

- prerecorded
- streaming

These are standalone projects, so you will need to follow the instructions in the `README.md` files for each project to get it running.

## Development and Contributing

Interested in contributing? We ❤️ pull requests!
Expand Down
76 changes: 76 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Examples for Testing Features Locally

The example projects are meant to be used to test features locally by contributors working on this SDK, but they can also be used as quickstarts to get up and running with the Deeegram Python SDK.

Here are the steps to follow to run the examples with the **local version** of the SDK:

## Add Your Code

Make your changes to the SDK (be sure you are on a branch you have created to do this work).

## Install dependencies

You can choose between two methods for installing the Deepgram SDK from the local folder:

### Install locally with the `examples/<example>/requirements.txt` file

Move to within the `examples/<example>` folder and run the following command to install the project dependencies. This command will install the dependencies from the local repo due to the package being added as `-e ../../` The`-e` indicates that a package should be installed in "editable" mode, which means in-place from the source code (local folder).

`pip install -r requirements.txt`

### Install locally with `pip install -e`

The other method that can be used to install the Deepgram SDK from the local project is to use `pip install -e`. In this case, you would:

```
pip uninstall deepgram-sdk # If it's already installed
cd /path/to/deepgram-python-sdk/ # navigate to inside the deepgram SDK
pip install -e .
```

This will install the SDK from the local source code in editable mode, so any changes made inside the project will be instantly usable from the example files.

### Edit the API key

Inside the example file, replace the API key where it says 'YOUR_DEEPGRAM_API_KEY'

`DEEPGRAM_API_KEY = 'YOUR_DEEPGRAM_API_KEY'`

### Run the project

Make sure you're in the directory with the `main.py` file and run the project with the following command.

`python main.py`

### After testing

After you have used the example files to test your code, be sure to reset the example file to the way it was when you started (i.e. discard features you may have added to the options dictionary when testing features).

## How to verify that you're testing the local changes

If you want to be sure that you are testing the local `deepgram` package, you can run this check.

### Step 1

Launch the Python interpreter by typing `python` in the terminal. Make sure you are in the folder with the `main.py` file you will be using to run the test.

```
python
```

### Step 2

Inside the interpreter, run the following code. This will import the `importlib` modules and use `find_spec()` to determine the location of the imported module.

```py
import importlib.util

spec = importlib.util.find_spec("deepgram")
if spec is not None:
print("Module 'deepgram' is imported from:", spec.origin)
else:
print("Module 'deepgram' is not found.")

```

This code checks whether the module named "deepgram" is imported and, if so, prints its origin (i.e., the location from where it's imported).
71 changes: 71 additions & 0 deletions examples/prerecorded/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Example filename: deepgram_test.py

import json
import asyncio

from deepgram import Deepgram

# Your Deepgram API Key
DEEPGRAM_API_KEY = 'YOUR_DEEPGRAM_API_KEY'

# Location of the file you want to transcribe. Should include filename and extension.
# Example of a local file: ../../Audio/life-moves-pretty-fast.wav
# Example of a remote file: https://static.deepgram.com/examples/interview_speech-analytics.wav
FILE = 'https://static.deepgram.com/examples/interview_speech-analytics.wav'

# Mimetype for the file you want to transcribe
# Include this line only if transcribing a local file
# Example: audio/wav
MIMETYPE = 'audio/mpeg'


async def main():

# Initialize the Deepgram SDK
deepgram = Deepgram(DEEPGRAM_API_KEY)

# Check whether requested file is local or remote, and prepare source
if FILE.startswith('http'):
# file is remote
# Set the source
source = {
'url': FILE
}
else:
# file is local
# Open the audio file
audio = open(FILE, 'rb')

# Set the source
source = {
'buffer': audio,
'mimetype': MIMETYPE
}

# Send the audio to Deepgram and get the response
response = await asyncio.create_task(
deepgram.transcription.prerecorded(
source,
{
'detect_language': "true",
'summarize': "v2",
}
)
)

# Write the response to the console
print(json.dumps(response, indent=4))

# Write only the transcript to the console
# print(response["results"]["channels"][0]["alternatives"][0]["transcript"])

# print(response["results"]["channels"])

try:
# If running in a Jupyter notebook, Jupyter is already running an event loop, so run main with this line instead:
# await main()
asyncio.run(main())
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
line_number = exception_traceback.tb_lineno
print(f'line {line_number}: {exception_type} - {e}')
1 change: 1 addition & 0 deletions examples/prerecorded/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-e ../../
54 changes: 54 additions & 0 deletions examples/streaming/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Example filename: deepgram_test.py

from deepgram import Deepgram
import asyncio
import aiohttp

# Your Deepgram API Key
DEEPGRAM_API_KEY = ''

# URL for the realtime streaming audio you would like to transcribe
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 UK English.
try:
deepgramLive = await deepgram.transcription.live({
'smart_format': True,
'interim_results': False,
'language': 'en-US',
'model': 'nova',
})
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 no data is being sent from the live stream, 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()

# If running in a Jupyter notebook, Jupyter is already running an event loop, so run main with this line instead:
# await main()
asyncio.run(main())
3 changes: 3 additions & 0 deletions examples/streaming/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-e ../../
asyncio
aiohttp
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ aiohttp
pytest
pytest-asyncio
fuzzywuzzy
pytest-cov

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading