import mlx_whisper import numpy as np import sounddevice as sd import queue import sys import torch from silero_vad import load_silero_vad, get_speech_timestamps # Parameters MODEL_PATH = "mlx-community/whisper-small.en-mlx" # MLX optimized small model CHANNELS = 1 SAMPLERATE = 16000 BLOCK_SIZE = 512 # Silero VAD prefers 512, 1024, or 1536 VAD_THRESHOLD = 0.5 BUFFER_LIMIT = SAMPLERATE * 30 MIN_SILENCE_DURATION_MS = 500 audio_queue = queue.Queue() def callback(indata, frames, time, status): if status: print(status, file=sys.stderr) audio_queue.put(indata.copy()) def main(): print(f"Loading MLX-optimized Whisper model '{MODEL_PATH}'...") # mlx-whisper uses the same model names or Hugging Face paths print("Loading Silero VAD model...") vad_model = load_silero_vad() print("Models loaded.") print("\nStarting live transcription (MLX + VAD)... (Press Ctrl+C to stop)") audio_buffer = [] speech_started = False try: with sd.InputStream(samplerate=SAMPLERATE, channels=CHANNELS, callback=callback, blocksize=BLOCK_SIZE): while True: while not audio_queue.empty(): data = audio_queue.get() audio_buffer.append(data.flatten()) if len(audio_buffer) > 0: current_audio = np.concatenate(audio_buffer) audio_tensor = torch.from_numpy(current_audio) speech_timestamps = get_speech_timestamps( audio_tensor, vad_model, sampling_rate=SAMPLERATE, threshold=VAD_THRESHOLD, min_silence_duration_ms=MIN_SILENCE_DURATION_MS ) if len(speech_timestamps) > 0: speech_started = True last_end = speech_timestamps[-1]['end'] buffer_len_samples = len(current_audio) if (buffer_len_samples - last_end) > (SAMPLERATE * MIN_SILENCE_DURATION_MS / 1000) or buffer_len_samples > BUFFER_LIMIT: # Transcribe with MLX result = mlx_whisper.transcribe(current_audio, path_or_hf_repo=MODEL_PATH) text = result['text'].strip() if text: print(f"Transcription: {text}") audio_buffer = [] speech_started = False elif not speech_started and len(current_audio) > SAMPLERATE * 2: audio_buffer = [] except KeyboardInterrupt: print("\nStopped by user.") except Exception as e: print(f"\nError: {e}") if __name__ == "__main__": main()