Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

70.7 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Whisper dictation sidecar; load and generate run in stt_transformers_worker.py in a spawn child."""

from __future__ import annotations

from hub.utils.hf_errors import modelscope_missing
from hub.utils.hf_tokens import normalize_token

import gc
import hashlib
import io
import json
import os
import re
import socket
import subprocess
import threading
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

from loggers import get_logger

logger = get_logger(__name__)

# Stable API/UI id -> Hub repo; a request may instead pass a validated `owner/model` id.
STT_MODELS: dict[str, str] = {
    "tiny": "unsloth/whisper-tiny",
    "base": "unsloth/whisper-base",
    "small": "unsloth/whisper-small",
    "large-v3-turbo": "unsloth/whisper-large-v3-turbo",
    "large-v3": "unsloth/whisper-large-v3",
}
DEFAULT_STT_MODEL = "small"
STT_KEEP_ALIVE_SECONDS = 5 * 60
_HF_REPO_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$")
_HF_COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")

# Bound decoded PCM length so a crafted upload cannot exhaust memory (callers also cap the encoded bytes).
_MAX_AUDIO_SECONDS = 30 * 60
_TARGET_SAMPLE_RATE = 16000
_STT_WINDOW_SECONDS = 30
_STT_WINDOW_SILENCE_LOOKBACK_SECONDS = 3
_STT_ENERGY_FRAME_SECONDS = 0.02
_STT_MIN_SILENCE_SECONDS = 0.1
_STT_SILENCE_ENERGY_RATIO = 0.01

# Safetensors only: custom repo ids are untrusted, .bin weights are pickles that run code, and this path skips the malware gate the normal loader applies.
_STT_SNAPSHOT_SUPPORT_FILES = (
    "config.json",
    "generation_config.json",
    "preprocessor_config.json",
    "processor_config.json",
    "tokenizer.json",
    "tokenizer_config.json",
    "vocab.json",
    "merges.txt",
    "normalizer.json",
    "special_tokens_map.json",
    "added_tokens.json",
)
_STT_SAFETENSORS_INDEX = "model.safetensors.index.json"
_STT_SAFETENSORS_WEIGHTS = "model.safetensors"
_STT_REVISION_RECORD_VERSION = 1


@dataclass(frozen = True)
class _SelectedHubFile:
    path: str
    size: int
    blob_key: Optional[str]


@dataclass(frozen = True)
class _CachedSttSnapshot:
    path: Optional[Path]
    is_multilingual: Optional[bool]


class SttDownloadCacheError(RuntimeError):
    """The shared Hub cache cannot safely admit an STT HTTP writer."""


def _capture_stt_hub_cache() -> Path:
    """Capture the configured Hub cache once for one STT download run."""
    from utils.hf_cache_settings import get_hf_cache_paths
    return Path(get_hf_cache_paths().hub_cache).expanduser()


def _claim_stt_repository(repo: str) -> tuple[object, object]:
    """Reserve *repo* against every Model Hub writer and delete."""
    from hub.utils.download_registry import get_models_registry

    registry = get_models_registry()
    owner = object()
    claimed, state = registry.claim_repository_owner(repo, owner)
    if not claimed:
        raise SttDownloadCacheError(
            f"'{repo}' is already active in the Model Hub ({state}); wait for it to finish."
        )
    return registry, owner


def _prepare_stt_cache_for_http(repo: str, hub_cache: Path) -> None:
    """Prepare *repo* for HTTP, rejecting unverified transport markers."""
    from hub.utils.download_registry import TRANSPORT_HTTP, prepare_cache_for_transport
    from hub.utils.hf_cache_state import (
        TRANSPORT_MARKER_NAME,
        iter_active_repo_cache_dirs,
        repo_cache_dir_name,
    )

    canonical = hub_cache / repo_cache_dir_name("model", repo)
    try:
        canonical.mkdir(parents = True, exist_ok = True)
    except OSError as exc:
        raise SttDownloadCacheError(
            f"Could not make the Hugging Face cache safe for '{repo}'. "
            "Close other programs using that cache and try again."
        ) from exc
    prepare_cache_for_transport("model", repo, TRANSPORT_HTTP, root = hub_cache)
    entries = list(iter_active_repo_cache_dirs("model", repo, root = hub_cache))
    try:
        all_marked_http = bool(entries) and all(
            (entry / TRANSPORT_MARKER_NAME).read_text(encoding = "utf-8").strip() == TRANSPORT_HTTP
            for entry in (*entries, canonical)
        )
    except (OSError, UnicodeDecodeError):
        all_marked_http = False
    if not all_marked_http:
        raise SttDownloadCacheError(
            f"Could not make the Hugging Face cache safe for '{repo}'. "
            "Close other programs using that cache and try again."
        )


def _downloaded_file_bytes(
    *,
    hub_cache: Path,
    repo: str,
    filename: str,
    size: int,
    blob_key: Optional[str],
    revision: Optional[str],
) -> int:
    """Count one selected file across partial, finalized, and snapshot forms."""
    repo_cache = _repo_cache_dir(repo, hub_cache = hub_cache)
    candidates: list[Path] = []
    if blob_key:
        blobs = repo_cache / "blobs"
        candidates.extend((blobs / f"{blob_key}.incomplete", blobs / blob_key))
        # huggingface_hub >= 1.18 writes a process-unique `<etag>.<8 hex>.incomplete` partial instead.
        from hub.utils.hf_cache_state import incomplete_blob_hash

        try:
            candidates.extend(
                partial
                for partial in blobs.glob(f"{blob_key}.*.incomplete")
                if incomplete_blob_hash(partial.name) == blob_key
            )
        except OSError:
            pass
    if revision:
        candidates.append(repo_cache / "snapshots" / revision / filename)
    sizes: list[int] = []
    for candidate in candidates:
        try:
            if candidate.is_file():
                sizes.append(max(0, int(candidate.stat().st_size)))
        except OSError:
            continue
    done = max(sizes, default = 0)
    return min(done, max(0, int(size)))


class SttUnavailableError(RuntimeError):
    """The STT backend (PyTorch/Transformers or PyAV) is not installed."""


class SttLoadCancelledError(RuntimeError):
    """An in-flight STT model load was cancelled for training."""


class SttTranscriptionCancelledError(RuntimeError):
    """An in-flight transcription was cancelled by its client."""


class SttModelNotDownloadedError(RuntimeError):
    """The selected model is not complete in the shared Hub cache."""


class SttModelBusyError(RuntimeError):
    """The current model cannot make way yet, so the switch has to be retried."""


class SttModelIdError(ValueError):
    """The requested custom model is not a valid Hugging Face repository id."""


class SttModelCompatibilityError(ValueError):
    """The requested repository is not a Transformers Whisper checkpoint."""


class SttAudioDecodeError(ValueError):
    """The uploaded bytes could not be decoded as audio."""


class SttAudioTooLongError(ValueError):
    """The decoded audio exceeds the bounded transcription duration."""


class SttContextSizeError(ValueError):
    """A recording cannot fit the selected context, or Auto cannot size it reliably."""


class SttIncompleteTranscriptionError(ValueError):
    """The server stopped at a limit instead of completing the transcription."""


class SttLanguageError(ValueError):
    """The requested language is not supported by the selected STT model."""


def _close_connection_on_cancel(connection, cancel_event, done_event) -> None:
    """Shuts the socket rather than the process, so a cancelled dictation keeps its server resident."""
    while not done_event.is_set():
        if not cancel_event.wait(0.05):
            continue
        while not done_event.is_set():
            sock = connection.sock
            if sock is not None:
                try:
                    sock.shutdown(socket.SHUT_RDWR)
                except OSError:
                    pass
                connection.close()
                return
            time.sleep(0.01)
        return


_WHISPER_LANGUAGE_ALIASES = {
    # Legacy/browser BCP-47 primaries whose Whisper code differs.
    "cmn": "zh",
    "fil": "tl",
    "in": "id",
    "iw": "he",
    "ji": "yi",
    "nb": "no",
    "nn": "no",
}


def normalize_whisper_language(language: Optional[str]) -> Optional[str]:
    if not language:
        return None
    normalized = language.strip().replace("_", "-").lower()
    if not normalized or normalized == "auto":
        return None
    primary = normalized.split("-", 1)[0]
    return _WHISPER_LANGUAGE_ALIASES.get(primary, primary)


# Whisper code -> Qwen3-ASR prompt name (config.support_languages; audio.cpp qwen3_asr/assets.cpp).
QWEN3_ASR_LANGUAGE_NAMES = {
    "ar": "Arabic",
    "cs": "Czech",
    "da": "Danish",
    "de": "German",
    "el": "Greek",
    "en": "English",
    "es": "Spanish",
    "fa": "Persian",
    "fi": "Finnish",
    "fr": "French",
    "hi": "Hindi",
    "hu": "Hungarian",
    "id": "Indonesian",
    "it": "Italian",
    "ja": "Japanese",
    "ko": "Korean",
    "mk": "Macedonian",
    "ms": "Malay",
    "nl": "Dutch",
    "pl": "Polish",
    "pt": "Portuguese",
    "ro": "Romanian",
    "ru": "Russian",
    "sv": "Swedish",
    "th": "Thai",
    "tl": "Filipino",
    "tr": "Turkish",
    "vi": "Vietnamese",
    "yue": "Cantonese",
    "zh": "Chinese",
}


def _stt_quiet_window_end(decoded_audio, start: int, window: int) -> Optional[int]:
    """Return a nearby quiet window boundary, or None when speech fills it."""
    import numpy as np

    hard_end = min(start + window, len(decoded_audio))
    if hard_end == len(decoded_audio):
        return None

    lookback = _STT_WINDOW_SILENCE_LOOKBACK_SECONDS * _TARGET_SAMPLE_RATE
    search_start = hard_end - lookback
    candidate = decoded_audio[search_start:hard_end]
    frame = round(_STT_ENERGY_FRAME_SECONDS * _TARGET_SAMPLE_RATE)
    frame_count = len(candidate) // frame
    framed = candidate[: frame_count * frame].reshape(frame_count, frame).astype(np.float64)
    framed -= np.mean(framed, axis = 1, keepdims = True)
    energy = np.mean(np.square(np.diff(framed, axis = 1)), axis = 1)
    silence_frames = round(_STT_MIN_SILENCE_SECONDS / _STT_ENERGY_FRAME_SECONDS)
    smoothed = np.convolve(
        energy, np.ones(silence_frames, dtype = np.float64) / silence_frames, mode = "valid"
    )
    quietest = int(np.argmin(smoothed))
    active_reference = float(np.mean(np.partition(energy, -silence_frames)[-silence_frames:]))
    if active_reference <= 0 or smoothed[quietest] > active_reference * _STT_SILENCE_ENERGY_RATIO:
        return None
    silence_midpoint = round(_STT_MIN_SILENCE_SECONDS * _TARGET_SAMPLE_RATE / 2)
    return search_start + quietest * frame + silence_midpoint


def _known_whisper_languages() -> Optional[frozenset[str]]:
    """Return Whisper's language codes without constructing/loading a model."""
    try:
        from transformers.models.whisper.tokenization_whisper import LANGUAGES
    except Exception:
        return None
    return frozenset(LANGUAGES)


