OFFLINE SLOVAK SPEECH-TO-TEXT & TRANSLATION DUAL ROUTE: FASTER-WHISPER & MLX PHONON-2.5 100% LOCAL MARIANMT & OLLAMA

Slovak Audio Suite: Real-Time Offline Speech-to-Text & Translation

A 100% offline personal tool for sitting in business meetings held in Slovak: captures live microphone audio at native hardware rates, segments complete sentences with a noise-floor tracking hysteresis gate, and delivers live Slovak transcripts and English translations directly on your laptop without sending a single byte of audio or text to a remote server.

16 kHz
Polyphase Kaiser Resampling
2 Engines
faster-whisper & MLX Phonon
4 UIs
Tkinter GUI & Textual TUI
100% Local
Zero-Cloud Offline Execution

A Personal Tool for Slovak Meetings

Slovak has roughly 5 million speakers and is underrepresented in common English-centric training corpora. Commercial cloud models often hallucinate or drop key Slovak terminology, and cloud APIs cannot be used during confidential in-person or internal meetings.

  • Dual-Engine Choice: Cross-platform CPU execution with faster-whisper (CTranslate2 int8) + MarianMT (Helsinki-NLP), or Apple Silicon GPU acceleration with Phonon-2.5 (MLX) + local Ollama.
  • Text Translation vs. Direct Audio Paraphrase: Whisper's direct audio translation paraphrases and drops proper nouns. Translating Slovak transcripts with MarianMT preserves sentence structure and exact terminology.
  • Spoken FIFO Ordering: Parallel recognition and translation workers push results into OrderedResults, guaranteeing phrase 2 never appears ahead of phrase 1 in the transcript.
  • Session Persistence: Automatically writes timestamped transcripts to disk upon stopping, ignoring idle sessions that contain no spoken turns.
Dual Recognition & Translation Matrix:
• Route A (CPU): faster-whisper (small) → MarianMT sk-en (PyTorch)
• Route B (Apple GPU): Phonon-2.5 (MLX) → Ollama translategemma:latest

Low-Latency Signal & Click Engineering

Solving the real-world obstacles of real-time audio on macOS laptops:

Hardware-Rate PortAudio Capture: Avoids driver resampling bugs by querying native input rates (44.1 kHz, 48 kHz, or Bluetooth profiles) and picking the highest-energy channel for stereo interfaces.
Adaptive Noise Floor & Pre-Roll: 95/5 exponential noise floor tracker with 50% hysteresis once speaking, 350 ms rolling pre-roll buffer, and 0.7s silence / 8.0s max phrase boundaries.
NFKD Accent-Folding Hallucination Filter: Unicode NFKD normalization folds Slovak diacritics (ďakujem → dakujem) to block 28 known subtitle captions and dash-loop hallucinations.
Cocoa Objective-C Swizzling: PyObjC + ctypes swizzles Tk's tkProcessMouseEvent: to clear stuck mouseInResizeArea flags and deliver first-clicks to ActionButtons.

Multi-Engine Pipeline & Concurrency Architecture

Every spoken Slovak phrase is captured at native device rates, segmented by an adaptive noise floor tracker, conditioned to prevent hallucinations, and processed across decoupled recognition and translation locks while maintaining strict spoken order.

+----------------------------------------------------------------------------------------------------+
|                               HARDWARE AUDIO CAPTURE LAYER (audio_input.py)                        |
|  [Physical Microphone / Headset]               [File CLI: --file clip.wav]                         |
|  (sd.InputStream @ native Hz, 250ms chunks)    (soundfile libsndfile reader)                       |
+----------------------+-------------------------------------------------------+---------------------+
                       │                                                       │
                       └───────────────────────────┬───────────────────────────┘
                                                   │
+--------------------------------------------------+------------------------------------------------+
|                    ADAPTIVE PHRASE GATE and PRE-ROLL (speech_audio.take_speech_phrase)            |
|  - 95/5 exponential noise floor tracker + 50% hysteresis threshold once speaking                  |
|  - 350 ms rolling pre-roll buffer prevents clipped word onsets; 0.2 s onset confirmation          |
|  - Closes after 0.7 s silence or 8.0 s ceiling; rejects clips < 0.4 s (cough / door slam)         |
+--------------------------------------------------+------------------------------------------------+
                                                   │
                                   put_nowait() to Background Worker
                                                   │
+--------------------------------------------------+------------------------------------------------+
|                    SIGNAL CONDITIONING and ANTI-HALLUCINATION (prepare_speech_audio)              |
|  1. 20 ms frame RMS gate (>= 0.005, >= 15% active frames) drops quiet hiss                        |
|  2. _trim_silence: Trims quiet heads and tails with 0.12 s padding (stops "thank you" loops)      |
|  3. _resample_16k: SciPy Kaiser-windowed (beta=14.0) polyphase resampler to 16 kHz mono           |
|  4. _level: 99.9th-percentile click-resistant peak normalization to 0.95 (max gain 6.0x)          |
+--------------------------------------------------+------------------------------------------------+
                                                   │
                         ┌─────────────────────────┴─────────────────────────┐
                         │                                                   │
