iTranslated by AI
Easily Running Generative AI Locally: Part 5.5 - faster-whisper and Microphone Recording
Introduction
In this article, we will create an environment for beginners to easily use generative AI in a Google Colaboratory local environment.
In Part 5, we used faster-whisper, which is also a speech recognition AI, on Google Colab to transcribe audio files. In this Part 5.5, we will consider transcribing audio recorded directly from a microphone.
(This is necessary for creating a voice dialogue system.)
While recording audio from a microphone is possible in Google Colab, the method for recording audio locally differs significantly from the method in Google Colab. Therefore, focusing on practicality, we will record locally and perform transcription this time.
This article is written on the assumption that you understand the content of the Part 5 article.
If you haven't read Part 5 yet, I recommend reading it as well.
Deliverables
Please see the repository below.
Explanation
The explanation is as follows.
First, please clone the repository above.
git clone https://github.com/personabb/colab_AI_sample.git
Afterward, place the cloned folder "colab_AI_sample" in any folder on your local machine.
Directory Structure
The local directory structure is assumed to be as follows.
(Only the items used in this article are listed.)
hogehoge/
└ colab_AI_sample/
└ colab_fasterwhisper_sample/
├ configs/
| └ config.ini
├ module/
| ├ module_recoder.py
| └ module_whisper.py
├ requirements.txt
└ main.py
- The
colab_AI_samplefolder name is arbitrary. Anything is fine. It doesn't have to be a single-level hierarchy and can be multiple levels like this:MyDrive/hogehoge/spamspam/hogespam/colab_AI_sample
- The
modulefolder contains the module for runningfaster-whisperand the module for recording audio from the microphone.-
configs/config.iniis a configuration file containing settings necessary for operating the models and recording. -
requirements.txtis a file required for environment setup.
-
Preparation (Environment Setup)
As a major prerequisite, the Python version is assumed to be 3.10 or 3.11. Operation has not been confirmed with other versions.
As a premise, please work in the directory after executing the following command:
cd colab_AI_sample/colab_fasterwhisper_sample
Specifying the Python Version
The Python version is specified using pyenv. Please see the following regarding the installation of pyenv itself.
If pyenv is installed, you can specify the Python version with the following commands:
pyenv install 3.10.14 # or 3.11.9, etc.
pyenv local 3.10.14 # or pyenv global 3.10.14
This allows you to specify the Python version.
Use pyenv global when you want to reflect this version throughout the entire system.
Use pyenv local when you want to reflect this version only in the current directory.
Execute the following command to check if the Python version has changed:
python -V
# Python 3.10.14
Installing Required Packages
Next, we will build a virtual environment to install the necessary packages.
We will create a virtual environment using venv.
Since venv is the official Python virtual environment, it can be used without installation as long as Python is available.
python -m venv env
source env/bin/activate
pip install -r requirements.txt
By executing the last script, you can obtain various weight information.
Configuration File Settings
If you use the default configuration file, you don't need to make any changes. However, by modifying the contents of this file, you can try different models or change the recording environment.
The configuration file is as follows:
[Recorder]
fs=16000
silence_threshold=0.5
min_duration=0.1
amplitude_threshold=0.05
start_threshold = 0.3
[FasterWhisper]
device = auto
language = ja
gpu_model_type = large-v3
gpu_beam_size = 1
gpu_compute_type = float16
cpu_model_type = small
cpu_beam_size = 1
cpu_compute_type = int8
use_kotoba = True
kotoba_model_type = kotoba-tech/kotoba-whisper-v1.0-faster
chunk_length = 15
condition_on_previous_text = False
This is the same configuration file used from Part 1 through Part 5. Previously, we rewrote the contents on Google Colab, but since this is for local operation, we will edit the configuration file itself directly.
First, the [Recorder] section contains settings related to the recording module.
-
fs=16000- Recording is done at a sampling rate of 16,000Hz. Since Whisper assumes 16,000Hz audio, you can leave this as is.
- While you can change it, the model pre-processes it to 16,000Hz before transcription, so increasing it won't necessarily improve transcription accuracy.
- Recording is done at a sampling rate of 16,000Hz. Since Whisper assumes 16,000Hz audio, you can leave this as is.
-
silence_threshold=0.5- A parameter to stop recording 0.5 seconds after it becomes silent.
-
min_duration=0.1- The chunk size when recording as a stream. No need to change this.
-
amplitude_threshold=0.05- The threshold for silence detection. Sounds with a volume lower than 0.05 are considered silence.
- If this is 0, even natural noise will be judged as sound, and the recording will never end.
- start_threshold = 0.3
- If a volume above the threshold (
amplitude_threshold) persists for 0.3 seconds or more, it is judged as the start of an utterance, and recording begins. - This process prevents recording from starting due to sudden noise.
- If a volume above the threshold (
The [FasterWhisper] section contains settings for the transcription module.
-
device = auto- Setting for whether to use the machine's GPU or CPU.
- If
auto, the GPU is used if available. - Alternatively, you can specify
cudaorcpu.
- If
- Setting for whether to use the machine's GPU or CPU.
-
language = ja- Specifies the language setting. Here, it is set to Japanese.
- The next 6 lines configure the models.
- Different models are used depending on whether a GPU or CPU is used.
- For GPU usage, a high-performance model called
large-v3is used. - For CPU usage, a lightweight model called
smallis used.- Additionally, for CPU, a small data type called
int8is used to reduce the amount of computation.
- Additionally, for CPU, a small data type called
- For GPU usage, a high-performance model called
- Different models are used depending on whether a GPU or CPU is used.
-
use_kotoba = True- Sets whether to use
kotoba-whisper-v1.0, a model specialized for Japanese. - This model is recommended because its processing speed is faster.
- Please try various models and compare the accuracy and processing speed.
- Sets whether to use
-
kotoba_model_type = kotoba-tech/kotoba-whisper-v1.0-faster- Specifies the faster-whisper model to use.
- By changing this, you can try different models.
- However, this only applies when
use_kotoba = True.
- However, this only applies when
- No need to change anything else.
How to Use
After building the environment, you can run the program with the following command:
main.py
Once stand by ready OK is displayed on the terminal, please speak into the microphone.
When you stop speaking, the recording will stop, and the content will be transcribed and displayed on the console.
Recording and transcription will be repeated indefinitely until you press Ctrl+C to stop the program.
Code Explanation
I will mainly explain the important files: main.py, module_recoder.py, and module_whisper.py.
main.py
The relevant code is as follows.
Full Code
import sounddevice as sd
from module.module_whisper import FasterWhisperModel
from module.module_recorder import Recorder
def main():
recorder = Recorder()
fasterWhispermodel = FasterWhisperModel()
while True:
audio_data = recorder.speech2audio()
text = fasterWhispermodel.audio2text(audio_data)
print(text)
if __name__ == "__main__":
main()
I will explain it below. It is a short piece of code, so it won't take long.
from module.module_whisper import FasterWhisperModel
from module.module_recorder import Recorder
This imports the recording module and the transcription module from the module folder.
recorder = Recorder()
fasterWhispermodel = FasterWhisperModel()
This creates instances of the classes from the imported modules.
while True:
audio_data = recorder.speech2audio()
text = fasterWhispermodel.audio2text(audio_data)
print(text)
Here, the recorder.speech2audio() method records the voice and stores the audio data in audio_data, and the fasterWhispermodel.audio2text() method transcribes the audio data and displays it as text.
Next, I will explain the contents of the relevant modules.
module_recoder.py
This module is for recording speech. The code is provided below.
Full Code
import numpy as np
import sounddevice as sd
import os
import configparser
# Module for checking file existence
import errno
class Recorderconfig:
def __init__(self, config_ini_path = './configs/config.ini'):
# Loading the ini file
self.config_ini = configparser.ConfigParser()
# If the specified ini file does not exist, an error occurs
if not os.path.exists(config_ini_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), config_ini_path)
self.config_ini.read(config_ini_path, encoding='utf-8')
Recorder_items = self.config_ini.items('Recorder')
self.Recorder_config_dict = dict(Recorder_items)
class Recorder:
def __init__(self, config_ini_path = './configs/config.ini'):
Recorder_config = Recorderconfig(config_ini_path = config_ini_path)
config_dict = Recorder_config.Recorder_config_dict
self.fs = int(config_dict["fs"])
self.silence_threshold = float(config_dict["silence_threshold"])
self.min_duration = float(config_dict["min_duration"])
self.amplitude_threshold = float(config_dict["amplitude_threshold"])
self.start_threshold = float(config_dict["start_threshold"])
def speech2audio(self):
record_Flag = False
non_recorded_data = []
recorded_audio = []
silent_time = 0
input_time = 0
start_threshold = 0.3
all_time = 0
with sd.InputStream(samplerate=self.fs, channels=1) as stream:
while True:
data, overflowed = stream.read(int(self.fs * self.min_duration))
all_time += 1
if all_time == 10:
print("stand by ready OK")
elif all_time >= 10:
if np.max(np.abs(data) > self.amplitude_threshold) and not record_Flag:
input_time += self.min_duration
if input_time >= start_threshold:
record_Flag = True
print("recording...")
recorded_audio=non_recorded_data[int(-1*start_threshold*10)-2:]
else:
input_time = 0
if overflowed:
print("Overflow occurred. Some samples might have been lost.")
if record_Flag:
recorded_audio.append(data)
else:
non_recorded_data.append(data)
if np.all(np.abs(data) < self.amplitude_threshold):
silent_time += self.min_duration
if (silent_time >= self.silence_threshold) and record_Flag:
print("finished")
record_Flag = False
break
else:
silent_time = 0
audio_data = np.concatenate(recorded_audio, axis=0)
return audio_data
Now, I will explain each part.
Recorderconfig Class
class Recorderconfig:
def __init__(self, config_ini_path = './configs/config.ini'):
# Loading the ini file
self.config_ini = configparser.ConfigParser()
# If the specified ini file does not exist, an error occurs
if not os.path.exists(config_ini_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), config_ini_path)
self.config_ini.read(config_ini_path, encoding='utf-8')
Recorder_items = self.config_ini.items('Recorder')
self.Recorder_config_dict = dict(Recorder_items)
Here, the configuration file specified by config_ini_path = './configs/config.ini' is loaded as Recorder_config_dict. Since it is loaded as a dictionary type, it becomes possible to access the contents of the configuration file as a Python dictionary.
Recorder Class init Method
class Recorder:
def __init__(self, config_ini_path = './configs/config.ini'):
Recorder_config = Recorderconfig(config_ini_path = config_ini_path)
config_dict = Recorder_config.Recorder_config_dict
self.fs = int(config_dict["fs"])
self.silence_threshold = float(config_dict["silence_threshold"])
self.min_duration = float(config_dict["min_duration"])
self.amplitude_threshold = float(config_dict["amplitude_threshold"])
self.start_threshold = float(config_dict["start_threshold"])
First, the contents of the configuration file are stored in config_dict. Since this is a dictionary type, values from the configuration file can be retrieved as strings using keys like config_dict["device"]. Note that as all values are retrieved as strings, you need to cast them to types like int or float as necessary.
Next, various values from the configuration file are stored in instance variables.
Recorder Class speech2audio Method
class Recorder:
...
def speech2audio(self):
record_Flag = False
non_recorded_data = []
recorded_audio = []
silent_time = 0
input_time = 0
start_threshold = 0.3
all_time = 0
with sd.InputStream(samplerate=self.fs, channels=1) as stream:
while True:
data, overflowed = stream.read(int(self.fs * self.min_duration))
all_time += 1
if all_time == 10:
print("stand by ready OK")
elif all_time >= 10:
if np.max(np.abs(data) > self.amplitude_threshold) and not record_Flag:
input_time += self.min_duration
if input_time >= start_threshold:
record_Flag = True
print("recording...")
recorded_audio=non_recorded_data[int(-1*start_threshold*10)-2:]
else:
input_time = 0
if overflowed:
print("Overflow occurred. Some samples might have been lost.")
if record_Flag:
recorded_audio.append(data)
else:
non_recorded_data.append(data)
if np.all(np.abs(data) < self.amplitude_threshold):
silent_time += self.min_duration
if (silent_time >= self.silence_threshold) and record_Flag:
print("finished")
record_Flag = False
break
else:
silent_time = 0
audio_data = np.concatenate(recorded_audio, axis=0)
return audio_data
In this section, the user's speech is captured through the microphone.
After "stand by ready OK" is displayed, recording starts if the volume of the audio input to the microphone exceeds the threshold (self.amplitude_threshold). When recording starts, "recording..." is displayed. It is designed so that recording stops once the volume falls below the threshold and 0.5 seconds (self.silence_threshold) have elapsed. When recording stops, "finished" is displayed.
module_whisper.py
The next module is for transcribing audio.
Since this module is almost identical to the one described in the Part 5 article, I will only explain the differences.
The code is provided below.
Full Code
from faster_whisper import WhisperModel
import numpy as np
import torch
import os
import configparser
# Module for checking file existence
import errno
class FasterWhisperconfig:
def __init__(self, config_ini_path = './configs/config.ini'):
# Loading the ini file
self.config_ini = configparser.ConfigParser()
# If the specified ini file does not exist, an error occurs
if not os.path.exists(config_ini_path):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), config_ini_path)
self.config_ini.read(config_ini_path, encoding='utf-8')
FasterWhisper_items = self.config_ini.items('FasterWhisper')
self.FasterWhisper_config_dict = dict(FasterWhisper_items)
class FasterWhisperModel:
def __init__(self,device = None, config_ini_path = './configs/config.ini'):
FasterWhisper_config = FasterWhisperconfig(config_ini_path = config_ini_path)
config_dict = FasterWhisper_config.FasterWhisper_config_dict
if device is not None:
self.DEVICE = device
else:
device = config_dict["device"]
self.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
if device != "auto":
self.DEVICE = device
self.BEAM_SIZE = int(config_dict["gpu_beam_size"]) if self.DEVICE == "cuda" else int(config_dict["cpu_beam_size"])
self.language = config_dict["language"]
self.COMPUTE_TYPE = config_dict["gpu_compute_type"] if self.DEVICE == "cuda" else config_dict["cpu_compute_type"]
self.MODEL_TYPE = config_dict["gpu_model_type"] if self.DEVICE == "cuda" else config_dict["cpu_model_type"]
self.kotoba_chunk_length = int(config_dict["chunk_length"])
self.kotoba_condition_on_previous_text = config_dict["condition_on_previous_text"]
if self.kotoba_condition_on_previous_text == "True":
self.kotoba_condition_on_previous_text = True
else:
self.kotoba_condition_on_previous_text = False
if config_dict["use_kotoba"] == "True":
self.use_kotoba = True
else:
self.use_kotoba = False
if not self.use_kotoba:
self.model = WhisperModel(self.MODEL_TYPE, device=self.DEVICE, compute_type=self.COMPUTE_TYPE)
else:
self.MODEL_TYPE = config_dict["kotoba_model_type"]
#self.model = WhisperModel(self.MODEL_TYPE, device=self.DEVICE, compute_type=self.cotoba_compute_type)
self.model = WhisperModel(self.MODEL_TYPE)
def audio2text(self, data):
result = ""
data = data.flatten().astype(np.float32)
if not self.use_kotoba:
segments, _ = self.model.transcribe(data, beam_size=self.BEAM_SIZE,language=self.language)
else:
segments, _ = self.model.transcribe(data, beam_size=self.BEAM_SIZE,language=self.language, chunk_length=self.kotoba_chunk_length, condition_on_previous_text=self.kotoba_condition_on_previous_text)
for segment in segments:
result += segment.text
return result
def audioFile2text(self, file_path):
result = ""
if not self.use_kotoba:
segments, _ = self.model.transcribe(file_path, beam_size=self.BEAM_SIZE,language=self.language)
else:
segments, _ = self.model.transcribe(file_path, beam_size=self.BEAM_SIZE,language=self.language, chunk_length=self.kotoba_chunk_length, condition_on_previous_text=self.kotoba_condition_on_previous_text)
for segment in segments:
result += segment.text
return result
Now, I will explain each part.
FasterWhisperconfig Class
Please refer to the Part 5 article. It is exactly the same.
FasterWhisperModel Class init Method
Please refer to the Part 5 article. It is exactly the same.
FasterWhisperModel Class audioFile2text Method
This method is not used in this article. This is the method used in the Part 5 article when transcribing from an audio file. For details, please refer to the Part 5 article. It is exactly the same.
FasterWhisperModel Class audio2text Method
class FasterWhisperModel:
...
def audio2text(self, data):
result = ""
data = data.flatten().astype(np.float32)
if not self.use_kotoba:
segments, _ = self.model.transcribe(data, beam_size=self.BEAM_SIZE,language=self.language)
else:
segments, _ = self.model.transcribe(data, beam_size=self.BEAM_SIZE,language=self.language, chunk_length=self.kotoba_chunk_length, condition_on_previous_text=self.kotoba_condition_on_previous_text)
for segment in segments:
result += segment.text
return result
Basically, it is the same method used in Part 5, calling the transcribe method of the faster-whisper model to perform speech recognition.
Appropriate arguments are used according to the model specified in the configuration file.
faster-whisper splits audio into segments for processing for audio longer than 30 seconds, so the text generated by the splitting is stored in the result variable and returned.
Also,
data = data.flatten().astype(np.float32)
In the above part, the audio data is formatted for input into the faster-whisper model.
Summary
In this article, we created an environment for beginners to easily use generative AI in a Google Colaboratory local environment.
In this Part 5.5, we recorded audio from a microphone locally and transcribed it using the speech recognition AI faster-whisper.
Since recording from a microphone and its transcription are essential for creating a voice dialogue system, we covered it here even though it was not on Google Colab. We will return to Google Colab from the next part onwards.
Furthermore, I have also written an article about voice dialogue systems using speech recognition AI below.
I would appreciate it if you could take a look if you are interested.
In the next Part 6, I would like to make it possible to use the image generation AI Stable-Diffusion.
Discussion