def ensure_stt_available() -> None:
    try:
        import av  # noqa: F401
        import torch  # noqa: F401
        import transformers  # noqa: F401
    except Exception as exc:
        raise SttUnavailableError(
            "Speech-to-text needs PyTorch, Transformers, and PyAV. "
            "Run `unsloth studio update` to install them."
        ) from exc


def is_available() -> bool:
    try:
        ensure_stt_available()
    except SttUnavailableError:
        return False
    return True


def resolve_model_id(model: Optional[str]) -> str:
    """Resolve a curated id or validate a custom Hugging Face repository."""
    if not model:
        return DEFAULT_STT_MODEL
    normalized = model.strip()
    if normalized in STT_MODELS:
        return normalized
    if _HF_REPO_ID.fullmatch(normalized):
        return normalized
    raise SttModelIdError(
        "STT model must be one of Unsloth's defaults or a Hugging Face "
        "repository in 'owner/model' form."
    )


def resolve_model_repo(model_id: str) -> str:
    resolved = resolve_model_id(model_id)
    return STT_MODELS.get(resolved, resolved)


def can_translate(model: Optional[str]) -> bool:
    """Whether Whisper's translate task works on this id. The turbo checkpoints were fine-tuned for transcription
    only and answer in the source language when asked to translate, as do mlx-audio checkpoints."""
    if "turbo" in (model or DEFAULT_STT_MODEL).lower():
        return False
    from core.inference.stt_mlx import mlx_stt_available

    if not model or model in STT_MODELS or not mlx_stt_available():
        return True
    try:
        snapshot = _find_complete_cached_snapshot(model)
    except Exception:  # noqa: BLE001 - an unreadable id is refused later, by the load
        return True
    return snapshot is None or _is_whisper_config(_read_json_object(snapshot / "config.json"))


def _is_whisper_config(config: object) -> bool:
    """True when Hub/local config metadata identifies a Whisper ASR model."""
    if not isinstance(config, dict):
        return False
    model_type = config.get("model_type")
    if isinstance(model_type, str) and model_type.strip().lower() == "whisper":
        return True
    architectures = config.get("architectures")
    return isinstance(architectures, list) and any(
        isinstance(name, str) and name == "WhisperForConditionalGeneration"
        for name in architectures
    )


def _read_json_object(path: Path) -> dict:
    try:
        with open(path, "r", encoding = "utf-8") as file:
            value = json.load(file)
        return value if isinstance(value, dict) else {}
    except Exception:
        return {}


def _active_hf_hub_cache() -> Path:
    """Return the currently configured Hub cache, including live relocation."""
    try:
        from utils.hf_cache_settings import get_hf_cache_paths

        paths = get_hf_cache_paths()
        # Unsloth's live cache setting takes precedence over environment defaults.
        if paths.source == "studio":
            return Path(paths.hub_cache)
        explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
        if explicit:
            return Path(explicit).expanduser()
        hf_home = (os.environ.get("HF_HOME") or "").strip()
        if hf_home:
            return Path(hf_home).expanduser() / "hub"
        return Path(paths.hub_cache)
    except Exception:
        explicit = (os.environ.get("HF_HUB_CACHE") or "").strip()
        if explicit:
            return Path(explicit).expanduser()
        hf_home = (os.environ.get("HF_HOME") or "").strip()
        if hf_home:
            return Path(hf_home).expanduser() / "hub"
        from huggingface_hub.constants import HF_HUB_CACHE

        return Path(HF_HUB_CACHE)


def _repo_cache_dir(repo: str, *, hub_cache: Optional[Path] = None) -> Path:
    root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
    return root / f"models--{repo.replace('/', '--')}"


def _revision_record_path(repo: str) -> Path:
    from utils.paths.storage_roots import cache_root
    digest = hashlib.sha256(repo.encode("utf-8")).hexdigest()
    return cache_root() / "stt-revisions" / f"{digest}.json"


def _write_revision_record(repo: str, revision: str) -> None:
    """Persist immutable identity only, never an HF-cache absolute path."""
    if not _HF_COMMIT_SHA.fullmatch(revision):
        return
    path = _revision_record_path(repo)
    tmp = path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex[:8]}")
    try:
        path.parent.mkdir(parents = True, exist_ok = True)
        with tmp.open("w", encoding = "utf-8") as handle:
            json.dump(
                {
                    "version": _STT_REVISION_RECORD_VERSION,
                    "repo": repo,
                    "revision": revision,
                },
                handle,
            )
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp, path)
    except OSError as exc:
        logger.debug("Could not persist STT revision for %s: %s", repo, exc)
        try:
            tmp.unlink(missing_ok = True)
        except OSError:
            pass


