I built this to answer a small, stubborn question: what actually happens between someone speaking and a translated line appearing on screen? Not in a diagram, but in a process I could run, break, and watch. The result is a macOS terminal app that listens to a microphone, cuts speech into phrases, transcribes each phrase in the language that was spoken, and translates it into English. If the speech was already English, it stays English and skips the translator entirely.
It is an experiment. There is no test suite, no packaging, no configuration file, and no promise that it behaves well on a machine other than mine. It is a single-user toy for Apple Silicon laptops, tuned by ear against real conversations. Treat it as a readable prototype, not as a production tool.
01. Two Files, One Pipeline
The code is split on purpose. live_translator/engine.py owns capture preparation, recognition, translation, and log rows. It does not import the UI. live_translator/app_whisper_textual.py owns the screen and the user's input. That line is what makes the pipeline approachable: I can import the engine in a REPL and poke at the pure helpers without booting a terminal interface.
The screen is built with Textual, a Python framework for terminal UIs that renders panels, selects, and focus handling more like a small desktop app than a print loop. Textual sits on Rich, the terminal formatting library behind its colors and markup. Audio arrives through sounddevice, the Python bindings for PortAudio, which in turn talks to Core Audio, macOS's audio stack. NumPy holds the samples and does the arithmetic.
Threads do the slow work and the UI thread only draws. That sounds like architecture astronautics until you try decoding a phrase on the event loop and watch the interface freeze. The microphone callback is deliberately boring: copy the buffer, compute a level reading, push the copy onto a bounded queue. PortAudio reuses that memory, so the copy is not optional. The queue drops its oldest frame when full rather than growing without limit, because a live translator that falls behind is worse than one that loses a fraction of a second:
def put_latest(target_queue: queue.Queue, item) -> None:
"""Insert an item, dropping the oldest entry if the queue is full."""
try:
target_queue.put_nowait(item)
except queue.Full:
try:
target_queue.get_nowait()
except queue.Empty:
pass
try:
target_queue.put_nowait(item)
except queue.Full:
pass
02. Finding the Edges of a Phrase
Whisper wants tidy clips. A microphone gives you a stream with no punctuation and no indication of where one sentence ends and the next begins. That job belongs to Silero VAD, a small pretrained neural network that scores short audio windows as speech or non-speech. It is tiny, fast on CPU, and good enough that I never felt the need for a second opinion.
Silero is picky about input: 512 samples at 16 kHz. The capture stream runs at the device's own rate, usually 44.1 or 48 kHz, so each 30 ms block gets linearly resampled and accumulated until there are 512 samples to hand over. The linear interpolation is cheap and slightly lossy, which is fine for a speech/non-speech decision. The final clip that goes to Whisper gets a proper polyphase resample instead, because that audio is what the model actually reads.
Around the detector there is a small amount of state. A pre-roll buffer keeps the last few hundred milliseconds (12 frames × 30 ms = 360 ms) so the first consonant is not clipped when the probability crosses the threshold. A slow noise-floor estimate lets the app distinguish “the room is quiet again” from “the speaker paused mid-sentence.” A phrase can close in three ways:
- Silero VAD release: Silero stays below its release threshold for 400 ms.
- Pause energy threshold: The audio level falls back near the room noise and well below the phrase's own peak for 550 ms (0.55 s).
- Ceiling cutoff: The phrase hits 24 seconds and gets cut to prevent runaway buffers during continuous speech.
# Chunking 16 kHz audio into 512-sample blocks for Silero VAD
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
# Triple close condition
if is_speaking and silent_seconds >= SILENCE_HOLD_SECONDS:
finish_segment("silence")
elif is_speaking and spoken_seconds >= MAX_SPEECH_SECONDS:
finish_segment("timeout")
Every close clears the detector's state. I learned that the hard way. Without the reset, the level meter and the SPEAKING light keep moving, so everything looks healthy, but only the first phrase of the session ever becomes a transcript. It is the kind of bug that makes you distrust your own ears before you distrust the model.
The moment a phrase closes, the app records caught_at. That timestamp travels with the audio through recognition and translation, and it is what eventually lands in the log. A phrase spoken at 19:41 should not be stamped 19:41:07 just because the translator was slow.
03. One Decode, Not Two
Recognition runs on Whisper through mlx-whisper, an MLX port that executes OpenAI's architecture directly on Apple Silicon's unified memory and Metal GPU cores.
The tempting path is mlx_whisper.transcribe, the high-level helper. I avoided it for live audio. It pads every clip to 30 seconds and, when it has to detect the language, encodes the audio twice. For a batch job that is irrelevant. For a stream of two-second phrases it is most of the latency budget spent on padding. Instead, the engine builds one mel spectrogram, pads that spectrogram to Whisper's fixed input size (N_FRAMES = 3000), and runs a single greedy decode in float16:
def transcribe(audio, model: str, language: str | None, task: str) -> dict:
"""Decode one short phrase in a single Whisper pass without 30s audio 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),
}
Timestamps are off because nothing downstream needs them. The token budget scales with clip length via decode_token_budget so the last word of a long phrase is not truncated, and the decoder still stops at the end-of-text token when the phrase is done.
Model weights come from the Hugging Face Hub via huggingface_hub. The app checks the cache first with local_files_only before considering a download, which is less about offline purity and more about not printing Hub warnings into a Textual screen. A stray stderr line does not scroll politely past a TUI—it corrupts the layout.
Whisper's failure modes on short, quiet clips are well known. It hallucinates “Thank you for watching,” loops a word until the compression ratio explodes, or confidently transcribes room tone. The engine filters those out with a few blunt checks: compression ratio (> 2.2), average log probability (< −0.5), no-speech probability (> 0.6), repeated-token ratios (≤ 0.34 unique tokens), and a list of 26 caption phrases in English and Slovak. A confident short phrase such as “thank you” survives; the same words on a weak decode do not.
Language detection is left to Whisper, with one exception. A second decode runs only when English and Slovak look swapped (needs_language_rescue): Slovak text made of ordinary English words, or English text containing Slovak letters. A low confidence score alone is not a reason to decode twice. Spanish, French, Japanese, and everything else keep their first transcript.
04. Two Translators, One Target
Translation is split by language, not by convenience. Slovak goes through MarianMT, a fast encoder-decoder machine translation toolkit, using the Helsinki-NLP opus-mt-sk-en checkpoint. It is small, starts quickly, and is noticeably better on Slovak than asking a giant multilingual model to do the same job.
Every other supported language goes through NLLB-200, Meta's “No Language Left Behind” model, specifically the distilled 600M parameter variant (facebook/nllb-200-distilled-600M). Both run through Hugging Face's transformers library on PyTorch, with Apple's Metal Performance Shaders (MPS) backend used when available, and CPU as fallback:
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 ""
# Route Slovak strictly to Helsinki-NLP MarianMT
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)
# Route all 50+ other languages to Meta NLLB-200 distilled 600M
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
)
if translated and fold(translated) == fold(text):
return ""
return translated
The two paths are not interchangeable. The Slovak model gets a dedicated loader thread, a warm-up sentence ("Ahoj."), and a clear “ready” or “unavailable” line on screen. NLLB is loaded lazily the first time a non-Slovak phrase needs it, because pulling 600M parameters into memory at launch would punish people who only speak Slovak. NLLB also needs a source language tag and a forced target token (eng_Latn).
Translation happens on its own thread, after the transcript line is already visible. Recognition can move on to the next phrase while the previous one is still being translated. That is why the original line can appear a beat before its English counterpart. A small guard discards translations that come back identical to the source after folding case and accents.
05. The Screen and the Log
The main panel is a transcript with the newest line at the top. Textual's RichLog appends at the bottom by default, so the app subclasses it and moves each new line to the front, then scrolls home. It is a small hack with a large effect: the latest phrase is always where your eyes already are, and older lines fall away below:
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:]
self.lines = fresh + self.lines[:before]
self._line_cache.clear()
self.scroll_home(animate=False, immediate=True, x_axis=False)
self.refresh()
return result
app_whisper_textual.py in a terminal, showing model selectors, live 20-block VU-meter, active SPEAKING status, and descending dialogue with language identifiers.
Workers never touch widgets. They post thread-safe messages (LogMessage, VadStatusMessage, LevelMessage, DeviceListMessage), and the UI thread applies them. The voice detector's SPEAKING indicator and the 20-block level meter are separate from transcription entirely, so when the meter moves but no text appears, you know the problem is downstream, not in the microphone.
live_transcript.md is an append-only Markdown table, one row per phrase, with a session heading per launch. Each row carries the caught time, the logging mode, the Whisper checkpoint, and the transcript with a language tag:
# Advanced Live Session - 2026-11-09 01:10:00
| Caught | Log Mode | Model Variant | Structured Transcript |
| :--- | :--- | :--- | :--- |
| 2026-11-09 01:10:04 | BOTH | mlx-community/whisper-large-v3-mlx | SK: Vitajte na našom stretnutí. EN: Welcome to our meeting. |
06. Rough Edges & Practical Lessons
The plumbing has real-world scars:
- tqdm Multiprocessing Lock Bug:
tqdm(pulled in by mlx-whisper) creates a multiprocessing lock by default. Starting its resource tracker from Textual's worker thread fails on macOS withbad value(s) in the fds_to_keep. Replacing the lock with a plain thread lock (tqdm.tqdm.set_lock(threading.RLock())) solves it completely. - Stderr Pollution: Model loaders write download progress and Hub warnings to stderr. Redirecting their output to
/dev/nullduring loading prevents corrupted TUI layouts. - Watchdog for Permissions: A six-second microphone watchdog warns you to grant macOS Privacy & Security permissions, because a denied microphone looks like an indefinite hang.
- Memory Footprint: Whisper Large V3 and NLLB 600M can coexist on unified memory (16 GB+), but swapping checkpoints mid-session requires deferring the reload to the next phrase to prevent Metal allocation crashes.
app_whisper_textual.py.
07. References & Technical Citations
Interface & Audio
- Textual Framework • Python TUI framework with reactive message queues.
- Rich Documentation • Rich text formatting and layout primitives.
- sounddevice • PortAudio bindings for Python.
- PortAudio • Cross-platform audio I/O library.
- Apple Core Audio
Speech Detection & Recognition
- Silero VAD • Pretrained enterprise-grade voice activity detector.
- OpenAI Whisper • Robust Speech Recognition via Large-Scale Weak Supervision.
- Apple MLX Framework • Deep learning array framework for Apple Silicon.
- mlx-whisper on GitHub
Translation Models
- Marian NMT • Fast neural machine translation in C++.
- Helsinki-NLP opus-mt-sk-en • MarianMT Slovak-to-English model.
- Meta NLLB-200 Distilled 600M • 200-language translation model.
- NLLB Research Paper
Explore the Companion Project Showcase
Inspect the pipeline topology diagram, multi-language routing matrix, and full implementation code walkthrough on the showcase page.
Félix Pupo Pérez
Over 20 years of experience building bare-metal firmware, real-time audio and speech pipelines, industrial IoT telemetries, and grounded AI systems.