Audio to Text utilizing Python and OpenAI

Audio to Text utilizing Python and OpenAI

Introduction

In the next tutorial, I’ll construct a fundamental app to acknowledge audio recordsdata and convert them to textual content. Moreover, with OpenAI API instruments, a Python library "pydub" for audio manipulation, and the library python-dotenv to avoid wasting atmosphere variables, it is simple to do. Without cumbersome code, it’s straightforward to observe with an in depth rationalization to make it work in your each day duties.

Let’s get soiled:

Clone the repository:

git clone https://github.com/ivansing/audio-to-text-app.git
    cd audio-to-text-app

You ought to get the pattern recordsdata in property and duplicate them to your property folder.

Setting Up the Environment

Prerequisites:

  • Basic Python language
  • Code Editor
  • Basic command line

Step 1: Setting Up the Project

  • Install Python Here. It is easy; simply observe the (beneficial) prompts to "sure."
  • I’ll use VS Code as managing any undertaking and improvement is comparatively straightforward.
  • Open VS Code on the prime of the bar and press Terminal within the dropdown field. Select New Terminal and sort the next bash command:
mkdir audio-text-app

Then transfer to the listing that we did beforehand:

cd audio-text-app

Your initiatives would then be situated in paths like:
/house/your-username/Projects/my_project (Linux)
/Users/your-username/Projects/my_project (Mac)

In your folder audio-text-app create the next recordsdata:

contact audio-to-text.py .env

The file audio-text-app is for this small script app’s major performance and entry level.
.env is the place I’ll save the API keys from OpenAi. I’ll use it within the following steps.

For Windows utilizing Linux subsystem WSL

  • Open VS Code, press F1, and choose connect with WSL.
  • Follow the earlier steps from Linux/Mac.

Step 2: Install Required Libraries and folders recordsdata

  • In your command line home windows, kind the next directions:
pip set up openai pydub python-dotenv
  • Install FFmpeg:

    • On macOS (utilizing Homebrew): brew set up ffmpeg
    • On Ubuntu: sudo apt set up ffmpeg
    • On Windows: Download and set up from ffmpeg.org
  • Make one other listing named: property contained in the audio-text-app folder. I’ll use it to get the audio .wav recordsdata for testing:

mkdir property

Step 3: Setup your OpenAI API Key:

  • Go to OpenAI and signal as much as generate your openai-api-key.

Follow to create API key

  • Then, Create a brand new secret key, which is the openai-api-key.

Create key button

  • Follow the steps within the popup modal window, and press "Create secret key."

Modal window form

  • Finally, Save this generated key in a notepad or protected place, all the time hidden from the general public, and press "Done."

Copy openai secret key

Now that we have now already generated our treasured hidden key, let’s maintain the next:

Step 4: Write the code

  • Import the libraries:
import openai
from pydub import AudioPhase
import os 
import uuid 
from dotenv import load_dotenv 
  • open: For interplay with the OpenAI Whisper API to transcribe audio.
  • pydub: This will make the file smaller in order to not stress an excessive amount of the CPU work when dealing with audio file manipulations like altering channels (mono) and resampling.
  • os: To generate distinctive file names for processed audio, eradicating redundant output recordsdata.
  • uuid: To generate distinctive file names for processed audio.
  • dotenv To load atmosphere variables from a .env file, which securely shops the API key.

Functions

convert_to_mono_16k

def convert_to_mono_16k(audio_file_path, output_dir="property"):
    """Converts audio to mono and 16kHz, returns the trail to the transformed audio."""
    sound = AudioPhase.from_file(audio_file_path)
    sound = sound.set_channels(1)  # Mono
    sound = sound.set_frame_rate(16000)  # 16kHz

    # Generate a singular filename for the mono model
    converted_file_name = f"{uuid.uuid4()}.wav"
    converted_file_path = os.path.be part of(output_dir, converted_file_name)

    # Export the transformed audio file
    sound.export(converted_file_path, format="wav")
    return converted_file_path

This operate takes an audio file, converts it to mono (1 audio channel), and resamples it to 16kHz, which is required for optimum transcription with Whisper.

  • The audio file is loaded utilizing AudioPhase.
  • It is transformed to mono with set_channels(1).
  • The pattern price is about to 16kHz utilizing set_frame_rate(16000).
  • A singular file identify is generated utilizing uuid to keep away from filename conflicts.
  • The processed audio file is exported to the desired output listing (property by default).
  • This operate returns the file path of the transformed audio, which can be used later for transcription.

transcribe_audio

def transcribe_audio(audio_file_path, clean_up=True):
    """Transcribes audio to textual content utilizing OpenAI's Whisper."""
    # Convert audio to mono and 16kHz
    mono_audio_path = convert_to_mono_16k(audio_file_path)

    # Transcribe audio utilizing OpenAI's Whisper
    with open(mono_audio_path, "rb") as audio_file:
        transcript = openai.Audio.transcribe("whisper-1", audio_file)

    # Clean up the transformed file if wanted
    if clean_up:
        os.take away(mono_audio_path)

    return transcript['text']

This operate transcribes an audio file into textual content utilizing the OpenAI Whisper API.

  • It calls the convert_to_mono_16k operate to make sure the audio is within the right format (mono, 16kHz).
  • The transformed file is opened in binary mode "rb" and handed to the Whisper API transcription.
  • The operate optionally cleans up (deletes) the momentary audio file after the transcription, managed by the clean_up argument.
  • The operate returns the transcription textual content extracted from the Whisper API’s response.

Test code

# Example utilization
audio_file = "property/jackhammer.wav"
transcription = transcribe_audio(audio_file)
print("Transcription:", transcription)

This part demonstrates easy methods to use the transcribe_audio operate.

Besides the samples which are saved within the property folder, you possibly can add extra .wav recordsdata to check it

Test the code with the next command:

python3 audio-to-text.py

Now test the output textual content from the audio file within the terminal:

Test Output text

  • The audio_file variable specifies the audio file to be transcribed.
  • The transcribre_audio operate is known as with the audio file path.
  • The transcription result’s printed to the console.

Summary

It was an excellent tutorial for studying the premise of utilizing numerous Python libraries. After all, we realized the OpenAI API Whisper, which is a educated mannequin primarily based on a neural internet on English speech recognition. And using pydub to govern the audio. I used native Python libraries os for path supply and definition and uuid to rename the mono output file.

Conclusion

Python is an enormous universe that’s used basically software program building. You can use this software as a part of a small software program bundle. It is a necessary program that wants many extra issues, like extra take a look at instances than you possibly can think about. Ideally, you possibly can have an output textual content file, however for this brief tutorial, I did not wish to add extra complexity; if you are going to add extra options, have a look at Python docs, and you’ll be amazed at what you possibly can manipulate on this world and with the assistance of API (exterior packages to speak), there can be unbelievable software program builds.

References

About the Author

Ivan Duarte is a backend developer with expertise working freelance. He is captivated with internet improvement and synthetic intelligence and enjoys sharing their data by way of tutorials and articles. Follow me on X, Github, and LinkedIn for extra insights and updates.

HI-FI News

through DEV Community https://dev.to

October 2, 2024 at 03:19AM