Skip to content

The agent that grows with you

refactor(stt): local backend detection helper, CPU-eviction helper, module docstrings and import packing

Teknium60aa491f3d95
diff --git a/tools/transcription_audio.py b/tools/transcription_audio.py
index f36044816cb..41fcaef36a5 100644
--- a/tools/transcription_audio.py
+++ b/tools/transcription_audio.py
@@ -1,8 +1,12 @@
-"""Audio preprocessing for STT: binary discovery, ffmpeg transcode/convert, source validation, silk decode, and the best-effort cloud pre-upload silence trim.
+"""Audio preprocessing for STT.
-Split out of ``tools/transcription_tools.py``; every moved name is re-imported there,
-so ``tools.transcription_tools.<name>`` keeps resolving (and monkeypatching) as before.
-Origin helpers are imported lazily inside functions so patches on the origin intercept.
+Binary discovery, the shared ffmpeg m4a encode (transcode + silence trim),
+source/format validation, WeChat .silk decoding, CAF conversion and the
+best-effort cloud pre-upload silence trim.
+
+Split out of ``tools/transcription_tools.py``; moved names are re-imported
+there so ``tools.transcription_tools.<name>`` keeps resolving and patches on the
+origin still intercept (origin helpers are imported lazily inside functions).
"""
from __future__ import annotations
@@ -14,17 +18,12 @@ import subprocess
import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
+
from hermes_cli._subprocess_compat import windows_hide_flags
from utils import is_truthy_value
from tools.transcription_common import (
- COMMON_LOCAL_BIN_DIRS,
- LOCAL_NATIVE_AUDIO_FORMATS,
- MAX_FILE_SIZE,
- SUPPORTED_FORMATS,
- _config_number,
- _error_result,
- _lazy_ensure_quietly,
- _process_error_detail,
+ COMMON_LOCAL_BIN_DIRS, LOCAL_NATIVE_AUDIO_FORMATS, MAX_FILE_SIZE, SUPPORTED_FORMATS,
+ _config_number, _error_result, _lazy_ensure_quietly, _process_error_detail,
)
# Log-record parity with the origin module.
diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.py
index 9ddc134c608..b2b9380ac02 100644
--- a/tools/transcription_cloud.py
+++ b/tools/transcription_cloud.py
@@ -1,8 +1,12 @@
-"""Cloud STT providers: the OpenAI-SDK-shaped backends (groq, openai, deepinfra), Mistral Voxtral, and the REST multipart backends (xAI, ElevenLabs), plus OpenAI audio credential resolution (config > keyless local server > env > managed Nous gateway).
+"""Cloud STT providers.
-Split out of ``tools/transcription_tools.py``; every moved name is re-imported there,
-so ``tools.transcription_tools.<name>`` keeps resolving (and monkeypatching) as before.
-Origin helpers are imported lazily inside functions so patches on the origin intercept.
+OpenAI-SDK-shaped backends (groq, openai, deepinfra), Mistral Voxtral, the REST
+multipart backends (xAI, ElevenLabs), and OpenAI audio credential resolution
+(config > keyless local server > env > managed Nous gateway).
+
+Split out of ``tools/transcription_tools.py``; moved names are re-imported
+there so ``tools.transcription_tools.<name>`` keeps resolving and patches on the
+origin still intercept (origin helpers are imported lazily inside functions).
"""
from __future__ import annotations
@@ -13,22 +17,13 @@ import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
from urllib.parse import urljoin
+
from utils import is_truthy_value
from tools.transcription_audio import _transcode_audio_for_stt
from tools.transcription_common import (
- DEFAULT_GROQ_STT_MODEL,
- DEFAULT_STT_MODEL,
- ELEVENLABS_STT_BASE_URL,
- GROQ_BASE_URL,
- GROQ_MODELS,
- OPENAI_BASE_URL,
- OPENAI_MODELS,
- XAI_STT_BASE_URL,
- _error_result,
- _get_stt_section,
- _lazy_ensure_quietly,
- _log_prompt_unsupported,
- _ok_result,
+ DEFAULT_GROQ_STT_MODEL, DEFAULT_STT_MODEL, ELEVENLABS_STT_BASE_URL, GROQ_BASE_URL, GROQ_MODELS,
+ OPENAI_BASE_URL, OPENAI_MODELS, XAI_STT_BASE_URL, _error_result, _get_stt_section,
+ _lazy_ensure_quietly, _log_prompt_unsupported, _ok_result,
)
# Log-record parity with the origin module.
diff --git a/tools/transcription_command.py b/tools/transcription_command.py
index d4137e9b7a9..9b8eccaa3ba 100644
--- a/tools/transcription_command.py
+++ b/tools/transcription_command.py
@@ -1,8 +1,12 @@
-"""User-declared STT command providers (stt.providers.<name>: type: command) and plugin-registered TranscriptionProvider dispatch, plus the pre_transcription hook that threads prompt/language/model overrides into every backend.
+"""User-declared and plugin STT providers.
-Split out of ``tools/transcription_tools.py``; every moved name is re-imported there,
-so ``tools.transcription_tools.<name>`` keeps resolving (and monkeypatching) as before.
-Origin helpers are imported lazily inside functions so patches on the origin intercept.
+``stt.providers.<name>: type: command`` registry, plugin-registered
+``TranscriptionProvider`` dispatch, and the ``pre_transcription`` hook that
+threads prompt/language/model overrides into every backend.
+
+Split out of ``tools/transcription_tools.py``; moved names are re-imported
+there so ``tools.transcription_tools.<name>`` keeps resolving and patches on the
+origin still intercept (origin helpers are imported lazily inside functions).
"""
from __future__ import annotations
@@ -12,17 +16,14 @@ import subprocess
import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
+
from tools.tts_command_provider import (
command_env_passthrough as _command_stt_env_passthrough,
render_command_template as _render_command_stt_template,
run_command_provider as _run_command_stt,
)
from tools.transcription_common import (
- BUILTIN_STT_PROVIDERS,
- _error_result,
- _get_stt_section,
- _log_prompt_unsupported,
- _ok_result,
+ BUILTIN_STT_PROVIDERS, _error_result, _get_stt_section, _log_prompt_unsupported, _ok_result,
)
# Log-record parity with the origin module.
diff --git a/tools/transcription_local.py b/tools/transcription_local.py
index 7bf39493318..a4332c1ca3e 100644
--- a/tools/transcription_local.py
+++ b/tools/transcription_local.py
@@ -1,8 +1,13 @@
-"""Local STT backends: faster-whisper loading (CUDA->CPU fallback, Apple Silicon pinning), anti-hallucination transcribe kwargs and segment gating, plus the local whisper CLI (local_command) provider. The cached-model singleton and its idle-unload watcher stay in transcription_tools (they own the module state).
+"""Local STT backends.
-Split out of ``tools/transcription_tools.py``; every moved name is re-imported there,
-so ``tools.transcription_tools.<name>`` keeps resolving (and monkeypatching) as before.
-Origin helpers are imported lazily inside functions so patches on the origin intercept.
+faster-whisper loading (CUDA->CPU fallback, Apple Silicon pinning), the
+anti-hallucination transcribe kwargs and segment gate, and the local whisper CLI
+(``local_command``) provider. The cached-model singleton and its idle-unload
+watcher stay in ``transcription_tools`` (they own the module state).
+
+Split out of ``tools/transcription_tools.py``; moved names are re-imported
+there so ``tools.transcription_tools.<name>`` keeps resolving and patches on the
+origin still intercept (origin helpers are imported lazily inside functions).
"""
from __future__ import annotations
@@ -16,17 +21,11 @@ import tempfile
import importlib.util as _ilu
from pathlib import Path
from typing import Any, Dict, Optional
+
from tools.transcription_audio import _run_quiet
from tools.transcription_common import (
- DEFAULT_LOCAL_MODEL,
- DEFAULT_LOCAL_STT_LANGUAGE,
- GROQ_MODELS,
- LOCAL_STT_COMMAND_ENV,
- OPENAI_MODELS,
- _config_number,
- _error_result,
- _log_prompt_unsupported,
- _ok_result,
+ DEFAULT_LOCAL_MODEL, DEFAULT_LOCAL_STT_LANGUAGE, GROQ_MODELS, LOCAL_STT_COMMAND_ENV,
+ OPENAI_MODELS, _config_number, _error_result, _log_prompt_unsupported, _ok_result,
_process_error_detail,
)
diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py
index d0371a96ff7..5efdf95bc84 100644
--- a/tools/transcription_tools.py
+++ b/tools/transcription_tools.py
@@ -6,6 +6,11 @@ openai (also serves the managed ``nous`` selection), mistral, xai, elevenlabs,
deepinfra; plus user-declared command providers and plugin providers.
result = transcribe_audio("/path/to/audio.ogg") # {"success", "transcript", "error"?, "provider"?}
+
+This module owns provider resolution, the dispatcher, and the cached local
+model + idle-unload state. Backends live in sibling modules
+(``transcription_{common,audio,local,cloud,command}``) and are re-imported
+here so ``tools.transcription_tools.<name>`` stays the patch/import surface.
"""
import logging
@@ -226,13 +231,21 @@ def _resolve_explicit_openai() -> str:
return "none"
-def _resolve_explicit_local() -> str:
+def _detect_local_backend() -> Optional[str]:
+ """faster-whisper > local whisper CLI > lazy-installed faster-whisper; None when nothing local works."""
if _HAS_FASTER_WHISPER:
return "local"
if _has_local_command():
return "local_command"
if _try_lazy_install_stt():
return "local"
+ return None
+
+
+def _resolve_explicit_local() -> str:
+ backend = _detect_local_backend()
+ if backend:
+ return backend
logger.warning(
"STT provider 'local' configured but unavailable "
"(install faster-whisper or set HERMES_LOCAL_STT_COMMAND)"
@@ -351,12 +364,9 @@ def _get_provider(stt_config: dict) -> str:
if explicit:
return _resolve_explicit_provider(provider)
- if _HAS_FASTER_WHISPER:
- return "local"
- if _has_local_command():
- return "local_command"
- if _try_lazy_install_stt():
- return "local"
+ backend = _detect_local_backend()
+ if backend:
+ return backend
for name, (_probe, available, _warning, message) in _CLOUD_PROVIDER_SPECS.items():
if available():
logger.info(message)
@@ -454,6 +464,17 @@ def _get_or_load_local_model(model_name: str, local_cfg: Dict[str, Any]):
return model
+def _replace_cached_model_on_cpu(model_name: str):
+ """Load *model_name* on CPU/int8 and make it the cached singleton."""
+ global _local_model, _local_model_name
+ from faster_whisper import WhisperModel
+ model = WhisperModel(model_name, device="cpu", compute_type="int8")
+ with _local_model_lock:
+ _local_model = model
+ _local_model_name = model_name
+ return model
+
+
def _transcribe_local(
file_path: str,
model_name: str,
@@ -462,8 +483,6 @@ def _transcribe_local(
prompt: Optional[str] = None,
) -> Dict[str, Any]:
"""Transcribe using faster-whisper (local, free)."""
- global _local_model, _local_model_name
-
if not _HAS_FASTER_WHISPER and not _try_lazy_install_stt():
return _error_result("faster-whisper not installed")
@@ -486,7 +505,6 @@ def _transcribe_local(
try:
segments, info = model.transcribe(file_path, **transcribe_kwargs)
- transcript = _join_confident_segments(segments, local_cfg)
except Exception as exc:
# CUDA libs sometimes only fail at dlopen-on-first-use, AFTER the
# model loaded. Evict the poisoned cached model, reload on CPU and
@@ -498,13 +516,9 @@ def _transcribe_local(
"evicting cached model and retrying on CPU (int8).",
exc,
)
- from faster_whisper import WhisperModel
- model = WhisperModel(model_name, device="cpu", compute_type="int8")
- with _local_model_lock:
- _local_model = model
- _local_model_name = model_name
+ model = _replace_cached_model_on_cpu(model_name)
segments, info = model.transcribe(file_path, **transcribe_kwargs)
- transcript = _join_confident_segments(segments, local_cfg)
+ transcript = _join_confident_segments(segments, local_cfg)
logger.info(
"Transcribed %s via local whisper (%s, lang=%s, %.1fs audio)",