File size: 10,379 Bytes
bc9f3e6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | """
whisper_cpp_backend.py β Optional whisper.cpp server backend for
Speech-to-Text, alongside the local HuggingFace (transformers/Whisper)
pipeline used elsewhere in the app.
A single mode is supported:
1. External process β the app launches (or reuses an alreadyβrunning)
`whisper-server` executable (https://github.com/ggerganov/whisper.cpp)
and talks to it over its OpenAIβcompatible HTTP API
(`POST /v1/audio/transcriptions`).
The server process is started lazily on first use and kept alive across
turns until the model or a config change triggers a restart.
"""
import atexit
import os
import shlex
import subprocess
import time
from pathlib import Path
from typing import Optional
from backend import user_config
from backend.local_server import (
CREATE_NO_WINDOW,
clear_health_cache,
collect_process_tail,
find_free_port,
port_is_free,
stop_subprocess,
tcp_health_ok,
)
try:
WHISPER_CPP_AVAILABLE = True
except ImportError:
WHISPER_CPP_AVAILABLE = False
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# whisper-server executable path β NOT hardcoded. Resolution order:
# 1. WHISPER_CPP_SERVER_EXE environment variable (perβlaunch override)
# 2. Persisted setting from user_config.json
# 3. Empty (feature off) if neither is set
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
WHISPER_CPP_SERVER_EXE_PATH = (
os.environ.get("WHISPER_CPP_SERVER_EXE", "").strip()
or str(user_config.USER_CONFIG.get("whisper_cpp_server_exe", "")).strip()
)
WHISPER_CPP_SERVER_EXTRA_ARGS = str(
user_config.USER_CONFIG.get("whisper_cpp_server_extra_args", "")
).strip()
WHISPER_SERVER_HOST = "127.0.0.1"
WHISPER_SERVER_DEFAULT_PORT = 8082
_MODEL_DIR = ( # same GGUF folder llama_backend uses β set together via
# rescan_gguf_models()/Settings; initialized from the SAME
# persisted config key so a restarted app rediscovers the
# user's whisper models without a manual re-scan.
os.environ.get("WHISPER_CPP_MODEL_DIR", "").strip()
or str(user_config.USER_CONFIG.get("gguf_model_dir", "")).strip()
)
_whisper_server_proc = None
_whisper_server_config = {} # {"model_path": ..., "port": ...}
def get_whisper_model_dir() -> str:
"""The folder discover_whisper_models() scans β the same GGUF folder
llama_backend uses (both are set together via Settings' model-dir
picker). Empty when no folder is configured."""
return _MODEL_DIR
def set_whisper_server_exe_path(path: str) -> None:
global WHISPER_CPP_SERVER_EXE_PATH
path = (path or "").strip()
WHISPER_CPP_SERVER_EXE_PATH = path
user_config.save_user_config({"whisper_cpp_server_exe": path})
def set_whisper_server_extra_args(args_str: str) -> None:
global WHISPER_CPP_SERVER_EXTRA_ARGS
WHISPER_CPP_SERVER_EXTRA_ARGS = (args_str or "").strip()
user_config.save_user_config({"whisper_cpp_server_extra_args": WHISPER_CPP_SERVER_EXTRA_ARGS})
def set_whisper_model_dir(folder_path: str) -> None:
global _MODEL_DIR
_MODEL_DIR = (folder_path or "").strip()
def discover_whisper_models(folder: Optional[str] = None) -> dict:
"""Scan `folder` for whisper.cpp model files (.ggml or .bin) and
return {label: path} entries.
Falls back to the current _MODEL_DIR if `folder` is not given.
"""
folder = folder if folder is not None else _MODEL_DIR
if not folder:
return {}
p = Path(folder)
if not p.exists():
return {}
found = {}
for f in sorted(p.rglob("*")):
if f.suffix.lower() in (".ggml", ".bin", ".gguf"):
size_mb = f.stat().st_size / (1024 ** 2)
label = f"π€ {f.stem} (~{size_mb:.0f} MB | whisper.cpp)"
found[label] = str(f)
return found
# ββ Server lifecycle ββββββββββββββββββββββββββββββββββββββββββββββ
def is_whisper_server_running() -> bool:
"""Best-effort: is the managed whisper-server subprocess currently
alive? Mirrors llama_backend.is_llama_server_running() β used by the
"Free All VRAM" handler to stop the server even when no Python model
wrapper is cached."""
return (_whisper_server_proc is not None
and _whisper_server_proc.poll() is None)
def stop_whisper_server() -> int:
"""Terminate the managed whisper-server subprocess (if one is running)
AND reap orphaned whisper-server processes a PREVIOUS app instance left
behind, returning how many processes were stopped (0 = nothing running).
Mirrors llama_backend.stop_llama_server()'s orphan sweep: a dead app
instance's whisper-server keeps its model resident in VRAM with no
Python wrapper left to trigger the stop. Matching is by the app's OWN
launch signature β the configured exe path, or a model path under the
app's whisper model dir (see
local_server.kill_stray_app_servers)."""
global _whisper_server_proc, _whisper_server_config
managed_pid = _whisper_server_proc.pid if _whisper_server_proc is not None else None
stopped = 0
if _whisper_server_proc is not None:
print("[whisper-server] Stopping subprocess β¦")
stop_subprocess(_whisper_server_proc, tag="whisper-server")
stopped += 1
_whisper_server_proc = None
_whisper_server_config = {}
clear_health_cache()
from backend.local_server import kill_stray_app_servers
stray = kill_stray_app_servers(
("whisper-server",),
WHISPER_CPP_SERVER_EXE_PATH,
(_MODEL_DIR,),
exclude_pid=managed_pid,
)
if stray:
print(f"[whisper-server] Reaped {stray} orphaned whisper-server "
f"process(es) from a previous app instance.")
stopped += stray
return stopped
atexit.register(stop_whisper_server)
def get_or_start_whisper_server(model_path: str,
port: Optional[int] = None,
startup_timeout: int = 60) -> str:
"""Ensure a whisper-server process is running with this exact model,
launching/relaunching it if needed, and return its base URL."""
global _whisper_server_proc, _whisper_server_config
if not WHISPER_CPP_SERVER_EXE_PATH:
raise RuntimeError(
"No whisper-server executable is configured. Set its path in the "
"'π₯οΈ whisper.cpp Server Path' box in the UI (or the "
"WHISPER_CPP_SERVER_EXE environment variable)."
)
exe = Path(WHISPER_CPP_SERVER_EXE_PATH)
if not exe.exists():
raise RuntimeError(
f"whisper-server executable not found at '{exe}'."
)
target_port = port or WHISPER_SERVER_DEFAULT_PORT
wanted = {"model_path": model_path, "port": target_port}
if (_whisper_server_proc is not None and _whisper_server_proc.poll() is None
and _whisper_server_config.get("model_path") == wanted["model_path"]
and tcp_health_ok(WHISPER_SERVER_HOST, _whisper_server_config.get("port", target_port))):
return f"http://{WHISPER_SERVER_HOST}:{_whisper_server_config['port']}"
stop_whisper_server()
if not port_is_free(WHISPER_SERVER_HOST, target_port):
target_port = find_free_port(WHISPER_SERVER_HOST, target_port)
wanted["port"] = target_port
cmd = [
str(exe),
"-m", model_path,
"--host", WHISPER_SERVER_HOST,
"--port", str(target_port),
]
if WHISPER_CPP_SERVER_EXTRA_ARGS:
cmd.extend(shlex.split(WHISPER_CPP_SERVER_EXTRA_ARGS))
print(f"[whisper-server] Launching: {' '.join(cmd)}")
_whisper_server_proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
creationflags=CREATE_NO_WINDOW,
)
_whisper_server_config = wanted
deadline = time.time() + startup_timeout
while time.time() < deadline:
if _whisper_server_proc.poll() is not None:
tail = collect_process_tail(_whisper_server_proc, max_lines=20)
_whisper_server_proc = None
_whisper_server_config = {}
raise RuntimeError(
f"whisper-server exited immediately. Last output:\n{tail}"
)
if tcp_health_ok(WHISPER_SERVER_HOST, target_port):
print(f"[whisper-server] Ready β http://{WHISPER_SERVER_HOST}:{target_port}")
return f"http://{WHISPER_SERVER_HOST}:{target_port}"
time.sleep(0.5)
stop_whisper_server()
raise RuntimeError(
f"whisper-server did not become reachable within {startup_timeout}s."
)
# ββ WhisperServerModel ββββββββββββββββββββββββββββββββββββββββββββ
class WhisperServerModel:
"""Transcribes audio by POSTing to a running whisper-server's
/v1/audio/transcriptions endpoint (OpenAI-compatible API)."""
def __init__(self, base_url: str, model_path: str, timeout: int = 120):
self.model_id = model_path
self.model_path = model_path
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def transcribe(self, audio_path: str, language: Optional[str] = None) -> str:
import requests
url = f"{self.base_url}/v1/audio/transcriptions"
with open(audio_path, "rb") as f:
files = {"file": (Path(audio_path).name, f, "audio/wav")}
data = {"model": self.model_path}
if language and language != "auto":
data["language"] = language
resp = requests.post(url, files=files, data=data, timeout=self.timeout)
resp.raise_for_status()
result = resp.json()
return result.get("text", "")
|