+------------------------+---------------------------+ +-----------------------+---------------------------+
| ROUTE A: faster-whisper and MarianMT (CPU Pipeline)| | ROUTE B: Phonon-2.5 and Ollama (Apple GPU/Metal)  |
| - Hugging Face cache offline loading (int8)        | | - mlx-audio on Apple MLX array framework          |
| - Size-adaptive beam search (5 for small, 1 med)   | | - 8,000-sample Metal shader pre-warming           |
| - Drops no_speech > 0.85, logprob < -1.1           | | - Dedicated phonon thread affinity worker         |
| - NFKD accent-folded banned captions filter        | | - Parallel Ollama chat (temp 0, keep-alive)       |
| - Helsinki-NLP/opus-mt-sk-en sentence batching     | | - Dynamic token caps and terms preservation       |
+------------------------+---------------------------+ +---------------------+-----------------------------+
                         │                                                   │
                         └─────────────────────────┬─────────────────────────┘
                                                   │
+--------------------------------------------------+-------------------------------------------------+
|                       CONCURRENCY ORDERING LAYER (ordered_results.py)                              |
|  - OrderedResults.push(index, item): Releases ready sequences in strict spoken FIFO order          |
|  - InFlight: Tracks active background jobs and waits up to 180 s on Stop before flushing           |
+--------------------------------------------------+-------------------------------------------------+
                                                   │
                         ┌─────────────────────────┴─────────────────────────┐
                         │                                                   │
