Skip to main content

The official Python SDK for the Deepgram automated speech recognition platform.

Project description

Deepgram Python SDK

GitHub Workflow Status PyPI Contributor Covenant

Official Python SDK for Deepgram. Start building with our powerful transcription & speech understanding API.

This SDK only supports hosted usage of api.deepgram.com.

Getting an API Key

🔑 To access the Deepgram API you will need a free Deepgram API Key.

Documentation

Complete documentation of the Python SDK can be found at Deepgram Docs.

You can learn more about the Deepgram API at developers.deepgram.com.

Getting Started

pip install deepgram-sdk

Usage

Transcribe an Existing File or Pre-recorded Audio

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()

Transcribe an Existing File or Pre-recorded Audio Asynchronously

from deepgram import Deepgram
import asyncio, json

DEEPGRAM_API_KEY = 'YOUR_API_KEY'
PATH_TO_FILE = 'some/file.wav'

async 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 = await deepgram.transcription.prerecorded(source, {'punctuate': True})
        print(json.dumps(response, indent=4))

asyncio.run(main())

Transcribe Audio in Real-Time or Streaming Audio

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.

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.

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 on our Deepgram blog.

Streaming Audio Code Samples

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:

  • Flask 2.0
  • FastAPI
  • Django
  • Quart

Development and Contributing

Interested in contributing? We ❤️ pull requests!

To make sure our community is safe for all, be sure to review and agree to our Code of Conduct. Then see the Contribution guidelines for more information.

Getting Help

We love to hear from you so if you have questions, comments or find a bug in the project, let us know! You can either:

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deepgram-sdk-2.9.0.tar.gz (20.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

deepgram_sdk-2.9.0-py3-none-any.whl (23.4 kB view details)

Uploaded Python 3

File details

Details for the file deepgram-sdk-2.9.0.tar.gz.

File metadata

  • Download URL: deepgram-sdk-2.9.0.tar.gz
  • Upload date:
  • Size: 20.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for deepgram-sdk-2.9.0.tar.gz
Algorithm Hash digest
SHA256 0653a648cbe556b4b2075c52a1adcdcd0064ba6af98e8b4812161c78442cc76f
MD5 6599fd32d35b0b68bebd2831c9e94a8a
BLAKE2b-256 7f44b459c3f040c758454f828ebc1712de711ddb69074a0b249b090dd91f57e0

See more details on using hashes here.

File details

Details for the file deepgram_sdk-2.9.0-py3-none-any.whl.

File metadata

  • Download URL: deepgram_sdk-2.9.0-py3-none-any.whl
  • Upload date:
  • Size: 23.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for deepgram_sdk-2.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6ec1472bac7e3ab8a5b5b66865c66585fe30b6e86d66c445edbed2695b9d5272
MD5 8e4fd691b2a674fb43400d530d224d7f
BLAKE2b-256 3a7d937252d37058af56d97ee8791e36e025b3e581defe02ad95e227ade1b67e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page