def _read_revision_record(repo: str) -> Optional[str]:
    payload = _read_json_object(_revision_record_path(repo))
    if payload.get("version") != _STT_REVISION_RECORD_VERSION or payload.get("repo") != repo:
        return None
    revision = payload.get("revision")
    return revision if isinstance(revision, str) and _HF_COMMIT_SHA.fullmatch(revision) else None


def _fallback_revisions(repo: str, *, hub_cache: Optional[Path] = None) -> list[str]:
    """Pinned downloads never write refs/main, so a lost revision record would hide a downloaded model."""
    repo_cache = _repo_cache_dir(repo, hub_cache = hub_cache)
    candidates: list[str] = []
    try:
        main_revision = (repo_cache / "refs" / "main").read_text(encoding = "utf-8").strip()
        if _HF_COMMIT_SHA.fullmatch(main_revision):
            candidates.append(main_revision)
    except OSError:
        pass
    try:
        snapshots = sorted(
            (p for p in (repo_cache / "snapshots").iterdir() if _HF_COMMIT_SHA.fullmatch(p.name)),
            key = lambda p: p.stat().st_mtime,
            reverse = True,
        )
    except OSError:
        snapshots = []
    candidates.extend(p.name for p in snapshots if p.name not in candidates)
    return candidates


def _safe_snapshot_for_revision(repo: str, revision: str) -> Optional[Path]:
    """Resolve a canonical SHA below this repository's active snapshots dir."""
    if not _HF_COMMIT_SHA.fullmatch(revision):
        return None
    snapshots = _repo_cache_dir(repo) / "snapshots"
    candidate = snapshots / revision
    try:
        snapshots_resolved = snapshots.resolve()
        candidate_resolved = candidate.resolve()
    except (OSError, RuntimeError):
        return None
    if snapshots_resolved not in candidate_resolved.parents or not candidate_resolved.is_dir():
        return None
    return candidate_resolved


def _is_servable_config(config: object) -> bool:
    from core.inference.stt_mlx import is_mlx_stt_config
    return _is_whisper_config(config) or is_mlx_stt_config(config)


def _snapshot_usable(model_id: str, snapshot: Path) -> bool:
    if not _snapshot_is_complete(snapshot):
        return False
    if model_id not in STT_MODELS:
        return _is_servable_config(_read_json_object(snapshot / "config.json"))
    return True


def _find_complete_cached_snapshot(model: Optional[str]) -> Optional[Path]:
    """Find one complete local snapshot without contacting the Hub."""
    model_id = resolve_model_id(model)
    repo = resolve_model_repo(model_id)

    recorded = _read_revision_record(repo)
    if recorded:
        snapshot = _safe_snapshot_for_revision(repo, recorded)
        if snapshot is not None and _snapshot_usable(model_id, snapshot):
            return snapshot

    ref = _repo_cache_dir(repo) / "refs" / "main"
    try:
        revision = ref.read_text(encoding = "utf-8").strip()
    except OSError:
        revision = ""
    snapshot = _safe_snapshot_for_revision(repo, revision)
    if snapshot is not None and _snapshot_usable(model_id, snapshot):
        _write_revision_record(repo, revision)
        return snapshot

    snapshots = _repo_cache_dir(repo) / "snapshots"
    try:
        revisions = sorted(
            (
                (path.stat().st_mtime_ns, path.name)
                for path in snapshots.iterdir()
                if path.is_dir() and _HF_COMMIT_SHA.fullmatch(path.name)
            ),
            reverse = True,
        )
    except OSError:
        return None
    for _mtime, revision in revisions:
        snapshot = _safe_snapshot_for_revision(repo, revision)
        if snapshot is not None and _snapshot_usable(model_id, snapshot):
            _write_revision_record(repo, revision)
            return snapshot
    return None


def _selected_file_from_sibling(sibling) -> _SelectedHubFile:
    lfs = getattr(sibling, "lfs", None)
    blob_key = getattr(lfs, "sha256", None) or getattr(sibling, "blob_id", None)
    return _SelectedHubFile(
        path = sibling.rfilename,
        size = max(0, int(getattr(sibling, "size", 0) or 0)),
        blob_key = blob_key if isinstance(blob_key, str) and blob_key else None,
    )


def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
    """Select support files and one complete safetensors weight set. Pickle
    (pytorch_model.bin) weights are never selected: they are an RCE sink on a
    custom repo id (see _STT_SNAPSHOT_SUPPORT_FILES)."""
    siblings = {
        sibling.rfilename: sibling
        for sibling in (getattr(info, "siblings", None) or [])
        if isinstance(getattr(sibling, "rfilename", None), str)
    }
    selected = {name for name in _STT_SNAPSHOT_SUPPORT_FILES if name in siblings}

    index_name: Optional[str] = None
    if _STT_SAFETENSORS_INDEX in siblings:
        index_name = _STT_SAFETENSORS_INDEX
    elif _STT_SAFETENSORS_WEIGHTS in siblings:
        selected.add(_STT_SAFETENSORS_WEIGHTS)
    else:
        raise SttModelCompatibilityError(
            "The STT repository has no safetensors model weights. Only safetensors "
            "checkpoints are supported; convert the model with save_pretrained(safe_serialization=True)."
        )

    if index_name is not None:
        weight_map = load_index(index_name).get("weight_map")
        if not isinstance(weight_map, dict) or not weight_map:
            raise SttModelCompatibilityError(f"Invalid checkpoint index '{index_name}'.")
        shards = set(weight_map.values())
        if not all(isinstance(shard, str) and shard in siblings for shard in shards):
            raise SttModelCompatibilityError(f"Checkpoint index '{index_name}' has missing shards.")
        # An index can name .bin shards that Transformers still pickle-loads; require safetensors.
        if not all(shard.endswith(".safetensors") for shard in shards):
            raise SttModelCompatibilityError(
                f"Checkpoint index '{index_name}' references non-safetensors shards."
            )
        selected.add(index_name)
        selected.update(shards)

    return tuple(_selected_file_from_sibling(siblings[name]) for name in sorted(selected))


def validate_remote_model(model: Optional[str], hf_token: Optional[str] = None) -> dict:
    """Verify a custom Hub repository is Whisper-compatible without downloading weights."""
    model_id = resolve_model_id(model)
    repo = resolve_model_repo(model_id)
    if model_id in STT_MODELS:
        return {"model": model_id, "repo": repo}

    try:
        from huggingface_hub import HfApi
        info = HfApi(token = hf_token or False).model_info(
            repo,
            expand = ["config", "sha"],
            timeout = 10,
        )
    except Exception as exc:
        raise SttModelCompatibilityError(
            f"Could not verify STT model '{model_id}'. "
            "Check that the repository exists and your Hugging Face token can access it."
        ) from exc

    if not _is_whisper_config(getattr(info, "config", None)):
        raise SttModelCompatibilityError(
            f"STT model '{model_id}' is not a compatible Transformers Whisper model."
        )
    revision = getattr(info, "sha", None)
    if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
        raise SttModelCompatibilityError(
            f"Could not resolve an immutable revision for STT model '{model_id}'."
        )
    # Download pins to the validated commit (TOCTOU).
    return {"model": model_id, "repo": repo, "revision": revision}