+------------------------+-------------------------+ +-----------------------+-----------------------+
| DESKTOP TKINTER INTERFACES (app.py / app_phonon) | | TERMINAL TEXTUAL INTERFACES (app_textual_*)   |
| - Custom ActionButton (tk.Label with debounce)   | | - Textual RichLog newest-first transcript     |
| - Objective-C tkProcessMouseEvent: swizzle       | | - _Quiet wrapper suppresses stdout corruption |
| - phrase_< index > marks pair Slovak and English | | - Responsive CSS hides header on small terms  |
+--------------------------------------------------+ +-----------------------------------------------+
                                                   │
                                                (on Stop)
                                                   │
                                      [transcripts/*.txt Session Log]

Application Architecture & Module Matrix

Module / File Primary Stack Core Responsibility Reliability & Platform Safeguards
app.py Tkinter + ttk Desktop window for faster-whisper + MarianMT pipeline with mode and model selectors. Uses custom ActionButton debounced to 0.3 s; schedules UI updates via root.after.
app_phonon.py Tkinter + ttk Desktop window for Phonon-2.5 MLX + Ollama pipeline with glossary term preservation. Uses Tk marks phrase_<index> with left gravity to place delayed English directly below Slovak.
app_textual.py Textual + Rich Interactive terminal UI for Whisper + MarianMT with live mic meter and bilingual log. Replaces sys.stdout/stderr with _Quiet to block library prints; responsive CSS.
app_textual_phonon.py Textual + Rich Interactive terminal UI for Phonon-2.5 MLX + Ollama with glossary inputs. Thread-safe message dispatching via call_from_thread; newest-first row dictionaries.
speech_audio.py NumPy, SciPy Adaptive noise floor tracker, phrase gate, 16 kHz Kaiser resampler, and peak leveling. Rejects clips < 0.4 s; trims quiet ends; Unicode NFKD accent-folded caption hallucination filter.
audio_input.py sounddevice + PortAudio Queries hardware default sample rates, opens 250 ms chunks, reduces stereo to mono. Selects channel with highest mean squared energy; graceful fallback to system default device.
engine.py faster-whisper (CTranslate2) Offline-first model loader, size-adaptive beam search, and split-lock recognition. Separate _RECOGNIZER_LOCK and _TRANSLATOR_LOCK enable simultaneous decode & translation.
translator.py MarianMT (PyTorch) Loads Helsinki-NLP/opus-mt-sk-en, splits sentences on punctuation, runs batch inference. Inference inside torch.no_grad() with max_length=256; silences unauthenticated hub warnings.
phonon_engine.py mlx-audio on Apple MLX Loads Phonon-2.5 on Apple Silicon GPU; enforces dedicated worker thread affinity. warm_phonon runs 8,000 zero samples to pay Metal shader compilation cost upfront.
ollama_translate.py Python http.client Direct HTTP JSON communication with local Ollama daemon; dynamic token caps. Sets think: false, temperature: 0, 30m keep_alive, and cleans preambles via exact_spoken_text.
ordered_results.py Python threading Buffers out-of-order worker results and releases contiguous ready sequences in FIFO order. Empty results count as valid completions to prevent silent phrase stalls; InFlight drain counter.
click_macos.py PyObjC + ctypes + Tcl Swizzles tkProcessMouseEvent: to clear stuck flags and deliver first-clicks on macOS. Patches Tcl combobox popdown procedures to release dead grabs every 400 ms.
session_log.py Python io & os Persists UTF-8 transcripts to transcripts/transcript_YYYYMMDD-HHMMSS.txt. Only writes when actual [English] or [Slovak] lines exist, ignoring empty sessions.

Core Implementation Deep Dive

Inspect key engineering mechanisms: adaptive energy phrase gating with pre-roll, spoken FIFO order preservation, split-lock decode pipelines, and low-level Cocoa Objective-C mouse swizzling.

1. Adaptive Phrase Gate & Pre-Roll
Python
# speech_audio.py
def take_speech_phrase(state: dict, chunk) -> Optional[np.ndarray]:
    sr = int(state["sr"])
    samples = np.asarray(chunk, dtype=np.float32).reshape(-1)
    rms = float(np.sqrt(np.mean(np.square(samples))))
    speaking = bool(state.get("is_speaking"))
    if not speaking:
        floor = float(state.get("noise_floor", 0.0015))
        state["noise_floor"] = (0.95 * floor) + (0.05 * rms)
    floor = max(float(state.get("noise_floor", 0.0015)), 1e-5)
    ceiling = min(max(float(state.get("cfg_thresh") or 0.008), 0.004), 0.01)
    open_at = max(0.004, min(ceiling, max(floor * 3.0, 0.004)))
    is_speech = rms >= (open_at * 0.5 if speaking else open_at)

    # 350 ms rolling pre-roll buffer ensures word onsets are preserved
    # Closes after 0.7 s silence or 8.0 s ceiling; rejects clips < 0.4 s
    ended = state["silent_frames"] >= int(sr * 0.7) or len(buffer) >= int(sr * 8.0)
    if ended:
        clip = np.concatenate(buffer)
        if len(clip) < int(sr * 0.4):
            return None  # Discard transient click or cough
        return clip
2. Spoken-Order FIFO Buffer
Python
# ordered_results.py
class OrderedResults(Generic[T]):
    """Buffer out-of-order worker completions and release them in spoken order."""
    def __init__(self):
        self._lock = threading.Lock()
        self._ready: dict[int, T] = {}
        self._next: int = 0

    def push(self, index: int, item: T) -> list[T]:
        with self._lock:
            self._ready[index] = item
            finished = []
            # Release all contiguous ready indices starting from _next
            while self._next in self._ready:
                finished.append(self._ready.pop(self._next))
                self._next += 1
            return finished

class InFlight:
    """Track pending worker jobs; wait up to 180s on Stop before writing logs."""
    def wait(self, timeout: float = 180.0) -> bool:
        return self._idle.wait(timeout)
3. Split-Lock Decode & MarianMT
Python
# engine.py & translator.py
def decode_audio(model, audio, sample_rate, task, translator, model_tag):
    # Phrase N+1 can recognize while Phrase N translates
    with _RECOGNIZER_LOCK:
        recognize = "transcribe" if task == "translate" and translator is not None else task
        text = recognize_phrase(model, audio, sample_rate, recognize, model_tag)
    if task != "translate" or translator is None:
        return text
    with _TRANSLATOR_LOCK:
        return translate_phrase(translator, text)

def translate_phrase(translator, text: str) -> str:
    # Sentence splitting prevents MarianMT max_length truncations
    parts = split_sentences(text)
    outputs = []
    with torch.no_grad():
        for chunk in parts:
            inputs = translator.tokenizer([chunk], return_tensors="pt", truncation=True)
            tokens = translator.model.generate(**inputs, max_length=256)
            outputs.append(translator.tokenizer.decode(tokens[0], skip_special_tokens=True))
    return " ".join(outputs)
4. Objective-C Cocoa Mouse Swizzle
Python
# click_macos.py
def swizzle_tk_mouse_event(root) -> bool:
    """Clear stuck mouseInResizeArea and deliver first-clicks to ActionButtons."""
    cls = NSClassFromString("TKApplication")
    if cls is None:
        return False
    orig = cls.tkProcessMouseEvent_

    def replacement(self, event):
        if event.type() == 1:  # LeftMouseDown
            window = event.window()
            if window is not None and hasattr(window, "setMouseInResizeArea_"):
                window.setMouseInResizeArea_(False)
            app = NSApplication.sharedApplication()
            if not app.isActive():
                _queue_click_at(root, event)
        return orig(self, event)

    cls.tkProcessMouseEvent_ = selector(replacement, selector=orig.selector, signature=orig.signature)
    return True