Download backend/whisper_cpp_backend.py from localailb/assistant: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/whisper_cpp_backend.py
- Command line
-
hf download hf://spaces/localailb/assistant/backend/whisper_cpp_backend.py
-
curl -L -o whisper_cpp_backend.py https://huggingface.co/spaces/localailb/assistant/resolve/main/backend/whisper_cpp_backend.py
10.4 kB
| """ | |
| 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", "") | |