def _is_missing_local_model_error(exc: BaseException) -> bool:
    """Recognize a local-cache-only miss by name/message, without importing HF
    internals (tolerates huggingface_hub/Transformers moving the exception)."""
    current: Optional[BaseException] = exc
    seen: set[int] = set()
    while current is not None and id(current) not in seen:
        seen.add(id(current))
        if type(current).__name__ in ("LocalEntryNotFoundError", "EntryNotFoundError"):
            return True
        message = str(current).lower()
        if "local_files_only" in message or "does not appear to have a file" in message:
            return True
        current = current.__cause__ or current.__context__
    return False


def _snapshot_is_complete(snapshot: Path) -> bool:
    """An aborted download leaves metadata only, so every file is checked; a cached pytorch_model.bin is a pickle and never counts as a usable snapshot."""
    index = snapshot / _STT_SAFETENSORS_INDEX
    if index.is_file():
        # Every shard must be safetensors: an index naming .bin shards would still pickle-load them.
        weight_map = _read_json_object(index).get("weight_map")
        if not isinstance(weight_map, dict) or not weight_map:
            return False
        shards = set(weight_map.values())
        if not all(isinstance(shard, str) and shard.endswith(".safetensors") for shard in shards):
            return False
        has_weights = all((snapshot / shard).is_file() for shard in shards)
    else:
        has_weights = (snapshot / _STT_SAFETENSORS_WEIGHTS).is_file()
    # WhisperProcessor needs the tokenizer: either the fast tokenizer.json or the slow vocab.json + merges.txt pair.
    has_tokenizer = (snapshot / "tokenizer.json").is_file() or (
        (snapshot / "vocab.json").is_file() and (snapshot / "merges.txt").is_file()
    )
    return (
        has_weights
        and has_tokenizer
        and (snapshot / "config.json").is_file()
        and (snapshot / "preprocessor_config.json").is_file()
    )


def is_model_downloaded(model: Optional[str]) -> bool:
    try:
        return _find_complete_cached_snapshot(model) is not None
    except Exception:
        return False


def _remember_completed_download(
    completed_download_ids: list[str], download_id: Optional[str], *, cancelled: bool
) -> bool:
    """Keep enough successful attempt ids for delayed UI pollers to settle."""
    if cancelled or download_id is None:
        return False
    completed_download_ids.append(download_id)
    del completed_download_ids[:-8]
    return True


class _SnapshotDownloadState:
    """Tracks one background snapshot_download of a dictation repository.

    Like stt_ggml_sidecar's tracker, but a Transformers checkpoint is a whole
    repo, so progress is the byte count of its cache blobs.
    """

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._thread: Optional[threading.Thread] = None
        self._process: Optional[subprocess.Popen] = None
        self._model_id: Optional[str] = None
        self._download_id: Optional[str] = None
        self._completed_download_ids: list[str] = []
        self._repo: Optional[str] = None
        self._revision: Optional[str] = None
        self._hub_cache: Optional[Path] = None
        self._error: Optional[str] = None
        self._total_bytes: Optional[int] = None
        self._selected_files: tuple[_SelectedHubFile, ...] = ()
        self._complete = False
        self._cancelled = False

    def status(self) -> dict:
        with self._lock:
            downloading = self._thread is not None and self._thread.is_alive()
            show_progress = downloading or self._complete
            snapshot = {
                "downloading": downloading,
                "model": self._model_id if downloading else None,
                "download_id": self._download_id,
                "completed_download_ids": list(self._completed_download_ids),
                "error": self._error,
                "cancelled": self._cancelled,
                # "model" goes None once the worker stops, so record which model a cancel applied to.
                "cancelled_model": self._model_id if self._cancelled else None,
                "bytes_total": self._total_bytes if show_progress else None,
            }
            captured = (
                self._repo,
                self._revision,
                self._hub_cache,
                self._selected_files,
                self._total_bytes,
            )
        # Outside the lock: _downloaded_bytes() stats the cache, and a cancel must not queue.
        snapshot["bytes_done"] = self._downloaded_bytes(*captured) if show_progress else None
        return snapshot

    def cancel(
        self,
        model_id: Optional[str] = None,
        download_id: Optional[str] = None,
    ) -> bool:
        """Partial blobs stay cached, so a restarted download resumes from them."""
        with self._lock:
            if self._thread is None or not self._thread.is_alive():
                return False
            if self._download_id in self._completed_download_ids:
                return False
            if download_id is not None:
                if self._download_id != download_id:
                    return False
            elif model_id is not None and self._model_id != model_id:
                return False
            self._cancelled = True
            process = self._process
        if process is not None and process.poll() is None:
            from core.inference.stt_download_worker import terminate_download
            terminate_download(process)
        return True

    def _downloaded_bytes(
        self,
        repo: Optional[str] = None,
        revision: Optional[str] = None,
        hub_cache: Optional[Path] = None,
        selected_files: Optional[tuple[_SelectedHubFile, ...]] = None,
        total: Optional[int] = None,
    ) -> Optional[int]:
        """Values come from status() under the lock, so a run starting mid-probe cannot mix totals."""
        try:
            repo = repo if repo is not None else self._repo
            revision = revision if revision is not None else self._revision
            hub_cache = hub_cache or self._hub_cache or _active_hf_hub_cache()
            selected_files = selected_files if selected_files is not None else self._selected_files
            total = total if total is not None else self._total_bytes
            if not repo or hub_cache is None or not selected_files:
                return None
            done = sum(
                _downloaded_file_bytes(
                    hub_cache = hub_cache,
                    repo = repo,
                    filename = selected.path,
                    size = selected.size,
                    blob_key = selected.blob_key,
                    revision = revision,
                )
                for selected in selected_files
            )
            return min(done, total) if total is not None else done
        except Exception:
            return None

    def _run_worker(
        self, args: list[str], hf_token: Optional[str], hub_cache: Path
    ) -> tuple[bool, bytes]:
        from core.inference.stt_download_worker import (
            reap_download,
            spawn_download,
            terminate_download,
        )

        process = spawn_download(args, hf_token = normalize_token(hf_token), hub_cache = hub_cache)
        with self._lock:
            if self._cancelled:
                terminate_download(process)
            self._process = process
        stderr = reap_download(process)
        with self._lock:
            if self._process is process:
                self._process = None
            cancelled = self._cancelled
        if process.returncode == 0 and not cancelled:
            return True, stderr
        if cancelled or process.returncode < 0:
            with self._lock:
                self._cancelled = True
            return False, stderr
        detail = stderr.decode("utf-8", "replace").strip()
        raise SttModelCompatibilityError(f"Download worker failed for '{self._repo}': {detail}")

    def start(
        self,
        model_id: str,
        hf_token: Optional[str] = None,
        revision: Optional[str] = None,
    ) -> str:
        model_id = resolve_model_id(model_id)
        hub_cache = _capture_stt_hub_cache()
        with self._lock:
            if self._thread is not None and self._thread.is_alive():
                if self._model_id == model_id:
                    if not self._cancelled:
                        return str(self._download_id)
                    raise SttModelIdError(
                        f"'{model_id}' is still cancelling; try again in a moment."
                    )
                raise SttModelIdError(
                    f"Another dictation model ('{self._model_id}') is still "
                    "downloading; wait for it to finish."
                )
            self._model_id = model_id
            self._download_id = uuid.uuid4().hex
            self._repo = resolve_model_repo(model_id)
            self._revision = None
            self._hub_cache = hub_cache
            self._error = None
            self._total_bytes = None
            self._selected_files = ()
            self._complete = False
            self._cancelled = False
            self._process = None
            thread = threading.Thread(
                target = self._run,
                args = (self._repo, hf_token, revision),
                daemon = True,
            )
            self._thread = thread
            thread.start()
            return str(self._download_id)

    def _run(
        self,
        repo: str,
        hf_token: Optional[str],
        revision: Optional[str] = None,
        hub_cache: Optional[Path] = None,
    ) -> None:
        hub_cache = hub_cache or self._hub_cache or _active_hf_hub_cache()
        registry = None
        owner = None
        try:
            from huggingface_hub import HfApi, hf_hub_download

            info = HfApi(token = normalize_token(hf_token)).model_info(
                repo,
                revision = revision,
                files_metadata = True,
                timeout = 30,
            )
            if not revision:
                revision = getattr(info, "sha", None)
            if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
                raise SttModelCompatibilityError(
                    f"Could not resolve an immutable revision for STT model '{repo}'."
                )

            # A cancel during metadata has no child to stop; mark it so the run does not rewrite the cache.
            with self._lock:
                if self._cancelled:
                    return
            registry, owner = _claim_stt_repository(repo)
            with self._lock:
                if self._cancelled:
                    return
            _prepare_stt_cache_for_http(repo, hub_cache)
            with self._lock:
                self._revision = revision

            def load_index(filename: str) -> dict:
                completed, _stderr = self._run_worker(
                    ["--repo-id", repo, "--revision", revision, "--filename", filename],
                    hf_token,
                    hub_cache,
                )
                if not completed:
                    return {}
                path = hf_hub_download(
                    repo_id = repo,
                    filename = filename,
                    revision = revision,
                    local_files_only = True,
                    cache_dir = str(hub_cache),
                )
                return _read_json_object(Path(path))

            selected_files = _select_snapshot_files(info, load_index)
            total = sum(selected.size for selected in selected_files)
            with self._lock:
                self._selected_files = selected_files
                self._total_bytes = total or None
            args = ["--repo-id", repo, "--revision", revision]
            for selected in selected_files:
                args += ["--filename", selected.path]
            completed, _stderr = self._run_worker(args, hf_token, hub_cache)
            if not completed:
                return
            snapshot = _repo_cache_dir(repo, hub_cache = hub_cache) / "snapshots" / revision
            if not _snapshot_is_complete(snapshot):
                raise SttModelCompatibilityError(
                    f"Downloaded STT snapshot for '{repo}' is incomplete."
                )
            _write_revision_record(repo, revision)
            with self._lock:
                self._complete = _remember_completed_download(
                    self._completed_download_ids,
                    self._download_id,
                    cancelled = self._cancelled,
                )
        except Exception as exc:
            with self._lock:
                if not self._cancelled:
                    logger.warning("STT snapshot download failed for %s: %s", repo, exc)
                    self._error = modelscope_missing(exc) or f"Download failed for '{repo}'."
        finally:
            if registry is not None and owner is not None:
                registry.release_repository_owner(repo, owner)


