Python Speech Recognition Tutorial – Full Course for Beginners
Course Introduction
This section introduces the course and its instructors. It also provides an overview of the projects that will be covered in the course.
Course Overview
- The course teaches how to implement speech recognition in Python by building five projects.
- The instructors are Patrick, an experienced software engineer, and Alyssa, an experienced data scientist. They are both developer advocates at Assembly AI.
- Assembly AI is a deep learning company that creates a speech-to-text API, which will be used in this course. They provided a grant that made this course possible.
- The five projects covered in the course are:
- Project 1: Capturing audio information from a microphone and saving it as a WAV file.
- Project 2: Speech recognition using assembly API's API.
- Project 3: Sentiment analysis on iPhone reviews found on YouTube.
- Project 4: Summarizing podcasts found online and building a web app to show results to users.
- Project 5: Using speech recognition with open AI API to make an app that can answer user questions.
Part One - Audio Processing Basics
This section covers audio processing basics such as different audio file formats, parameters of audio signals, loading and saving WAV files, plotting wave signals, microphone recording in Python, and loading other file formats like mp3 files.
Different Audio File Formats
- Three popular audio file formats are mp3 (lossy compression format), FLAC (lossless compression format), and WAV (uncompressed format). WAV is the standard for CD audio quality and is easy to work with in Python because of the built-in wav module.
Parameters of Audio Signals
- Important parameters of audio signals include:
- Number of channels (usually one or two)
- Sample width (number of bytes for each sample)
- Frame rate (sample rate or sample frequency, number of samples per second)
- Number of frames
- Values in each frame (in binary format, can be converted to integer values later)
Loading and Saving WAV Files
- The built-in wav module can be used to load and save WAV files.
Plotting Wave Signals
- Wave signals can be plotted using Python.
Microphone Recording in Python
- Microphone recording in Python is possible using the PyAudio library.
Loading Other File Formats
- Other file formats like mp3 files can also be loaded using Python libraries such as pydub.
Python WAV File Processing
In this section, the speaker explains how to read and extract parameters from a WAV file using Python.
Reading Parameters from a WAV File
- To read a WAV file in Python, create an object with
wave.openand specify the filename.
- Use
read binaryto read the file.
- Extract parameters such as number of channels, sample width, frame rate, and number of frames using
object.getNchannels,object.getsampwidth,object.getframerate, andobject.getnframes.
- Get all parameters at once by calling
object.getparams().
Calculating Time and Extracting Frames
- Calculate the time of the audio by dividing the number of frames by the frame rate.
- Extract frames using
object.readframes(-1)to read all frames or specify a specific number of frames.
- The length of the frames object is twice as much as the number of frames because there are two bytes per sample. Divide by two to get the correct number of frames.
Writing Parameters to a New WAV File
- Create a new object with
wave.openin write binary mode and specify a new filename for writing data.
- Set parameters such as number of channels, sample width, frame rate using setters like
new.setnchannels(1),new.setsampwidth(2), andnew.setframerate(16000).
- Write data to the new file using
new.writeframes(frames)where 'frames' is extracted from original file's object.
Plotting a WAV File in Python
In this section, the speaker explains how to plot a WAV file using Python.
Plotting a Wave Signal
- Install matplotlib and NumPy libraries.
- Import necessary modules such as wave and matplotlib.pyplot.
- Read frames from the WAV file object using
object.readframes(-1).
- Convert the frames to an array using NumPy's
frombuffermethod.
- Plot the signal using
matplotlib.pyplot.plot().
Reading and Plotting Audio Files
In this section, the speaker explains how to read and plot audio files using Python.
Reading Audio Files
- To read an audio file, use the wave module in Python.
- Use
wave.open()to open the file andobject.readframes(-1)to get all the frames of the signal.
- Calculate the length of the signal in seconds by dividing the number of samples by sample frequency.
Plotting Audio Signals
- Convert the bytes object into a numpy array using
numpy.frombuffer().
- Create an object for x-axis or time axis using
numpy.linspace().
- Create a figure with fixed size using
plt.figure().
- Plot times against signal array using
plt.plot().
- Add title, y-label, x-label, and limit for x-axis using
plt.title(),plt.ylabel(),plt.xlabel(), andplt.xlim()respectively.
- Display plot using
plt.show().
Recording Audio with Microphone
In this section, the speaker explains how to record audio with a microphone and capture it in Python.
Setting Up Parameters
- Use PyAudio library to play and record audio.
- Set up parameters such as frames per buffer, format (e.g. PRint16), number of channels (e.g. 1), and frame rate (e.g. 16000).
Recording Audio
- Create PyAudio object using
pyaudio.PyAudio().
- Create stream object using
.open()method with specified parameters.
- Start recording for a certain duration (e.g. 5 seconds).
- Store recorded frames in a list object.
Saving Recorded Audio
In this section, the speaker explains how to save recorded audio in a WAV file.
Saving Audio
- Use wave module to create a new WAV file using
wave.open().
- Set parameters such as number of channels, sample width (e.g. 2), frame rate, and number of frames.
- Write frames to the file using
.writeframes()method.
- Close the file using
.close()method.
Recording Audio with Python
In this section, the speaker explains how to record audio using Python.
Recording Audio
- To record audio, we need to import the PyAudio library.
- We set up a stream and define its parameters such as sample rate, chunk size, and format.
- We then start the stream and read data from it for five seconds.
- After reading each chunk of data, we append it to a list called frames.
- Once we have all the frames, we close the stream and terminate the process.
Saving Recorded Audio
- To save recorded audio in a WAV file format, we use the wave module.
- We open a new WAV file in write binary mode and set its parameters such as number of channels, sample width, frame rate etc.
- We then write all the frames into this file by converting them into binary strings using join().
- Finally, we close the file object to complete saving our recorded audio in WAV format.
Loading MP3 Files with Python
In this section, the speaker explains how to load MP3 files using Python.
Loading MP3 Files
- To load MP3 files in Python, we need to install an additional third-party library called Pydub which provides an easy-to-use interface for loading and manipulating audio files.
- We can install Pydub using pip after installing FFmpeg on our system.
- Once installed, we can import the AudioSegment class from Pydub and use it to load MP3 files.
- We can also manipulate loaded audio files using various methods such as increasing volume, repeating clips, fading in/out etc.
- Finally, we can export our manipulated audio file in any desired format such as MP3 or WAV.
Speech Recognition with Python
In this section, the speaker explains how to perform speech recognition using Python.
Speech Recognition
- To perform speech recognition in Python, we need to install a third-party library called SpeechRecognition which provides an easy-to-use interface for performing speech recognition on audio files.
- Once installed, we can import the Recognizer class from SpeechRecognition and use its recognize_google() method to convert our recorded audio file into text.
- We can also specify various parameters such as language and duration while performing speech recognition.
Introduction to Assembly AI API
In this section, Patrick introduces the project and explains the two main things needed for it. He also explains how to get an API token from Assembly AI.
Setting up the Project
- The project requires two things - Assembly API's API for speech recognition and Python's request library to talk to Assembly API's API.
- To get started, create a free account on assemblyai.com and copy your API key.
- Create a configure file and put your API key there for authentication purposes.
Four Steps of the Project
In this section, Patrick outlines the four steps of the project.
Four Steps
- There are four steps in this project - uploading the file locally to Assembly AI, starting transcription, pulling Assembly AI until transcription is done, and seeing the transcript.
Uploading File to Assembly AI
In this section, Patrick explains how to upload a file to Assembly AI using Python.
Uploading File
- Uploading a file is simple. Referencing documentation from Assembly AI, we can use Python's requests library.
- We need headers for authentication purposes. We set these headers with our API key.
- We read audio files from our system in chunks of 5 megabytes.
- We can get the filename from a terminal tool by importing system.
Starting Transcription
In this section, Patrick explains how to start transcription using Assembly AI.
Starting Transcription
- We can start transcription by using the transcript endpoint from Assembly AI.
- We need to send JSON data to Assembly AI for transcription.
Introduction to AssemblyAI API
In this section, the speaker introduces the AssemblyAI API and explains how it can be used for transcription.
Uploading Audio Files
- To start a transcription job, an audio file needs to be uploaded to the AssemblyAI API.
- The response from the upload is a JSON object that contains an audio URL.
Starting Transcription Job
- After uploading the audio file, a transcription job needs to be started by sending a request to the AssemblyAI API.
- The response from starting the transcription job contains an ID that can be used to check if the job is completed or not.
Polling for Transcription Completion
- To check if a transcription job is completed, polling needs to be set up using a polling endpoint specific to that job.
- A GET request with this endpoint will return information about whether or not the job is completed and provide access to the transcript.
Refactoring Code for Better Functionality
In this section, the speaker refactors code related to uploading and transcribing audio files in order to make it more modular and reusable.
Cleaning Up Code
- The code related to uploading and transcribing audio files is cleaned up so that everything is nicely packed into functions that can be reused later on.
- Two functions are created: one for uploading audio files and another for starting transcription jobs.
Testing Refactored Code
- The refactored code is tested by calling both functions with an audio file name as input.
- The output of these functions includes an audio URL and a job ID which can be used later on when checking if the transcription job has completed.
Polling for Transcription Completion
In this section, the speaker explains how to set up polling for transcription completion and provides an overview of how it works.
Creating a Polling Endpoint
- A polling endpoint is created by combining the transcript endpoint with a job ID.
- This endpoint can be used to check if a transcription job has completed or not.
Setting Up Polling Functionality
- To set up polling functionality, a GET request needs to be sent to the polling endpoint.
- The response from this request will indicate whether or not the transcription job has completed and provide access to the transcript.
Introduction to Assembly AI
In this section, the speaker introduces Assembly AI and explains how it can be used for transcription.
Assembly AI Features
- Assembly AI is a platform that provides automatic speech recognition services.
- The speaker demonstrates how to use the API to get a JSON response from an audio file.
- The status of the transcription process is checked using polling.
- The results of the transcription are returned in JSON format.
Transcription Results
In this section, the speaker explains how to extract and save the transcript generated by Assembly AI.
Saving Transcript Results
- The transcript generated by Assembly AI can be saved as a text file.
- A file name is created for the text file based on the original audio file name.
- The transcript results are written to a text file.
Saving Transcripts
In this section, the speaker explains how to save the transcript of an audio file in a text format.
Saving Transcripts
- To save the transcript, create a txt file with the name of the audio file plus ".txt".
- Open the txt file in writing format and write down the transcription data.
- Prompt the user that transcription is saved. If there is an error, print out the error message.
- Wrap up all these steps into a function called "Save Transcript" that takes in data and error returned from get transcripts URL. Pass over your URL as well.
Checking Saved Transcript
In this section, we check if our saved transcript is correct.
Checking Saved Transcript
- After calling upload function, call Save Transcript function to save transcript data.
- The output should be a txt file with transcription data inside it. Open it up to verify its contents are correct.
Cleaning Up Code
In this section, we clean up our code for future use.
Adding Wait Time During Polling
- Include waiting times during polling so that it waits 30 seconds before asking assembly AI again if it's not completed yet. Import time module for this purpose.
Creating API Communication File
- Create an extra python file named "API communication" where all functions communicating with API will reside.
- Move all functions that communicate with the API to this file.
- Import all functions from "API communication" file to use in the main python script.
Introduction to Transcription
In this section, Patrick introduces the concept of transcription and demonstrates how to transcribe an audio file using Python.
Transcribing Audio Files
- Patrick introduces himself and explains what transcription is.
- He demonstrates how to transcribe an audio file using Python's AssemblyAI API.
- He shows the output of the transcription and plays the audio while it is open.
Sentiment Analysis on YouTube Videos
In this section, Patrick teaches how to apply sentiment analysis to YouTube videos using Python.
Applying Sentiment Analysis
- Patrick introduces sentiment analysis and its applications.
- He explains how to use the YouTube DL package in Python to extract information from a YouTube video.
- He shows an example of applying sentiment analysis on iPhone 30 review videos.
- He demonstrates how positive, negative, or neutral sentiments are assigned based on the text extracted from each sentence in the video.
Extracting Video Information with YouTube DL
In this section, Patrick explains how to extract video information using the popular command line program, YouTube DL.
Using YouTube DL for Video Extraction
- Patrick explains what YouTube DL is and its popularity as a command line program for downloading videos from various sites including Youtube.
- He shows how to install and import it into Python code.
- He creates a helper function that extracts video information by passing in a URL.
- He creates another helper function that prints all the video information extracted.
Extracting Audio from YouTube Videos
In this section, the speaker demonstrates how to extract audio from a YouTube video using the YouTube DL package.
Extracting Audio URL
- To extract audio from a YouTube video, we need to use the YouTube DL package.
- The speaker provides an example URL of a YouTube video and shows how to copy it as a string.
- After passing the URL to the
YouTubeInfofunction, we can print out all available formats for that video.
- We can then print only the formats dictionary by accessing its key called "formats".
- Since "formats" is a list of dictionaries, we can iterate over it and print out each format's extension and URL.
- We filter for audio formats by checking if the extension equals "m4a".
- Finally, we return the URL of the first audio format found.
Sentiment Analysis with AssemblyAI
In this section, the speaker explains how to use AssemblyAI's sentiment analysis feature to detect positive, negative or neutral sentiment in speech.
Using AssemblyAI for Sentiment Analysis
- AssemblyAI offers various features including sentiment analysis which detects positive, negative or neutral sentiment in speech.
- To use this feature in our code, we simply need to add
sentiment_analysis=trueas JSON data when calling the transcript endpoint.
- The speaker creates a helper function called
safe_video_sentimentsthat extracts both transcript and sentiment analysis results from a YouTube video.
- The function first gets the video info and audio URL using the
get_video_infoandget_audio_urlfunctions respectively.
- It then calls the
save_transcriptsfunction to save both transcript and sentiment analysis results to a file.
Building a Sentiment Analysis App with AssemblyAI
In this tutorial, the speaker demonstrates how to build a sentiment analysis app using AssemblyAI. The app is built in Python and uses the AssemblyAI API to transcribe audio from a YouTube video and analyze the sentiment of each sentence.
Setting up the Project
- Create an account on AssemblyAI and get an API key.
- Install required packages such as requests, youtube-dl, etc.
- Download the audio from a YouTube video using youtube-dl.
- Use requests to send the audio file to AssemblyAI for transcription.
Analyzing Sentiments
- Replace all spaces with underscores in title and store it in a separate folder called data.
- Add additional argument "sentiment analysis" to safe transcript file function with default value of false.
- Pass "sentiment analysis" parameter through get_transcription_result_url() function and transcribe() function as JSON data.
- Save sentiments into JSON file if "sentiment analysis" parameter is true using JSON.dump().
- Extract text, start/end time, sentiment, and confidence for each sentence analyzed by AssemblyAI.
Calculating Positive Ratio
- Read JSON file containing sentiments data.
- Calculate number of positives, negatives, neutrals sentences
- Append text to corresponding list based on sentiment (positive/negative/neutral).
- Calculate length of each list.
- Calculate positive ratio by dividing number of positives by total number of positive/negative sentences.
- Print number of positives, negatives, neutrals and positive ratio.
Conclusion
- Sentiment analysis can be applied to many different use cases.
- Building a web app to display sentiment analysis results would be a cool next step.
- Next tutorial will cover building a podcast summarization app with a web interface.
Building a Front End for Podcast Summarization
In this section, the speaker discusses building a front end for podcast summarization. They mention that they will have different chapters and summaries of each chapter in the episode.
Setting Up the Project
- The project will have a main script and a supporting script API communication.
- The upload endpoint is not needed since the podcasts will be received from Listen Notes API.
- The chunk size is also not relevant anymore.
Using Listen Notes API
- Listen Notes is a database of podcasts where you can search for any podcast or episode.
- To get an episode, you need to send it an episode ID which can be found on the platform itself.
- The speaker shows how to find an episode ID on 99% Invisible's website.
Communicating with Listen Notes API
- To communicate with Listen Notes API, you need to use their endpoints and headers for authentication.
- The speaker imports the API key for Listen Notes and creates headers for authentication.
Getting Episode Audio URL
- A new function called
get_episode_audio_urlis created to get the audio URL of an episode using its ID.
- A GET request is sent to Listen Notes using the episode endpoint and headers for authentication.
Introduction to the Python Script
In this section, the speaker introduces a simple Python script that imports everything from API communications and calls get episode audio Euro using an episode ID.
Creating a Simple Python Script
- The speaker creates a simple Python script that imports everything from API communications.
- They call get episode audio Euro using an episode ID.
Printing Response from Listen Notes
In this section, the speaker prints the response received from Listen Notes after calling get episode audio Euro.
Printing Response
- The speaker prints the response received from Listen Notes after calling get episode audio Euro.
- They use pretty print to make it more readable.
Extracting Information About Podcast Episode
In this section, the speaker extracts information about the podcast episode such as its description, explicit content, image, and extra information about the podcast itself.
Extracting Information
- The speaker extracts information about the podcast episode such as its description, explicit content, image, and extra information about the podcast itself.
- They mention that including more of this information in a web application can make it more interesting and interactive.
Renaming Variables for Assembly AI Integration
In this section, the speaker renames variables for Assembly AI integration and changes wait time for transcription results to 60 seconds instead of 30 seconds.
Renaming Variables
- The speaker renames variables for Assembly AI integration.
- They change wait time for transcription results to 60 seconds instead of 30 seconds.
Uploading Audio to Assembly AI for Transcription Results
In this section, the speaker explains how they will upload audio to Assembly AI for transcription results by passing the episode ID to get episode audio URL from Listen Notes.
Uploading Audio
- The speaker explains how they will upload audio to Assembly AI for transcription results by passing the episode ID to get episode audio URL from Listen Notes.
Extracting Chapter Information from Assembly AI
In this section, the speaker discusses how to extract chapter information from Assembly AI and save it in a JSON file for later use.
Getting Response from Assembly AI
- To get transcription results URL, we need to pass the order.
- The response from Assembly AI includes information about auto chapters.
- The data received is already in JSON format.
Understanding Chapter Information
- Each chapter has a starting point, an ending point, a headline, and a summary.
- The goal is to extract this information and display it on the web interface.
Saving Chapter Information
- The chapter information is saved in a separate JSON file along with other relevant data such as episode thumbnail, title, and podcast title.
- A message is displayed to let the user know that the transcript has been saved successfully.
Introduction to Streamlit
In this section, the speaker introduces Streamlit and explains how to use it.
Using Streamlit
- To use Streamlit, you need to call
import streamlitin your code.
- To run a Streamlit application, use
streamlit run <filename>.
- When installing Streamlit with pip, make sure to use lowercase "s" for "streamlit".
- The speaker demonstrates a simple application that displays a title using Streamlit.
Building an Application
In this section, the speaker discusses building an application using Streamlit.
Creating a Sidebar
- The first step in building the application is creating a sidebar. This can be done using
streamlet.sidebar.text_input().
- The speaker adds a button to the sidebar that says "Get podcast summary".
Adding a Title
- The speaker updates the title of the application to say "Welcome to my application that creates podcast summaries".
- The speaker uses
streamlet.header()to display the name of the podcast and episode title along with an episode thumbnail.
Parsing Data
In this section, the speaker discusses parsing data from an API and displaying it in the application.
Getting Episode ID
- The user inputs an episode ID which is saved as a variable.
Loading JSON Data
- JSON data is loaded into a variable called 'data'.
Displaying Podcast Information
- The chapters are extracted from the 'data' variable.
- The podcast title and episode title are extracted from the 'data' variable.
- The speaker uses
streamlet.header()to display the podcast title and episode title along with an episode thumbnail.
Creating Expanders for Podcast Chapters
In this section, the speaker demonstrates how to create expanders for podcast chapters using the streamlit library.
Using a For Loop to Stream Chapters
- To show the chapters of a podcast, a for loop can be used.
- The loop iterates through each chapter and streams it using the
streamlitlibrary.
Creating Expanders for Chapter Summaries
- Instead of displaying all chapter summaries in one long list, expanders can be used to make it more organized.
- To create an expander, use
st.expander()and specify what information should be inside it.
- The title of the expander is set as the gist of each chapter while the summary is displayed inside.
Adding Start and End Points for Chapters
- The JSON file contains start points for each chapter in milliseconds.
- A function can convert these milliseconds into minutes and seconds or hours, minutes, and seconds.
- This information can be added to display how long each chapter is.
I'm sorry, but I don't see any transcript provided. Could you please provide me with the transcript so that I can summarize it for you?
Implementing WebSocket Connection
In this section, the speaker explains how to implement a WebSocket connection using Python's asyncio library.
Waiting for Connection
- Use
await asyncio.sleep(0.1)to wait for the connection to establish.
- Use
asyncio.gather()to combine the send and receive functions.
Sending and Receiving Messages
- Create infinite loops for sending and receiving messages using
while True.
- Use
try-exceptblocks to handle errors.
- Sleep after each iteration of the loop using
await asyncio.sleep().
Sending Audio Data
- Read microphone input using
stream.read().
- Encode data in base64 and convert it to a JSON object.
- Send JSON data using WebSocket connection.
Receiving Transcription Results
- Wait for transcription results from Assembly AI using WebSocket connection.
- Convert results to dictionary format using
JSON.load().
- Check keys in dictionary, such as "text" and "message type", to retrieve transcription information.
Retrieving Transcription Information
In this section, the speaker explains how to retrieve transcription information from Assembly AI.
Parsing Transcription Results
- Convert transcription results from JSON format into a dictionary format.
- Retrieve relevant keys from dictionary, such as "text" and "message type".
Handling Errors
- Use try-except blocks to handle errors when retrieving transcription results.
- Print error message and break out of loop if necessary.
Conclusion
In this section, the speaker concludes by summarizing what was covered in the tutorial.
Summary of Tutorial Content
- The tutorial covered how to implement a WebSocket connection in Python using asyncio library
- It also explained how to send audio data through the WebSocket connection and retrieve transcription results from Assembly AI.
Final Thoughts
- The speaker encourages viewers to experiment with the code and explore other features of the Assembly AI API.
Building a Virtual Assistant with Real-Time Speech Recognition and OpenAI
In this video, the presenter demonstrates how to build a virtual assistant that works with real-time speech recognition together with OpenAI. The video covers setting up the environment, creating a chatbot, integrating speech recognition, and using OpenAI for question answering.
Setting Up the Environment
- Install Python 3.8 or higher.
- Create a new project directory.
- Create a virtual environment.
- Install required packages: PyAudio, SpeechRecognition, and openai.
Creating a Chatbot
- Import necessary libraries: pyttsx3 and random.
- Define functions for speaking and generating random text.
- Implement the main function for receiving user input and generating responses.
Integrating Speech Recognition
- Import necessary library: speech_recognition.
- Define function for recognizing speech input.
- Modify main function to use speech recognition instead of text input.
Using OpenAI for Question Answering
- Sign up for an OpenAI API key.
- Install openai package and import necessary libraries in Python script.
- Use OpenAI's GPT3 engine to perform natural language tasks such as question answering.
- Define helper function to ask computer questions using OpenAI's API key.
Turn any video into a summary like this
YouTube links, meetings, lectures. With transcripts, search, and chat.