Building a speech recognizer AI/ML model in Python
Building a speech recognizer AI/ML model in python for audio
Visualizing audio signals
There are different aspects of speech that contributes to complexity, such as emotion, accent, intonation, affectation and language.
For humans its fairly easy to understand speech cues, but for machines, it is difficult to define a set of robust rules to analyze speech signals.
Let’s visualize an audio signal. We will read an audio file and work with it to help us understand how an audio signal is structured. Audio signals are analog and continuous waves, but when we capture through digital medium, it is converted into discrete values at a certain frequency.
Most commonly speech signals are sampled at 44,100 Hz, which means each second is broken down into 44,100 parts i.e. 1/44,100 seconds.
Let's visualize an audio signal:
Create a new Python file and import the following packages.
# Importing packages
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfileRead the input audio file using wavfile.read method. it will return two values i.e. sampling frequency and the audio signal.
Important notice, provide your own audio file. make sure the file format is .wav
# Read audio file
sampling_freq, signal = wavfile.read("audio.wav")Print the shape of the audio signal, the datatype and the length of the duration of audio signal.
# Display params
print("\nSignal shape:", signal.shape)
print("Datatype", signal.dtype)
print('Signal duration:', round(signal.shape[0]/float(sampling_freq), 2), 'seconds')The output should look like this,
Shapes, screenshot by the author

Normalize the signal.
We normalize to raise the overall intensity (loudness) of the audio without distorting the audio itself.
# Normalize the signal
signal = signal / np.power(2, 15)Extract the first 50 values from numpy array for plotting
# Extract the first 50 values
signal = signal[:50]Construct the time axis in milliseconds
# Construct the time axis in milliseconds
time_axis = 1000 * np.arange(0, len(signal), 1)/float(sampling_freq)Plot the audio signal.
# Plot the audio signal
plt.plot(time_axis, signal, color='black')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
plt.title('Input audio signal')
plt.show()Audio, screenshot by the author

Finally, we have audio visualization.
So far, we have visualized audio signals, in this part let's explore the underlying frequency components.
Transforming audio signals to frequency domain
We need to extract meaningful information from audio signal. Audio signals are composed of sine waves of varying frequencies, phases, and amplitudes. If we dissect the frequency component, we can identify a lot of characteristics within audio signals, which is characterized by its distribution in frequency spectrum.
In order to convert a time domain signal into frequency domain, we would need a mathematical function called Fourier Transform. a Fourier transform of a signal shows the individual frequency components of a signal. If you need a refresher, please see: https://www.thefouriertransform.com
Let’s transform audio signal to the frequency domain:
Create a new Python file and import the following packages.
# Importing packages
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfileJust like in previous exercise, we would need to read the audio signal using the wavefile.read method.
# Read audio file
sampling_freq, signal = wavfile.read('audio.wav')Normalize the audio signal value so the audio intensity can be increased without distorting.
# Normalize the audio signal value
signal = signal / np.power(2, 15)Extract the length and half-length of the audio signal and apply Fourier transform to the signal.
# Extract the length
len_signal = len(signal)
#Extract half-length
len_half = np.ceil((len_signal + 1) /2.0).astype(int)
# Apply Fourier transform to the signal
freq_signal = np.fft.fft(signal)Normalize the frequency domain signal and take the square.
# Normalization
freq_signal = abs(freq_signal[0:len_half]) / len_signal
#Take the square
freq_signal **=2Adjust the Fourier-transformed signal of even and odd cases.
# Extract the length of the frequency transformed signal
len_fts = len(freq_signal)
# Adjust the signal for even and odd cases
if len_signal % 2:
freq_signal[1:len_fts] *= 2
else:
freq_signal[1:len_fts-1] *=2Extract the power signal in decibals (dB)
# Extract power value in dB
signal_power = 10 * np.log10(freq_signal)Build the X axis, which is frequency measured in KHz.
# Build X axis
x_axis = np.arange(0, len_half, 1) * (sampling_freq / len_signal) / 1000.0Plot the figure
# Plot
plt.figure()
plt.plot(x_axis, signal_power, color = 'black')
plt.xlabel('Freq (KHz)')
plt.ylabel('Signal power (dB)')
plt.show()Audio, screenshot by the author