_download_state = _SnapshotDownloadState()


def start_model_download(
    model: Optional[str],
    hf_token: Optional[str] = None,
    revision: Optional[str] = None,
) -> str:
    return _download_state.start(resolve_model_id(model), hf_token, revision = revision)


def download_status() -> dict:
    return _download_state.status()


def cancel_model_download(model: Optional[str] = None, download_id: Optional[str] = None) -> bool:
    try:
        model_id = resolve_model_id(model) if model is not None else None
    except SttModelIdError:
        return False
    return _download_state.cancel(model_id, download_id)


def _training_active() -> bool:
    try:
        from core.training import get_training_backend
        return bool(get_training_backend().is_training_active())
    except Exception:
        return False


def _clear_device_cache(device: Optional[str], collect: bool = True) -> None:
    """collect=False only for a caller that just collected and dropped nothing since; a full gc pass costs about a second on a long-lived backend."""
    if collect:
        gc.collect()
    try:
        import torch
        if device == "cuda":
            torch.cuda.empty_cache()
        elif device == "mps":
            torch.mps.empty_cache()
    except Exception:
        pass


def _reported_device(device: Optional[str]) -> Optional[str]:
    """Device name for status. Torch calls the HIP device "cuda", which is right for the
    API and wrong on screen: an AMD card reported as cuda reads like a bug."""
    if device != "cuda":
        return device
    try:
        import torch
        if getattr(torch.version, "hip", None):
            return "rocm"
    except Exception:  # noqa: BLE001 - a label must never fail a status call
        pass
    return device


def _pick_device(preference: Optional[str] = None):
    """CUDA fp16; MPS and CPU fp32 (Whisper fp16 decoder degenerates on MPS). A cpu preference skips detection even on a machine with a working GPU."""
    from core.inference.audio_device import audio_device_forces_cpu
    try:
        import torch

        if audio_device_forces_cpu(preference):
            return "cpu", torch.float32
        # New loads use CPU during training; a resident GPU model may stay if admission confirms headroom.
        training_active = _training_active()
        if not training_active and torch.cuda.is_available():
            return "cuda", torch.float16
        if (
            not training_active
            and getattr(torch.backends, "mps", None) is not None
            and torch.backends.mps.is_available()
        ):
            return "mps", torch.float32
        return "cpu", torch.float32
    except Exception as exc:
        logger.debug("STT device detection failed, using CPU: %s", exc)
        import torch
        return "cpu", torch.float32


def _dtype_name(dtype) -> str:
    """Returns a plain string so the worker command carries no torch object across the process boundary."""
    return str(dtype).rsplit(".", 1)[-1]


def _engine_is_alive(engine) -> bool:
    """Only a confirmed-dead worker reads as not alive; a probe that cannot answer counts as alive."""
    is_alive = getattr(engine, "is_alive", None)
    if is_alive is None:
        return True
    try:
        return bool(is_alive())
    except Exception as exc:  # noqa: BLE001 - an unanswerable probe must not fail a status read
        logger.warning("Could not check whether the STT worker is alive: %s", exc)
        return True


def _engine_survived_kill(engine) -> bool:
    """A cancelled command raises over close()'s answer, so the handle's own flag is the only record."""
    return bool(getattr(engine, "survived_kill", False))


def _close_engine(engine) -> bool:
    """False if the child survived or close() raised with it alive, so its memory is not advertised as free; a child already gone counts as released."""
    close = getattr(engine, "close", None)
    if close is None:
        return True
    try:
        return close() is not False
    except Exception as exc:  # noqa: BLE001 - a stuck worker must not block the unload
        logger.warning("Could not stop the STT worker: %s", exc)
        return not _engine_is_alive(engine)


# An upload probed as a concat playlist would otherwise decode the files it names.
NO_PROTOCOLS = {"protocol_whitelist": "none"}


def _av_open(av, source, **extra):
    """Open ``source`` for reading with undecodable metadata ignored. PyAV 19 removed ``metadata_errors`` from ``av.open``, so passing it there raises TypeError before anything is read; retry without it."""
    try:
        return av.open(source, mode = "r", metadata_errors = "ignore", **extra)
    except TypeError as exc:
        if "metadata_errors" not in str(exc):
            raise
        # format = None is PyAV's own default (probe the container); spelling it keeps this call
        # distinguishable from Path.open for the text-encoding lint.
        return av.open(source, mode = "r", format = None, **extra)


