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 from transformers import MarianMTModel, MarianTokenizer # Parameters WHISPER_MODEL = "mlx-community/whisper-small.en-mlx" # Dedicated EN-ES translation model (very fast and accurate) TRANSLATE_MODEL = "Helsinki-NLP/opus-mt-en-es" CHANNELS = 1 SAMPLERATE = 16000 BLOCK_SIZE = 512 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(): # Set device for translation model device = "mps" if torch.backends.mps.is_available() else "cpu" print(f"Using device for translation: {device}") print(f"Loading Whisper model '{WHISPER_MODEL}'...") print(f"Loading dedicated translation model '{TRANSLATE_MODEL}'...") tokenizer = MarianTokenizer.from_pretrained(TRANSLATE_MODEL) model = MarianMTModel.from_pretrained(TRANSLATE_MODEL).to(device) print("Loading Silero VAD model...") vad_model = load_silero_vad() print("Models loaded.") print(f"\nStarting live transcription & translation... (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: # 1. Transcribe (English) result = mlx_whisper.transcribe(current_audio, path_or_hf_repo=WHISPER_MODEL) original_text = result['text'].strip() if original_text: # 2. Translate using dedicated MarianMT inputs = tokenizer(original_text, return_tensors="pt", padding=True).to(device) with torch.no_grad(): translated_tokens = model.generate(**inputs) translated_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True) print(f"\nEN: {original_text}") print(f"ES: {translated_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()