Add offline whisper.cpp adapter and verified model downloads

This commit is contained in:
Vickenty Zherebov 2026-10-19 14:51:35 +03:00
parent 0d95cca437
commit ec51abcc10
4 changed files with 666 additions and 0 deletions

View file

@ -0,0 +1,164 @@
"""Local whisper.cpp subprocess adapter; never falls back to a network service."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
import tempfile
import wave
from datetime import UTC, datetime
from decimal import Decimal
from pathlib import Path
from voice_dictation.core.models import TranscriptionResult
from voice_dictation.infrastructure.errors import TranscriptionError
def discover_executable(name: str) -> Path:
"""Find a bundled runtime first, then PATH and standard Homebrew prefixes."""
filename = f"{name}.exe" if sys.platform == "win32" else name
bundle_root = Path(getattr(sys, "_MEIPASS", Path(sys.executable).parent))
candidates = [
bundle_root / "bin" / filename,
bundle_root / filename,
Path(sys.executable).parent.parent / "Resources" / "bin" / filename,
]
found = shutil.which(filename)
if found:
candidates.append(Path(found))
candidates.extend([Path("/opt/homebrew/bin") / filename, Path("/usr/local/bin") / filename])
for candidate in candidates:
if candidate.is_file() and os.access(candidate, os.X_OK):
return candidate
raise TranscriptionError(
f"Не найден {filename}. Установите whisper.cpp и ffmpeg или используйте сборку с движком."
)
class LocalTranscriber:
"""Transcribe with a managed model and a separately discovered whisper-cli."""
def __init__(self, model_path: Path, executable: Path | None = None) -> None:
self._model_path = model_path
self._executable = executable
def transcribe(
self,
audio_path: Path,
prompt: str = "",
language: str | None = None,
model: str | None = None,
duration_sec: float | None = None,
) -> TranscriptionResult:
"""Convert to 16 kHz mono PCM, run locally and parse whisper.cpp JSON."""
requested_at = datetime.now(tz=UTC)
if not self._model_path.is_file():
raise TranscriptionError("Локальная модель не установлена. Скачайте её в настройках")
executable = self._executable or discover_executable("whisper-cli")
if not executable.is_file():
raise TranscriptionError("Не найден исполняемый файл whisper-cli")
timeout = max(120.0, (duration_sec or 0.0) * 10 + 60)
try:
with tempfile.TemporaryDirectory(prefix="voice-local-") as temporary:
root = Path(temporary)
wav = audio_path
if not self._is_pcm_wav(audio_path):
wav = root / "audio.wav"
self._run(
[
str(discover_executable("ffmpeg")),
"-nostdin",
"-v",
"error",
"-y",
"-i",
str(audio_path),
"-ar",
"16000",
"-ac",
"1",
"-c:a",
"pcm_s16le",
str(wav),
],
timeout,
)
output = root / "result"
command = [
str(executable),
"-m",
str(self._model_path),
"-f",
str(wav),
"-l",
language or "auto",
"-oj",
"-of",
str(output),
]
if prompt:
command.extend(["--prompt", prompt])
self._run(command, timeout)
payload = json.loads(output.with_suffix(".json").read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError("Expected JSON object")
segments = payload.get("transcription")
if not isinstance(segments, list) or any(
not isinstance(segment, dict) or not isinstance(segment.get("text"), str)
for segment in segments
):
raise ValueError("Missing transcription segments")
text = " ".join(segment["text"].strip() for segment in segments).strip()
result_metadata = payload.get("result", {})
detected_language = (
result_metadata.get("language") if isinstance(result_metadata, dict) else None
)
return TranscriptionResult(
text=text,
duration_sec=duration_sec if duration_sec is not None else self._duration(wav),
model=model or self._model_path.stem,
language=detected_language if isinstance(detected_language, str) else language,
prompt_used=prompt or None,
requested_at=requested_at,
cost_usd=Decimal("0"),
)
except (OSError, ValueError, KeyError, TypeError) as exc:
raise TranscriptionError(
"Не удалось прочитать результат локального распознавания"
) from exc
@staticmethod
def _run(command: list[str], timeout: float) -> None:
try:
completed = subprocess.run(command, capture_output=True, timeout=timeout, check=False)
except subprocess.TimeoutExpired as exc:
raise TranscriptionError("Локальное распознавание превысило время ожидания") from exc
except OSError as exc:
raise TranscriptionError("Не удалось запустить локальный движок или ffmpeg") from exc
if completed.returncode:
# Runtime stderr may contain transcript, prompts or local paths: don't expose it.
raise TranscriptionError(f"Локальный движок завершился с кодом {completed.returncode}")
@staticmethod
def _is_pcm_wav(path: Path) -> bool:
try:
with wave.open(str(path), "rb") as audio:
return (
audio.getnchannels() == 1
and audio.getframerate() == 16000
and audio.getsampwidth() == 2
and audio.getcomptype() == "NONE"
)
except (wave.Error, EOFError, OSError):
return False
@staticmethod
def _duration(path: Path) -> float:
with wave.open(str(path), "rb") as audio:
return audio.getnframes() / audio.getframerate()
def close(self) -> None:
"""No persistent process or network client to close."""

View file

@ -0,0 +1,214 @@
"""Verified local model downloads, independent of the application bundle."""
from __future__ import annotations
import hashlib
import sys
import threading
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO
import httpx
class ModelError(RuntimeError):
"""A model operation failed safely."""
class DownloadCancelled(ModelError): # noqa: N818 - public cancellation event name
"""The user cancelled a model download."""
@dataclass(frozen=True, slots=True)
class ModelSpec:
"""Pinned model metadata from the upstream Hugging Face LFS tree."""
id: str
name: str
url: str
size: int
sha256: str
@property
def size_bytes(self) -> int:
"""Expected download size in bytes."""
return self.size
# SHA256 and exact size verified 2026-10-19 against the official LFS metadata:
# https://huggingface.co/api/models/ggerganov/whisper.cpp/tree/main
# Hash verification pins the content even if upstream main changes later.
CATALOG: tuple[ModelSpec, ...] = (
ModelSpec(
"whisper-base",
"Whisper Base · 148 MB",
"https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin",
147951465,
"60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe",
),
ModelSpec(
"whisper-small",
"Whisper Small · 488 MB",
"https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",
487601967,
"1be3a9b2063867b937e64e2ec7483364a79917e157fa98c5d94b5c1fffea987b",
),
ModelSpec(
"whisper-turbo-q5",
"Whisper Large v3 Turbo Q5 · 574 MB",
"https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3-turbo-q5_0.bin",
574041195,
"394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2",
),
)
class ModelManager:
"""Manage explicitly requested downloads with integrity and process-safe locks."""
def __init__(self, models_dir: Path) -> None:
self.models_dir = models_dir
@staticmethod
def _spec(model_id: str) -> ModelSpec:
for spec in CATALOG:
if spec.id == model_id:
return spec
raise ModelError(f"Неизвестная локальная модель: {model_id!r}")
def path_for(self, model_id: str) -> Path:
"""Return the managed path, rejecting arbitrary filenames and symlinks."""
spec = self._spec(model_id)
path = self.models_dir / f"{spec.id}.bin"
if path.is_symlink():
raise ModelError("Путь модели не должен быть символической ссылкой")
return path
def is_installed(self, model_id: str) -> bool:
"""Check size and SHA256; partial or corrupted files are never installed."""
spec = self._spec(model_id)
path = self.path_for(model_id)
return self._valid(path, spec)
@staticmethod
def _valid(path: Path, spec: ModelSpec) -> bool:
if not path.is_file() or path.stat().st_size != spec.size:
return False
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest() == spec.sha256
@contextmanager
def _lock(self, model_id: str) -> Iterator[None]:
self.models_dir.mkdir(parents=True, exist_ok=True)
lock = self.models_dir / f".{model_id}.lock"
if lock.is_symlink():
raise ModelError("Путь блокировки не должен быть символической ссылкой")
# The file stays on disk; the OS releases its advisory lock on process exit.
# Unlinking a lock file would let another process lock a different inode.
with lock.open("a+b") as stream:
try:
self._acquire(stream)
except OSError as exc:
raise ModelError("Модель используется в другом окне или процессе") from exc
try:
yield
finally:
self._release(stream)
@staticmethod
def _acquire(stream: BinaryIO) -> None:
if sys.platform == "win32":
import msvcrt
stream.seek(0, 2)
if stream.tell() == 0:
stream.write(b"0")
stream.flush()
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
@staticmethod
def _release(stream: BinaryIO) -> None:
if sys.platform == "win32":
import msvcrt
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
@contextmanager
def use(self, model_id: str) -> Iterator[Path]:
"""Hold a process-safe inference lease, preventing deletion/replacement."""
path = self.path_for(model_id)
with self._lock(model_id):
if not self.is_installed(model_id):
raise ModelError("Модель не установлена или повреждена. Скачайте её в настройках")
yield path
def download(
self,
model_id: str,
progress: Callable[[int, int], None] | None = None,
cancel: threading.Event | None = None,
) -> Path:
"""Download on explicit request, verify fully, then atomically publish.
A cancelled/failed download removes only its own partial file. Existing
installed models remain untouched. OS locks release even after a crash.
"""
spec = self._spec(model_id)
path = self.path_for(model_id)
with self._lock(model_id):
if self.is_installed(model_id):
return path
partial = path.with_suffix(".bin.part")
if partial.is_symlink():
raise ModelError("Временный путь модели не должен быть символической ссылкой")
try:
received = 0
digest = hashlib.sha256()
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
with (
httpx.stream("GET", spec.url, follow_redirects=True, timeout=30.0) as response,
partial.open("wb") as output,
):
response.raise_for_status()
for chunk in response.iter_bytes(1024 * 1024):
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
received += len(chunk)
if received > spec.size:
raise ModelError("Размер модели превышает ожидаемый")
output.write(chunk)
digest.update(chunk)
if progress is not None:
progress(received, spec.size)
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
if received != spec.size or digest.hexdigest() != spec.sha256:
raise ModelError("Проверка размера или SHA256 модели не пройдена")
partial.replace(path)
return path
except httpx.HTTPError as exc:
raise ModelError(
"Не удалось скачать модель. Проверьте соединение и повторите"
) from exc
finally:
partial.unlink(missing_ok=True)
def delete(self, model_id: str) -> None:
"""Remove a managed model, refusing to race with a download."""
path = self.path_for(model_id)
with self._lock(model_id):
path.unlink(missing_ok=True)

View file

@ -0,0 +1,135 @@
"""Subprocess adapter tests with synthetic silence and fake CLI output."""
from __future__ import annotations
import json
import subprocess
import wave
from decimal import Decimal
from pathlib import Path
from unittest.mock import patch
import pytest
from voice_dictation.core.local_transcriber import LocalTranscriber
from voice_dictation.infrastructure.errors import TranscriptionError
@pytest.fixture
def local_setup(tmp_path):
model = tmp_path / "model.bin"
model.write_bytes(b"fake")
executable = tmp_path / "whisper-cli"
executable.touch()
audio = tmp_path / "silence.wav"
with wave.open(str(audio), "wb") as stream:
stream.setnchannels(1)
stream.setsampwidth(2)
stream.setframerate(16000)
stream.writeframes(b"\x00\x00" * 16000)
return LocalTranscriber(model, executable), audio
def test_pcm_wav_transcription_is_local(local_setup):
transcriber, audio = local_setup
calls = []
def run(command, **kwargs):
calls.append(command)
output = Path(command[command.index("-of") + 1]).with_suffix(".json")
output.write_text(
json.dumps(
{
"transcription": [{"text": " Привет "}, {"text": " мир "}],
"result": {"language": "ru"},
}
)
)
return subprocess.CompletedProcess(command, 0)
with patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run):
result = transcriber.transcribe(audio, prompt="terms", model="whisper-base")
assert result.text == "Привет мир"
assert result.cost_usd == Decimal("0")
assert result.duration_sec == 1.0
assert result.language == "ru"
assert result.model == "whisper-base"
assert result.prompt_used == "terms"
assert len(calls) == 1
assert "--prompt" in calls[0]
assert calls[0][calls[0].index("-l") + 1] == "auto"
assert not Path(calls[0][calls[0].index("-of") + 1]).parent.exists()
def test_missing_model_no_process(tmp_path):
with patch("voice_dictation.core.local_transcriber.subprocess.run") as run:
with pytest.raises(TranscriptionError, match="не установлена"):
LocalTranscriber(tmp_path / "absent").transcribe(tmp_path / "audio")
run.assert_not_called()
def test_timeout_no_fallback(local_setup):
transcriber, audio = local_setup
with (
patch(
"voice_dictation.core.local_transcriber.subprocess.run",
side_effect=subprocess.TimeoutExpired("whisper-cli", 120),
),
pytest.raises(TranscriptionError, match="время ожидания"),
):
transcriber.transcribe(audio)
def test_failure_does_not_expose_stderr(local_setup):
transcriber, audio = local_setup
with (
patch(
"voice_dictation.core.local_transcriber.subprocess.run",
return_value=subprocess.CompletedProcess([], 1, stderr=b"PRIVATE TRANSCRIPT"),
),
pytest.raises(TranscriptionError, match="кодом 1") as exc,
):
transcriber.transcribe(audio)
assert "PRIVATE" not in str(exc.value)
def test_invalid_json(local_setup):
transcriber, audio = local_setup
def run(command, **kwargs):
Path(command[command.index("-of") + 1]).with_suffix(".json").write_text("[]")
return subprocess.CompletedProcess(command, 0)
with (
patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run),
pytest.raises(TranscriptionError, match="результат"),
):
transcriber.transcribe(audio)
def test_opus_converted_before_inference(local_setup, tmp_path):
transcriber, source = local_setup
audio = tmp_path / "audio.ogg"
audio.write_bytes(b"fake ogg")
calls = []
def run(command, **kwargs):
calls.append(command)
if "-of" in command:
Path(command[command.index("-of") + 1]).with_suffix(".json").write_text(
'{"transcription": [{"text": "ok"}]}'
)
else:
Path(command[-1]).write_bytes(source.read_bytes())
return subprocess.CompletedProcess(command, 0)
with (
patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run),
patch(
"voice_dictation.core.local_transcriber.discover_executable",
return_value=Path("/fake/ffmpeg"),
),
):
assert transcriber.transcribe(audio).text == "ok"
assert len(calls) == 2
assert "pcm_s16le" in calls[0]

View file

@ -0,0 +1,153 @@
"""Model installation invariants without network or real model downloads."""
from __future__ import annotations
import hashlib
import threading
from unittest.mock import MagicMock
import httpx
import pytest
from voice_dictation.core import model_manager as module
from voice_dictation.core.model_manager import (
DownloadCancelled,
ModelError,
ModelManager,
ModelSpec,
)
@pytest.fixture
def fixture_model(monkeypatch):
content = b"small synthetic model bytes"
spec = ModelSpec(
"test",
"Test",
"https://example.invalid/model",
len(content),
hashlib.sha256(content).hexdigest(),
)
monkeypatch.setattr(module, "CATALOG", (spec,))
response = MagicMock()
response.iter_bytes.return_value = iter([content[:8], content[8:]])
stream = MagicMock()
stream.__enter__.return_value = response
monkeypatch.setattr(module.httpx, "stream", lambda *a, **kw: stream)
return spec, content, response
def test_verified_atomic_download(tmp_path, fixture_model):
spec, content, _ = fixture_model
manager = ModelManager(tmp_path)
progress = []
path = manager.download(spec.id, lambda done, total: progress.append((done, total)))
assert path.read_bytes() == content
assert manager.is_installed(spec.id)
assert progress[-1] == (len(content), len(content))
assert not list(tmp_path.glob("*.part"))
manager.delete(spec.id)
assert not manager.is_installed(spec.id)
def test_corrupt_download_never_installed(tmp_path, fixture_model):
spec, _, response = fixture_model
response.iter_bytes.return_value = iter([b"corrupt"])
manager = ModelManager(tmp_path)
with pytest.raises(ModelError, match="SHA256"):
manager.download(spec.id)
assert not manager.is_installed(spec.id)
assert not list(tmp_path.glob("*.part"))
def test_cancel_removes_partial(tmp_path, fixture_model):
spec, _, _ = fixture_model
cancel = threading.Event()
manager = ModelManager(tmp_path)
with pytest.raises(DownloadCancelled):
manager.download(spec.id, lambda *_: cancel.set(), cancel)
assert not manager.path_for(spec.id).exists()
assert not list(tmp_path.glob("*.part"))
def test_concurrent_download_and_delete_rejected(tmp_path, fixture_model):
spec, _, _ = fixture_model
manager = ModelManager(tmp_path)
with manager._lock(spec.id):
with pytest.raises(ModelError, match="другом окне"):
ModelManager(tmp_path).download(spec.id)
with pytest.raises(ModelError, match="другом окне"):
ModelManager(tmp_path).delete(spec.id)
def test_network_failure_preserves_old_model(tmp_path, fixture_model):
spec, content, response = fixture_model
manager = ModelManager(tmp_path)
path = manager.path_for(spec.id)
path.write_bytes(b"previous corrupt model")
response.raise_for_status.side_effect = httpx.ConnectError("failed")
with pytest.raises(ModelError):
manager.download(spec.id)
assert path.read_bytes() == b"previous corrupt model"
assert not list(tmp_path.glob("*.part"))
path.write_bytes(content)
assert manager.download(spec.id) == path
@pytest.mark.parametrize("model_id", ["../escape", "/tmp/escape", "unknown", "test/../../escape"])
def test_unknown_ids_rejected(tmp_path, fixture_model, model_id):
with pytest.raises(ModelError):
ModelManager(tmp_path).download(model_id)
def test_symlink_rejected(tmp_path, fixture_model):
target = tmp_path / "target"
target.write_bytes(b"keep")
(tmp_path / "test.bin").symlink_to(target)
with pytest.raises(ModelError, match="ссылкой"):
ModelManager(tmp_path).delete("test")
assert target.read_bytes() == b"keep"
def test_inference_lease_blocks_delete_and_releases(tmp_path, fixture_model):
spec, content, _ = fixture_model
manager = ModelManager(tmp_path)
manager.path_for(spec.id).write_bytes(content)
with manager.use(spec.id) as path:
assert path.read_bytes() == content
with pytest.raises(ModelError, match="другом окне"):
ModelManager(tmp_path).delete(spec.id)
manager.delete(spec.id)
assert not manager.is_installed(spec.id)
@pytest.mark.parametrize("oversize", [False, True])
def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize):
spec, content, response = fixture_model
response.iter_bytes.return_value = iter([b"x" * (len(content) + int(oversize))])
manager = ModelManager(tmp_path)
with pytest.raises(ModelError):
manager.download(spec.id)
assert not manager.path_for(spec.id).exists()
assert not list(tmp_path.glob("*.part"))
def test_precancelled_download_makes_no_request(tmp_path, fixture_model, monkeypatch):
spec, _, _ = fixture_model
request = MagicMock()
monkeypatch.setattr(module.httpx, "stream", request)
cancel = threading.Event()
cancel.set()
with pytest.raises(DownloadCancelled):
ModelManager(tmp_path).download(spec.id, cancel=cancel)
request.assert_not_called()
def test_partial_symlink_cannot_overwrite_target(tmp_path, fixture_model):
spec, _, _ = fixture_model
target = tmp_path / "target"
target.write_bytes(b"keep")
(tmp_path / "test.bin.part").symlink_to(target)
with pytest.raises(ModelError, match="ссылкой"):
ModelManager(tmp_path).download(spec.id)
assert target.read_bytes() == b"keep"