Translate the speech using OpenAI in Python

Discover how to translate any audio to English text using the OpenAI model in Python. This notebook covers opening an audio file, sending a translation request, and printing the response.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

MLJAR Studio imports packages automatically so you don't have to worry about it.

# import packages
import os
from dotenv import load_dotenv
from openai import OpenAI, AuthenticationError

# we added below import manually
from IPython.display import IFrame

Connection with OpenAI client:

# load .env file
load_dotenv()

# get api key from environment
api_key = os.environ["OPENAI_KEY"]

# create OpenAI client
def create_client(api_key):
    try:
        client = OpenAI(api_key=api_key)
        client.models.list()
        return client
    except AuthenticationError:
        print("Incorrect API")
    return None

client = create_client(api_key)

In this example, we will use the video with popular Polish celebrity - Mariusz Pudzianowski

# we added the cell with IFrame manually to show which video we used
IFrame('https://www.youtube.com/embed/NbFJPpbH51s', width=640, height=360)

The code that allows to create the translation:

# open the file
file = open(r"../../../../Downloads/mariusz-pudzianowski.mp4", "rb")

# send translation request
translation = client.audio.translations.create(
    model="whisper-1",
    file=file,
    response_format="text"
)

# print response
print(translation)

Conclusions

Video translation is a handy skill that can save you in many situations. It's also important to remember that you can translate only into English.

Recipes used in the openai-speech-translation.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the openai-speech-translation.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.

openai>=1.35.14

python-dotenv>=1.0.1