Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

25.6 KB
Raw Blame
"""The dictation lane's on-device final-pass recognizer, hosted out of process.

Why this exists (2026-09-02 forensics, 220 dictations over four days): every
one of them ran on a cloud Whisper although the settings named the local
engine, because a user-scope environment override had moved the VOICE lane to
the cloud — deliberately, to keep the CUDA DLL load and a second large model
out of the desktop process (the 15-30 s loader-lock freezes of BUG-189 and
the VRAM oversubscription of BUG-204). The cloud round-trip was the lag the
user felt, and the cloud model's near-empty answers on 25 s windows were the
"truncated window" repairs that doubled it.

The dictation lane does not need the voice lane's provider at all. It needs a
strong local model that never touches this process's loader lock or VRAM
budget on its own — which is exactly the shape the live-preview worker already
has (:mod:`dodaios.dictation.preview_worker`). This module reuses that worker
with a stronger checkpoint and beam search, and presents it as an ordinary
``transcribe_pcm`` provider so the existing cross-family chain
(:class:`dodaios.speech.stt_fallback.FallbackSTT`) can put it IN FRONT of the
configured cloud provider:

* the worker builds off the press path (``warm_up`` after boot) and, failing
  that, on the first press;
* a card without enough free memory, a host whose worker only comes up on
  the CPU, a missing local runtime or a wedged worker all raise a CROSSABLE
  failure, so the chain moves to the cloud for that call and comes back
  later — no press is ever lost to the local engine being unavailable;
* a call that outlives its ceiling leaves a response in the pipe; the next
  call kills the worker rather than reading someone else's answer (AP-24:
  a wedged native engine is recovered by replacing it, never by waiting).

Nothing here is Windows-specific: the worker is our own interpreter running
our own module, the free-memory probe reports "unknown" where there is no
NVIDIA tooling (and unknown ALLOWS the spawn, AP-22 shape), and a worker that
comes up on the CPU is declined because a beam-search turbo decode of a 25 s
window on a CPU is slower than the cloud it would replace.
"""

from __future__ import annotations

import asyncio
import logging
import threading
import time
from typing import Any

from dodaios.core.protocols import Transcript

log = logging.getLogger(__name__)

#: Checkpoint the final pass decodes with when the user has not chosen one.
#: ``large-v3-turbo`` is the accuracy of ``large-v3`` at a fraction of the
#: decode time and ~1 GB of VRAM at ``int8_float16``.
DEFAULT_FINAL_MODEL = "large-v3-turbo"

#: Compute type asked of the worker on CUDA. ``int8_float16`` halves the
#: weights against ``float16`` at no measurable accuracy cost, which matters
#: on a card that already holds the wake model, a local voice brain and the
#: local TTS server.
FINAL_COMPUTE = "int8_float16"

#: Beam width for the final pass. The preview decodes greedily (latency); the
#: final pass is read once after release and can afford the search.
FINAL_BEAM_SIZE = 5

#: Decode speed (seconds of decode per second of audio) above which a beam
#: decode counts as running on a CONTENDED card. An idle mid-range card reads a
#: turbo beam-5 pass at well under 0.1; a card another program saturates
#: (a renderer, a local LLM) read 0.9 live on 2026-10-27, so a 15 s dictation
#: waited 13 s after release. Above this line the next calls decode greedily,
#: which measured roughly twice as fast on the same saturated card.
CONTENDED_BEAM_RTF = 0.2

#: Greedy decode speed below which the card counts as free again, and the
#: beam search comes back. Lower than the line above on purpose (hysteresis),
#: so one quick call on a still-busy card does not flip the width back.
UNCONTENDED_GREEDY_RTF = 0.06

#: How often a busy card is measured again while the cloud provider behind it
#: takes the dictations. The measurement is a greedy decode of the dictation
#: that was just handed over, run in the BACKGROUND after the cloud answered,
#: so nobody waits on it. (The first version retried a real dictation locally
#: every 90 s; with a dictation every couple of minutes that made every
#: dictation a slow one — live logs 2026-10-27.)
_BUSY_RECHECK_S = 60.0

#: Audio shorter than this never moves the decode width: a one-word clip is
#: dominated by fixed per-call overhead and says nothing about the card.
_MIN_RTF_SAMPLE_S = 1.0

#: Free accelerator memory the spawn asks for by default — the turbo weights
#: plus a CUDA context, with a little headroom.
DEFAULT_MIN_FREE_GB = 1.5

