* chore(build): migrate justfile tooling to uv All recipes now run through 'uv run' against .venv, with a shared DEV_EXTRAS variable (dev + vad) because uv syncs the environment exactly and would otherwise uninstall the dev tools between recipes. 'deps' installs dev+vad; new 'deps-all' covers every extra. 'build' switches to 'uv build'; 'version' uses --no-sync. Bump [tool.uv] required-version to >=0.12,<0.13 for uv 0.12.x, and raise the mypy python_version target to 3.12: mypy 1.19 in the lock cannot target 3.9 and numpy 2.x stubs need a 3.12 target to parse (mypy is not run in CI or pre-commit; this only affects 'just typecheck'). * fix(tests): isolate test runs from real XDG state; fix Arch model-path crash Local test runs failed en masse (185 failures) while CI stayed green: tests picked up the developer's real ~/.local/share/vocalinux models via the default XDG paths and switched IBus/keyboard code paths through the desktop session env (XDG_CURRENT_DESKTOP/ XDG_SESSION_TYPE on GNOME/Wayland, issue #478 branches). conftest now points XDG base dirs at a throwaway session-wide directory and clears session variables at import time, mirroring a fresh CI runner (paths like MODELS_DIR freeze at first import during collection, so fixture-time isolation is too late). Also guard the Arch branch of _get_system_model_paths(): it removed /usr/local/share/vocalinux/models unconditionally and crashed with ValueError on Arch hosts when a custom XDG_DATA_DIRS never added that path. Add regression tests, and make the lock-file test assert the actual $XDG_DATA_HOME/vocalinux contract instead of the hardcoded ~/.local/share default. * fix(tests): keep the IBus engine double a plain class Python 3.14's unittest.mock re-instantiates a user subclass when it builds child mocks (klass(name=...)). VocalinuxEngine inherits from whatever IBus.Engine resolves to, and the test module bound that to the MagicMock class itself, so every engine instantiation raised TypeError: VocalinuxEngine.__init__() got an unexpected keyword argument 'name' on 3.14 while passing on 3.13. Replace it with a plain stand-in class that still hands out per-instance MagicMocks for the IBus API surface the engine touches. The same pattern remains in test_ibus_engine.py, test_ibus_engine_utils.py, test_ibus_active_engine_guard.py and test_ibus_xkb_wayland.py; those never instantiate the engine, so they are unaffected for now. * fix(install): build the venv from the system Python install.sh looked up a bare `python3` from PATH. Started from an activated virtualenv — a shell left in uv's .venv after `just deps` — it built venv/ from that interpreter, where distro PyGObject is invisible even with --system-site-packages, and the run aborted with Distro PyGObject (python3-gi / python3-gobject) is not importable in the venv. A mismatched venv/ then survived every retry, because the installer reuses whatever venv it finds. - drop an inherited VIRTUAL_ENV (and its bin from PATH) before any interpreter lookup - select the interpreter explicitly: $SYSTEM_PYTHON (default /usr/bin/python3) or PATH python3, preferring one that can import gi, and create the venv with it instead of `python3` - recreate venv/ when it was built by a different interpreter - name the interpreter in the PyGObject guard's error Documents the two environments (uv's .venv for tooling, venv/ for the installed app) in CONTRIBUTING, the justfile header and AGENTS.md, and adds the mismatch symptom to the INSTALL troubleshooting section. * chore(python): raise the supported floor to 3.11 requires-python promised 3.9 while the CI matrix ran 3.9/3.10/3.11/3.13, the classifiers advertised up to 3.14, mypy targeted 3.12 and install.sh enforced 3.9 — five different answers to "which Python does this support". Settle on 3.11 everywhere: pyproject (requires-python, classifiers, black targets), install.sh's MIN_VERSION, check-system-deps.sh, the distro package map, the CI matrix (now 3.11-3.14, matching the classifiers), the release and nightly workflows, and the docs. mypy now targets the floor instead of 3.12, so type checking covers what we promise; numpy 2.x ships stubs in 3.12 syntax that a 3.11 target cannot parse, so its imports are skipped. (mypy has 71 pre-existing errors either way; no CI job gates on it.) uv.lock and the requirements/* exports are regenerated — dropping 3.9/3.10 removes most of the version-conditional resolution branches. tests/test_python_version_policy.py pins the invariant: install.sh's floor, requires-python, the classifiers and the CI matrix must agree. * ci: run lint and tests from uv.lock The lock file and the hash-pinned exports were not enforced anywhere: CI still built a venv by hand and installed unpinned `PyGObject` plus `-e ".[dev,vad]"`, so the tool versions it checked against had nothing to do with the ones `just lint` uses locally. Both Python jobs now use astral-sh/setup-uv and run through `uv sync --locked` / `uv run --locked`, which also fails the build when uv.lock drifts from pyproject.toml. Partially covers phase 5 of #701 (tests install from the lock, lock freshness gate); trusted publishing, artifact checksums and action SHA pinning are still open there. * ci: lint from a dedicated dependency group The lint job failed on this branch: `uv run --extra dev` syncs the whole project, so it tried to build pyaudio from source on a runner that installs no system dependencies. src/pyaudio/device_api.c:9:10: fatal error: portaudio.h: No such file or directory Move black/isort/flake8 out of the `dev` extra into a `lint` dependency group. CI runs `uv run --locked --only-group lint`, which installs the three pure-Python tools and skips the project entirely — no portaudio or girepository headers needed. `just deps` and DEV_EXTRAS request the group alongside the dev extras, so the local environment still carries test and lint tooling at once and `just lint` matches CI version for version. pre-commit is unaffected: its hooks pin their own tool versions upstream. * fix(install): never configure an engine the venv cannot import vosk became an optional extra in #705, but the installer still writes `"engine": "vosk"` into config.json on the whisper.cpp fallback path even when installing the extra only produced a warning. config.json also survives reinstalls — every writer guards on "file does not exist" — so an engine picked by an earlier attempt outlives the venv that supported it. Either way Vocalinux dies at startup: ModuleNotFoundError: No module named 'vosk' - the fallback now writes the vosk config only when `import vosk` actually succeeds, and otherwise leaves the engine configuration alone - a new verify_configured_engine() runs near the end of the install: if config.json selects vosk and the venv cannot import it, it says so and prints both fixes instead of leaving a broken install behind * feat(models): verify every model download against a pinned digest Pins a sha256/md5 per downloadable speech model in src/vocalinux/utils/model_checksums.txt and verifies against it in both install.sh and the runtime downloaders, before the file is moved into place. Verification fails closed. Covers phase 2.5 of #701; see the PR for details. * docs(agents): rebase AGENTS.md onto the #727 rewrite * fix(install): hash models that are already on disk instead of trusting them * refactor(models): one download path per engine, and fix Whisper's * docs(install): drop distros that cannot meet the 3.11 floor * docs: retire the distros and Python versions the 3.11 floor rules out * fix(install): abort instead of warning when Python is below the floor * fix(install): fall back to the system Python, not the one on PATH * fix(install): match an existing venv by installation, not by X.Y * fix(install): repair a config naming an engine the venv cannot import * fix(models): pin VOSK by the sha256 of bytes we fetched, not upstream's md5 * fix(justfile): request the dev set in every recipe that syncs * test(version): scan the docs and website trees for a stale Python floor * docs: correct the stale model-checksum and distro claims * fix(models): stamp the VOSK tree the app extracts, as the installer does * fix(install): replace an unverified VOSK model only once its successor is ready * docs(install): align the Fedora floor with the rest of the tree * test(install): drop an f-string with no placeholders * test(models): stub the downloader probe the VOSK installer test relies on * docs: drop the long dashes from two model-checksum comments * fix(install): gate on the interpreter, not on the distro release label * fix(justfile): export the lint group into requirements/dev.txt * fix(models): unpack the VOSK tree into staging and stamp it before the swap * fix(whisper): adopt a checkpoint an earlier release stored under the catalog name * docs(settings): state what a stray Whisper copy really means for deletion * fix(models): hash a whisper.cpp model found on disk before it reaches ctypes * docs(contributing): stop telling readers to uninstall their linters * fix(install): stop warning off distros the project documents as supported * docs(distros): file the supported derivatives under supported
225 lines
8.5 KiB
Python
225 lines
8.5 KiB
Python
"""Integrity verification for downloaded speech models.
|
|
|
|
Vocalinux pulls 40MB-2GB model files from Hugging Face, Alphacephei and
|
|
openaipublic.azureedge.net, then feeds them to native code -- whisper.cpp maps
|
|
its ggml files through ``ctypes.cdll``. A tampered or truncated model is
|
|
therefore not merely a bad transcription, so every download is checked against a
|
|
digest pinned in this repository before it is moved into place, and a model that
|
|
is merely found on disk is hashed before it is handed to native code.
|
|
|
|
One source of truth, consulted without a network lookup: ``model_checksums.txt``
|
|
next to this module pins a sha256 per file name, for whisper.cpp (the
|
|
``lfs.oid`` at the pinned Hugging Face revision) and for VOSK (the hash of the
|
|
bytes the generator downloaded; the md5 Alphacephei publishes beside a model
|
|
pins nothing they could not change alongside it). Regenerate it with
|
|
``scripts/generate-model-checksums.py``.
|
|
|
|
OpenAI Whisper ``.pt`` checkpoints are absent from it: ``openai-whisper``
|
|
downloads and verifies those itself, against the sha256 it reads out of the URL
|
|
path, so Vocalinux neither fetches nor hashes them. ``install.sh`` does preinstall
|
|
the tiny checkpoint, and verifies it there with its own bash implementation.
|
|
|
|
Verification fails closed: a file with no pinned digest is an error, not a
|
|
warning. ``tests/test_model_checksums.py`` asserts the manifest covers every
|
|
model the application can download, so that strictness is caught in CI rather
|
|
than on a user's machine.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import logging
|
|
import os
|
|
import re
|
|
from functools import lru_cache
|
|
from typing import Dict, NamedTuple, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_MANIFEST_NAME = "model_checksums.txt"
|
|
|
|
# Written into an extracted model tree to record the digest of the archive it
|
|
# came out of. A directory has no hash of its own and the zip is deleted after
|
|
# unpacking, so this file is the only evidence the tree was ever verified.
|
|
# install.sh reads it under the same name; keep the two in step.
|
|
VERIFICATION_STAMP_NAME = ".vocalinux_verified"
|
|
|
|
# Hash of a 2GB model read in one go would sit in RAM; stream it instead.
|
|
_CHUNK_SIZE = 1024 * 1024
|
|
|
|
_REVISION_HEADER = re.compile(r"^#\s*whispercpp-revision:\s*([0-9a-f]{7,40})\s*$")
|
|
|
|
|
|
class ChecksumError(Exception):
|
|
"""A downloaded model did not match its pinned digest, or has no pin at all."""
|
|
|
|
|
|
class Expected(NamedTuple):
|
|
"""The pinned identity of one artifact."""
|
|
|
|
algo: str
|
|
digest: str
|
|
size: int
|
|
|
|
|
|
def _manifest_text() -> str:
|
|
"""Read the manifest from the installed package, falling back to the source tree.
|
|
|
|
A missing manifest yields an empty one rather than an import-time crash: the
|
|
consequence is that every model then lacks a pin and is refused by
|
|
:func:`verify_model_file`, which is the safe direction to fail.
|
|
"""
|
|
try:
|
|
from importlib.resources import files
|
|
|
|
return files(__package__).joinpath(_MANIFEST_NAME).read_text(encoding="utf-8")
|
|
except (ImportError, TypeError, ModuleNotFoundError):
|
|
pass
|
|
except (FileNotFoundError, OSError):
|
|
return ""
|
|
|
|
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), _MANIFEST_NAME)
|
|
try:
|
|
with open(path, encoding="utf-8") as handle:
|
|
return handle.read()
|
|
except OSError:
|
|
logger.error("%s is missing; no model download can be verified", _MANIFEST_NAME)
|
|
return ""
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def _parse_manifest() -> tuple[Dict[str, Expected], str]:
|
|
entries: Dict[str, Expected] = {}
|
|
revision = ""
|
|
|
|
for line in _manifest_text().splitlines():
|
|
stripped = line.strip()
|
|
if not stripped:
|
|
continue
|
|
if stripped.startswith("#"):
|
|
match = _REVISION_HEADER.match(stripped)
|
|
if match:
|
|
revision = match.group(1)
|
|
continue
|
|
|
|
fields = stripped.split()
|
|
if len(fields) != 4:
|
|
logger.warning("Ignoring malformed line in %s: %r", _MANIFEST_NAME, line)
|
|
continue
|
|
filename, algo, digest, size = fields
|
|
entries[filename] = Expected(algo=algo, digest=digest.lower(), size=int(size))
|
|
|
|
return entries, revision
|
|
|
|
|
|
#: Branch to build URLs from when the manifest pins no revision. Only reachable
|
|
#: with a missing or hand-damaged manifest, and deliberately not fatal: URL
|
|
#: construction runs at import time, whereas refusing an unverifiable file is
|
|
#: :func:`verify_model_file`'s job. A download made from this fallback still has
|
|
#: no pinned digest, so it is rejected before it is installed.
|
|
_UNPINNED_REVISION = "main"
|
|
|
|
|
|
def whispercpp_revision() -> str:
|
|
"""The pinned Hugging Face commit the whisper.cpp digests were taken at."""
|
|
_, revision = _parse_manifest()
|
|
if not revision:
|
|
logger.warning(
|
|
"%s pins no whisper.cpp revision; falling back to %r. Downloads will "
|
|
"fail verification until it is regenerated with "
|
|
"scripts/generate-model-checksums.py.",
|
|
_MANIFEST_NAME,
|
|
_UNPINNED_REVISION,
|
|
)
|
|
return _UNPINNED_REVISION
|
|
return revision
|
|
|
|
|
|
def expected_for(filename: str) -> Optional[Expected]:
|
|
"""Return the pinned digest for a model file name, or None when unpinned."""
|
|
entries, _ = _parse_manifest()
|
|
return entries.get(os.path.basename(filename))
|
|
|
|
|
|
def write_verification_stamp(tree_path: str, archive_name: str) -> None:
|
|
"""Record inside ``tree_path`` the pinned digest of the archive it came from.
|
|
|
|
Only archives get a digest, so an extracted tree is trustworthy later only if
|
|
something writes down what was checked. ``install.sh`` re-downloads any VOSK
|
|
model whose stamp does not match the digest pinned today, which means a tree
|
|
left unstamped here — a first-run or Settings download — is refetched on the
|
|
next ``./install.sh``. That makes a failed write an error, not a warning.
|
|
"""
|
|
expected = expected_for(archive_name)
|
|
if expected is None:
|
|
raise ChecksumError(f"Cannot stamp {tree_path}: {archive_name} has no pinned digest")
|
|
stamp = os.path.join(tree_path, VERIFICATION_STAMP_NAME)
|
|
with open(stamp, "w", encoding="utf-8") as handle:
|
|
handle.write(f"{expected.digest}\n")
|
|
logger.debug("Recorded verified digest for %s in %s", archive_name, stamp)
|
|
|
|
|
|
def pinned_filenames() -> frozenset:
|
|
"""Every file name the manifest pins. Used by the coverage test."""
|
|
entries, _ = _parse_manifest()
|
|
return frozenset(entries)
|
|
|
|
|
|
def file_digest(path: str, algo: str) -> str:
|
|
"""Stream ``path`` through ``algo`` and return the lowercase hex digest."""
|
|
try:
|
|
digest = hashlib.new(algo)
|
|
except ValueError as exc:
|
|
raise ChecksumError(f"Unsupported checksum algorithm {algo!r}") from exc
|
|
|
|
with open(path, "rb") as handle:
|
|
for chunk in iter(lambda: handle.read(_CHUNK_SIZE), b""):
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def verify_file(path: str, expected: Expected, *, description: str = "") -> None:
|
|
"""Raise :class:`ChecksumError` unless ``path`` matches ``expected``.
|
|
|
|
The size is checked first: it is free, and a truncated download (the common
|
|
case) is then reported as a truncated download rather than as a hash
|
|
mismatch that reads like tampering.
|
|
"""
|
|
label = description or os.path.basename(path)
|
|
|
|
if expected.size:
|
|
actual_size = os.path.getsize(path)
|
|
if actual_size != expected.size:
|
|
raise ChecksumError(
|
|
f"{label} is {actual_size} bytes, expected {expected.size}. "
|
|
"The download was truncated or the file was replaced upstream."
|
|
)
|
|
|
|
actual = file_digest(path, expected.algo)
|
|
if actual != expected.digest:
|
|
raise ChecksumError(
|
|
f"{label} failed {expected.algo} verification.\n"
|
|
f" expected: {expected.digest}\n"
|
|
f" actual: {actual}\n"
|
|
"The file does not match the digest pinned in this release. Delete it "
|
|
"and retry; if it keeps failing, do not use it."
|
|
)
|
|
|
|
logger.info("%s verified (%s)", label, expected.algo)
|
|
|
|
|
|
def verify_model_file(path: str, filename: Optional[str] = None) -> None:
|
|
"""Verify a downloaded model against the manifest.
|
|
|
|
``filename`` overrides the lookup key when ``path`` is still a temporary
|
|
name such as ``ggml-tiny.bin.tmp``.
|
|
"""
|
|
key = filename or os.path.basename(path)
|
|
expected = expected_for(key)
|
|
if expected is None:
|
|
raise ChecksumError(
|
|
f"No checksum is pinned for {key}. Regenerate "
|
|
f"{_MANIFEST_NAME} with scripts/generate-model-checksums.py."
|
|
)
|
|
verify_file(path, expected, description=key)
|