The expected output should show you how powerful the signal is across the frequency spectrum, as expected the power of signal goes down in higher frequencies.
Generating audio signals
we learned how audio signals work, in this part let’s see how we can generate one such signal.
We will use NumPy package to generate various audio signals. Since audio signals are amalgamation of sinusoids, we can generate audio signal by introducing some predefined parameters.
Let's generate audio signals using Python:
Create a new Python file and import the packages.
# Import packages
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile
import writeDefine the output audio file’s name.
# Output file, audio save repo
output_file = "generated_audio.wav"Specify the audio parameters.
# Specify audio parameters
duration = 4
sampling_freq = 44100
tone_freq = 784
min_val = -4 * np.pi
max_val = 4 * np.piGenerate audio signal using the defined parameters.
# Generate audio signals
t = np.linspace(min_val, max_val, duration * sampling_freq)
signal = np.sin(2 * np.pi * tone_freq * t)Normalize and scale the audio signal.
# Scale the signal to 16-bit int values
scaling_factor = np.power(2, 15) - 1
signal_normalized = signal /np.max(np.abs(signal))
signal_scaled = np.int16(signal_normalized * scaling_factor)Saving the generated audio signal in a file.
# Save the audio signal in a file
write(output_file, sampling_freq, signal_scaled)Extract the first 200 values for plotting.
# Extract first 200 values
signal = signal[:200]Construct the time axis in ms.
# Constructing time axis in ms
time_axis = 1000 * np.arange(0, len(signal), 1)/ float(sampling_freq)Finally let’s plot the signal.
# Plot
plt.plot(time_axis, signal, color = "black")
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
plt.title('Generated audio signal')
plt.show()You should be able to see a file called generated_audio.wav, which you can play using your computer’s media player. It should be a mixture of 784 Hz and sounds like a noise signal.
Synthesizing tones to generate music
Previously we explored how to generate a monotone, but monotone is not very meaningful as it's just a single frequency.
Let’s use the same principle to synthesize music by stitching different tones together. Similarly to music theory, we will use tones such as A, C, G, and F to create music.
Let’s synthesizing tones to generate music.
Create a new Python file and import the packages.
# Import packages
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write
import jsonLet’s define a function which we use to generate a tone based on parameters.
# Synthesize the tone
def tone_synthesizer(freq, duration, amplitude=1.0, sampling_freq=44100):
# Construct the time axis
time_axis = np.linspace(int(0), int(duration), int(duration * sampling_freq))Construct the audio signal using the parameters specified and return it.
# Construct audio signal
signal = amplitude * np.sin(2 * np.pi * freq * time_axis)
return signal.astype(np.int16)Define main function.
if _name_=='_main_':
file_tone_single = 'generated_tone_single.wav'
file_tone_sequence = 'generated_tone_sequence.wav'We will use a tone mapping that contains mapping from tones, such as A, C and G to the corresponding frequencies.
# Source:
mapping_file = 'tone_mapping.json'
# Load the tone to frequency map
with open(mapping_file, 'r') as f:
tone_map = json.loads(f.read())Let’s generate the F tone.
tone_name = 'F'
duration = 3
amplitude = 12000
sampling_freq = 44100Extract the corresponding frequency and generate tone using synthesizer function.
# Extract
tone_freq = tone_map[tone_name]
# Generate tone
synthesized_tone = tone_synthesizer(tone_freq, duration, amplitude, sampling_freq)
# Writing the generated tone
write(file_tone_single, sampling_freq, synthesized_tone)In-order to make it sound like music, we will create a tone sequence.
# Tone sequence
tone_sequence = [('G', 0.4), ('D', 0.5), ('F', 0.3), ('C', 0.6), ('A', 0.4)]Construct audio signal based on tone sequence.
# Contruct audio signal
signal = np.array([])
for item in tone_sequence:
tone_name = item[0]For each tone, extract the corresponding frequency.
# Extract the corresponding frequency of the tone
freq = tone_map[tone_name]
duration = item[1]
# Synthesize tone
synthesized_tone = tone_synthesizer(freq, duration, amplitude, sampling_freq)Append the extraction to the main output signal and save.
# Append signal
signal = np.append(signal, synthesized_tone, axis=0)
# Save audio file
write(file_tone_sequence,l sampling_freq, signal)Once the final block of code has been run, you should be able to play the audio. The example is a rudimentary example of speech and tone synthesizer used in advanced audio sampling tools.
Extracting speech features
So far, we have learned how to handle signals and linear frequency domain. The frequency domain features are what we use for analysis of speech recognition systems. The concepts we learned earlier are introduction, but real-world frequency domain features are complex.
Once we convert a signal into the frequency domain, we need to ensure that its useful in the form of a feature vector. MFCCs, or Mel Frequency Cepstral Coefficients is a tool we use to extract the features from an audio file.
MFCCs extracts power spectrum, it then uses filter banks and Discrete Cosine Transform (DCT) to extract the features.
DCT for beginners:When you want to compress a series of data (say, a sound recording) you can look for patterns in the data, and just record the patterns instead of the original measurements.
DCT describes data as the sum of a series of waves (cosine functions) vibrating at different frequencies. This turns out to be a great way to describe sounds using just a small set of numbers. So it’s used in audio compression. It’s also used in video compression, since pictures also tend to have patterns.
We will be using a python package called python_speech_features to extract the MFCC features.
Create a new python file and import the packages.
# Import packages
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from python_speech_features import mfcc, logfbankIn order to extract speech features, we first need to read the file that contains audio.
# Read input audio file
sampling_freq, signal = wavfile.read('audio.wav')
# Take 10,000 samples for analysis
signal = signal[:10000]We then need to extract MFCC and print the MFCC parameters.
# Extract MFCC features
features_mfcc = mfcc(signal, sampling_freq)
# Print MFCC parameters
print('\nMFCC:\nNumber of windows=', features_mfcc.shape[0])
print('Length of each feature =', features_mfcc.shape[1])MFCC features