#: The recognition setting a user picks when they want per-utterance detection.
#: Every cloud STT plugin normalises it away before the call (``groq_api``,
#: ``fwhisper``, ``gemini_api``, ``deepgram_api``); this module is the only one
#: that drives faster-whisper DIRECTLY, and the library rejects the word with a
#: ``ValueError`` listing its 99 codes. Passing it through cost every dictation
#: on this box: the local pass died on its first decode, the worker was replaced
#: and locked out for a minute, and the call crossed to the cloud round-trip the
#: local pass exists to avoid (live logs 2026-09-03, 8 of 8 calls).
AUTO_LANGUAGE = "auto"

#: How long a refused or failed spawn is remembered before the next call may
#: try again. Free memory moves with every model load, so the door is not
#: closed for the process — but probing the card on every press would turn
#: a full card into a slow cloud.
_RETRY_AFTER_S = 60.0


def _concrete_language(language: str | None) -> str | None:
    """A decoder-ready language code, or ``None`` to let Whisper detect one.

    ``None`` for both the empty value and :data:`AUTO_LANGUAGE`, which mean the
    same thing to faster-whisper and only one of which it accepts.
    """
    value = str(language or "").strip()
    if not value or value.lower() == AUTO_LANGUAGE:
        return None
    return value


class LocalEngineUnavailable(RuntimeError):
    """The on-device final pass cannot take this call; another provider may.

    Carries ``status = 503`` so :func:`dodaios.speech.stt_failure.classify_stt_failure`
    reads it as ``unavailable`` — the crossable class — without this module
    importing the classifier or the classifier learning a new marker. A
    dictation must never end because the LOCAL engine is missing; the cloud
    behind it in the chain takes the call.
    """

    status = 503


