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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
# 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.cpp (GGML/GGUF) speech-to-text sidecar for Unsloth dictation.
Runs the same curated Whisper checkpoints as the Transformers sidecar
(stt_sidecar.py) through whisper.cpp's `whisper-server`, ~2.5x faster at
identical quality on Apple Silicon and CPU because its Metal/CPU kernels run
the weights in f16 where PyTorch MPS requires fp32.
Owns a single `whisper-server` subprocess bound to 127.0.0.1 on an ephemeral
port; the model loads on demand, stays warm between dictations, and unloads
after the same keep-alive as the Transformers sidecar. Curated GGML checkpoints
are single files from `unslothai/whisper-*-GGUF`, downloaded directly rather
than through the Model Hub (whose variant planner only handles `.gguf` chat
layouts).
Binary discovery mirrors `_find_llama_server_binary`: env override, then managed
Unsloth home, then PATH. With no binary the engine is unavailable and dictation
falls back to the Transformers sidecar; `scripts/build_whisper_cpp.sh` installs
the binary.
"""
from __future__ import annotations
import http.client
import io
import json
import os
import re
import secrets
import shutil
import socket
import subprocess
import sys
import threading
import time
import urllib.request
import uuid
import wave
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator, Optional
from loggers import get_logger
from hub.utils.hf_errors import modelscope_missing
from hub.utils.hf_tokens import normalize_token
from core.inference.stt_sidecar import (
STT_KEEP_ALIVE_SECONDS,
SttAudioDecodeError,
SttLanguageError,
SttLoadCancelledError,
SttModelIdError,
SttModelNotDownloadedError,
SttUnavailableError,
SttTranscriptionCancelledError,
_capture_stt_hub_cache,
_claim_stt_repository,
_close_connection_on_cancel,
_decode_audio_bounded,
_downloaded_file_bytes,
_fallback_revisions,
_HF_COMMIT_SHA,
_known_whisper_languages,
_prepare_stt_cache_for_http,
_read_revision_record,
_remember_completed_download,
_TARGET_SAMPLE_RATE,
_training_active,
_write_revision_record,
normalize_whisper_language,
)
from utils.prebuilt.child_env import isolate_home, scrub_env, wsl_system_rocm_lib_dirs
from utils.prebuilt.runtime_libs import dedupe_existing_dirs
from utils.prebuilt.whisper_layout import lookup_marker
from utils.process_lifetime import (
adopt_pid,
child_popen_kwargs,
forget_pid,
is_process_shutting_down,
)
from utils.subprocess_compat import windows_hidden_subprocess_kwargs
logger = get_logger(__name__)
# Keys match the Transformers sidecar's ids so the frontend reuses one picker.
GGML_STT_REPOS: dict[str, str] = {
"tiny": "unslothai/whisper-tiny-GGUF",
"base": "unslothai/whisper-base-GGUF",
"small": "unslothai/whisper-small-GGUF",
"large-v3-turbo": "unslothai/whisper-large-v3-turbo-GGUF",
"large-v3": "unslothai/whisper-large-v3-GGUF",
}
GGML_STT_MODELS: dict[str, str] = {
"tiny": "whisper-tiny.bin",
"base": "whisper-base.bin",
"small": "whisper-small.bin",
"large-v3-turbo": "whisper-large-v3-turbo.bin",
"large-v3": "whisper-large-v3.bin",
}
DEFAULT_GGML_STT_MODEL = "small"
_SERVER_START_TIMEOUT_SECONDS = 120.0
_TRANSCRIBE_TIMEOUT_SECONDS = 600.0
class SttEngineUnavailableError(SttUnavailableError):
"""whisper-server is not installed; the GGUF dictation engine is off."""
def resolve_ggml_model_id(model: Optional[str]) -> str:
"""Validate a curated GGML model id. Custom repos are not supported here."""
if model is None or not str(model).strip():
return DEFAULT_GGML_STT_MODEL
normalized = str(model).strip()
if normalized in GGML_STT_MODELS:
return normalized
raise SttModelIdError(
f"STT model '{model}' is not a curated GGUF dictation model. "
f"Choose one of: {', '.join(GGML_STT_MODELS)}."
)
def _managed_whisper_cpp_dir() -> Path:
"""UNSLOTH_HOME/whisper.cpp if set, else STUDIO_HOME/whisper.cpp in custom mode, else ~/.unsloth/whisper.cpp; mirrors managed_node_dir."""
legacy = Path.home() / ".unsloth" / "whisper.cpp"
try:
from utils.paths.storage_roots import studio_root, unsloth_home
# setup.sh installs whisper.cpp at <master root>, beside studio/. No env var bridges it.
master = unsloth_home()
if master is not None:
return master / "whisper.cpp"
resolved = studio_root()
legacy_studio = Path.home() / ".unsloth" / "studio"
try:
is_legacy = resolved.resolve() == legacy_studio.resolve()
except (OSError, ValueError):
is_legacy = resolved == legacy_studio
return legacy if is_legacy else (resolved / "whisper.cpp")
except (ImportError, OSError, ValueError):
override = (
os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or ""
).strip()
if override:
try:
return Path(override).expanduser().resolve() / "whisper.cpp"
except (OSError, ValueError):
return Path(override).expanduser() / "whisper.cpp"
return legacy
def find_whisper_server_binary() -> Optional[str]:
"""Locate the whisper-server binary, in order: WHISPER_SERVER_PATH (direct path),
UNSLOTH_WHISPER_CPP_PATH (custom install dir), the managed dir <STUDIO_HOME or
~/.unsloth>/whisper.cpp/{,build/bin/}whisper-server, then whisper-server on PATH."""
binary_name = "whisper-server.exe" if sys.platform == "win32" else "whisper-server"
def _layout_candidates(d: Path) -> list[Path]:
cands = [d / binary_name, d / "build" / "bin" / binary_name]
if sys.platform == "win32":
cands.append(d / "build" / "bin" / "Release" / binary_name)
return cands
env_path = os.environ.get("WHISPER_SERVER_PATH")
if env_path:
p = Path(env_path)
if _is_runnable(p):
return str(p)
custom_dir = os.environ.get("UNSLOTH_WHISPER_CPP_PATH")
if custom_dir:
for p in _layout_candidates(Path(custom_dir)):
if _is_runnable(p):
return str(p)
for p in _layout_candidates(_managed_whisper_cpp_dir()):
if _is_runnable(p):
return str(p)
return shutil.which(binary_name)
def _is_runnable(p: Path) -> bool:
"""A real whisper-server is an executable file. On Windows os.access(X_OK) is
effectively an existence check; on Unix it rejects a non-executable stub so a
half-written or wrong-mode file isn't mistaken for the server."""
try:
return p.is_file() and (sys.platform == "win32" or os.access(p, os.X_OK))
except OSError:
# is_file() raises EACCES: an unreadable dir must read as unavailable, not a 500.
return False
def _whisper_install_marker(binary: str) -> Optional[dict]:
"""The prebuilt install marker above ``binary``, or None (source/custom builds)."""
return lookup_marker(binary).marker
def slim_runtime_intact(binary: str) -> bool:
"""All linked runtime files must be present; legacy markers lacking linked_libraries use per-OS ggml name globs; broken slim reads as unavailable, never a crash."""
lookup = lookup_marker(binary)
marker = lookup.marker
if lookup.invalid or marker is None:
return not lookup.slim_collision
if not marker or marker.get("install_kind") != "slim":
return True
if lookup.authoritative:
valid = marker.get("component") == "whisper.cpp"
valid = valid and isinstance(marker.get("schema_version"), int)
valid = valid and all(
isinstance(marker.get(key), str) and marker[key]
for key in ("release_tag", "backend", "paired_llama_tag")
)
valid = valid and isinstance(marker.get("linked_libraries"), list)
valid = valid and bool(marker.get("linked_libraries"))
valid = valid and all(
isinstance(name, str) and name and Path(name).name == name
for name in marker["linked_libraries"]
)
if not valid:
return False
bin_dir = Path(binary).parent
linked = marker.get("linked_libraries")
if isinstance(linked, list) and linked and all(isinstance(name, str) for name in linked):
intact = all((bin_dir / name).is_file() for name in linked)
else:
if sys.platform == "win32":
required = ("ggml.dll", "ggml-base.dll")
elif sys.platform == "darwin":
required = ("libggml*.dylib", "libggml-base*.dylib")
else:
required = ("libggml.so*", "libggml-base.so*")
intact = all(any(p.is_file() for p in bin_dir.glob(pattern)) for pattern in required)
runtime_dirs = marker.get("linked_runtime_directories")
if intact and isinstance(runtime_dirs, list) and runtime_dirs:
intact = all(
isinstance(name, str)
and name
and (bin_dir / name).is_dir()
and any(path.is_file() for path in (bin_dir / name).rglob("*"))
for name in runtime_dirs
)
if intact and marker.get("backend") == "rocm":
# hipBLASLt has no RDNA2 (gfx1030) catalog, so only rocblas is required (backend links librocblas directly); other names are stale wiring. Windows wires none.
known_runtime_dirs = set() if sys.platform == "win32" else {"hipblaslt", "rocblas"}
required_runtime_dirs = set() if sys.platform == "win32" else {"rocblas"}
# Pin a version floor, not one version: wiring from version 2 on records linked_runtime_directories; an installer bump must not strand installs.
wiring_version = marker.get("runtime_wiring_version")
intact = (
isinstance(wiring_version, int)
and wiring_version >= 2
and isinstance(runtime_dirs, list)
and set(runtime_dirs) <= known_runtime_dirs
and required_runtime_dirs <= set(runtime_dirs)
)
if not intact:
logger.warning(
"slim whisper install is missing its linked ggml runtime at "
f"{bin_dir}; run `unsloth studio update` to reinstall it"
)
return intact
# Set when inference fails on a runtime that looks healthy (ROCm missing Tensile libs); cleared on success. Process lifetime: a reinstall restarts Unsloth.
_runtime_inference_failure: Optional[str] = None
_runtime_failure_lock = threading.Lock()
def note_runtime_inference_failure(reason: str) -> None:
global _runtime_inference_failure
with _runtime_failure_lock:
if _runtime_inference_failure is None:
logger.warning(
"whisper.cpp runtime failed to serve a transcription (%s); "
"treating the engine as unavailable and using Transformers instead",
reason,
)
_runtime_inference_failure = reason
def clear_runtime_inference_failure() -> None:
global _runtime_inference_failure
with _runtime_failure_lock:
_runtime_inference_failure = None
def runtime_inference_failure() -> Optional[str]:
with _runtime_failure_lock:
return _runtime_inference_failure
def is_available() -> bool:
binary = find_whisper_server_binary()
if binary is None:
return False
if not slim_runtime_intact(binary):
return False
if runtime_inference_failure() is not None:
return False
try:
import av # noqa: F401
except Exception:
# No PyAV means every transcription 501s on decode.
return False
return True
def ensure_engine_available() -> str:
binary = find_whisper_server_binary()
if binary is None:
raise SttEngineUnavailableError(
"The local transcription runtime is not installed. Run "
"`unsloth studio update` to install it."
)
if not slim_runtime_intact(binary):
raise SttEngineUnavailableError(
"The local transcription runtime is missing its paired ggml "
"libraries. Run `unsloth studio update` to reinstall it."
)
return binary
# Child env: binary dir first, secrets scrubbed, WSL2 ROCm system HIP libs before the bundle HIP (it cannot drive /dev/dxg). Aliases keep test patch points.
_wsl_system_rocm_lib_dirs = wsl_system_rocm_lib_dirs
_dedupe_existing_dirs = dedupe_existing_dirs
def _whisper_server_child_env(binary: str) -> dict[str, str]:
"""Scrubs secrets and points home vars at a scratch dir so the binary cannot read token caches; WSL2 ROCm system HIP libs go first."""
binary = str(Path(binary).resolve())
env = scrub_env(os.environ)
isolate_home(env, str(_managed_whisper_cpp_dir() / ".child_home"))
bin_dir = str(Path(binary).parent)
# CUDA bundles need PyTorch's nvidia wheel lib dirs; after bin_dir so co-located libs win.
cuda_runtime_dirs: list[str] = []
bundle_dir = Path(bin_dir)
has_cuda_module = any(
path.is_file()
for pattern in ("libggml-cuda.so*", "ggml-cuda*.dll")
for path in bundle_dir.glob(pattern)
)
vendored_cuda_dirs: list[str] = []
if has_cuda_module:
try:
from utils.prebuilt.runtime_libs import python_runtime_dirs
cuda_runtime_dirs = python_runtime_dirs()
except Exception:
cuda_runtime_dirs = []
try:
from utils.llama_cpp_freshness import read_install_marker as read_llama_install_marker
from utils.prebuilt.runtime_libs import vendored_cuda_runtime_dirs
marker = _whisper_install_marker(binary)
# Slim bundles hardlink CUDA from their paired llama.cpp install; its marker holds the runtime.
linked_from = marker.get("linked_from") if isinstance(marker, dict) else None
paired_marker = (
read_llama_install_marker(linked_from)
if isinstance(linked_from, str) and linked_from
else None
)
vendored_cuda_dirs = vendored_cuda_runtime_dirs(paired_marker or marker)
except Exception:
vendored_cuda_dirs = []
if sys.platform == "win32":
var, lead = "PATH", [bin_dir, *cuda_runtime_dirs]
elif sys.platform == "darwin":
var, lead = "DYLD_LIBRARY_PATH", [bin_dir]
else:
var, lead = "LD_LIBRARY_PATH", [bin_dir, *cuda_runtime_dirs]
wsl_rocm = _wsl_system_rocm_lib_dirs()
if wsl_rocm:
lead = [*wsl_rocm, bin_dir, *cuda_runtime_dirs]
env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")
existing = [p for p in env.get(var, "").split(os.pathsep) if p]
env[var] = os.pathsep.join(_dedupe_existing_dirs([*lead, *existing, *vendored_cuda_dirs]))
return env
# Model file download: single files, deliberately outside the Model Hub flow.
def _cached_model_path(
model_id: str,
*,
hub_cache: Optional[Path] = None,
revision: Optional[str] = None,
) -> Optional[str]:
"""Path of a fully downloaded GGML file in the shared HF cache, else None."""
from huggingface_hub import hf_hub_download
from core.inference.stt_sidecar import _active_hf_hub_cache
repo_id = GGML_STT_REPOS[model_id]
root = hub_cache if hub_cache is not None else _active_hf_hub_cache()
def cached_at(candidate_revision: str) -> Optional[str]:
try:
return hf_hub_download(
repo_id = repo_id,
filename = GGML_STT_MODELS[model_id],
revision = candidate_revision,
local_files_only = True,
cache_dir = str(root),
)
except Exception:
return None
# Explicit revisions keep verification on the downloaded commit.
if revision is not None:
return cached_at(revision)
recorded = _read_revision_record(repo_id)
if recorded:
cached = cached_at(recorded)
if cached is not None:
return cached
for candidate in _fallback_revisions(repo_id, hub_cache = root):
cached = cached_at(candidate)
if cached is not None:
_write_revision_record(repo_id, candidate)
return cached
return None
class _GgmlDownloadState:
"""Tracks one background hf_hub_download of a curated GGML file."""
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._error: Optional[str] = None
self._total_bytes: Optional[int] = None
self._etag: Optional[str] = None
self._revision: Optional[str] = None
self._hub_cache: Optional[Path] = None
self._cancelled = False
def status(self) -> dict:
with self._lock:
downloading = self._thread is not None and self._thread.is_alive()
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 downloading else None,
}
captured = (
self._model_id,
self._etag,
self._total_bytes,
self._hub_cache,
self._revision,
)
# Outside the lock: _downloaded_bytes() stats the cache, and a cancel must not queue.
snapshot["bytes_done"] = self._downloaded_bytes(*captured) if downloading 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,
model_id: Optional[str] = None,
etag: Optional[str] = None,
total: Optional[int] = None,
hub_cache: Optional[Path] = None,
revision: Optional[str] = None,
) -> Optional[int]:
"""Callers pass values captured under the lock, so a run starting mid-probe cannot mix totals."""
try:
model_id = model_id if model_id is not None else self._model_id
etag = etag if etag is not None else self._etag
total = total if total is not None else self._total_bytes
hub_cache = hub_cache if hub_cache is not None else self._hub_cache
revision = revision if revision is not None else self._revision
if not model_id or not etag or total is None or hub_cache is None:
return None
return _downloaded_file_bytes(
hub_cache = hub_cache,
repo = GGML_STT_REPOS[model_id],
filename = GGML_STT_MODELS[model_id],
size = total,
blob_key = etag,
revision = revision,
)
except Exception:
return None
def start(
self,
model_id: str,
hf_token: Optional[str] = None,
) -> str:
model_id = resolve_ggml_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 GGUF 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._error = None
self._total_bytes = None
self._etag = None
self._revision = None
self._hub_cache = hub_cache
self._cancelled = False
self._process = None
thread = threading.Thread(
target = self._run,
args = (model_id, hf_token),
daemon = True,
)
self._thread = thread
thread.start()
return str(self._download_id)
def _run(
self,
model_id: str,
hf_token: Optional[str],
hub_cache: Optional[Path] = None,
) -> None:
if hub_cache is None:
from core.inference.stt_sidecar import _active_hf_hub_cache
hub_cache = self._hub_cache or _active_hf_hub_cache()
repo_id = GGML_STT_REPOS[model_id]
filename = GGML_STT_MODELS[model_id]
registry = None
owner = None
try:
from huggingface_hub import get_hf_file_metadata, hf_hub_url
try:
meta = get_hf_file_metadata(
hf_hub_url(repo_id, filename), token = normalize_token(hf_token)
)
total_bytes = int(meta.size or 0)
except (AttributeError, TypeError, ValueError) as exc:
raise RuntimeError("could not resolve GGML download metadata") from exc
revision = meta.commit_hash
etag = meta.etag
if not isinstance(revision, str) or not _HF_COMMIT_SHA.fullmatch(revision):
raise RuntimeError("could not resolve an immutable GGML revision")
if not isinstance(etag, str) or not etag:
raise RuntimeError("could not resolve the GGML blob identity")
if total_bytes <= 0:
raise RuntimeError("could not resolve the GGML file size")
# 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_id)
with self._lock:
if self._cancelled:
return
_prepare_stt_cache_for_http(repo_id, hub_cache)
with self._lock:
self._total_bytes = total_bytes
self._etag = etag
self._revision = revision
# out of process so cancel() can terminate it; a thread blocked in hf_hub_download could not be interrupted
from core.inference.stt_download_worker import (
reap_download,
spawn_download,
terminate_download,
)
args = [
"--repo-id",
repo_id,
"--revision",
revision,
"--filename",
filename,
]
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
# Use reap_download(), not communicate(): only it drops the adopted PID, so terminate_all cannot signal a reused PID.
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:
if (
_cached_model_path(
model_id,
hub_cache = hub_cache,
revision = revision,
)
is None
):
raise RuntimeError("downloaded file is missing from the captured cache")
_write_revision_record(repo_id, revision)
with self._lock:
_remember_completed_download(
self._completed_download_ids,
self._download_id,
cancelled = self._cancelled,
)
return
with self._lock:
if cancelled or process.returncode < 0:
self._cancelled = True
return
detail = (stderr or b"").decode("utf-8", "replace").strip()
logger.warning("GGUF STT download failed for %s: %s", model_id, detail)
with self._lock:
self._error = modelscope_missing(detail) or f"Download failed for '{model_id}'."
except Exception as exc:
with self._lock:
if not self._cancelled:
logger.warning("GGUF STT download failed for %s: %s", model_id, exc)
self._error = modelscope_missing(exc) or f"Download failed for '{model_id}'."
finally:
if registry is not None and owner is not None:
registry.release_repository_owner(repo_id, owner)
_download_state = _GgmlDownloadState()
def start_model_download(model: Optional[str], hf_token: Optional[str] = None) -> str:
return _download_state.start(resolve_ggml_model_id(model), hf_token)
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_ggml_model_id(model) if model is not None else None
except SttModelIdError:
return False
return _download_state.cancel(model_id, download_id)
_REQUEST_PATH_SUPPORT: dict[tuple[str, int], bool] = {}
def _supports_request_path(binary: str) -> bool:
"""Whether ``binary`` accepts ``--request-path``; an older user-supplied whisper-server exits on it."""
try:
key = (binary, os.stat(binary).st_mtime_ns)
except OSError:
return False
cached = _REQUEST_PATH_SUPPORT.get(key)
marker = _whisper_install_marker(binary) if cached is None else None
if marker is not None and marker.get("published_repo") == "unslothai/whisper.cpp":
# Every unslothai/whisper.cpp release has the flag: skip the ~0.6 s --help probe.
cached = _REQUEST_PATH_SUPPORT[key] = True
if cached is None:
try:
probe = subprocess.run(
[binary, "--help"],
capture_output = True,
timeout = 20,
env = _whisper_server_child_env(binary),
**windows_hidden_subprocess_kwargs(),
)
cached = b"--request-path" in probe.stdout + probe.stderr
except Exception: # noqa: BLE001 -- a probe failure only means no route
cached = False
_REQUEST_PATH_SUPPORT[key] = cached
return cached
def _pcm_to_wav_bytes(decoded_audio) -> bytes:
"""Wrap decoded float32 mono 16 kHz PCM into an in-memory 16-bit WAV."""
import numpy as np
clipped = np.clip(decoded_audio, -1.0, 1.0)
pcm16 = (clipped * 32767.0).astype("<i2")
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(_TARGET_SAMPLE_RATE)
w.writeframes(pcm16.tobytes())
return buf.getvalue()
class GgmlSttSidecar:
"""Owns one whisper-server subprocess and proxies dictation to it."""
def __init__(self, keep_alive_seconds: float = STT_KEEP_ALIVE_SECONDS) -> None:
self._lock = threading.RLock()
self._load_state_lock = threading.Lock()
self._process: Optional[subprocess.Popen] = None
self._port: Optional[int] = None
# Secret route prefix: a web page that finds the loopback port cannot reach whisper-server.
self._route = ""
self._model_id: Optional[str] = None
# --no-gpu at the user's request, tracked because it varies per request.
self._forced_cpu = False
self._idle_timer: Optional[threading.Timer] = None
self._idle_generation = 0
self._keep_alive_seconds = keep_alive_seconds
# Set while whisper-server starts, so training admission can count the accelerator memory it is about to bind. Read without the lock.
self._loading = False
# Set under _lock, read without it: cancel_pending_load() runs during load(); the event is the source of truth, terminate is best-effort.
self._load_cancel_event: Optional[threading.Event] = None
self._load_owner_cancel_event: Optional[threading.Event] = None
self._starting_process: Optional[subprocess.Popen] = None
# set before the updater waits for _lock and kept set while it atomically replaces the managed install tree
self._update_in_progress = False
@property
def loaded_model(self) -> Optional[str]:
# Lock-free: transcribe() holds _lock for the whole inference and status polls must not block.
return self._model_id if self._process_alive() else None
@property
def device(self) -> Optional[str]:
return "whisper.cpp" if self._process_alive() else None
def is_loading(self) -> bool:
with self._load_state_lock:
return self._loading
@property
def keep_alive_seconds(self) -> float:
return self._keep_alive_seconds
def _process_alive(self) -> bool:
# Snapshot once: a concurrent unload() can null it between the check and .poll().
process = self._process
return process is not None and process.poll() is None
def _cancel_idle_unload_locked(self) -> None:
self._idle_generation += 1
if self._idle_timer is not None:
self._idle_timer.cancel()
self._idle_timer = None
def _schedule_idle_unload_locked(self) -> None:
self._cancel_idle_unload_locked()
if not self._process_alive():
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:
return
logger.info("Unloading idle GGUF STT model %s", self._model_id)
self._release_locked()
def _release_locked(self) -> None:
self._cancel_idle_unload_locked()
process = self._process
self._process = None
self._port = None
self._route = ""
self._model_id = None
self._forced_cpu = False
if process is not None and process.poll() is None:
process.terminate()
try:
process.wait(timeout = 10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout = 10)
if process is not None:
forget_pid(process.pid)
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 == expected:
return True
try:
return current == resolve_ggml_model_id(expected)
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 skip a busy sidecar."""
if not self._lock.acquire(blocking = wait):
return
try:
if not self._holds_expected_model(expected_model):
return
self._release_locked()
finally:
self._lock.release()
def _raise_if_update_in_progress(self) -> None:
if self._update_in_progress:
raise SttEngineUnavailableError(
"The local transcription runtime is being updated. Try dictation again shortly."
)
@contextmanager
def update_maintenance(self) -> Iterator[bool]:
"""Publishes the flag before waiting on the lock so no load starts on a half-swapped tree; the lock stays held across the install, as Windows relocks the exe."""
self._update_in_progress = True
try:
with self._lock:
model_was_active = self._process_alive()
self._release_locked()
yield model_was_active
finally:
self._update_in_progress = False
def cancel_pending_load(self) -> bool:
# load() holds self._lock through startup, so signal abort and terminate without it.
with self._load_state_lock:
event = self._load_cancel_event
if not self._loading or event is None:
return False
event.set()
process = self._starting_process
if process is not None and process.poll() is None:
try:
process.terminate()
except Exception:
pass
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()
process = self._starting_process
if process is not None and process.poll() is None:
try:
process.terminate()
except Exception:
pass
return True
def wait_for_load_to_settle(self) -> None:
# load() holds _lock through startup and cancel cleanup, so this waits until the server is reaped.
with self._lock:
pass
@staticmethod
def _reserve_free_port() -> tuple[socket.socket, int]:
"""Held open until the caller closes it just before spawn, to shrink the race window."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", 0))
return s, s.getsockname()[1]
def _ensure_model_downloaded(self, model_id: str) -> str:
path = _cached_model_path(model_id)
if path is None:
raise SttModelNotDownloadedError(
f"STT model '{model_id}' (GGUF) is not downloaded yet."
)
return path
def load(
self,
model: Optional[str] = None,
request_cancel_event: Optional[threading.Event] = None,
device: Optional[str] = None,
) -> None:
"""A None device keeps the running server's placement, so a caller that sends none cannot
move it."""
from core.inference.audio_device import stt_device_forces_cpu
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
model_id = resolve_ggml_model_id(model)
with self._lock:
if request_cancel_event is not None and request_cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
self._raise_if_update_in_progress()
binary = ensure_engine_available()
force_cpu = (
self._forced_cpu
if device is None and self._process_alive()
else stt_device_forces_cpu(device)
)
if (
self._process_alive()
and self._model_id == model_id
and self._forced_cpu == force_cpu
):
self._schedule_idle_unload_locked()
return
model_path = self._ensure_model_downloaded(model_id)
reservation, port = self._reserve_free_port()
command = [binary, "-m", model_path, "--host", "127.0.0.1", "--port", str(port)]
route = ""
if _supports_request_path(binary):
route = "/" + secrets.token_hex(16)
command.extend(["--request-path", route])
else:
logger.warning(
"whisper-server at %s has no --request-path; its routes stay at the root path.",
binary,
)
marker = _whisper_install_marker(binary)
cancel_event = (
request_cancel_event if request_cancel_event is not None else threading.Event()
)
with self._load_state_lock:
self._load_cancel_event = cancel_event
self._load_owner_cancel_event = request_cancel_event
self._loading = True
try:
if cancel_event.is_set():
raise SttLoadCancelledError("GGUF STT model loading was cancelled.")
# Decided under the loading flag: training reads is_loading() without this lock.
if force_cpu:
# Tracked, so the reuse check above restarts on a change.
command.append("--no-gpu")
elif _training_active():
# Stays off the GPU during training, so dictation cannot reclaim the VRAM training just freed.
command.append("--no-gpu")
elif marker is not None and marker.get("backend") == "cpu":
# Slim wiring links every ggml backend, so a cpu install still grabs the GPU without this.
command.append("--no-gpu")
logger.info(
"Starting whisper-server for STT model %s on 127.0.0.1:%s",
model_id,
port,
)
self._release_locked()
# release the reservation as late as possible: whisper-server binds the port moments after this close
reservation.close()
# No shutdown step stops this sidecar, so refuse to spawn once shutdown has begun.
if is_process_shutting_down():
raise SttLoadCancelledError(
"Unsloth is shutting down; not starting whisper-server."
)
process = subprocess.Popen(
command,
stdout = subprocess.DEVNULL,
stderr = subprocess.DEVNULL,
stdin = subprocess.DEVNULL,
# Co-located GPU libs on the loader path (WSL system HIP first); secrets scrubbed from child env.
env = _whisper_server_child_env(binary),
# Die with Unsloth (Linux PDEATHSIG, Windows job) so a crash cannot orphan the model server.
**child_popen_kwargs(),
)
with self._load_state_lock:
self._starting_process = process
adopt_pid(process.pid) # terminate_all backstop for graceful exits
# Recheck after adopt_pid: shutdown may have started between the gate and the record.
if is_process_shutting_down():
if process.poll() is None:
process.kill()
process.wait(timeout = 10)
forget_pid(process.pid)
raise SttLoadCancelledError(
"Unsloth is shutting down; not starting whisper-server."
)
try:
self._wait_for_server(process, port, cancel_event, route = route)
except Exception:
if process.poll() is None:
process.kill()
process.wait(timeout = 10)
forget_pid(process.pid)
raise
self._process = process
self._port = port
self._route = route
self._model_id = model_id
self._forced_cpu = force_cpu
self._schedule_idle_unload_locked()
finally:
reservation.close() # no-op when already released before spawn
with self._load_state_lock:
self._loading = False
self._load_cancel_event = None
self._load_owner_cancel_event = None
self._starting_process = None
@staticmethod
def _wait_for_server(
process: subprocess.Popen,
port: int,
cancel_event: Optional[threading.Event] = None,
route: str = "",
) -> None:
deadline = time.monotonic() + _SERVER_START_TIMEOUT_SECONDS
while time.monotonic() < deadline:
if cancel_event is not None and cancel_event.is_set():
raise SttLoadCancelledError(
"GGUF STT model loading was cancelled so training could start."
)
if process.poll() is not None:
raise SttEngineUnavailableError(
"The local transcription runtime exited before becoming "
"ready; the model file may be corrupt or unsupported."
)
# Require a whisper-server-specific response twice, with the managed child alive around each probe. An
# arbitrary local process that won the bind race would otherwise be mistaken for the sidecar and receive the
# user's microphone audio.
if GgmlSttSidecar._probe_is_whisper_server(process, port, route) and (
GgmlSttSidecar._probe_is_whisper_server(process, port, route)
):
return
time.sleep(0.2)
raise SttEngineUnavailableError("The local transcription runtime did not start in time.")
@staticmethod
def _probe_is_whisper_server(
process: subprocess.Popen,
port: int,
route: str = "",
) -> bool:
"""Child alive, responder looks like whisper.cpp (index page and errors name whisper)."""
if process.poll() is not None:
return False
try:
req = urllib.request.Request(f"http://127.0.0.1:{port}{route}/", method = "GET")
with urllib.request.urlopen(req, timeout = 2) as response:
body = response.read(65536)
except Exception:
return False
if process.poll() is not None:
return False
return b"whisper" in body.lower()
def transcribe(
self,
audio: bytes,
model: Optional[str] = None,
language: Optional[str] = None,
fast: bool = False,
cancel_event: Optional[threading.Event] = None,
) -> dict:
"""Accepts any container PyAV decodes, under the same validation and caps as the
Transformers sidecar."""
self._raise_if_update_in_progress()
ensure_engine_available()
model_id = resolve_ggml_model_id(model)
lang = normalize_whisper_language(language)
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
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}'."
)
# Reject a missing model before decoding, so a long clip does not burn CPU just to 409.
self._ensure_model_downloaded(model_id)
decoded_audio = _decode_audio_bounded(audio, cancel_event)
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
wav_bytes = _pcm_to_wav_bytes(decoded_audio)
with self._lock:
try:
if cancel_event is None:
self.load(model_id)
else:
self.load(model_id, request_cancel_event = cancel_event)
text = self._post_inference(wav_bytes, lang, fast, cancel_event)
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
except Exception:
if cancel_event is not None and cancel_event.is_set():
raise SttTranscriptionCancelledError("Transcription cancelled.")
raise
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:
already_cancelled = cancel_event.is_set()
cancel_event.set()
return self._cancel_owned_load(cancel_event) or not already_cancelled
def _post_inference(
self,
wav_bytes: bytes,
lang: Optional[str],
fast: bool,
cancel_event: Optional[threading.Event] = None,
) -> str:
boundary = uuid.uuid4().hex
fields = {
"temperature": "0.0",
"response_format": "json",
# Match the Transformers sidecar: 5-way beam search, greedy for fast.
"beam_size": "1" if fast else "5",
"language": lang or "auto",
}
parts: list[bytes] = []
for name, value in fields.items():
parts.append(
(
f"--{boundary}\r\nContent-Disposition: form-data; "
f'name="{name}"\r\n\r\n{value}\r\n'
).encode()
)
parts.append(
(
f"--{boundary}\r\nContent-Disposition: form-data; "
'name="file"; filename="dictation.wav"\r\n'
"Content-Type: audio/wav\r\n\r\n"
).encode()
+ wav_bytes
+ b"\r\n"
)
parts.append(f"--{boundary}--\r\n".encode())
body = b"".join(parts)
# http.client, not urllib: a cancel needs the socket, and urlopen exposes none.
connection = http.client.HTTPConnection(
"127.0.0.1", self._port, timeout = _TRANSCRIBE_TIMEOUT_SECONDS
)
cancel_done = threading.Event()
if cancel_event is not None:
threading.Thread(
target = _close_connection_on_cancel,
args = (connection, cancel_event, cancel_done),
daemon = True,
).start()
try:
connection.request(
"POST",
f"{self._route}/inference",
body = body,
headers = {"Content-Type": f"multipart/form-data; boundary={boundary}"},
)
with connection.getresponse() as response:
if not 200 <= response.status < 300:
raise SttEngineUnavailableError(
f"The local transcription runtime returned HTTP {response.status}."
)
payload = json.loads(response.read().decode("utf-8"))
except (SttAudioDecodeError, SttEngineUnavailableError):
raise
except Exception as exc:
# A deliberate cancel closes the socket; do not mark the runtime broken.
if cancel_event is None or not cancel_event.is_set():
note_runtime_inference_failure(f"{type(exc).__name__}: {exc}")
raise SttEngineUnavailableError(
"The local transcription runtime did not answer the request. "
"Transcription will use the Transformers engine from now on."
) from exc
finally:
cancel_done.set()
connection.close()
text = payload.get("text")
if not isinstance(text, str):
raise SttAudioDecodeError("Could not decode the audio.")
# It served a transcription, so whatever failed earlier was transient.
clear_runtime_inference_failure()
# whisper.cpp joins segments with newlines; dictation wants one line.
return " ".join(part.strip() for part in text.splitlines() if part.strip()).strip()
_sidecar: Optional[GgmlSttSidecar] = None
def get_ggml_stt_sidecar() -> GgmlSttSidecar:
global _sidecar
if _sidecar is None:
_sidecar = GgmlSttSidecar()
return _sidecar