Make this code work faster import os os.environ["KMPDUPLICATELIBOK"]="TRUE" import numpy…
- User
Make this code work faster import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import numpy as np import sounddevice as sd from faster_whisper import WhisperModel import threading import queue import time
Initialize the model
model_size = "small" model = WhisperModel(model_size, device="cuda", compute_type="int8") # Use 'cuda' if you have a compatible GPU
Audio parameters
sample_rate = 16000 # Whisper expects 16kHz audio block_size = 4000 # Number of samples per audio block (approximately 0.25 seconds) channels = 1 # Mono audio
Silence detection parameters
silence_threshold = 0.01 # Threshold for detecting silence (adjust based on ambient noise) silence_duration = 3.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): """ Callback function called by sounddevice for each audio block. """ 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 to detect speech presence rms = np.sqrt(np.mean(audio_data ** 2)) current_time = time.time() # Check if the audio block contains speech if rms > silence_threshold: last_speech_time = current_time if not is_speaking: is_speaking = True print("Speech detected.", flush=True) else: if is_speaking and (current_time - last_speech_time) >= silence_duration: is_speaking = False print("Silence detected.", flush=True) # Send the current audio buffer for transcription if len(audio_buffer) > 0: # Send the buffered audio to the transcription thread audio_queue.put(audio_buffer.copy()) # Reset the buffer audio_buffer = np.empty((0,), dtype=np.float32)def transcription_worker(): """ Function that runs in a separate thread to process 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
# Skip empty audio data if len(audio_data) == 0: continue # 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) - Assistant