def _decode_audio_bounded(audio: bytes, cancel_event = None):
    """Enforces the sample cap frame by frame and polls cancel_event inside the loop, since a small compressed upload can expand far past the cap."""
    try:
        import av
        import numpy as np
        from av.error import FFmpegError, InvalidDataError
    except ImportError as exc:
        raise SttUnavailableError(
            "Speech-to-text needs the PyAV package to decode audio. "
            "Run `unsloth studio update` to install it."
        ) from exc

    max_samples = _MAX_AUDIO_SECONDS * _TARGET_SAMPLE_RATE
    sample_count = 0
    raw_buffer = io.BytesIO()
    resampler = av.audio.resampler.AudioResampler(
        format = "s16",
        layout = "mono",
        rate = _TARGET_SAMPLE_RATE,
    )
    # group frames before resampling so short clips need one resampler call rather than one per codec frame
    fifo = av.audio.fifo.AudioFifo()

    def write_frame(frame) -> None:
        nonlocal sample_count
        array = frame.to_ndarray()
        sample_count += array.size
        if sample_count > max_samples:
            max_minutes = _MAX_AUDIO_SECONDS // 60
            unit = "minute" if max_minutes == 1 else "minutes"
            raise SttAudioTooLongError(f"Audio must be {max_minutes} {unit} or shorter.")
        raw_buffer.write(array)

    try:
        with _av_open(av, io.BytesIO(audio), options = NO_PROTOCOLS) as container:
            if not container.streams.audio:
                raise SttAudioDecodeError("Could not decode the audio.")
            try:
                for packet in container.demux(audio = 0):
                    if cancel_event is not None and cancel_event.is_set():
                        raise SttTranscriptionCancelledError("Transcription cancelled.")
                    try:
                        frames = packet.decode()
                    except InvalidDataError:
                        continue
                    for frame in frames:
                        frame.pts = None
                        fifo.write(frame)
                        if fifo.samples >= 500000:
                            for resampled in resampler.resample(fifo.read()):
                                write_frame(resampled)
            except (SttAudioTooLongError, SttTranscriptionCancelledError):
                raise
            except (FFmpegError, ValueError, RuntimeError) as exc:
                if not (sample_count or fifo.samples):
                    raise
                logger.info("STT decode stopped early: %s", exc)
            if fifo.samples > 0:
                for resampled in resampler.resample(fifo.read()):
                    write_frame(resampled)
            for resampled in resampler.resample(None):
                write_frame(resampled)
    except (SttAudioDecodeError, SttAudioTooLongError, SttTranscriptionCancelledError):
        raise
    except (FFmpegError, ValueError, RuntimeError) as exc:
        raise SttAudioDecodeError("Could not decode the audio.") from exc
    finally:
        del fifo, resampler

    if sample_count == 0:
        raise SttAudioDecodeError("Could not decode the audio.")
    decoded = np.frombuffer(raw_buffer.getbuffer(), dtype = np.int16).astype(np.float32)
    decoded /= 32768.0
    return decoded


