Certainly! Below is a Python script that uses the faster-whisper library to recognize the user's voice in real-time. It captures audio from the microphone using the sounddevice library, processes it in chunks, and detects pauses or stops in the speech.
Before running the script, make sure you have the necessary libraries installed:
pip install sounddevice numpy faster-whisper
Here's the code:
import numpy as np
import sounddevice as sd
from faster_whisper import WhisperModel
import threading
import queue
import time
# Initialize the model
# You can choose from 'tiny', 'base', 'small', 'medium', 'large-v1', 'large-v2'
model_size = "base"
model = WhisperModel(model_size, device="cpu", compute_type="int8") # or 'cuda' if you have a GPU
# Audio parameters
sample_rate = 16000 # Whisper expects 16kHz audio
block_size = 4000 # Number of samples per audio block (0.25 seconds)
channels = 1 # Mono audio
# Silence detection parameters
silence_threshold = 0.01 # Threshold for detecting silence
silence_duration = 1.0 # Duration of silence to consider as a pause/stop (in seconds)
# Queue to communicate between the audio thread and the transcription thread
audio_queue = queue.Queue()
# Buffer to hold audio data
audio_buffer = np.empty((0,), dtype=np.float32)
# Variables to track silence
last_speech_time = time.time()
is_speaking = False
def audio_callback(indata, frames, time_info, status):
"""
This callback is called for each audio block from the microphone.
"""
global audio_buffer, last_speech_time, is_speaking
if status:
print(f"Audio callback status: {status}", flush=True)
# Flatten the array and append to buffer
audio_data = indata[:, 0]
audio_buffer = np.concatenate((audio_buffer, audio_data))
# Calculate the root mean square (RMS) energy
rms = np.sqrt(np.mean(audio_data ** 2))
# Check if the audio block contains speech
if rms > silence_threshold:
last_speech_time = time.time()
if not is_speaking:
is_speaking = True
print("Speech detected.", flush=True)
else:
if is_speaking and (time.time() - last_speech_time) >= silence_duration:
is_speaking = False
print("Silence detected.", flush=True)
# Signal that the user has stopped speaking
audio_queue.put(None)
# If buffer is sufficiently long, send it for transcription
if len(audio_buffer) >= sample_rate * 1: # Process every 1 second of audio
# Send a copy of the buffer to the transcription thread
audio_queue.put(audio_buffer.copy())
# Reset the buffer
audio_buffer = np.empty((0,), dtype=np.float32)
def transcription_worker():
"""
This function runs in a separate thread and processes audio data from the queue.
"""
while True:
audio_data = audio_queue.get()
if audio_data is None:
print("Transcription worker received stop signal.", flush=True)
break
# Run the transcription
segments, _ = model.transcribe(audio_data, language='en', beam_size=5)
# Print the transcription
for segment in segments:
print(f"[{segment.start:.2f}s - {segment.end:.2f}s]: {segment.text}", flush=True)
print("Transcription worker stopped.", flush=True)
def main():
# Start the transcription thread
transcription_thread = threading.Thread(target=transcription_worker)
transcription_thread.start()
# Open the audio stream
with sd.InputStream(callback=audio_callback,
channels=channels,
samplerate=sample_rate,
blocksize=block_size,
dtype='float32'):
print("Recording audio. Press Ctrl+C to stop.", flush=True)
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print("Stopping audio recording.", flush=True)
# Signal the transcription thread to stop
audio_queue.put(None)
transcription_thread.join()
if __name__ == "__main__":
main()
Explanation of the Code:
-
Import Statements:
- numpy: For numerical operations on audio data.
- sounddevice: To capture audio from the microphone.
- faster_whisper: To load and run the Whisper model.
- threading and queue: To handle audio data processing in a separate thread.
- time: For timing and detecting silence durations.
-
Model Initialization:
- We initialize the Whisper model using
WhisperModel. The model_size can be adjusted based on your requirements and hardware capabilities.
- Set
device="cpu" for CPU inference or device="cuda" if you have an NVIDIA GPU.
-
Audio Parameters:
- sample_rate: Set to 16000 Hz as the Whisper model expects audio at this sample rate.
- block_size: Determines how many samples are processed in each audio block. A smaller block size results in lower latency.
- channels: Mono audio is used (
channels = 1).
-
Silence Detection Parameters:
- silence_threshold: The RMS energy below which the audio is considered silent.
- silence_duration: The duration of continuous silence required to detect a pause or stop in speech.
-
Audio Callback Function (audio_callback):
- This function is called by
sounddevice for each block of audio data captured from the microphone.
- It appends the incoming audio data to a buffer.
- Calculates the RMS energy to detect if there's speech in the audio block.
- Updates the
last_speech_time when speech is detected.
- Checks if the user has stopped speaking based on the silence duration.
- When the buffer accumulates enough data (e.g., 1 second), it sends a copy of the buffer to the transcription thread and resets the buffer.
-
Transcription Worker Function (transcription_worker):
- Runs in a separate thread to process audio data without blocking the main thread.
- Retrieves audio data from the queue and runs the method of the model.
Notes:
- Latency: There might be some latency between speaking and seeing the transcription because the audio is processed in chunks.
- Model Size: The
base model is used in this example. You can choose a smaller model like tiny for faster performance or a larger one for better accuracy.
- Adjusting Parameters:
- silence_threshold: You may need to adjust this based on the ambient noise level.
- silence_duration: Increase or decrease this to change how quickly a pause is detected.
- block_size and buffer processing intervals can be adjusted for lower latency.
Running the Script:
- Install Dependencies:
pip install sounddevice numpy faster-whisper
- Run the Script:
python realtime_whisper.py
-
Use the Application:
- Speak into your microphone.
- The script will transcribe your speech in real-time.
- It will detect pauses or stops in your speech and output "Silence detected."
-
Stop the Application:
- Press
Ctrl+C in the terminal to stop the script.
Troubleshooting:
- Microphone Access: Ensure that your microphone is properly set up and accessible by Python.
- Permissions: On some systems, you may need additional permissions to access audio devices.
- CPU Usage: Real-time transcription can be CPU-intensive. Using a smaller model or running on a machine with a GPU can improve performance.
Feel free to adjust the parameters and enhance the script according to your specific needs!