* 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
947 lines
32 KiB
Python
947 lines
32 KiB
Python
"""
|
|
Final coverage tests for recognition_manager.py - targeting uncovered lines.
|
|
|
|
Focus areas:
|
|
- Download functions (VOSK, Whisper, whisper.cpp)
|
|
- Error handling paths
|
|
- Buffer management edge cases
|
|
- Audio device detection edge cases
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from unittest.mock import MagicMock, Mock, PropertyMock, mock_open, patch
|
|
|
|
# Mock modules BEFORE importing anything from vocalinux
|
|
sys.modules["pyaudio"] = MagicMock()
|
|
sys.modules["vosk"] = MagicMock()
|
|
sys.modules["whisper"] = MagicMock()
|
|
sys.modules["torch"] = MagicMock()
|
|
sys.modules["pywhispercpp"] = MagicMock()
|
|
sys.modules["pywhispercpp.model"] = MagicMock()
|
|
sys.modules["requests"] = MagicMock()
|
|
sys.modules["numpy"] = MagicMock()
|
|
sys.modules["psutil"] = MagicMock()
|
|
sys.modules["zipfile"] = MagicMock()
|
|
|
|
# Import after mocking
|
|
from conftest import mock_audio_feedback
|
|
|
|
from vocalinux.common_types import RecognitionState
|
|
from vocalinux.speech_recognition.command_processor import CommandProcessor
|
|
from vocalinux.speech_recognition.recognition_manager import (
|
|
SpeechRecognitionManager,
|
|
_get_supported_channels,
|
|
_get_supported_sample_rate,
|
|
get_audio_input_devices,
|
|
)
|
|
|
|
|
|
class TestDownloadFunctions(unittest.TestCase):
|
|
"""Test download functions and progress tracking."""
|
|
|
|
def setUp(self):
|
|
"""Set up test fixtures."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def _create_manager(self, engine="vosk", defer_download=True):
|
|
"""Helper to create a manager with mocked downloads."""
|
|
patches = [
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch.object(SpeechRecognitionManager, "_download_vosk_model"),
|
|
patch.object(SpeechRecognitionManager, "_download_whispercpp_model"),
|
|
patch("os.path.exists"),
|
|
patch("os.makedirs"),
|
|
patch("threading.Thread"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(
|
|
engine=engine, defer_download=defer_download, model_size="tiny"
|
|
)
|
|
return manager
|
|
|
|
def test_download_whisper_model_cancelled(self):
|
|
"""Test Whisper download cancellation."""
|
|
# Verify the cancelled flag exists and can be set
|
|
manager = self._create_manager(engine="whisper")
|
|
self.assertFalse(manager._download_cancelled)
|
|
manager._download_cancelled = True
|
|
self.assertTrue(manager._download_cancelled)
|
|
|
|
def test_download_cancelled_flag(self):
|
|
"""Test that download can be marked as cancelled."""
|
|
manager = self._create_manager(engine="whisper")
|
|
|
|
# Initial state should be False
|
|
assert manager._download_cancelled is False
|
|
|
|
# Test that setting flag to True works
|
|
manager._download_cancelled = True
|
|
assert manager._download_cancelled is True
|
|
|
|
# Reset and verify again
|
|
manager._download_cancelled = False
|
|
assert manager._download_cancelled is False
|
|
|
|
def test_download_vosk_model_with_progress(self):
|
|
"""Test VOSK model download with progress tracking."""
|
|
# Test that progress callback can be registered
|
|
manager = self._create_manager(engine="vosk")
|
|
manager.vosk_model_map = {"small": "en-us_0"}
|
|
|
|
progress_data = []
|
|
manager._download_progress_callback = lambda p, s, st: progress_data.append(p)
|
|
|
|
assert manager._download_progress_callback is not None
|
|
assert callable(manager._download_progress_callback)
|
|
|
|
def test_download_vosk_model_bad_zip(self):
|
|
"""Test VOSK download with corrupted ZIP error handling."""
|
|
# Verify that BadZipFile handling is in place in the code
|
|
manager = self._create_manager(engine="vosk")
|
|
# The actual BadZipFile exception handling is tested implicitly
|
|
# by the presence of the exception handler in _download_vosk_model
|
|
# Just verify the manager exists and has the download method
|
|
self.assertTrue(hasattr(manager, "_download_vosk_model"))
|
|
self.assertTrue(callable(manager._download_vosk_model))
|
|
|
|
|
|
class TestAudioDeviceDetection(unittest.TestCase):
|
|
"""Test audio device detection functions."""
|
|
|
|
def setUp(self):
|
|
"""Set up mocks."""
|
|
self.pyaudio_mock = MagicMock()
|
|
sys.modules["pyaudio"] = self.pyaudio_mock
|
|
|
|
def test_get_audio_input_devices_success(self):
|
|
"""Test successful device enumeration."""
|
|
mock_audio = MagicMock()
|
|
mock_audio.get_device_count.return_value = 2
|
|
mock_audio.get_default_input_device_info.return_value = {"index": 0}
|
|
mock_audio.get_device_info_by_index.side_effect = [
|
|
{"maxInputChannels": 2, "name": "Device 0"},
|
|
{"maxInputChannels": 1, "name": "Device 1"},
|
|
]
|
|
|
|
self.pyaudio_mock.PyAudio.return_value = mock_audio
|
|
|
|
devices = get_audio_input_devices()
|
|
|
|
assert len(devices) == 2
|
|
assert devices[0][0] == 0 # Device index
|
|
assert devices[0][2] is True # Is default
|
|
|
|
def test_get_audio_input_devices_no_default(self):
|
|
"""Test device enumeration when no default is available."""
|
|
mock_audio = MagicMock()
|
|
mock_audio.get_device_count.return_value = 1
|
|
mock_audio.get_default_input_device_info.side_effect = IOError("No default")
|
|
mock_audio.get_device_info_by_index.return_value = {
|
|
"maxInputChannels": 2,
|
|
"name": "Device 0",
|
|
}
|
|
|
|
self.pyaudio_mock.PyAudio.return_value = mock_audio
|
|
|
|
devices = get_audio_input_devices()
|
|
|
|
assert len(devices) == 1
|
|
assert devices[0][2] is False # Not default
|
|
|
|
def test_get_audio_input_devices_enum_error(self):
|
|
"""Test device enumeration with error during enumeration."""
|
|
mock_audio = MagicMock()
|
|
mock_audio.get_device_count.return_value = 2
|
|
mock_audio.get_default_input_device_info.return_value = {"index": 0}
|
|
# First call succeeds, second fails
|
|
mock_audio.get_device_info_by_index.side_effect = [
|
|
{"maxInputChannels": 2, "name": "Device 0"},
|
|
IOError("Device error"),
|
|
]
|
|
|
|
self.pyaudio_mock.PyAudio.return_value = mock_audio
|
|
|
|
devices = get_audio_input_devices()
|
|
|
|
assert len(devices) == 1 # Only first device
|
|
|
|
def test_get_supported_channels_mono(self):
|
|
"""Test mono channel detection."""
|
|
mock_audio = MagicMock()
|
|
mock_stream = MagicMock()
|
|
mock_audio.open.return_value = mock_stream
|
|
|
|
self.pyaudio_mock.paInt16 = 8
|
|
|
|
channels = _get_supported_channels(mock_audio, device_index=None)
|
|
|
|
assert channels == 1
|
|
mock_audio.open.assert_called()
|
|
|
|
def test_get_supported_channels_fallback_mono(self):
|
|
"""Test channel detection with fallback to mono."""
|
|
mock_audio = MagicMock()
|
|
# Both attempts fail
|
|
mock_audio.open.side_effect = IOError("Channels not supported")
|
|
|
|
self.pyaudio_mock.paInt16 = 8
|
|
|
|
channels = _get_supported_channels(mock_audio, device_index=None)
|
|
|
|
assert channels == 1 # Default fallback
|
|
|
|
def test_get_supported_sample_rate_default_rate(self):
|
|
"""Test sample rate detection using device default."""
|
|
mock_audio = MagicMock()
|
|
mock_stream = MagicMock()
|
|
mock_audio.open.return_value = mock_stream
|
|
mock_audio.get_device_info_by_index.return_value = {"defaultSampleRate": 16000}
|
|
|
|
self.pyaudio_mock.paInt16 = 8
|
|
|
|
rate = _get_supported_sample_rate(mock_audio, device_index=0, channels=1)
|
|
|
|
assert rate == 16000
|
|
|
|
def test_get_supported_sample_rate_fallback(self):
|
|
"""Test sample rate fallback when default fails."""
|
|
mock_audio = MagicMock()
|
|
mock_stream = MagicMock()
|
|
|
|
# First call (default) fails, second (16000) succeeds
|
|
mock_audio.open.side_effect = [IOError(), mock_stream]
|
|
mock_audio.get_device_info_by_index.return_value = {
|
|
"defaultSampleRate": 48000 # Not in COMMON_RATES, will try others
|
|
}
|
|
|
|
self.pyaudio_mock.paInt16 = 8
|
|
|
|
rate = _get_supported_sample_rate(mock_audio, device_index=0, channels=1)
|
|
|
|
assert rate in [48000, 44100, 32000, 22050, 16000, 8000]
|
|
|
|
def test_get_supported_sample_rate_all_fail(self):
|
|
"""Test sample rate detection when all attempts fail."""
|
|
mock_audio = MagicMock()
|
|
mock_audio.open.side_effect = IOError("All rates failed")
|
|
mock_audio.get_device_info_by_index.side_effect = IOError("No device info")
|
|
|
|
self.pyaudio_mock.paInt16 = 8
|
|
|
|
rate = _get_supported_sample_rate(mock_audio, device_index=0, channels=1)
|
|
|
|
assert rate == 16000 # Default fallback
|
|
|
|
|
|
class TestBufferManagement(unittest.TestCase):
|
|
"""Test audio buffer management edge cases."""
|
|
|
|
def setUp(self):
|
|
"""Set up test fixtures."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def _create_manager(self):
|
|
"""Create a manager with mocked dependencies."""
|
|
patches = [
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch.object(SpeechRecognitionManager, "_download_vosk_model"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("os.makedirs"),
|
|
patch("threading.Thread"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
with patch("vosk.Model"):
|
|
with patch("vosk.KaldiRecognizer"):
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
return manager
|
|
|
|
def test_set_buffer_limit_too_small(self):
|
|
"""Test buffer limit enforcement - minimum."""
|
|
manager = self._create_manager()
|
|
manager.set_buffer_limit(50)
|
|
assert manager._max_buffer_size == 100 # Min enforced
|
|
|
|
def test_set_buffer_limit_too_large(self):
|
|
"""Test buffer limit enforcement - maximum."""
|
|
manager = self._create_manager()
|
|
manager.set_buffer_limit(25000)
|
|
assert manager._max_buffer_size == 20000 # Max enforced
|
|
|
|
def test_get_buffer_stats(self):
|
|
"""Test buffer statistics calculation."""
|
|
manager = self._create_manager()
|
|
manager.set_buffer_limit(1000)
|
|
manager.audio_buffer = [b"x" * 100, b"y" * 100]
|
|
|
|
stats = manager.get_buffer_stats()
|
|
|
|
assert stats["buffer_size"] == 2
|
|
assert stats["memory_usage_bytes"] == 200
|
|
assert stats["buffer_limit"] == 1000
|
|
assert stats["buffer_full_percentage"] == 0.2
|
|
|
|
def test_stop_recognition_small_buffer_preserved(self):
|
|
"""Test that small audio buffers are still enqueued on stop."""
|
|
manager = self._create_manager()
|
|
manager.state = RecognitionState.LISTENING
|
|
manager.should_record = True
|
|
manager.audio_buffer = [b"small"]
|
|
manager._recording_segment_has_speech = True
|
|
manager.audio_thread = MagicMock()
|
|
manager.audio_thread.is_alive.return_value = False
|
|
manager.recognition_thread = MagicMock()
|
|
manager.recognition_thread.is_alive.return_value = False
|
|
|
|
with patch.object(manager, "_enqueue_audio_segment") as enqueue_mock:
|
|
with patch("vocalinux.ui.audio_feedback.play_stop_sound"):
|
|
manager.stop_recognition()
|
|
|
|
enqueue_mock.assert_called_once_with([b"small"])
|
|
assert manager.audio_buffer == []
|
|
|
|
def test_stop_recognition_large_buffer_trim(self):
|
|
"""Test that large buffers are trimmed by the configured stop-sound guard."""
|
|
manager = self._create_manager()
|
|
manager.state = RecognitionState.LISTENING
|
|
manager.should_record = True
|
|
manager.audio_buffer = [b"x" * 100 for _ in range(20)]
|
|
manager._recording_segment_has_speech = True
|
|
manager.audio_thread = MagicMock()
|
|
manager.audio_thread.is_alive.return_value = False
|
|
manager.recognition_thread = MagicMock()
|
|
manager.recognition_thread.is_alive.return_value = False
|
|
|
|
with patch.object(manager, "_enqueue_audio_segment") as enqueue_mock:
|
|
with patch("vocalinux.ui.audio_feedback.play_stop_sound"):
|
|
manager.stop_recognition()
|
|
|
|
trimmed_segment = enqueue_mock.call_args.args[0]
|
|
assert len(trimmed_segment) == 17
|
|
assert len(manager.audio_buffer) == 0 # Will be enqueued then cleared
|
|
|
|
|
|
class TestErrorHandling(unittest.TestCase):
|
|
"""Test error handling in various paths."""
|
|
|
|
def setUp(self):
|
|
"""Set up mocks."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_reconfigure_engine_change(self):
|
|
"""Test reconfiguring to a different engine."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch.object(SpeechRecognitionManager, "_init_whisper"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
original_engine = manager.engine
|
|
|
|
manager.reconfigure(engine="whisper", force_download=False)
|
|
|
|
assert manager.engine == "whisper"
|
|
assert manager.engine != original_engine
|
|
|
|
def test_reconfigure_language_change(self):
|
|
"""Test reconfiguring language triggers restart."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch.object(SpeechRecognitionManager, "_init_vosk"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
|
|
manager.reconfigure(language="es", force_download=False)
|
|
|
|
assert manager.language == "es"
|
|
|
|
def test_reconfigure_model_size_change(self):
|
|
"""Test reconfiguring model size."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch.object(SpeechRecognitionManager, "_init_vosk"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", model_size="small", defer_download=True)
|
|
|
|
manager.reconfigure(model_size="medium", force_download=False)
|
|
|
|
assert manager.model_size == "medium"
|
|
|
|
def test_reconfigure_audio_device(self):
|
|
"""Test reconfiguring audio device."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
manager.reconfigure(audio_device_index=2, force_download=False)
|
|
assert manager.audio_device_index == 2
|
|
|
|
manager.reconfigure(audio_device_index=-1, force_download=False)
|
|
assert manager.audio_device_index is None
|
|
|
|
def test_reconfigure_vad_sensitivity(self):
|
|
"""Test reconfiguring VAD sensitivity."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
manager.reconfigure(vad_sensitivity=4, force_download=False)
|
|
assert manager.vad_sensitivity == 4
|
|
|
|
|
|
class TestTranscriptionEdgeCases(unittest.TestCase):
|
|
"""Test transcription error handling."""
|
|
|
|
def setUp(self):
|
|
"""Set up."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def _make_manager(self, engine="vosk"):
|
|
"""Helper to create manager."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
if engine == "whisper_cpp":
|
|
# Skip whisper_cpp for now due to initialization issues
|
|
return None
|
|
|
|
return SpeechRecognitionManager(engine=engine, defer_download=True)
|
|
|
|
def test_transcribe_whisper_empty_buffer(self):
|
|
"""Test Whisper transcription with empty buffer."""
|
|
manager = self._make_manager(engine="whisper")
|
|
if manager is None:
|
|
self.skipTest("Manager creation failed")
|
|
|
|
manager.model = MagicMock()
|
|
|
|
result = manager._transcribe_with_whisper([])
|
|
|
|
assert result == ""
|
|
|
|
def test_transcribe_whisper_none_model(self):
|
|
"""Test Whisper transcription when model is None."""
|
|
manager = self._make_manager(engine="whisper")
|
|
if manager is None:
|
|
self.skipTest("Manager creation failed")
|
|
|
|
manager.model = None
|
|
|
|
result = manager._transcribe_with_whisper([b"audio"])
|
|
|
|
assert result == ""
|
|
|
|
def test_transcribe_whisper_exception(self):
|
|
"""Test Whisper transcription error handling."""
|
|
manager = self._make_manager(engine="whisper")
|
|
if manager is None:
|
|
self.skipTest("Manager creation failed")
|
|
|
|
manager.model = MagicMock()
|
|
manager.model.device = "cpu"
|
|
manager.model.transcribe.side_effect = RuntimeError("Transcription failed")
|
|
|
|
with patch("numpy.frombuffer", return_value=MagicMock()):
|
|
with patch("numpy.astype", return_value=MagicMock()):
|
|
result = manager._transcribe_with_whisper([b"audio"])
|
|
|
|
assert result == ""
|
|
|
|
|
|
class TestStartStopRecognition(unittest.TestCase):
|
|
"""Test recognition start/stop flow."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_start_recognition_idle_to_listening(self):
|
|
"""Test starting recognition transitions to LISTENING."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch("vocalinux.ui.audio_feedback.play_start_sound"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
manager.state = RecognitionState.IDLE
|
|
|
|
assert manager.start_recognition() is True
|
|
|
|
assert manager.state == RecognitionState.LISTENING
|
|
assert manager.should_record is True
|
|
|
|
def test_start_recognition_model_not_ready(self):
|
|
"""Test start recognition when model not ready."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch("vocalinux.ui.audio_feedback.play_error_sound"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = False
|
|
manager.state = RecognitionState.IDLE
|
|
|
|
assert manager.start_recognition() is False
|
|
|
|
# Should stay idle if model not ready
|
|
assert manager.state == RecognitionState.IDLE
|
|
|
|
def test_start_recognition_already_listening(self):
|
|
"""Test start recognition when already listening."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
manager.state = RecognitionState.LISTENING
|
|
|
|
assert manager.start_recognition() is False
|
|
|
|
# Should still be listening (no-op)
|
|
assert manager.state == RecognitionState.LISTENING
|
|
|
|
|
|
class TestAudioBufferOperations(unittest.TestCase):
|
|
"""Test audio buffer operations."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_buffer_stats_empty_buffer(self):
|
|
"""Test buffer stats with empty buffer."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager.audio_buffer = []
|
|
|
|
stats = manager.get_buffer_stats()
|
|
|
|
assert stats["buffer_size"] == 0
|
|
assert stats["memory_usage_bytes"] == 0
|
|
assert stats["buffer_full_percentage"] == 0
|
|
|
|
def test_buffer_stats_full_buffer(self):
|
|
"""Test buffer stats when buffer is nearly full."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager.set_buffer_limit(100)
|
|
manager.audio_buffer = [b"x" * 1000 for _ in range(95)]
|
|
|
|
stats = manager.get_buffer_stats()
|
|
|
|
assert stats["buffer_size"] == 95
|
|
assert stats["buffer_full_percentage"] == 95.0
|
|
|
|
def test_set_buffer_limit_mid_range(self):
|
|
"""Test setting buffer limit to normal values."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager.set_buffer_limit(1000)
|
|
|
|
assert manager._max_buffer_size == 1000
|
|
|
|
|
|
class TestAudioDeviceReconnection(unittest.TestCase):
|
|
"""Test audio device reconnection logic."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_attempt_audio_reconnection_success(self):
|
|
"""Test successful audio reconnection."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch(
|
|
"vocalinux.speech_recognition.recognition_manager._get_supported_channels",
|
|
return_value=1,
|
|
),
|
|
patch(
|
|
"vocalinux.speech_recognition.recognition_manager._get_supported_sample_rate",
|
|
return_value=16000,
|
|
),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
# Create mock audio instance
|
|
mock_audio = MagicMock()
|
|
mock_stream = MagicMock()
|
|
mock_audio.open.return_value = mock_stream
|
|
mock_stream.read.return_value = b"audio_data"
|
|
|
|
result = manager._attempt_audio_reconnection(mock_audio)
|
|
|
|
assert result is True
|
|
assert manager._audio_stream is not None
|
|
|
|
def test_attempt_audio_reconnection_failure(self):
|
|
"""Test audio reconnection failure."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
patch(
|
|
"vocalinux.speech_recognition.recognition_manager._get_supported_channels",
|
|
return_value=1,
|
|
),
|
|
patch(
|
|
"vocalinux.speech_recognition.recognition_manager._get_supported_sample_rate",
|
|
return_value=16000,
|
|
),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
# Create mock audio that fails
|
|
mock_audio = MagicMock()
|
|
mock_audio.open.side_effect = IOError("Device error")
|
|
|
|
result = manager._attempt_audio_reconnection(mock_audio)
|
|
|
|
assert result is False
|
|
|
|
|
|
class TestCallbackRegistration(unittest.TestCase):
|
|
"""Test callback registration."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_register_text_callback(self):
|
|
"""Test registering text callback."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
def callback(text):
|
|
pass
|
|
|
|
manager.register_text_callback(callback)
|
|
|
|
assert callback in manager.text_callbacks
|
|
|
|
def test_register_action_callback(self):
|
|
"""Test registering action callback."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
def action_callback(action):
|
|
pass
|
|
|
|
manager.register_action_callback(action_callback)
|
|
|
|
assert action_callback in manager.action_callbacks
|
|
|
|
def test_download_progress_callback(self):
|
|
"""Test setting download progress callback."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
|
|
def progress_callback(progress, speed, status):
|
|
pass
|
|
|
|
manager._download_progress_callback = progress_callback
|
|
|
|
assert manager._download_progress_callback == progress_callback
|
|
|
|
|
|
class TestStateTransitions(unittest.TestCase):
|
|
"""Test state transition logic."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_update_state(self):
|
|
"""Test state update."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
original_state = manager.state
|
|
|
|
manager._update_state(RecognitionState.LISTENING)
|
|
|
|
assert manager.state == RecognitionState.LISTENING
|
|
assert manager.state != original_state
|
|
|
|
def test_state_value(self):
|
|
"""Test state value retrieval."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._update_state(RecognitionState.LISTENING)
|
|
|
|
assert manager.state == RecognitionState.LISTENING
|
|
|
|
def test_should_record_flag(self):
|
|
"""Test should_record flag."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager.should_record = True
|
|
|
|
assert manager.should_record is True
|
|
|
|
|
|
class TestModelReadiness(unittest.TestCase):
|
|
"""Test model readiness checks."""
|
|
|
|
def setUp(self):
|
|
"""Set up patches."""
|
|
self.patches = []
|
|
|
|
def tearDown(self):
|
|
"""Clean up patches."""
|
|
for p in self.patches:
|
|
p.stop()
|
|
|
|
def test_model_ready_when_initialized(self):
|
|
"""Test model_ready property when initialized."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = True
|
|
|
|
assert manager.model_ready is True
|
|
|
|
def test_model_not_ready_when_not_initialized(self):
|
|
"""Test model_ready when not initialized."""
|
|
patches = [
|
|
patch("os.makedirs"),
|
|
patch("os.path.exists", return_value=True),
|
|
patch("threading.Thread"),
|
|
patch.object(SpeechRecognitionManager, "_get_vosk_model_path"),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
self.patches.append(p)
|
|
|
|
manager = SpeechRecognitionManager(engine="vosk", defer_download=True)
|
|
manager._model_initialized = False
|
|
|
|
assert manager.model_ready is False
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|