class WhisperSttSidecar:
    """Lazily loaded Whisper model with idle eviction. Thread-safe."""

    def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
        self._engine = None
        self._model_id: Optional[str] = None
        self._device: Optional[str] = None
        self._device_preference: Optional[str] = None
        self._lock = threading.RLock()
        self._load_state_lock = threading.Lock()
        self._loading = False
        self._load_cancel_event: Optional[threading.Event] = None
        self._load_owner_cancel_event: Optional[threading.Event] = None
        self._keep_alive_seconds = max(0.0, keep_alive_seconds)
        self._idle_timer: Optional[threading.Timer] = None
        self._idle_generation = 0
        # Kept only for memory accounting; a worker that outlived its kill is never reused.
        self._survivor = False
        # Written and read under _lock.
        self._start_survivor = None

    @property
    def loaded_model(self) -> Optional[str]:
        # A dead worker holds nothing; reporting its model would make training reserve memory.
        engine = self._engine
        if engine is not None and not _engine_is_alive(engine):
            return None
        return self._model_id

    @property
    def device(self) -> Optional[str]:
        # ROCm torch reports "cuda" for HIP; report a name the user recognises.
        return _reported_device(self._device)

    def is_loading(self) -> bool:
        with self._load_state_lock:
            return self._loading

    def cancel_pending_load(self) -> bool:
        """Cancel a model load without waiting for the model lock."""
        with self._load_state_lock:
            event = self._load_cancel_event
            if not self._loading or event is None:
                return False
            event.set()
            return True

    def _cancel_owned_load(self, owner: threading.Event) -> bool:
        """Cancel startup only when it belongs to this transcription."""
        with self._load_state_lock:
            event = self._load_cancel_event
            if not self._loading or event is None or self._load_owner_cancel_event is not owner:
                return False
            event.set()
            return True

    def wait_for_load_to_settle(self) -> None:
        """Taking _lock waits out load(), which holds it through allocation and cancel cleanup."""
        with self._lock:
            pass

    def _begin_load(self, owner: Optional[threading.Event] = None) -> threading.Event:
        event = owner if owner is not None else threading.Event()
        with self._load_state_lock:
            self._load_cancel_event = event
            self._load_owner_cancel_event = owner
            self._loading = True
        return event

    def _end_load(self, event: threading.Event) -> None:
        with self._load_state_lock:
            if self._load_cancel_event is event:
                self._load_cancel_event = None
                self._load_owner_cancel_event = None
                self._loading = False

    @staticmethod
    def _raise_if_load_cancelled(event: threading.Event) -> None:
        if event.is_set():
            raise SttLoadCancelledError("STT model loading was cancelled so training could start.")

    @property
    def keep_alive_seconds(self) -> float:
        return self._keep_alive_seconds

    def _cancel_idle_unload_locked(self) -> None:
        self._idle_generation += 1
        timer = self._idle_timer
        self._idle_timer = None
        if timer is not None:
            timer.cancel()

    def _schedule_idle_unload_locked(self) -> None:
        self._cancel_idle_unload_locked()
        if self._engine is None or self._keep_alive_seconds <= 0:
            return
        generation = self._idle_generation
        timer = threading.Timer(
            self._keep_alive_seconds,
            self._idle_unload,
            args = (generation,),
        )
        timer.daemon = True
        self._idle_timer = timer
        timer.start()

    def _idle_unload(self, generation: int) -> None:
        with self._lock:
            if generation != self._idle_generation or self._engine is None:
                return
            logger.info("Unloading idle STT model %s", self._model_id)
            self._release_engine_locked()

    def _release_engine_locked(self) -> bool:
        """Clears the fields only once the worker is confirmed dead; a survivor stays resident and
        is retried."""
        self._cancel_idle_unload_locked()
        engine = self._engine
        device = self._device
        released = _close_engine(engine)
        if released:
            self._engine = None
            self._model_id = None
            self._device = None
            self._device_preference = None
            self._survivor = False
        else:
            self._survivor = True
        del engine
        _clear_device_cache(device)
        if not released:
            self._schedule_idle_unload_locked()
        return released

    def _keep_survivor_locked(
        self,
        engine,
        model_id: str,
        device: Optional[str] = None,
    ) -> None:
        """Held for its memory only: the next dictation loads a fresh worker rather than this wedged one."""
        self._engine = engine
        self._model_id = model_id
        self._survivor = True
        self._device = getattr(engine, "device", None) or device
        logger.error(
            "The dictation worker for %s outlived the kill and still holds its memory; "
            "keeping it resident so it is not reported unloaded",
            model_id,
        )
        self._schedule_idle_unload_locked()

    def _is_survivor_locked(self) -> bool:
        """Also reads the handle's own flag, since a cancelled command's close() result never
        reaches this."""
        if self._survivor:
            return True
        if self._engine is not None and _engine_survived_kill(self._engine):
            self._survivor = True
            return True
        return False

    def _release_dead_engine_locked(self) -> None:
        """Drop a worker whose process is gone, so the next use loads a fresh one."""
        if self._engine is not None and not _engine_is_alive(self._engine):
            logger.warning("STT worker for %s exited; it will be reloaded", self._model_id)
            self._release_engine_locked()

    def _build_model(self, snapshot_path: str, device: str, dtype, cancel_event: threading.Event):
        """Start a worker process holding this model and return its handle.

        Out of process because an accelerator context is never given back while the process holding
        it lives, so an in-process load made the backend permanently heavier even after unload.

        A host that cannot create a child at all (a sandbox, or a frozen POSIX build) falls back to
        loading here instead, on the CPU: this move may take work out of the backend, never take
        dictation away from someone who had it. The fallback waits for the CPU attempt, so a spawn
        failure on an accelerator still goes through the caller's own CPU retry.

        A child that outlived start()'s own kill is left in ``_start_survivor`` for the caller.
        start() ends its child on every failure, so a handle still reporting a live process is one
        holding memory that nothing else knows about: dropping it here is what would let this failed
        load read as nothing resident.
        """
        from core.inference.stt_mlx import is_mlx_stt_config
        from core.inference.stt_transformers_worker import (
            InProcessWhisperEngine,
            SttWorkerSpawnError,
            WhisperWorker,
        )

        mlx = is_mlx_stt_config(_read_json_object(Path(snapshot_path) / "config.json"))
        worker = WhisperWorker()
        try:
            # start() kills its own child on any failure, including cancellation.
            if mlx:
                worker.start(
                    str(snapshot_path), device, _dtype_name(dtype), cancel_event, runtime = "mlx"
                )
            else:
                worker.start(str(snapshot_path), device, _dtype_name(dtype), cancel_event)
        except SttWorkerSpawnError as exc:
            if device != "cpu" or mlx:
                raise
            logger.warning(
                "No dictation worker process could be started (%s); "
                "loading the model in the backend on the CPU instead",
                exc,
            )
            engine = InProcessWhisperEngine()
            engine.start(str(snapshot_path), "cpu", _dtype_name(dtype), cancel_event)
            return engine
        except BaseException:
            if _engine_is_alive(worker):
                self._start_survivor = worker
            raise
        return worker

    def _ensure_model_downloaded(
        self,
        model_id: str,
        use_resident: bool = True,
    ) -> _CachedSttSnapshot:
        """use_resident=False resolves on disk (the shortcut returns no path); a survivor does not answer for the model, so its snapshot is read from disk."""
        model_id = resolve_model_id(model_id)
        with self._lock:
            reusable = use_resident and self._engine is not None and self._model_id == model_id
            if reusable and not self._is_survivor_locked():
                resident_model = (
                    self._engine[0] if isinstance(self._engine, (tuple, list)) else self._engine
                )
                generation_config = getattr(resident_model, "generation_config", None)
                is_multilingual = getattr(generation_config, "is_multilingual", None)
                return _CachedSttSnapshot(
                    path = None,
                    is_multilingual = is_multilingual if isinstance(is_multilingual, bool) else None,
                )
        snapshot_path = _find_complete_cached_snapshot(model_id)
        if snapshot_path is None:
            raise SttModelNotDownloadedError(f"STT model '{model_id}' is not downloaded yet.")

        if model_id in STT_MODELS:
            return _CachedSttSnapshot(path = snapshot_path, is_multilingual = True)

        config = _read_json_object(snapshot_path / "config.json")
        if not _is_servable_config(config):
            raise SttModelCompatibilityError(
                f"STT model '{model_id}' is not a compatible Transformers Whisper model."
            )
        if not _is_whisper_config(config):
            from core.inference.stt_mlx import ships_custom_code
            if ships_custom_code(snapshot_path):
                raise SttModelCompatibilityError(
                    f"STT model '{model_id}' ships its own code, which dictation does not run."
                )
            return _CachedSttSnapshot(path = snapshot_path, is_multilingual = None)
        generation_config = _read_json_object(snapshot_path / "generation_config.json")
        is_multilingual = generation_config.get("is_multilingual")
        if isinstance(is_multilingual, bool):
            return _CachedSttSnapshot(path = snapshot_path, is_multilingual = is_multilingual)
        if resolve_model_repo(model_id).lower().endswith(".en"):
            return _CachedSttSnapshot(path = snapshot_path, is_multilingual = False)
        return _CachedSttSnapshot(path = snapshot_path, is_multilingual = None)

    def load(
        self,
        model: Optional[str] = None,
        request_cancel_event: Optional[threading.Event] = None,
        device: Optional[str] = None,
    ):
        """An explicit device differing from the resident one reloads the model; None keeps what is
        resident."""
        from core.inference.audio_device import normalize_audio_device, stt_device_default

        if request_cancel_event is not None and request_cancel_event.is_set():
            raise SttTranscriptionCancelledError("Transcription cancelled.")
        model_id = resolve_model_id(model)
        # None means no opinion, not auto: do not move a model another surface placed.
        requested = None if device is None else normalize_audio_device(device)
        preference = stt_device_default() if requested is None else requested
        with self._lock:
            if request_cancel_event is not None and request_cancel_event.is_set():
                raise SttTranscriptionCancelledError("Transcription cancelled.")
            ensure_stt_available()
            self._release_dead_engine_locked()
            placement_matches = (
                requested is None
                or self._device_preference is None
                or self._device_preference == requested
            )
            reusable = self._engine is not None and self._model_id == model_id and placement_matches
            if reusable and not self._is_survivor_locked():
                self._schedule_idle_unload_locked()
                return self._engine
            import torch

            cancel_event = self._begin_load(request_cancel_event)
            candidate = None
            device: Optional[str] = None
            resident_released = False
            self._start_survivor = None
            try:
                self._raise_if_load_cancelled(cancel_event)
                # The resident shortcut returns no path, and this load replaces it.
                cached = self._ensure_model_downloaded(model_id, use_resident = placement_matches)
                snapshot_path = cached.path
                if snapshot_path is None:
                    raise SttModelNotDownloadedError(
                        f"STT model '{model_id}' is not downloaded yet."
                    )
                self._raise_if_load_cancelled(cancel_event)
                device, dtype = _pick_device(preference)
                if not self._release_engine_locked():
                    # Never start a second child over one that did not exit: it doubles the memory this release frees.
                    raise SttModelBusyError(
                        "The previous dictation worker did not exit and still holds its "
                        "memory. Try again shortly."
                    )
                resident_released = True
                logger.info("Loading STT model %s (%s) on %s", model_id, snapshot_path, device)

                def not_downloaded(cause: BaseException) -> SttModelNotDownloadedError:
                    return SttModelNotDownloadedError(
                        f"STT model '{model_id}' is not downloaded yet."
                    )

                retry_on_cpu = False
                try:
                    candidate = self._build_model(str(snapshot_path), device, dtype, cancel_event)
                    self._raise_if_load_cancelled(cancel_event)
                except SttLoadCancelledError:
                    raise
                except Exception as exc:
                    # The worker classifies a cache miss; the exception cannot cross processes.
                    if isinstance(exc, SttModelNotDownloadedError) or _is_missing_local_model_error(
                        exc
                    ):
                        raise not_downloaded(exc) from exc
                    if device == "cpu":
                        raise
                    if self._start_survivor is not None:
                        # A child that outlived its kill still holds memory; refuse rather than spawn beside it.
                        raise SttModelBusyError(
                            "The previous dictation worker did not exit and still holds its "
                            "memory. Try again shortly."
                        ) from exc
                    logger.warning("STT load on %s failed (%s); retrying on CPU", device, exc)
                    retry_on_cpu = True
                if retry_on_cpu:
                    # Outside the handler: live exception frames pin the partly loaded model.
                    _clear_device_cache(device)
                    try:
                        candidate = self._build_model(
                            str(snapshot_path),
                            "cpu",
                            torch.float32,
                            cancel_event,
                        )
                        self._raise_if_load_cancelled(cancel_event)
                    except SttLoadCancelledError:
                        raise
                    except Exception as cpu_exc:
                        if isinstance(
                            cpu_exc, SttModelNotDownloadedError
                        ) or _is_missing_local_model_error(cpu_exc):
                            raise not_downloaded(cpu_exc) from cpu_exc
                        raise
                    device = "cpu"
                with self._load_state_lock:
                    self._raise_if_load_cancelled(cancel_event)
                    self._engine = candidate
                    self._model_id = model_id
                    self._device = device
                    self._device_preference = preference
                    self._survivor = False
                    self._load_cancel_event = None
                    self._load_owner_cancel_event = None
                    self._loading = False
                self._schedule_idle_unload_locked()
                logger.info("STT model %s ready on %s", model_id, device)
                return self._engine
            except SttLoadCancelledError:
                # The cancel can land after start() returned a live child; dropping that handle would leave the process holding the context training waits for, so close it.
                if self._start_survivor is not None:
                    # This child survived start()'s own kill; keep the handle so its memory stays accounted.
                    self._keep_survivor_locked(self._start_survivor, model_id, device)
                    _clear_device_cache(device)
                    raise
                if not _close_engine(candidate):
                    # It survived terminate and kill; keep it so training is not admitted against its memory.
                    self._keep_survivor_locked(candidate, model_id)
                    candidate = None
                    _clear_device_cache(device)
                    raise
                candidate = None
                if resident_released:
                    # Second call only empties the cache of the device this load picked.
                    self._release_engine_locked()
                    _clear_device_cache(device, collect = False)
                else:
                    _clear_device_cache(device)
                raise
            except BaseException:
                # Keep the survivor on any failed load: it is the only handle on a child still holding its memory.
                if self._start_survivor is not None and self._engine is None:
                    self._keep_survivor_locked(self._start_survivor, model_id, device)
                    _clear_device_cache(device)
                raise
            finally:
                self._start_survivor = None
                self._end_load(cancel_event)

    def _transcribe_decoded(
        self,
        model_id: str,
        decoded_audio,
        generate_kwargs: dict,
        cancel_event: Optional[threading.Event] = None,
        on_progress = None,
    ) -> str:
        """Windowing stays in the parent, so a cancel stops between 30s windows even while the
        worker is busy."""
        import numpy as np

        if cancel_event is not None and cancel_event.is_set():
            raise SttTranscriptionCancelledError("Transcription cancelled.")
        if cancel_event is None:
            engine = self.load(model_id)
        else:
            engine = self.load(model_id, request_cancel_event = cancel_event)
        effective_generate_kwargs = dict(generate_kwargs)
        generation_config = getattr(engine, "generation_config", None)
        if getattr(generation_config, "is_multilingual", None) is False:
            # English-only checkpoints fix language/task in generation config; Transformers rejects them.
            effective_generate_kwargs.pop("task", None)
            effective_generate_kwargs.pop("language", None)
        window = _STT_WINDOW_SECONDS * _TARGET_SAMPLE_RATE
        parts: list[str] = []
        supports_timestamps = getattr(generation_config, "supports_timestamps", True) is not False
        start = 0
        while start < len(decoded_audio):
            if cancel_event is not None and cancel_event.is_set():
                raise SttTranscriptionCancelledError("Transcription cancelled.")
            end = min(start + window, len(decoded_audio))
            window_generate_kwargs = dict(effective_generate_kwargs)
            if end < len(decoded_audio):
                quiet_end = _stt_quiet_window_end(decoded_audio, start, window)
                if quiet_end is not None:
                    end = quiet_end
                elif supports_timestamps:
                    # Whisper's long-form seek: keep only finished segments and resume where the last one ended.
                    window_generate_kwargs["return_timestamps"] = True
            segment = decoded_audio[start:end]
            pcm = np.ascontiguousarray(segment, dtype = np.float32).tobytes()
            text, consumed = engine.transcribe_window(pcm, window_generate_kwargs, cancel_event)
            parts.append(text)
            start += consumed
            if on_progress is not None:
                on_progress(
                    {
                        "text": " ".join(part.strip() for part in parts if part.strip()),
                        "processed_seconds": min(start, len(decoded_audio)) / _TARGET_SAMPLE_RATE,
                        "duration": len(decoded_audio) / _TARGET_SAMPLE_RATE,
                    }
                )
            if cancel_event is not None and cancel_event.is_set():
                raise SttTranscriptionCancelledError("Transcription cancelled.")
        return " ".join(part.strip() for part in parts if part.strip()).strip()

    def transcribe(
        self,
        audio: bytes,
        model: Optional[str] = None,
        language: Optional[str] = None,
        fast: bool = False,
        cancel_event: Optional[threading.Event] = None,
        on_progress = None,
        task: str = "transcribe",
    ) -> dict:
        """Accepts any container PyAV can decode; task=translate returns English text."""
        ensure_stt_available()
        if cancel_event is not None and cancel_event.is_set():
            raise SttTranscriptionCancelledError("Transcription cancelled.")
        # A set language beats auto-detect. API takes BCP-47; Whisper wants short codes like en or fr.
        lang = normalize_whisper_language(language)
        # Pin the id: another request may switch the resident model mid-transcription.
        model_id = resolve_model_id(model)
        known_languages = _known_whisper_languages()
        if lang is not None and known_languages is not None and lang not in known_languages:
            raise SttLanguageError(
                f"Language '{language}' is not supported by STT model '{model_id}'."
            )
        cached = self._ensure_model_downloaded(model_id)
        if cached.is_multilingual is False and lang not in (None, "en"):
            raise SttLanguageError(
                f"Language '{language}' is not supported by English-only STT model '{model_id}'."
            )
        if cached.is_multilingual is False and task == "translate":
            # The checkpoint's generation config pins the task, so it would only transcribe.
            raise SttLanguageError(f"English-only STT model '{model_id}' cannot translate.")
        decoded_audio = _decode_audio_bounded(audio, cancel_event)
        if cancel_event is not None and cancel_event.is_set():
            raise SttTranscriptionCancelledError("Transcription cancelled.")
        # condition_on_prev_tokens=False stops a fresh clip inheriting prior context, which causes runaway repeats.
        generate_kwargs = {
            "task": task,
            "condition_on_prev_tokens": False,
            "num_beams": 5,
        }
        if lang is not None:
            generate_kwargs["language"] = lang
        if fast:
            # Short voiced clips: greedy decoding drops beam search for latency.
            generate_kwargs["num_beams"] = 1
        with self._lock:
            try:
                if on_progress is not None:
                    text = self._transcribe_decoded(
                        model_id, decoded_audio, generate_kwargs, cancel_event, on_progress
                    )
                elif cancel_event is None:
                    text = self._transcribe_decoded(model_id, decoded_audio, generate_kwargs)
                else:
                    text = self._transcribe_decoded(
                        model_id,
                        decoded_audio,
                        generate_kwargs,
                        cancel_event,
                    )
            finally:
                self._schedule_idle_unload_locked()
        duration = (len(decoded_audio) / _TARGET_SAMPLE_RATE) if len(decoded_audio) else None
        return {
            "text": text,
            "language": lang,
            "duration": duration,
            "model": model_id,
        }

    def cancel_transcription(self, cancel_event: threading.Event) -> bool:
        """Only this request's event is set, so a cancel never reaches another request's window."""
        already_cancelled = cancel_event.is_set()
        cancel_event.set()
        return self._cancel_owned_load(cancel_event) or not already_cancelled

    def _holds_expected_model(self, expected: Optional[str]) -> bool:
        """Compared under the lock: another surface can switch the resident model before the release
        arrives."""
        if expected is None:
            return True
        current = self._model_id
        if current is None:
            return False
        if current.casefold() == expected.casefold():
            return True
        try:
            return current.casefold() == resolve_model_id(expected).casefold()
        except Exception:  # noqa: BLE001 - an unresolvable name is not this model
            return False

    def unload(
        self,
        wait: bool = True,
        expected_model: Optional[str] = None,
    ) -> None:
        """Transcription holds the lock throughout, so wait=False lets a non-owner leave a busy
        sidecar alone."""
        if not self._lock.acquire(blocking = wait):
            return
        try:
            # Skip gc.collect when nothing is resident: it cost ~130 ms per request.
            if self._model_id is None or not self._holds_expected_model(expected_model):
                return
            self._release_engine_locked()
        finally:
            self._lock.release()


_sidecar: Optional[WhisperSttSidecar] = None


def get_stt_sidecar() -> WhisperSttSidecar:
    global _sidecar
    if _sidecar is None:
        _sidecar = WhisperSttSidecar()
    return _sidecar