A real-time terminal translation application tuned for Apple Silicon laptops. Cuts microphone audio into phrases
using Silero VAD, decodes speech in a single greedy float16 pass with mlx-whisper on unified
memory,
and dynamically routes translations: Slovak speech goes to MarianMT, while 50+ other languages go to Meta's
NLLB-200 on Metal Performance Shaders (MPS)—skipping translation entirely if English was spoken.
Building a live speech translator inside a terminal requires solving real-world latency and memory traps:
high-level helpers like mlx_whisper.transcribe pad every clip to 30 seconds and encode audio
twice to detect the spoken language, burning the entire latency budget before translation begins.
Helsinki-NLP/opus-mt-sk-en
(MarianMT) for faithful syntax, and routes 50+ other languages to Meta's distilled NLLB-200
600M model on PyTorch MPS.
Overcoming system-level hurdles on macOS:
threading.RLock to stop
fds_to_keep worker crashes.
/dev/null during Hugging Face snapshot loads, preserving
TUI layout integrity.Explore the interactive Textual terminal UI in action: real-time descending multilingual logs, audio meters, and device configuration.
Active Textual terminal session showing model selection, 20-block input level meter, SPEAKING indicator, and descending bilingual log with language tags.
Hardware input device selector, Whisper checkpoint switcher, and logging modes (Both, English only, Original only) within the terminal window.
Every spoken utterance is captured at the microphone's native rate, accumulated into 512-sample Silero VAD chunks, decoded on unified memory with mlx-whisper, and translated through language-specific neural pipelines on Apple Silicon Metal cores.
+----------------------------------------------------------------------------------------------------+
| HARDWARE AUDIO CAPTURE LAYER (sounddevice) |
| [Hardware Microphone] -> (InputStream @ native Hz, 30 ms frames, bounded queue AUDIO_QUEUE_SIZE) |
| - put_latest(): Drops oldest frame when full to prevent drift and buffer bloat |
+--------------------------------------------------+-------------------------------------------------+
│
+----------------------------------------------------------------------------------------------------+
| SILERO VAD PHRASE BOUNDARY DETECTOR (engine.run_vad) |
| - 30 ms linear resampler accumulates 512-sample blocks @ 16 kHz for Silero VAD neural network |
| - 12-frame (360 ms) pre-roll buffer prevents clipped word onsets; adaptive noise floor tracking |
| - Triple close condition: Silero release (400 ms), pause near floor (550 ms), or 24 s ceiling |
| - Immediate state clearing on close; tags phrase with caught_at timestamp |
+--------------------------------------------------+-------------------------------------------------+
│
put_nowait() to Transcription Queue
│
+-----------------------------------------------------------------------------------------------------+
| AUDIO PREPARATION AND SINGLE-PASS MLX-WHISPER DECODE |
| 1. prepare_audio(): RMS speech presence check (>= 0.005), quiet tail trimming, polyphase Kaiser |
| 16 kHz resampling, and robust 99.9th-percentile click-resistant leveling to 0.95 |
| 2. transcribe(): Log mel spectrogram padded to N_FRAMES (3000), single greedy decode in float16 |
| (skips mlx_whisper.transcribe 30 s padding and double language-detection pass) |
| 3. needs_language_rescue(): Disambiguates flipped Slovak/English decodes |
| 4. looks_invented(): Discards compression loops, low logprob noise, and 26 banned caption phrases |
+--------------------------------------------------+--------------------------------------------------+
│
Is text already English?
│
┌─────────────────────────┴─────────────────────────┐
│ YES │ NO
│ │
[Keep Original EN] ┌─────────────────┴─────────────────┐
│ │ Language == "sk"? │
│ └────────┬─────────────────┬────────┘
│ YES │ NO │
│ │ │
│ [MarianMT sk->en] [Meta NLLB-200]
│ (Helsinki-NLP) (distilled 600M)
│ (PyTorch MPS/CPU) (forced eng_Latn)
│ │ │
└─────────────────────────┬────────────────┴─────────────────┘
│
+-----------------------------------------------------------------------------------------------------+
| USER INTERFACE AND SESSION LOGGING LAYER |
| - Textual TUI Screen (app_whisper_textual.py): Thread-safe messages (LogMessage, VadStatusMessage) |
| - NewestFirstLog: Subclassed RichLog that inverts rows so newest phrases appear at the top |
| - SessionLog: Writes structured append-only Markdown table to live_transcript.md |
+-----------------------------------------------------------------------------------------------------+
| Module / Component | Primary Technology | Core Responsibility | Platform Safeguards & Optimizations |
|---|---|---|---|
| engine.py | Python, NumPy, SciPy | Audio capture prep, Silero VAD loop, mlx-whisper decode, and translation. | Decoupled from UI; drops oldest frames via put_latest; suppresses Hugging Face stderr
warnings. |
| app_whisper_textual.py | Textual, Rich | Interactive terminal UI, device picker, checkpoint selector, and VU-meter. | UI thread only draws; workers communicate exclusively through thread-safe Textual messages. |
| Silero VAD | PyTorch, TorchScript | 512-sample neural voice activity detection at 16 kHz. | Triple close boundary (Silero release 400 ms, pause hold 550 ms, 24 s ceiling); pre-roll deque buffer. |
| mlx-whisper | Apple MLX, Metal | Single-pass greedy speech recognition on unified Apple Silicon memory. | Direct greedy float16 mel spectrogram decode; skips 30 s padding and double language-detection pass. |
| MarianMT (sk-en) | Helsinki-NLP, Transformers | High-fidelity Slovak-to-English neural machine translation. | Dedicated loader thread; "Ahoj." warm-up sentence; sentence-boundary splitting. |
| NLLB-200 (600M) | Meta AI, PyTorch MPS | Multilingual translation across 54 supported languages to English. | Lazy loaded on demand; maps language codes to NLLB tags; forced eng_Latn target token.
|
| NewestFirstLog | Textual RichLog | Inverted scrolling transcript display. | Prepends incoming lines to the head of the buffer and executes instant scroll_home().
|
| SessionLog | Python io, Markdown | Appends structured session records to live_transcript.md. |
Escapes pipes and newlines; thread-safe file handle locks; preserves caught_at timestamp.
|
Inspect key engineering mechanisms: Silero VAD frame accumulation, single-pass greedy mel decoding on Metal, dual translation routing with PyTorch MPS placement, and inverted terminal scrolling.
# engine.py
while len(vad_remainder) >= VAD_CHUNK_SIZE:
chunk = np.ascontiguousarray(vad_remainder[:VAD_CHUNK_SIZE], dtype=np.float32)
vad_remainder = vad_remainder[VAD_CHUNK_SIZE:]
try:
speech_prob = float(model_vad(torch.from_numpy(chunk), VAD_SAMPLE_RATE).item())
except Exception as error:
on_frame_error(str(error))
model_vad.reset_states()
low_prob_seconds = 0.0
continue
if speech_prob >= VAD_THRESHOLD:
low_prob_seconds = 0.0
if not is_speaking:
is_speaking = True
speech_buffer = list(pre_roll)
pre_roll.clear()
silent_seconds = 0.0
spoken_seconds = 0.0
speech_peak = frame_rms
on_status("speaking")
elif is_speaking and speech_prob < (VAD_THRESHOLD - 0.15):
low_prob_seconds += VAD_CHUNK_SIZE / VAD_SAMPLE_RATE
if low_prob_seconds >= VAD_MIN_SILENCE_MS / 1000:
finish_segment("vad")
break
# engine.py
def transcribe(audio, model: str, language: str | None, task: str) -> dict:
"""Decode one short phrase in a single Whisper pass without 30s padding."""
audio = np.ascontiguousarray(audio, dtype=np.float32).copy()
dtype = mx.float16
whisper = ModelHolder.get_model(cached_repo_path(model), dtype)
mel = log_mel_spectrogram(audio, n_mels=whisper.dims.n_mels)
mel = pad_or_trim(mel, N_FRAMES, axis=-2).astype(dtype)
result = whisper_decode(
whisper,
mel,
DecodingOptions(
task=task,
language=language,
temperature=0.0,
without_timestamps=True,
fp16=True,
sample_len=decode_token_budget(len(audio)),
),
)
return {
"text": (result.text or "").strip(),
"language": result.language or language or "",
"avg_logprob": float(result.avg_logprob),
"no_speech": float(result.no_speech_prob),
"compression": float(result.compression_ratio),
}
# engine.py
def translate(self, text: str, language: str, on_error) -> str:
if not text or not text.strip():
return ""
pieces = split_translation_sentences(text)
if not pieces:
return ""
if prefers_slovak_model(language, text):
bundle = self.slovak_model(wait_s=30.0)
if bundle is None:
return ""
tokenizer, model, device = bundle
translated = self._generate(tokenizer, model, device, pieces, on_error)
else:
source = NLLB_SOURCE.get(language)
if source is None:
return ""
bundle = self._many_model(on_error)
if bundle is None:
return ""
tokenizer, model, device = bundle
tokenizer.src_lang = source
bos = tokenizer.convert_tokens_to_ids("eng_Latn")
translated = self._generate(
tokenizer, model, device, [" ".join(text.split())], on_error, forced_bos_token_id=bos
)
return translated
# app_whisper_textual.py
class NewestFirstLog(RichLog):
"""Transcript log with the latest line at the top of the screen."""
def write(self, content, width=None, expand=False, shrink=True, scroll_end=None, animate=False):
before = len(self.lines)
result = super().write(content, width=width, expand=expand, shrink=shrink, scroll_end=False, animate=False)
added = len(self.lines) - before
if added <= 0:
return result
fresh = self.lines[before:]
# Prepend new line to head of buffer
self.lines = fresh + self.lines[:before]
self._line_cache.clear()
self.scroll_home(animate=False, immediate=True, x_axis=False)
self.refresh()
return result