class LocalFinalSTT:
    """``transcribe_pcm`` provider whose decodes run in the dictation worker.

    Built once per pipeline and kept; the worker process it owns is spawned
    lazily (``warm_up`` off-path, else the first call) and replaced whenever
    it fails. Not safe for concurrent calls by design — the chain in front of
    it serialises callers because ``supports_concurrent_requests`` is False.
    """

    supports_concurrent_requests = False
    runs_on_device = True

    def __init__(
        self,
        model_name: str = DEFAULT_FINAL_MODEL,
        *,
        min_free_gb: float = DEFAULT_MIN_FREE_GB,
        compute: str = FINAL_COMPUTE,
        allow_cpu: bool = False,
        beam_size: int = FINAL_BEAM_SIZE,
    ) -> None:
        self._model_name = str(model_name or DEFAULT_FINAL_MODEL).strip()
        self._min_free_gb = max(0.0, float(min_free_gb))
        self._compute = compute
        self._allow_cpu = allow_cpu
        self._beam_size = max(1, int(beam_size))
        #: True after a decode measured the card as contended; the next calls
        #: decode greedily until a greedy decode measures it free again.
        self._contended = False
        self._contended_at = 0.0
        #: Set by the dictation lane: True when a cloud provider stands behind
        #: this one in the chain. Only then may a busy card hand calls over.
        self.cloud_behind = False
        #: True while a background measurement holds the call lock.
        self._probe_running = False
        self._worker: Any = None
        self._device = ""
        self._engine_compute = ""
        self._spawn_lock = threading.Lock()
        self._call_lock = threading.Lock()
        #: True while a worker spawn is in flight. Read WITHOUT the lock (a bool
        #: read is atomic) because the whole point is to answer while the lock is
        #: held: a cold spawn takes minutes on a contended box (137 s on the
        #: 2026-09-03 boot), and both a press and the dictation lane's own
        #: patience check must be able to see "starting" rather than "wedged".
        self._spawn_in_flight = False
        self._next_attempt_at = 0.0
        self._last_refusal = ""

    # ------------------------------------------------------------------
    # Identity — read by the chain, the history row and the health panel
    # ------------------------------------------------------------------

    @property
    def name(self) -> str:
        return "faster-whisper"

    @property
    def provider_label(self) -> str:
        return "faster-whisper"

    @property
    def last_used_model(self) -> str:
        return self._model_name

    @property
    def is_warm(self) -> bool:
        return self._worker is not None

    @property
    def is_loading(self) -> bool:
        """True while the worker is coming up — starting, not wedged.

        The dictation lane reads this through the chain's attribute forwarding
        (``FallbackSTT.__getattr__``) to tell a slow FIRST load from a hung
        provider. Without it a cold load looked like a wedge: the lane gave up
        at its 20 s ceiling, cancelled the warm-up and rebuilt the chain — and
        since cancelling ``asyncio.to_thread`` does not stop the running thread,
        the fresh instance spawned a SECOND multi-gigabyte worker onto a card
        already loading one (the BUG-204 shape).
        """
        return self._spawn_in_flight

    @property
    def device(self) -> str:
        """``"cuda"`` / ``"cpu"`` of the live worker, ``""`` without one."""
        return self._device

    @property
    def unavailable_reason(self) -> str:
        """Why the last spawn was declined, for the log and the status card."""
        return self._last_refusal

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    def warm_up(self) -> None:
        """Spawn the worker off the press path. BLOCKING — call from a thread.

        Quiet when the host declines: the reason is logged once and the first
        press asks again after :data:`_RETRY_AFTER_S`. Raising here would only
        turn a full card into a warning nobody can act on.
        """
        self._ensure_worker()

    def recover(self) -> None:
        """Drop the worker so the next call starts a fresh one (AP-24)."""
        with self._spawn_lock:
            self._drop_worker_locked()
            self._next_attempt_at = 0.0

    def close(self) -> None:
        self.recover()

    # ------------------------------------------------------------------
    # Transcription
    # ------------------------------------------------------------------

    async def transcribe_pcm(
        self,
        pcm_bytes: bytes,
        sample_rate: int = 16_000,
        language: str | None = None,
    ) -> Transcript:
        """int16 PCM bytes → transcript, decoded in the worker.

        A second caller while one is in flight means the previous call was
        abandoned at its ceiling and its answer is still in the pipe; that
        worker is replaced rather than read from, and THIS call crosses over.
        """
        if sample_rate != 16_000:
            raise LocalEngineUnavailable(
                f"the dictation worker takes 16 kHz audio, not {sample_rate} Hz"
            )
        if not self._call_lock.acquire(blocking=False):
            if self._probe_running:
                # Only ever set while the card is busy and a cloud is behind.
                raise LocalEngineUnavailable(
                    "the card is busy with another program; the next provider takes this dictation"
                )
            if self.is_loading:
                raise LocalEngineUnavailable("the local dictation engine is still starting")
            await asyncio.to_thread(self.recover)
            raise LocalEngineUnavailable(
                "a previous call is still waiting on the dictation worker; "
                "it was replaced — this call goes to the next provider"
            )
        # The blocking reader owns the guard, including after cancellation of
        # its asyncio waiter. Releasing it on timeout lets the next request
        # consume the previous request's response from the same pipe (AP-24).
        guard = self._call_lock

        def read() -> Transcript:
            try:
                return self._transcribe_blocking(pcm_bytes, language)
            finally:
                guard.release()

        work = asyncio.create_task(asyncio.to_thread(read))
        try:
            return await asyncio.shield(work)
        except asyncio.CancelledError:
            # Keep a cold build single-flight. An active decoder, however,
            # must be killed so its blocked pipe reader can finish.
            if self._worker is not None:
                await asyncio.to_thread(self.recover)

            def consume(done: asyncio.Task) -> None:
                try:
                    done.result()
                except asyncio.CancelledError:
                    pass  # Loop shutdown cancels this detached observer.
                except Exception:
                    log.debug("Abandoned dictation reader finished", exc_info=True)

            work.add_done_callback(consume)
            raise

    def _transcribe_blocking(self, pcm_bytes: bytes, language: str | None) -> Transcript:
        if self._contended and self.cloud_behind:
            # A saturated card decodes at speech speed: the cloud behind us
            # answers in about a second. Crossable, so the chain moves on.
            if time.monotonic() - self._contended_at >= _BUSY_RECHECK_S:
                self._start_background_probe(pcm_bytes, language)
            raise LocalEngineUnavailable(
                "the card is busy with another program; the next provider takes this dictation"
            )
        worker = self._ensure_worker(blocking=False)
        if worker is None:
            raise LocalEngineUnavailable(self._last_refusal or "no local dictation worker")
        import numpy as np

        samples = np.frombuffer(pcm_bytes, dtype=np.int16).astype(np.float32) / 32768.0
        asked_for = _concrete_language(language)
        beam_size = self.current_beam_size
        started = time.perf_counter()
        try:
            segments, info = worker.transcribe(samples, language=asked_for, beam_size=beam_size)
        except Exception as exc:  # noqa: BLE001 — classified as crossable below
            failure = f"{type(exc).__name__}: {exc}"
            with self._spawn_lock:
                # A late failure from a replaced worker must not retire the
                # replacement or overwrite its healthy readiness state.
                if self._worker is worker:
                    self._drop_worker_locked()
                    self._next_attempt_at = time.monotonic() + _RETRY_AFTER_S
                    self._last_refusal = failure
            log.warning(
                "Local dictation worker failed (%s) — replaced; this call crosses "
                "to the next provider.",
                failure,
            )
            raise LocalEngineUnavailable(failure) from exc
        # Whisper segment texts carry their own leading space, so a bare join
        # reproduces the decoder's spacing (a " " join would double it).
        text = "".join(str(getattr(seg, "text", "") or "") for seg in segments).strip()
        seg_dicts = tuple(
            {
                "start": getattr(seg, "start", None),
                "end": getattr(seg, "end", None),
                "text": str(getattr(seg, "text", "") or ""),
            }
            for seg in segments
        )
        detected = str(getattr(info, "language", "") or "") or (asked_for or "")
        try:
            confidence = float(getattr(info, "language_probability", 0.0) or 0.0)
        except (TypeError, ValueError):
            confidence = 0.0
        audio_s = len(pcm_bytes) / 32_000.0
        decode_s = time.perf_counter() - started
        self._note_decode_speed(audio_s, decode_s, beam_size)
        log.info(
            "Local dictation final pass: %.1fs of audio in %.2fs on %s (%s, beam %d).",
            audio_s,
            decode_s,
            self._device,
            self._engine_compute,
            beam_size,
        )
        from dodaios.plugins.stt.transcript_filter import clean_stt_text

        return Transcript(
            text=clean_stt_text(text, language=detected),
            language=detected,
            confidence=confidence,
            is_partial=False,
            segments=seg_dicts,
            raw_text=text,
        )

    # ------------------------------------------------------------------
    # Worker ownership
    # ------------------------------------------------------------------

    def _start_background_probe(self, pcm_bytes: bytes, language: str | None) -> None:
        """Measure the card again on this audio, after the caller has moved on.

        Runs on its own thread once the current call has released the lock, so
        the dictation itself goes to the cloud without waiting. A greedy decode
        that is fast again brings the local engine back for the next press.
        """
        self._contended_at = time.monotonic()  # one probe per interval

        def probe() -> None:
            if not self._call_lock.acquire(timeout=5.0):
                return
            self._probe_running = True
            try:
                worker = self._worker
                if worker is None:
                    return
                import numpy as np

                samples = np.frombuffer(pcm_bytes, dtype=np.int16).astype(np.float32) / 32768.0
                started = time.perf_counter()
                worker.transcribe(samples, language=_concrete_language(language), beam_size=1)
                self._note_decode_speed(len(pcm_bytes) / 32_000.0, time.perf_counter() - started, 1)
            except Exception as exc:  # noqa: BLE001 — a failed probe just waits for the next
                log.debug("local dictation: busy-card probe failed (%s)", exc)
            finally:
                self._probe_running = False
                self._call_lock.release()

        threading.Thread(target=probe, name="dictation-busy-probe", daemon=True).start()

    @property
    def current_beam_size(self) -> int:
        """Beam width the next decode uses: greedy while the card is contended."""
        return 1 if self._contended else self._beam_size

    def _note_decode_speed(self, audio_s: float, decode_s: float, beam_size: int) -> None:
        """Move the decode width from how fast the last decode actually ran.

        Measured rather than probed: asking the driver for its utilisation took
        0.3-0.7 s on a saturated card, which is longer than the saving on a
        short clip. The decode we just ran is free and says exactly how busy
        the card is for THIS model.
        """
        if audio_s < _MIN_RTF_SAMPLE_S or self._beam_size <= 1:
            return
        rtf = decode_s / audio_s
        if self._contended and beam_size == 1 and rtf >= UNCONTENDED_GREEDY_RTF:
            self._contended_at = time.monotonic()  # still busy: hand over again
        elif not self._contended and beam_size > 1 and rtf > CONTENDED_BEAM_RTF:
            self._contended = True
            self._contended_at = time.monotonic()
            log.info(
                "Local dictation: the card is busy (%.1fs of audio took %.1fs); "
                "%s until it is free again.",
                audio_s,
                decode_s,
                "the cloud provider takes dictations" if self.cloud_behind else "decoding greedily",
            )
        elif self._contended and beam_size == 1 and rtf < UNCONTENDED_GREEDY_RTF:
            self._contended = False
            log.info(
                "Local dictation: the card is free again (%.1fs of audio in "
                "%.2fs); beam search is back.",
                audio_s,
                decode_s,
            )

    def _ensure_worker(self, *, blocking: bool = True) -> Any:
        """The live worker, spawning one when allowed; ``None`` when declined.

        ``blocking=False`` is the PRESS path. A caller that would have to queue
        behind an in-flight spawn is told so instead of waiting it out, so the
        chain crosses to the cloud in milliseconds rather than holding a worker
        thread for the length of a cold model load — 137 s on the 2026-09-03
        boot, during which every dictation would otherwise have stalled.
        """
        if self._worker is not None:
            return self._worker  # set once, never mutated in place
        if not self._spawn_lock.acquire(blocking=blocking):
            raise LocalEngineUnavailable(
                "the local dictation engine is still starting; this call goes to the next provider"
            )
        try:
            return self._spawn_worker_locked()
        finally:
            self._spawn_lock.release()

    def _spawn_worker_locked(self) -> Any:
        """Spawn and adopt a worker. Caller holds ``_spawn_lock``."""
        if self._worker is not None:
            return self._worker
        now = time.monotonic()
        if now < self._next_attempt_at:
            return None
        self._next_attempt_at = now + _RETRY_AFTER_S
        refusal = self._spawn_refusal()
        if refusal:
            self._last_refusal = refusal
            log.info("Local dictation engine not started: %s", refusal)
            return None
        from dodaios.dictation.local_preview import _spawn_worker_model

        started = time.perf_counter()
        self._spawn_in_flight = True
        try:
            worker = _spawn_worker_model(self._model_name, compute=self._compute)
        finally:
            self._spawn_in_flight = False
        if worker is None:
            self._last_refusal = "the dictation worker did not come up"
            # A cold build can outlast the retry interval. Start the cooldown
            # when it fails, or the very next transcription launches another
            # full build immediately after the warm-up already timed out.
            self._next_attempt_at = time.monotonic() + _RETRY_AFTER_S
            return None
        device = str(getattr(worker, "device", "") or "")
        if device == "cpu" and not self._allow_cpu:
            # A beam-search turbo decode of a 25 s window on a CPU takes
            # longer than the cloud round-trip it would replace; the
            # preview keeps its own CPU floor, the final pass does not.
            worker.close()
            self._last_refusal = (
                "the local engine only runs on the CPU here, which is slower "
                "than the configured provider for a final pass"
            )
            log.info("Local dictation engine declined: %s", self._last_refusal)
            return None
        self._worker = worker
        self._device = device
        self._engine_compute = str(getattr(worker, "compute", "") or "")
        self._last_refusal = ""
        # Timed: a cold load is two orders of magnitude slower than a warm one
        # (137 s against 3.5 s measured), and the number is the only way to see
        # from the log which one a boot got.
        log.info(
            "Local dictation engine ready in %.0f ms: %s on %s (%s), out of process.",
            (time.perf_counter() - started) * 1000.0,
            self._model_name,
            self._device,
            self._engine_compute,
        )
        return worker

    def _spawn_refusal(self) -> str:
        """Why the worker must not be started right now, or ``""``."""
        try:
            from dodaios.dictation.local_preview import faster_whisper_available

            if not faster_whisper_available():
                return "the local speech engine (faster-whisper) is not installed here"
        except Exception as exc:  # noqa: BLE001 — a broken probe reads as "absent"
            return f"the local engine probe failed ({type(exc).__name__}: {exc})"
        if self._allow_cpu or self._min_free_gb <= 0.0:
            return ""
        try:
            from dodaios.hardware.detection import free_accelerator_gb

            free_gb, source = free_accelerator_gb()
        except Exception:  # noqa: BLE001 — an unreadable card must not veto the spawn
            log.debug("local dictation: free-memory probe failed", exc_info=True)
            return ""
        if source == "none" or free_gb <= 0.0:
            # Unknown is not "full": Apple unified memory and ROCm have no cheap
            # reading here, and the worker's own device ladder still decides.
            return ""
        if free_gb >= self._min_free_gb:
            return ""
        return (
            f"only {free_gb:.1f} GB of accelerator memory is free ({source}) and "
            f"{self._model_name} needs ~{self._min_free_gb:.1f} GB; the configured "
            "provider takes this dictation"
        )

    def _drop_worker_locked(self) -> None:
        worker, self._worker = self._worker, None
        self._device = ""
        self._engine_compute = ""
        if worker is None:
            return
        try:
            worker.close()
        except Exception as exc:  # noqa: BLE001 — a dead worker is the goal state
            log.debug("local dictation: worker close skipped (%s)", exc)


__all__ = [
    "CONTENDED_BEAM_RTF",
    "DEFAULT_FINAL_MODEL",
    "DEFAULT_MIN_FREE_GB",
    "FINAL_BEAM_SIZE",
    "FINAL_COMPUTE",
    "LocalEngineUnavailable",
    "LocalFinalSTT",
    "UNCONTENDED_GREEDY_RTF",
]