Let’s plot the MFCC features.
# Plot
features_mfcc = features_mfcc.T
plt.matshow(features_mfcc)
plt.title('MFCC')Press enter or click to view image in full sizeMFCC visualization

Extract the filter bank features.
# Extract filter bank features
features_fb = logfbank(signal, sampling_freq)
# Extract the parameter
print('\nFilter bank:\nNumber of windows =', features_fb.shape[0])
print('Length of each feature =', features_fb.shape[1])Press enter or click to view image in full sizeFilter bank features

Plot the features.
# Plot
features_fb = features_fb.T
plt.matshow(features_fb)
plt.title('Filter bank')Filter bank visualization

As we convert sound into pictures, it helps us to analyze sound and derive insights from it.
Recognizing spoken words
We have learned all the techniques to analyze speech signal, in this final part, we will learn how to recognize spoken words. The speech recognition takes in audio signal and outputs recognized words. We will use Hidden Markov Models (HMMs) for the speech recognition task.
HMMs are great for analyzing sequential data and an audio signal is a time series signal, which is a manifestation of sequential data. The assumption is that the outputs are being generated by the system going through a series of hidden states. Our goal is to find out what these hidden states are so we can identify the words in our signal.
We will use the package called hmmlearn to build our speech recognition system.
In order to train our speech recognition system, we need a dataset of audio files for each word. We will use https://code.google.com/archive/p/hmm-speech-recognition/downloads.
Let’s create a new Python file and import the packages.
# Packages
import os
import argparse
import warnings
import numpy as np
from scipy.io import wavfile
from hmmlearn import hmm
from python_speech_features import mfccDefine a function to parse the input arguments. We need to specify the input folder containing the audio files, that will be used to train our speech recognition system.
# Define function
def build_arg_parser():
parser = argparse.ArgumentParser(description = 'Trains the speech recognizer')
parser.add_argument('--input-folder', dest='input_folder', required=True, help = 'Input folder containing the audio file for training')
return parserDefine class to train HMMs.
# Define class to train HMM
class ModelHMM(object):
def __init__(self, num_components = 4, num_iter = 1000):
self.n_components = num_components
self.n_iter = num_iter
# Define the covariance and HMM type
self.cov_type = 'diag'
self.model_name = 'GaussianHMM'
# Initialize the variable in which we will store the models for each word
self.models = []
# Define model using parameters
self.model = hmm.GaussianHMM(n_components = self.n_components, covariance_type = self.cov_type, n_iter = self.n_iter)Define method to train the model.
# Define method to train model
def train(self, training_data):
np.seterr( all = 'ignore')
cur_model = self.model.fit(training_data)
self.models.append(cur_model)Define a method to compute the score for input data.
# Run HMM model for inference on input data
def compute_score(self, input_data):
return self.model.score(input_data)Define a function to build model for each word in training dataset.
# Define function
def build_models(input_folder):
speech_models = []
# Parse the input directory
for dirname in os.listdir(input_folder):
subfolder = os.path.join(input_folder, dirname)
if not os.path.isdir(subfolder):
continue
# Extract the label
label = subfolder[subfolder.rfind('/') + 1:]
# Initialize the variable
X = np.array([])
# Create list of files used for training
training_files = [x for x in os.listdir(subfolder) if x.endswith('.wav')][:-1]
# Iterate through the training files and build model
for filename in training_files:
# Extract the current filepath
filepath = os.path.join(subfolder, filename)
# Read audio file
sampling_freq, signal = wavfile.read(filepath)
# Extract the MFCC features
with warnings.catch_warnings():
warnings.simplefilter('ignore')
features_mfcc = mfcc(signal, sampling_freq)
# Append to the variable X
if len(X) == 0:
X = features_mfcc
else:
X = np.append(X, features_mfcc, axis = 0)Initialize, train and save the HMM model.
# Create HMM model
model = ModelHMM()
# Train HMM model
model.train(X)
# Save model
speech_models.append((model, label))
# Reset variable
model = none
return speech_modelsDefine function to test-on-test dataset.
# Define function
def run_tests(test_files):
# Classify input data
for test_file in test_files:
sampling_freq, signal = wavfile.read(test_file)
# Extract MFCC features
with warnings.catch_warnings():
warnings.simplefilter('ignore')
features_mfcc = mfcc(signal, sampling_freq)
# Define variables
max_score = -float('inf')
output_label = None
# Iterate through each model to pick the best one
# Run the current feature vector
for item in speech_models:
model, label = item
# Evaluate score and compare against maximum score
score = model.compute_score(features_mfcc)
if score > max_score:
max_score = score
predicted_label = label
# Print output
start_index = test_file.find('/') + 1
end_index = test_file.rfind('/')
original_label = test_file[start_index:end_index]
print('\nOrginal: ', original_label)
print('Predicted: ', predicted_label)For each tone, extract the corresponding frequency.
Define the main function and get input folder from input parameter.
# Define main function
if __name__=='__main__':
args = build_arg_parser().parse_args()
input_folder = args.input_folderBuild HMM model for each word.
# Build HMM model
speech_models = build_models(input_folder)
#Test files
test_files = []
for root, dirs, files in os.walk(input_folder):
for filename in (x for x in files if '15' in x):
filepath = os.path.join(root, filename)
test_files.append(filepath)
run_tests(test_files)We explored how to work with speech signals. In NLP, we utilize speech recognition to process audio and text queries, providing users with results based on their input. The advanced algorithm seamlessly integrates a series of complex codes to achieve functions that humans can perform effortlessly.