diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3242d23..4953673 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,9 +46,9 @@ Actions включены для репозитория. До первого ус ## Изолированная macOS beta -Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b1`). +Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b2`). Метаданные пакета и macOS bundle берут версию оттуда; CFBundleShortVersionString -содержит `0.3.0`, CFBundleVersion — `0.3.0.1`. +содержит `0.3.0`, CFBundleVersion — `0.3.0.2`. ```bash # В собственной .venv; не менять venv работающей установки. diff --git a/docs/README.md b/docs/README.md index 3a577d5..4016ce9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,6 +2,8 @@ - [Тестирование macOS beta](beta-testing.md) - [План: облачный API, наш сервер, локальные модели](roadmap.md) +- [Экспериментальный GigaAM: установка и замеры](gigaam-development.md) +- [Исследование каталога моделей — заготовка issue](issues/model-catalog-research.md) - [Разработка и проверка](../CONTRIBUTING.md) - [Архитектура текущего приложения](../ARCHITECTURE.md) - [Сборка Windows](../BUILD_WINDOWS.md) diff --git a/docs/beta-testing.md b/docs/beta-testing.md index 50121d1..8e396b9 100644 --- a/docs/beta-testing.md +++ b/docs/beta-testing.md @@ -46,6 +46,35 @@ Windows-совместимость проверена unit-тестами, на требует отдельной проверки. Base — компактный вариант для запуска, не победитель сравнения качества. GigaAM сравним отдельно на тех же записях с эталоном человека. +## Экспериментальный GigaAM + +В списке моделей добавлены GigaAM v3 E2E CTC и Multilingual Large CTC. +Веса скачиваются в приложении, runtime пока устанавливается отдельно. +На тестовом Mac он уже установлен в профиле беты. Это CPU-эксперимент: +каждая обработка заново загружает модель; выигрыш в скорости не обещается. +Инструкция и проверенные замеры — [GigaAM для разработки](gigaam-development.md). + +## История диктовок и папка аудио + +В «Настройки → Статистика» выберите строку: «Копировать полный текст» копирует +итоговый текст после обработки, «Открыть папку аудио» открывает каталог записи. +В строке отдельно показаны длительность аудио, время обработки и стоимость. +Время обработки измеряется от остановки записи до готового итогового текста, +включая подготовку аудио и постобработку; ожидание вставки в него не входит. +Локальная модель показывает нулевую API-стоимость, а время остаётся измеряемым. +Старым строкам без измерений соответствует «—»; полный текст из короткого +предпросмотра не восстанавливается. + +В «Общие → Папка аудио» можно выбрать каталог новых записей. Старые записи +автоматически не перемещаются. Папка содержит сессии с аудио, расшифровкой +и данными восстановления; прежние каталоги продолжают использоваться для +поиска незавершённых сессий. Правила срока хранения действуют и в новом каталоге. +Если файл уже удалён, статистика сообщит, что аудио отсутствует. + +Проверка: сделать короткую диктовку, обновить статистику, сравнить скопированный +текст со вставленным, открыть папку; выбрать другой каталог и повторить. +Проверить, что новые файлы появились там, а старые остались на месте. + ## Сборка разработчиком ```bash diff --git a/docs/gigaam-development.md b/docs/gigaam-development.md new file mode 100644 index 0000000..0a1bae0 --- /dev/null +++ b/docs/gigaam-development.md @@ -0,0 +1,102 @@ +# Экспериментальный GigaAM runtime для macOS arm64 + +Реализованы GigaAM v3 E2E **CTC** и Multilingual Large CTC. PyTorch запускается +отдельным процессом; в основной venv и `.app` он не устанавливается. Это +экспериментальный backend с отдельным шагом установки, а не автоматический +загрузчик runtime внутри приложения. Веса скачиваются через обычный UI. + +## Установка для разработки и теста + +Требуются Python 3.12 arm64 и git. Запускать из checkout: + +```bash +./scripts/install_gigaam_runtime.sh +``` + +По умолчанию runtime создаётся в `~/.dictate-beta/runtimes/gigaam`. +Существующая папка никогда не перезаписывается. При другом профиле: + +```bash +VOICE_DICTATION_HOME=/absolute/profile ./scripts/install_gigaam_runtime.sh +``` + +Для явно выбранного альтернативного runtime можно задать +`VOICE_GIGAAM_PYTHON=/absolute/runtime/bin/python3`. Интерпретатор должен быть +отдельным от интерпретатора приложения. Скрипт устанавливает обычный пакет, +а не editable-ссылку; `/tmp` в рабочем runtime не требуется. + +После установки открыть вкладку распознавания новой beta, выбрать GigaAM, +скачать веса, затем сохранить выбор. Без найденного runtime UI не сохраняет +GigaAM как активную модель. Наличие Python-файла ещё не доказывает исправность +зависимостей: ошибка worker показывается как ошибка GigaAM, облачного fallback нет. + +## Пины и лицензия + +Официальный [upstream](https://github.com/salute-developers/GigaAM) закреплён на +`7447938d791c4f3e643386ee22c33777004293a5`. Код опубликован под +[MIT](https://github.com/salute-developers/GigaAM/blob/7447938d791c4f3e643386ee22c33777004293a5/LICENSE); +в README upstream также отмечен переход семейства на MIT. Веса берутся с +официального CDN, указанного в `gigaam/__init__.py` этого commit. + +[Каталог приложения](../src/voice_dictation/core/model_manager.py) содержит +проверенные размеры и SHA256. SHA256 вычислены после полного скачивания; +MD5 checkpoint дополнительно совпал с официальным `_MODEL_HASHES`: + +| Модель | Размер checkpoint | Официальный MD5 | +|---|---:|---| +| v3_e2e_ctc | 442 404 646 B | `367074d6498f426d960b25f49531cf68` | +| multilingual_large_ctc | 2 341 654 513 B | `79a9adde50dd7f35bbf70927cb6557d0` | + +Для v3 дополнительно нужен tokenizer 240 941 B. Он является скрытой зависимостью +каталога: без проверенного tokenizer модель не считается установленной, а +lease распознавания блокирует его удаление. Изменение CDN-файла приведёт к +ошибке SHA256, а не к автоматическому принятию новых весов. `torch.load` использует +upstream checkpoint format с pickle; поэтому проверка закреплённых весов до +загрузки обязательна. Произвольные checkpoint не являются поддержанным входом. + +## Контракт и ограничения + +- `GigaAMTranscriber` передаёт JSON через stdin отдельному Python с `-I`. +- Worker повторно проверяет SHA256, принимает PCM16 mono WAV 16 kHz и возвращает + JSON с текстом/длительностью. stdout отделён от диагностик upstream. +- Выбран только CPU. MPS и MLX не заявлены поддержанными или проверенными. +- Во время inference worker блокирует создание сетевых сокетов. Он не вызывает + upstream `load_model`/`transcribe_longform`, скачивание VAD или облачный API. +- Основной pipeline режет GigaAM на окна до 20 секунд с существующим + overlap/stitch и checkpoint сессии. Worker также ограничивает прямые длинные + вызовы окнами 20 секунд; этот аварийный путь без overlap может разрезать слово. +- Процесс и модель создаются заново для каждого вызова. Warm decode ниже не + является полной задержкой приложения. Persistent worker пока не реализован. +- Prompts и принудительный выбор языка не реализованы. v3 предназначен для + русского; multilingual использует собственный multilingual CTC словарь. +- Tokenizer остаётся небольшим общим cache-файлом после удаления основных весов. +- Runtime требует около 0.7 GB, веса вместе около 2.8 GB; дополнительно нужны + свободная RAM и место для временных файлов/системного swap. На 16 GB тест + большой модели прошёл, но это не гарантия для всех нагрузок и записей. + +## Проверено 20 октября 2026 + +Apple M1, 16 GB, macOS; Python 3.12 arm64, PyTorch/torchaudio 2.8.0. +Неперсональный WAV создан установленным голосом Milena через macOS `say`: +«Проверяем локальное распознавание речи. Сегодня мы тестируем голосовую диктовку +на русском языке». Длительность 5.9078125 s. Сеть внутри worker была заблокирована. + +| Модель | Полный worker wall | Загрузка/импорт/SHA | Первый decode | Повтор decode в той же модели | +|---|---:|---:|---:|---:| +| v3 E2E CTC, повторный процесс | 4.88 s | 3.31 s | 0.72 s | 0.53 s | +| Multilingual Large CTC | 18.14 s | 15.22 s | 1.13 s | 1.19 s | + +Самый первый v3 запуск до прогрева OS/package cache занял 15.70 s по внутреннему +worker timer. У v3 совпали слова и пунктуация; Large вернула те же слова в нижнем +регистре без пунктуации. Один TTS-пример проверяет работоспособность, а не качество +на реальной диктовке, шуме, длинных записях или превосходство над Whisper. + +## Связанные файлы + +- [Навигация](README.md) +- [Тестирование беты](beta-testing.md) + +- [Installer](../scripts/install_gigaam_runtime.sh) +- [Pinned runtime dependencies](../runtime/gigaam/requirements.txt) +- [Адаптер и worker](../src/voice_dictation/core/gigaam_transcriber.py) +- [Проверки границ worker](../tests/unit/test_gigaam_transcriber.py) diff --git a/docs/issues/model-catalog-research.md b/docs/issues/model-catalog-research.md new file mode 100644 index 0000000..85cc32c --- /dev/null +++ b/docs/issues/model-catalog-research.md @@ -0,0 +1,23 @@ +# Исследовать и сравнить локальные ASR-модели для выбора в приложении + +Статус: готово к созданию Forgejo issue; 2026-10-20 API и SSH недоступны. + +## Задача +Расширить выбор локальных моделей распознавания: пользователь скачивает модели внутри приложения, сравнивает их на своей задаче и выбирает подходящую. + +## Исследование +- Составить каталог моделей и движков помимо Whisper и GigaAM: русский язык, смешанная речь и технические термины. +- Для каждой фиксировать версию, лицензию, размер загрузки, RAM, поддержку macOS Apple Silicon/Windows и полностью автономный режим. +- В GigaAM отдельно сравнить v3 e2e и большую multilingual_large_ctc; не считать multilingual автоматически лучшей для русской диктовки. +- Сравнивать на одинаковых неперсональных записях: точность, пропуски, числа/даты, пунктуация, холодный и повторный запуск, время обработки и RTF. +- Проверить постоянный runtime/загрузку модели один раз и аппаратное ускорение. + +## Результат +Обоснованный shortlist и дальнейшие задачи интеграции: выбор движка/модели, скачивание с проверкой целостности и отменой, требования к устройству, удаление моделей. Метрики модели видны по каждой диктовке в статистике. Основная установленная версия приложения не меняется. + +Связанный текущий PR: #2. Исследование запрошено пользователем после расширения статистики и первого сравнения GigaAM. + +## Связанные документы + +- [Навигация](../README.md) +- [План](../roadmap.md) diff --git a/runtime/gigaam/requirements.txt b/runtime/gigaam/requirements.txt new file mode 100644 index 0000000..329a860 --- /dev/null +++ b/runtime/gigaam/requirements.txt @@ -0,0 +1,4 @@ +# Separate Python 3.12 arm64 venv ONLY; do not install into desktop/shared venv. +torch==2.8.0 +torchaudio==2.8.0 +gigaam @ git+https://github.com/salute-developers/GigaAM.git@7447938d791c4f3e643386ee22c33777004293a5 diff --git a/scripts/install_gigaam_runtime.sh b/scripts/install_gigaam_runtime.sh new file mode 100755 index 0000000..d25cf42 --- /dev/null +++ b/scripts/install_gigaam_runtime.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Explicit experimental setup. Never install PyTorch into the desktop app venv. +set -euo pipefail +GIGAAM_COMMIT="7447938d791c4f3e643386ee22c33777004293a5" +RUNTIME_ROOT="${1:-${VOICE_DICTATION_HOME:-$HOME/.dictate-beta}/runtimes/gigaam}" +PYTHON_BIN="${PYTHON_GIGAAM:-/Library/Frameworks/Python.framework/Versions/3.12/bin/python3}" +if [[ -e "${RUNTIME_ROOT}" ]]; then + echo "Runtime target already exists; refusing to overwrite: ${RUNTIME_ROOT}" >&2 + exit 1 +fi +"${PYTHON_BIN}" -c 'import platform,sys; assert sys.version_info[:2] == (3,12); assert platform.machine() == "arm64"' +"${PYTHON_BIN}" -m venv "${RUNTIME_ROOT}" +if [[ -n "${GIGAAM_SOURCE:-}" ]]; then + git clone --no-hardlinks "${GIGAAM_SOURCE}" "${RUNTIME_ROOT}/source" +else + git clone https://github.com/salute-developers/GigaAM.git "${RUNTIME_ROOT}/source" +fi +git -C "${RUNTIME_ROOT}/source" checkout --detach "${GIGAAM_COMMIT}" +[[ "$(git -C "${RUNTIME_ROOT}/source" rev-parse HEAD)" == "${GIGAAM_COMMIT}" ]] +"${RUNTIME_ROOT}/bin/python" -m pip install 'torch==2.8.0' 'torchaudio==2.8.0' "${RUNTIME_ROOT}/source" +"${RUNTIME_ROOT}/bin/python" -I -c 'import gigaam,torch,torchaudio; print("GigaAM isolated runtime installed; CPU available")' +echo "Runtime: ${RUNTIME_ROOT}/bin/python3" diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index e9af8e1..4df067f 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.3.0b1" +__version__ = "0.3.0b2" diff --git a/src/voice_dictation/core/config.py b/src/voice_dictation/core/config.py index 38485de..37ca340 100644 --- a/src/voice_dictation/core/config.py +++ b/src/voice_dictation/core/config.py @@ -120,6 +120,7 @@ class Config: vad_search_window_sec: float = 12.0 vad_min_silence_sec: float = 0.35 vad_noise_db: float = -35.0 + audio_storage_dir: str = "" audio_retention_days: int = 30 # Не включать в JSON-сериализацию diff --git a/src/voice_dictation/core/fx.py b/src/voice_dictation/core/fx.py index 3ce15a2..962c3b9 100644 --- a/src/voice_dictation/core/fx.py +++ b/src/voice_dictation/core/fx.py @@ -76,3 +76,9 @@ _singleton = UsdRubRate() def get_rate() -> Decimal | None: """Глобальный кэшируемый курс USD/RUB (singleton).""" return _singleton.get() + + +def get_cached_rate() -> Decimal | None: + """Return the last known rate without network access, even if expired.""" + with _singleton._lock: + return _singleton._rate diff --git a/src/voice_dictation/core/gigaam_transcriber.py b/src/voice_dictation/core/gigaam_transcriber.py new file mode 100644 index 0000000..98cfd53 --- /dev/null +++ b/src/voice_dictation/core/gigaam_transcriber.py @@ -0,0 +1,172 @@ +"""Experimental GigaAM worker isolated from the desktop application's dependencies.""" + +from __future__ import annotations + +import json +import math +import os +import subprocess +import sys +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 + +# Executed by the separate, pinned runtime interpreter, never by the app process. +# Upstream checkpoint loading reproduced from GigaAM/__init__.py at 7447938d. +# No load_model(): that API can implicitly download weights and tokenizers. +_WORKER = r""" +import contextlib, hashlib, json, socket, sys, time, wave +from pathlib import Path +request = json.loads(sys.stdin.read()) +started = time.monotonic() +def deny_network(*args, **kwargs): + raise RuntimeError("GigaAM inference cannot access the network") +with contextlib.redirect_stdout(sys.stderr): + import torch + from gigaam.model import GigaAMASR + socket.socket = deny_network + checkpoint_path = Path(request["checkpoint"]) + digest = hashlib.sha256() + with checkpoint_path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != request["sha256"]: + raise RuntimeError("Checkpoint integrity check failed") + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + cfg = checkpoint["cfg"] + cfg.encoder.flash_attn = False + if request.get("tokenizer"): + cfg.decoding.model_path = request["tokenizer"] + model = GigaAMASR(cfg) + model.load_state_dict(checkpoint["state_dict"]) + del checkpoint + device = request.get("device", "cpu") + if device not in ("cpu", "mps"): + raise RuntimeError("Unsupported device") + if device == "mps" and not torch.backends.mps.is_available(): + raise RuntimeError("MPS is unavailable") + model = model.eval().to(device) + loaded = time.monotonic() + inference_seconds = 0.0 + with wave.open(request["audio"], "rb") as audio: + if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 16000): + raise RuntimeError("Expected 16 kHz mono PCM16 WAV") + frames = audio.getnframes() + texts = [] + with torch.inference_mode(): + # Bounded windows avoid upstream's >25s VAD/pyannote download path. + # This experimental baseline can split a word at a 20s boundary. + while pcm := audio.readframes(20 * 16000): + wav = torch.frombuffer(bytearray(pcm), dtype=torch.int16).float() / 32768.0 + wav = wav.to(device).unsqueeze(0) + length = torch.tensor([wav.shape[-1]], device=device) + inference_started = time.monotonic() + encoded, encoded_len = model.forward(wav, length) + text = model._decode(encoded, encoded_len, length)[0][0] + inference_seconds += time.monotonic() - inference_started + texts.append(text) +result = {"text": " ".join(texts).strip(), "duration_sec": frames / 16000, + "device": device, "elapsed_sec": time.monotonic() - started, + "load_sec": loaded - started, "inference_sec": inference_seconds} +print(json.dumps(result, ensure_ascii=False)) +""" + + +def runtime_python() -> Path: + """Locate an explicitly installed optional runtime; never install implicitly.""" + from voice_dictation.core.paths import AppPaths + + configured = os.environ.get("VOICE_GIGAAM_PYTHON") + executable = ( + Path(configured).expanduser() + if configured + else (AppPaths.default().root / "runtimes" / "gigaam" / "bin" / "python3") + ) + if not executable.is_file() or not os.access(executable, os.X_OK): + raise TranscriptionError( + "GigaAM требует отдельный экспериментальный runtime. " + "Установите его по инструкции runtime/gigaam или задайте VOICE_GIGAAM_PYTHON. " + "Скачивание весов само по себе не устанавливает runtime." + ) + if executable.resolve() == Path(sys.executable).resolve(): + raise TranscriptionError("GigaAM должен запускаться в отдельном runtime") + return executable + + +class GigaAMTranscriber: + """Run verified GigaAM weights in a separate CPU worker without cloud fallback.""" + + def __init__(self, model_path: Path, model_id: str) -> None: + self._model_path = model_path + self._model_id = model_id + + def transcribe( + self, + audio_path: Path, + prompt: str = "", + language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, + ) -> TranscriptionResult: + """Recognize local PCM with fixed <=20 second windows and no remote VAD.""" + from voice_dictation.core.local_transcriber import LocalTranscriber + from voice_dictation.core.model_manager import ModelManager + + if not LocalTranscriber._is_pcm_wav(audio_path): + raise TranscriptionError("Экспериментальный GigaAM принимает PCM16 WAV 16 кГц mono") + spec = ModelManager._spec(self._model_id) + tokenizer = self._model_path.parent / "gigaam-v3-e2e-tokenizer.bin" + request = { + "checkpoint": str(self._model_path), + "sha256": spec.sha256, + "tokenizer": str(tokenizer) if spec.dependencies else None, + "audio": str(audio_path), + "device": "cpu", + } + requested_at = datetime.now(tz=UTC) + try: + result = subprocess.run( + [str(runtime_python()), "-I", "-c", _WORKER], + input=json.dumps(request), + text=True, + capture_output=True, + timeout=max(300, (duration_sec or 0) * 30 + 120), + check=False, + ) + if result.returncode: + # Upstream exceptions may include local paths; do not log raw stderr. + raise TranscriptionError( + "GigaAM worker завершился с ошибкой. Проверьте отдельный runtime и модель" + ) + payload = json.loads(result.stdout) + if not isinstance(payload, dict): + raise ValueError("Invalid worker response") + text = payload["text"] + duration = payload["duration_sec"] + if ( + not isinstance(text, str) + or not isinstance(duration, (float, int)) + or isinstance(duration, bool) + or not math.isfinite(duration) + or duration < 0 + ): + raise ValueError("Invalid worker response") + return TranscriptionResult( + text=text, + duration_sec=float(duration), + model=model or f"local:{self._model_id}", + language=language, + prompt_used=None, + requested_at=requested_at, + cost_usd=Decimal(0), + ) + except subprocess.TimeoutExpired as exc: + raise TranscriptionError("Превышено время локального распознавания GigaAM") from exc + except (OSError, ValueError, KeyError, TypeError) as exc: + raise TranscriptionError("Не удалось получить результат GigaAM worker") from exc + + def close(self) -> None: + """Worker resources are released when its process exits.""" diff --git a/src/voice_dictation/core/model_manager.py b/src/voice_dictation/core/model_manager.py index 1defb56..d8ba3f6 100644 --- a/src/voice_dictation/core/model_manager.py +++ b/src/voice_dictation/core/model_manager.py @@ -10,7 +10,7 @@ import sys import threading import time from collections.abc import Callable, Iterator -from contextlib import contextmanager, suppress +from contextlib import ExitStack, contextmanager, suppress from dataclasses import dataclass from pathlib import Path from typing import BinaryIO @@ -38,6 +38,8 @@ class ModelSpec: url: str size: int sha256: str + dependencies: tuple[str, ...] = () + selectable: bool = True @property def size_bytes(self) -> int: @@ -70,6 +72,30 @@ CATALOG: tuple[ModelSpec, ...] = ( 574041195, "394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2", ), + # Official source 7447938d, CDN checkpoint verified against upstream MD5. + ModelSpec( + "gigaam-v3-e2e-ctc", + "GigaAM v3 E2E CTC · 443 MB · эксперимент", + "https://cdn.chatwm.opensmodel.sberdevices.ru/GigaAM/v3_e2e_ctc.ckpt", + 442404646, + "73e27ec8f904e486ab063d5bb7c6ab701838b7e5a967ee79b71ccc5aefde146f", + dependencies=("gigaam-v3-e2e-tokenizer",), + ), + ModelSpec( + "gigaam-v3-e2e-tokenizer", + "GigaAM tokenizer", + "https://cdn.chatwm.opensmodel.sberdevices.ru/GigaAM/v3_e2e_ctc_tokenizer.model", + 240941, + "0b9a1960898fbfdf5424ab852ea17445eb3da960fba23e977ff100eb0054fbc8", + selectable=False, + ), + ModelSpec( + "gigaam-multilingual-large-ctc", + "GigaAM Multilingual Large CTC · 2.34 GB · эксперимент", + "https://cdn.chatwm.opensmodel.sberdevices.ru/GigaAM/multilingual_large_ctc.ckpt", + 2341654513, + "47626500d4d680d0483ad79ba578f1e35ca63cc9d203f06889b1ba76db2a9741", + ), ) @@ -98,7 +124,9 @@ class ModelManager: """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) + return self._valid(path, spec) and all( + self.is_installed(dependency) for dependency in spec.dependencies + ) @staticmethod def _valid(path: Path, spec: ModelSpec) -> bool: @@ -157,7 +185,10 @@ class ModelManager: 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): + with ExitStack() as leases: + spec = self._spec(model_id) + for identity in sorted((model_id, *spec.dependencies)): + leases.enter_context(self._lock(identity)) if not self.is_installed(model_id): raise ModelError("Модель не установлена или повреждена. Скачайте её в настройках") yield path @@ -168,6 +199,18 @@ class ModelManager: progress: Callable[[int, int], None] | None = None, cancel: threading.Event | None = None, stage: Callable[[str], None] | None = None, + ) -> Path: + """Install all verified support files before publishing the main model.""" + for dependency in self._spec(model_id).dependencies: + self.download(dependency, cancel=cancel, stage=stage) + return self._download_one(model_id, progress=progress, cancel=cancel, stage=stage) + + def _download_one( + self, + model_id: str, + progress: Callable[[int, int], None] | None = None, + cancel: threading.Event | None = None, + stage: Callable[[str], None] | None = None, ) -> Path: """Download on explicit request, verify fully, then atomically publish. diff --git a/src/voice_dictation/core/models.py b/src/voice_dictation/core/models.py index 6a8aeff..ae1b263 100644 --- a/src/voice_dictation/core/models.py +++ b/src/voice_dictation/core/models.py @@ -63,6 +63,9 @@ class UsageRecord: cost_usd: Decimal model: str text_preview: str + full_text: str = "" + processing_sec: float | None = None + audio_path: str = "" @dataclass(frozen=True, slots=True) diff --git a/src/voice_dictation/core/orchestrator.py b/src/voice_dictation/core/orchestrator.py index 21c0a84..b17fb5c 100644 --- a/src/voice_dictation/core/orchestrator.py +++ b/src/voice_dictation/core/orchestrator.py @@ -159,7 +159,18 @@ class DictationOrchestrator: config = self._config_provider() config = _config_from_dict(_config_to_dict(config)) self._recording_config = config - output_path = self._session_store.create() + try: + output_path = self._session_store.create( + Path(config.audio_storage_dir) if config.audio_storage_dir else None + ) + except OSError: + self._recording_config = None + logger.warning("Не удалось создать сессию в выбранном каталоге аудио") + self._notifier.show( + "Ошибка записи", "Каталог аудио недоступен. Проверьте настройки и права" + ) + self._sound_player.play(SoundKind.ERROR, config=config) + return self._session_store.update( output_path.parent, recording_config=_config_to_dict(config), @@ -182,6 +193,7 @@ class DictationOrchestrator: def _stop_recording(self) -> None: """Останавливает запись и запускает транскрипцию (вызывается внутри lock).""" + processing_started = time.monotonic() config = self._recording_config or self._config_provider() self._recording_config = None try: @@ -198,7 +210,9 @@ class DictationOrchestrator: self._session_store.mark_recorded(recording.path, recording.duration_sec) # Запрос к API — в отдельном потоке, не блокируем hotkey - self._current_future = self._executor.submit(self._process_recording, recording, config) + self._current_future = self._executor.submit( + self._process_recording, recording, config, processing_started=processing_started + ) def _process_recording( self, @@ -207,6 +221,7 @@ class DictationOrchestrator: *, finalize_state: bool = True, allow_auto_paste: bool = True, + processing_started: float | None = None, ) -> None: """Транскрибирует запись и вставляет текст (выполняется в worker-потоке). @@ -218,6 +233,8 @@ class DictationOrchestrator: recording: Результат записи. config: Текущая конфигурация. """ + if processing_started is None: + processing_started = time.monotonic() session_dir = recording.path.parent try: if config.transcription_backend not in {"local", "openai"}: @@ -228,6 +245,8 @@ class DictationOrchestrator: config, finalize_state=finalize_state, allow_auto_paste=allow_auto_paste, + processing_started=processing_started, + session_dir=session_dir, ) except (CompressionError, TranscriptionError) as exc: self._session_store.mark_failed(session_dir, str(exc)) @@ -336,8 +355,9 @@ class DictationOrchestrator: if local: from dataclasses import replace - config = replace(config, chunk_duration_sec=min(config.chunk_duration_sec, 60.0)) - identity = { + limit = 20.0 if config.local_model.startswith("gigaam-") else 60.0 + config = replace(config, chunk_duration_sec=min(config.chunk_duration_sec, limit)) + identity: dict[str, object] = { "engine": config.transcription_backend, "model": effective_model, "language": config.language, @@ -356,7 +376,15 @@ class DictationOrchestrator: if spec is None: raise TranscriptionError("Неизвестная локальная модель") identity["model_sha256"] = spec.sha256 - identity["runtime"] = "whisper.cpp-cli-json-v1" + if spec.dependencies: + identity["dependency_sha256"] = { + item.id: item.sha256 for item in CATALOG if item.id in spec.dependencies + } + identity["runtime"] = ( + "gigaam-worker-v1" + if config.local_model.startswith("gigaam-") + else "whisper.cpp-cli-json-v1" + ) previous = self._session_store.read(session_dir) old_identity = previous.get("transcription_identity") if old_identity is not None and old_identity != identity: @@ -546,6 +574,8 @@ class DictationOrchestrator: *, finalize_state: bool = True, allow_auto_paste: bool = True, + processing_started: float | None = None, + session_dir: Path | None = None, ) -> None: """Обрабатывает успешную транскрипцию. @@ -566,24 +596,6 @@ class DictationOrchestrator: len(result.text), ) - today_cost = None - if self._usage_db is not None: - try: - self._usage_db.insert( - UsageRecord( - id=None, - created_at=result.requested_at, - duration_sec=result.duration_sec, - cost_usd=result.cost_usd, - model=result.model, - text_preview=result.text[:80], - ) - ) - tz = datetime.now().astimezone().tzinfo - today_cost = self._usage_db.today_total(tz=tz).total_cost_usd - except Exception as exc: - logger.warning("Не удалось записать UsageRecord: %s", exc) - # Post-processing через активный пресет (если есть и не пустой) final_text = result.text active = self._resolve_active_preset(config) @@ -609,6 +621,42 @@ class DictationOrchestrator: ) final_text = result.text + processing_sec = ( + max(0.0, time.monotonic() - processing_started) + if processing_started is not None + else None + ) + audio_path = "" + if session_dir is not None: + for filename in ("source.ogg", "source.wav"): + candidate = session_dir / filename + if candidate.is_file(): + audio_path = str(candidate.resolve()) + break + self._session_store.save_final_output( + session_dir, final_text, processing_sec, audio_path + ) + today_cost = None + if self._usage_db is not None: + try: + self._usage_db.insert( + UsageRecord( + id=None, + created_at=result.requested_at, + duration_sec=result.duration_sec, + cost_usd=result.cost_usd, + model=result.model, + text_preview=final_text[:80], + full_text=final_text, + processing_sec=processing_sec, + audio_path=audio_path, + ) + ) + tz = datetime.now().astimezone().tzinfo + today_cost = self._usage_db.today_total(tz=tz).total_cost_usd + except Exception as exc: + logger.warning("Не удалось записать UsageRecord: %s", exc) + self._clipboard.copy(final_text) if config.notifications_enabled: diff --git a/src/voice_dictation/core/session_store.py b/src/voice_dictation/core/session_store.py index 57a3b5e..3d46e7e 100644 --- a/src/voice_dictation/core/session_store.py +++ b/src/voice_dictation/core/session_store.py @@ -4,6 +4,7 @@ from __future__ import annotations import json import logging +import re import shutil from datetime import UTC, datetime, timedelta from decimal import Decimal @@ -26,11 +27,20 @@ class SessionStore: self._sessions_dir = sessions_dir self._sessions_dir.mkdir(parents=True, exist_ok=True) - def create(self) -> Path: + def create(self, storage_dir: Path | None = None) -> Path: """Создаёт сессию и возвращает путь для потоковой записи WAV.""" now = datetime.now(tz=UTC) session_id = f"{now.strftime('%Y%m%dT%H%M%SZ')}_{uuid4().hex[:8]}" - session_dir = self._sessions_dir / session_id + root = storage_dir.expanduser().resolve() if storage_dir is not None else self._sessions_dir + root.mkdir(parents=True, exist_ok=True) + # Persist discovery separately from config so changing storage does not + # orphan pending sessions in an earlier location. + if root != self._sessions_dir.resolve(): + registry = self._sessions_dir / "storage-roots.json" + roots = self._roots() + roots.append(root) + self._write_json(registry, {"roots": sorted({str(item.resolve()) for item in roots})}) + session_dir = root / session_id session_dir.mkdir(parents=True) self.update( session_dir, @@ -133,10 +143,49 @@ class SessionStore: last_error=None, ) + def save_final_output( + self, session_dir: Path, text: str, processing_sec: float | None, audio_path: str + ) -> None: + """Persist the exact final clipboard text and measured processing metadata.""" + self._write_text(session_dir / "final.txt", text) + self.update( + session_dir, + final_text_file="final.txt", + processing_sec=processing_sec, + audio_path=audio_path, + ) + + def _roots(self) -> list[Path]: + registry = self._sessions_dir / "storage-roots.json" + roots = [self._sessions_dir] + if registry.exists(): + try: + payload = json.loads(registry.read_text(encoding="utf-8")) + if isinstance(payload, dict) and isinstance(payload.get("roots"), list): + roots.extend(Path(item) for item in payload["roots"] if isinstance(item, str)) + except (OSError, ValueError): + logger.warning("Не удалось прочитать индекс каталогов аудиосессий") + return roots + + def _session_directories(self) -> list[Path]: + directories: set[Path] = set() + for root in self._roots(): + try: + directories.update( + item.resolve() + for item in root.iterdir() + if item.is_dir() + and not item.is_symlink() + and re.fullmatch(r"\d{8}T\d{6}Z_[0-9a-f]{8}", item.name) + ) + except OSError: + logger.warning("Каталог аудиосессий временно недоступен") + return sorted(directories) + def pending(self) -> list[Path]: """Возвращает незавершённые сессии, для которых осталось аудио.""" pending: list[Path] = [] - for session_dir in sorted(self._sessions_dir.iterdir()): + for session_dir in self._session_directories(): if not session_dir.is_dir(): continue manifest = self.read(session_dir) @@ -152,7 +201,7 @@ class SessionStore: return 0 cutoff = datetime.now(tz=UTC) - timedelta(days=retention_days) removed = 0 - for session_dir in self._sessions_dir.iterdir(): + for session_dir in self._session_directories(): if not session_dir.is_dir(): continue manifest = self.read(session_dir) diff --git a/src/voice_dictation/core/transcription.py b/src/voice_dictation/core/transcription.py index d8f8338..9dac8c6 100644 --- a/src/voice_dictation/core/transcription.py +++ b/src/voice_dictation/core/transcription.py @@ -55,7 +55,12 @@ class RoutingTranscriber: model_id = model.removeprefix("local:") try: with manager.use(model_id) as model_path: - local_engine = LocalTranscriber(model_path) + if model_id.startswith("gigaam-"): + from voice_dictation.core.gigaam_transcriber import GigaAMTranscriber + + local_engine: Transcriber = GigaAMTranscriber(model_path, model_id) + else: + local_engine = LocalTranscriber(model_path) return local_engine.transcribe( audio_path, prompt, language, model, duration_sec ) diff --git a/src/voice_dictation/core/usage_db.py b/src/voice_dictation/core/usage_db.py index a8f0d20..590d949 100644 --- a/src/voice_dictation/core/usage_db.py +++ b/src/voice_dictation/core/usage_db.py @@ -16,7 +16,7 @@ from voice_dictation.core.models import UsageRecord logger = logging.getLogger(__name__) -_SCHEMA_VERSION = 1 +_SCHEMA_VERSION = 2 _SCHEMA_V1 = """ CREATE TABLE IF NOT EXISTS usage ( @@ -62,9 +62,16 @@ class UsageDB: def _ensure_schema(self) -> None: self._path.parent.mkdir(parents=True, exist_ok=True) with self._connect() as conn: + conn.execute("BEGIN IMMEDIATE") current = conn.execute("PRAGMA user_version").fetchone()[0] if current < 1: - conn.executescript(_SCHEMA_V1) + for statement in _SCHEMA_V1.split(";"): + if statement.strip(): + conn.execute(statement) + if current < 2: + conn.execute("ALTER TABLE usage ADD COLUMN full_text TEXT NOT NULL DEFAULT ''") + conn.execute("ALTER TABLE usage ADD COLUMN processing_sec REAL") + conn.execute("ALTER TABLE usage ADD COLUMN audio_path TEXT NOT NULL DEFAULT ''") conn.execute(f"PRAGMA user_version = {_SCHEMA_VERSION}") conn.commit() logger.debug("usage.db: схема инициализирована (v%d)", _SCHEMA_VERSION) @@ -89,14 +96,17 @@ class UsageDB: preview = record.text_preview[:80] with self._lock, self._connect() as conn: cursor = conn.execute( - "INSERT INTO usage(created_at, duration_sec, cost_usd, model, text_preview) " - "VALUES (?, ?, ?, ?, ?)", + "INSERT INTO usage(created_at, duration_sec, cost_usd, model, text_preview, " + "full_text, processing_sec, audio_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ( record.created_at.astimezone(UTC).isoformat(), record.duration_sec, str(record.cost_usd), record.model, preview, + record.full_text, + record.processing_sec, + record.audio_path, ), ) conn.commit() @@ -108,6 +118,9 @@ class UsageDB: cost_usd=record.cost_usd, model=record.model, text_preview=preview, + full_text=record.full_text, + processing_sec=record.processing_sec, + audio_path=record.audio_path, ) def today_total(self, tz: tzinfo | None = None) -> UsageStats: @@ -162,7 +175,8 @@ class UsageDB: """ with self._connect() as conn: rows = conn.execute( - "SELECT id, created_at, duration_sec, cost_usd, model, text_preview " + "SELECT id, created_at, duration_sec, cost_usd, model, text_preview, " + "full_text, processing_sec, audio_path " "FROM usage ORDER BY id DESC LIMIT ?", (limit,), ).fetchall() @@ -174,6 +188,9 @@ class UsageDB: cost_usd=Decimal(r[3]), model=r[4], text_preview=r[5], + full_text=r[6], + processing_sec=float(r[7]) if r[7] is not None else None, + audio_path=r[8], ) for r in rows ] diff --git a/src/voice_dictation/ui/recognition_tab.py b/src/voice_dictation/ui/recognition_tab.py index 1fcf09a..b9e4298 100644 --- a/src/voice_dictation/ui/recognition_tab.py +++ b/src/voice_dictation/ui/recognition_tab.py @@ -25,7 +25,7 @@ def build_recognition_tab( """Build controls; all widget updates stay on the Tk main thread.""" config = store.load() manager = ModelManager(paths.models_dir) - labels = {m.name: m.id for m in CATALOG} + labels = {m.name: m.id for m in CATALOG if m.selectable} initial_label = next( (k for k, v in labels.items() if v == config.local_model), next(iter(labels)) ) @@ -45,7 +45,7 @@ def build_recognition_tab( wraplength=620, ).pack(anchor="w", padx=12, pady=8) ctk.CTkLabel( - parent, text="Локальная модель (Whisper; только CPU/Metal, macOS arm64 beta):" + parent, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):" ).pack(anchor="w", padx=12) ctk.CTkOptionMenu(parent, values=list(labels), variable=selected, width=460).pack( anchor="w", padx=12, pady=6 @@ -102,7 +102,12 @@ def build_recognition_tab( stage=lambda name: events.put((stages[name], -2)), cancel=cancel, ) - events.put(("Модель скачана и проверена. Можно использовать.", 1)) + message = ( + "Веса GigaAM проверены. Для распознавания требуется отдельный runtime." + if model_id.startswith("gigaam-") + else "Модель скачана и проверена. Можно использовать." + ) + events.put((message, 1)) elif action == "delete": manager.delete(model_id) events.put(("Модель удалена.", 0)) @@ -199,6 +204,15 @@ def build_recognition_tab( cancel_button.pack(side="left") def save() -> None: + if backend.get() == "Локально" and labels[selected.get()].startswith("gigaam-"): + from voice_dictation.core.gigaam_transcriber import runtime_python + from voice_dictation.infrastructure.errors import TranscriptionError + + try: + runtime_python() + except TranscriptionError as exc: + toast(str(exc)) + return updated = replace( store.load(), transcription_backend="local" if backend.get() == "Локально" else "openai", diff --git a/src/voice_dictation/ui/settings_window.py b/src/voice_dictation/ui/settings_window.py index cc6888c..bcf5962 100644 --- a/src/voice_dictation/ui/settings_window.py +++ b/src/voice_dictation/ui/settings_window.py @@ -8,7 +8,7 @@ from collections.abc import Callable from dataclasses import replace from datetime import datetime from pathlib import Path -from tkinter import filedialog +from tkinter import filedialog, ttk from typing import TYPE_CHECKING import customtkinter as ctk @@ -331,12 +331,37 @@ class SettingsWindow: row=row, column=1, sticky="w", padx=8, pady=8 ) + row += 1 + ctk.CTkLabel(parent, text="Папка хранения аудио:").grid( + row=row, column=0, sticky="w", padx=8, pady=8 + ) + storage_var = ctk.StringVar(value=config.audio_storage_dir) + ctk.CTkEntry(parent, textvariable=storage_var, width=280).grid( + row=row, column=1, sticky="w", padx=8, pady=8 + ) + + def _choose_storage() -> None: + directory = filedialog.askdirectory(title="Папка хранения аудиозаписей") + if directory: + storage_var.set(directory) + + ctk.CTkButton(parent, text="Выбрать…", width=100, command=_choose_storage).grid( + row=row, column=2, padx=4 + ) + row += 1 + ctk.CTkLabel( + parent, + text="Пустое поле — стандартная папка. Изменение действует для новых записей; " + "старые файлы остаются на месте.", + wraplength=660, + justify="left", + ).grid(row=row, column=0, columnspan=3, sticky="w", padx=8) row += 1 def _save_general() -> None: language_choice = language_var.get() new_hotkey = hotkey_var.get().strip().lower() - current = self._config_store.current() + current = self._config_store.load() updated = replace( current, hotkey=new_hotkey, @@ -346,6 +371,7 @@ class SettingsWindow: show_cost_in_notification=cost_var.get(), auto_paste=auto_paste_var.get(), paste_delay_ms=int(delay_var.get()), + audio_storage_dir=storage_var.get().strip(), ) self._config_store.save(updated) if new_hotkey != current.hotkey: @@ -508,55 +534,128 @@ class SettingsWindow: ctk.CTkButton(controls, text="Импорт...", command=_open_file).pack(side="left", padx=4) def _build_stats_tab(self, parent: ctk.CTkFrame) -> None: - text_widget = ctk.CTkTextbox(parent, wrap="none") - text_widget.pack(fill="both", expand=True, padx=8, pady=8) + from voice_dictation.core.models import UsageRecord - def _refresh() -> None: - text_widget.configure(state="normal") - text_widget.delete("1.0", "end") + summary = ctk.CTkLabel(parent, text="", justify="left", anchor="w") + summary.pack(fill="x", padx=8, pady=8) + frame = ctk.CTkFrame(parent) + frame.pack(fill="both", expand=True, padx=8, pady=8) + columns = ("date", "model", "audio", "processing", "cost", "text") + table = ttk.Treeview(frame, columns=columns, show="headings", selectmode="browse") + headings = ("Дата", "Модель", "Аудио", "Обработка", "Стоимость", "Текст") + for column, heading, width in zip( + columns, headings, (100, 170, 65, 80, 90, 180), strict=True + ): + table.heading(column, text=heading) + table.column(column, width=width, minwidth=55, stretch=column == "text") + vertical = ttk.Scrollbar(frame, orient="vertical", command=table.yview) + horizontal = ttk.Scrollbar(frame, orient="horizontal", command=table.xview) + table.configure(yscrollcommand=vertical.set, xscrollcommand=horizontal.set) + table.grid(row=0, column=0, sticky="nsew") + vertical.grid(row=0, column=1, sticky="ns") + horizontal.grid(row=1, column=0, sticky="ew") + frame.grid_columnconfigure(0, weight=1) + frame.grid_rowconfigure(0, weight=1) + records: dict[str, UsageRecord] = {} + detail = ctk.CTkLabel(parent, text="Выберите запись", anchor="w", wraplength=740) + detail.pack(fill="x", padx=8) + controls = ctk.CTkFrame(parent, fg_color="transparent") + controls.pack(fill="x", padx=8, pady=8) + + def selected_record() -> UsageRecord | None: + selection = table.selection() + return records.get(selection[0]) if selection else None + + def update_selection(_event: object = None) -> None: + record = selected_record() + copy_button.configure(state="normal" if record and record.full_text else "disabled") + audio_button.configure(state="normal" if record and record.audio_path else "disabled") + if record is None: + detail.configure(text="Выберите запись") + else: + detail.configure( + text=("Полный текст сохранён" if record.full_text else "Полный текст: —") + + (" · Путь аудио сохранён" if record.audio_path else " · Путь аудио: —") + ) + + def copy_text() -> None: + record = selected_record() + if record and record.full_text and self._root is not None: + from voice_dictation.ui.stats_helpers import copy_saved_text + + try: + copy_saved_text(record.full_text) + except Exception: + self._toast("Не удалось скопировать текст") + return + self._toast("Полный текст скопирован") + + def open_audio() -> None: + record = selected_record() + if record is None or not record.audio_path: + return + path = Path(record.audio_path) + if not path.exists(): + self._toast("Аудиофайл отсутствует: возможно, истёк срок хранения") + return + try: + from voice_dictation.ui.stats_helpers import open_directory + + open_directory(path.parent) + except OSError: + self._toast("Не удалось открыть папку аудио") + + def refresh() -> None: tz = datetime.now().astimezone().tzinfo - today = self._usage_db.today_total(tz=tz) now = datetime.now(tz=tz) - month = self._usage_db.month_stats(now.year, now.month, tz=tz) - total = self._usage_db.all_time() - recent = self._usage_db.recent(limit=20) + totals = ( + ("Сегодня", self._usage_db.today_total(tz=tz)), + ("Месяц", self._usage_db.month_stats(now.year, now.month, tz=tz)), + ("Всего", self._usage_db.all_time()), + ) + from voice_dictation.core.fx import get_cached_rate, get_rate, usd_to_rub - from voice_dictation.core.fx import get_rate, usd_to_rub - - rate = get_rate() - - def _row(label: str, stats: object) -> str: - from voice_dictation.core.usage_db import UsageStats - - assert isinstance(stats, UsageStats) - mins = stats.total_duration_sec / 60 + local_mode = self._config_store.load().transcription_backend == "local" + rate = get_cached_rate() if local_mode else get_rate() + lines = [] + for label, stats in totals: rub = usd_to_rub(stats.total_cost_usd, rate) rub_part = f" ({rub:.2f} ₽)" if rub is not None else "" - return ( - f"{label:<12}{stats.count:>4} · {mins:6.1f} мин · " + lines.append( + f"{label}: {stats.count} записей · {stats.total_duration_sec / 60:.1f} мин · " f"${stats.total_cost_usd:.4f}{rub_part}" ) - - lines: list[str] = [ - _row("Сегодня:", today), - _row("Месяц:", month), - _row("Всего:", total), - "", - "Последние:", - ] - for r in recent: - ts = r.created_at.astimezone(tz).strftime("%m-%d %H:%M") + if local_mode: lines.append( - f" {ts} {r.duration_sec:5.1f}с ${r.cost_usd:7.4f} {r.text_preview}" + f"Курс: {rate} ₽/$ (из кэша)" + if rate is not None + else "Курс: — (локальный режим, без запроса в сеть)" ) + summary.configure(text="\n".join(lines)) + for item in table.get_children(): + table.delete(item) + records.clear() + from voice_dictation.ui.stats_helpers import record_values - text_widget.insert("1.0", "\n".join(lines)) - text_widget.configure(state="disabled") + for index, record in enumerate(self._usage_db.recent(limit=100)): + key = str(index) + records[key] = record + table.insert("", "end", iid=key, values=record_values(record, tz)) + update_selection() - controls = ctk.CTkFrame(parent, fg_color="transparent") - controls.pack(fill="x", padx=8, pady=(0, 8)) - ctk.CTkButton(controls, text="Обновить", command=_refresh).pack(side="left", padx=4) - _refresh() + ctk.CTkButton(controls, text="Обновить", width=110, command=refresh).pack( + side="left", padx=4 + ) + copy_button = ctk.CTkButton( + controls, text="Копировать полный текст", command=copy_text, state="disabled" + ) + copy_button.pack(side="left", padx=4) + audio_button = ctk.CTkButton( + controls, text="Открыть папку аудио", command=open_audio, state="disabled" + ) + audio_button.pack(side="left", padx=4) + table.bind("<>", update_selection) + refresh() def _build_balance_tab(self, parent: ctk.CTkFrame) -> None: info = ctk.CTkLabel( diff --git a/src/voice_dictation/ui/stats_helpers.py b/src/voice_dictation/ui/stats_helpers.py new file mode 100644 index 0000000..c76ff7c --- /dev/null +++ b/src/voice_dictation/ui/stats_helpers.py @@ -0,0 +1,47 @@ +"""Display and file-manager helpers for saved dictation records.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from datetime import tzinfo +from pathlib import Path + +from voice_dictation.core.models import UsageRecord + + +def record_values(record: UsageRecord, timezone: tzinfo | None) -> tuple[str, ...]: + """Format only known values; old records never acquire invented timings.""" + return ( + record.created_at.astimezone(timezone).strftime("%m-%d %H:%M"), + record.model or "—", + f"{record.duration_sec:.1f} с", + f"{record.processing_sec:.1f} с" if record.processing_sec is not None else "—", + f"${record.cost_usd:.4f}", + " ".join(record.text_preview.splitlines()), + ) + + +def open_directory(directory: Path) -> None: + """Open a directory using the operating system's file manager.""" + if sys.platform == "win32": + os.startfile(str(directory)) # type: ignore[attr-defined] + else: + subprocess.Popen(["open" if sys.platform == "darwin" else "xdg-open", str(directory)]) + + +def copy_saved_text(text: str) -> None: + """Use persistent native clipboard ownership, independent of the Tk window.""" + if sys.platform == "darwin": + from voice_dictation.platform.macos.clipboard import MacClipboard + + MacClipboard().copy(text) + elif sys.platform == "win32": + from voice_dictation.platform.windows.clipboard import WinClipboard + + WinClipboard().copy(text) + else: + import pyperclip + + pyperclip.copy(text) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 7581138..d03700a 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -159,3 +159,10 @@ def test_older_summary_toggle_migrates(tmp_path: Path) -> None: next(p for p in config.summary_presets if p.name == config.active_preset).model == "legacy-model" ) + + +def test_audio_storage_directory_persists(tmp_paths): + store = ConfigStore(tmp_paths.config_file) + config = Config(audio_storage_dir="/synthetic/external audio") + store.save(config) + assert ConfigStore(tmp_paths.config_file).load().audio_storage_dir == config.audio_storage_dir diff --git a/tests/unit/test_gigaam_transcriber.py b/tests/unit/test_gigaam_transcriber.py new file mode 100644 index 0000000..d086139 --- /dev/null +++ b/tests/unit/test_gigaam_transcriber.py @@ -0,0 +1,107 @@ +"""Optional GigaAM runtime boundaries; no model downloads or torch imports.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +import wave +from pathlib import Path + +import pytest + +from voice_dictation.core import gigaam_transcriber, model_manager +from voice_dictation.core.gigaam_transcriber import GigaAMTranscriber +from voice_dictation.core.model_manager import ModelError, ModelManager, ModelSpec +from voice_dictation.infrastructure.errors import TranscriptionError + + +@pytest.mark.parametrize( + "payload", + [ + [], + {"text": "x", "duration_sec": True}, + {"text": "x", "duration_sec": float("nan")}, + {"text": "x", "duration_sec": -1}, + {"text": None, "duration_sec": 1}, + ], +) +def test_invalid_worker_payload_rejected(tmp_path, monkeypatch, payload): + audio = tmp_path / "input.wav" + with wave.open(str(audio), "wb") as output: + output.setnchannels(1) + output.setsampwidth(2) + output.setframerate(16000) + output.writeframes(b"\x00\x00" * 16) + monkeypatch.setattr(gigaam_transcriber, "runtime_python", lambda: Path("/optional/python")) + monkeypatch.setattr( + gigaam_transcriber.subprocess, + "run", + lambda *a, **kw: subprocess.CompletedProcess(a, 0, json.dumps(payload), ""), + ) + engine = GigaAMTranscriber(tmp_path / "weights.bin", "gigaam-v3-e2e-ctc") + with pytest.raises(TranscriptionError): + engine.transcribe(audio) + + +def test_missing_optional_runtime_does_not_install_or_use_app_python(tmp_path, monkeypatch): + monkeypatch.setenv("VOICE_GIGAAM_PYTHON", str(tmp_path / "absent")) + with pytest.raises(TranscriptionError, match="отдельный"): + gigaam_transcriber.runtime_python() + + +def test_tokenizer_is_required_and_leased_with_weights(tmp_path, monkeypatch): + weights, tokenizer = b"weights", b"tokenizer" + specs = ( + ModelSpec( + "weights", + "Weights", + "https://example.invalid/weights", + len(weights), + hashlib.sha256(weights).hexdigest(), + dependencies=("tokenizer",), + ), + ModelSpec( + "tokenizer", + "Tokenizer", + "https://example.invalid/tokenizer", + len(tokenizer), + hashlib.sha256(tokenizer).hexdigest(), + selectable=False, + ), + ) + monkeypatch.setattr(model_manager, "CATALOG", specs) + manager = ModelManager(tmp_path) + manager.path_for("weights").write_bytes(weights) + assert not manager.is_installed("weights") + manager.path_for("tokenizer").write_bytes(tokenizer) + assert manager.is_installed("weights") + with manager.use("weights"), pytest.raises(ModelError, match="используется"): + manager.delete("tokenizer") + + +def test_support_file_downloaded_before_main_model(tmp_path, monkeypatch): + payloads = {"weights": b"weights", "tokenizer": b"tokenizer"} + specs = tuple( + ModelSpec( + name, + name, + "https://example.invalid/" + name, + len(data), + hashlib.sha256(data).hexdigest(), + dependencies=("tokenizer",) if name == "weights" else (), + ) + for name, data in payloads.items() + ) + monkeypatch.setattr(model_manager, "CATALOG", specs) + visited = [] + + async def fake_download(spec, partial, progress, cancel, notify): + visited.append(spec.id) + partial.write_bytes(payloads[spec.id]) + + monkeypatch.setattr(ModelManager, "_download_async", staticmethod(fake_download)) + manager = ModelManager(tmp_path) + manager.download("weights") + assert visited == ["tokenizer", "weights"] + assert manager.is_installed("weights") diff --git a/tests/unit/test_local_pipeline.py b/tests/unit/test_local_pipeline.py index bdeb997..255cdb9 100644 --- a/tests/unit/test_local_pipeline.py +++ b/tests/unit/test_local_pipeline.py @@ -174,3 +174,20 @@ def test_renamed_beta_bundle_still_cannot_use_production_profile(tmp_path, monke monkeypatch.setattr(sys, "executable", "/tmp/Renamed.app/Contents/MacOS/VoiceDictation") assert AppPaths.default().root == tmp_path / ".dictate-beta" assert AppPaths.default().pid_file != tmp_path / ".dictate/dictate.pid" + + +def test_gigaam_session_tracks_engine_and_bounded_windows(tmp_paths): + config = Config( + transcription_backend="local", local_model="gigaam-v3-e2e-ctc", paste_delay_ms=0 + ) + orchestrator = _make_orchestrator(tmp_paths, config=config) + orchestrator.toggle() + orchestrator.toggle() + _wait(orchestrator) + manifest = next(tmp_paths.sessions_dir.glob("*/manifest.json")) + identity = json.loads(manifest.read_text())["transcription_identity"] + assert identity["runtime"] == "gigaam-worker-v1" + assert "gigaam-v3-e2e-tokenizer" in identity["dependency_sha256"] + assert identity["chunk_duration_sec"] == 20.0 + assert identity["model"] == "local:gigaam-v3-e2e-ctc" + orchestrator.shutdown() diff --git a/tests/unit/test_orchestrator.py b/tests/unit/test_orchestrator.py index f251c71..0a60d75 100644 --- a/tests/unit/test_orchestrator.py +++ b/tests/unit/test_orchestrator.py @@ -336,3 +336,65 @@ def test_restart_resumes_from_saved_chunk_checkpoint(tmp_paths: AppPaths) -> Non assert len(resumed_transcriber.calls) == 2 assert clipboard.copy_calls[-1] == "раз два три четыре пять шесть семь" + + +def test_history_measures_stop_to_final_including_postprocess(tmp_paths, monkeypatch): + from datetime import UTC, datetime + from decimal import Decimal + + from voice_dictation.core.config import SummaryPreset + from voice_dictation.core.models import TranscriptionResult + from voice_dictation.core.usage_db import UsageDB + + config = Config( + notifications_enabled=False, + summary_presets=[SummaryPreset("test", "synthetic", "format")], + active_preset="test", + ) + orchestrator = _make_orchestrator(tmp_paths, config=config) + db = UsageDB(tmp_paths.usage_db) + orchestrator._usage_db = db + session = tmp_paths.sessions_dir / "synthetic" + session.mkdir() + (session / "source.ogg").write_bytes(b"synthetic") + result = TranscriptionResult("raw", 3.0, "fake", "ru", None, datetime.now(UTC), Decimal("0")) + clock = [10.0] + + def postprocess(text, preset): + clock[0] = 15.25 + return "Final text " * 100 + + monkeypatch.setattr(orchestrator, "_summarize", postprocess) + monkeypatch.setattr("voice_dictation.core.orchestrator.time.monotonic", lambda: clock[0]) + orchestrator._on_transcription_success( + result, config, processing_started=10.0, session_dir=session + ) + record = db.recent()[0] + assert record.full_text == "Final text " * 100 + assert record.processing_sec == 5.25 + assert record.audio_path == str((session / "source.ogg").resolve()) + assert (session / "final.txt").read_text() == record.full_text + orchestrator.shutdown() + + +def test_new_recording_uses_configured_storage(tmp_paths, tmp_path): + custom = tmp_path / "custom-audio" + orchestrator = _make_orchestrator(tmp_paths, config=Config(audio_storage_dir=str(custom))) + orchestrator.toggle() + assert list(custom.glob("*/manifest.json")) + assert not list(tmp_paths.sessions_dir.glob("*/manifest.json")) + orchestrator.cancel() + orchestrator.shutdown() + + +def test_unavailable_audio_directory_does_not_start_or_fallback(tmp_paths, tmp_path): + blocked = tmp_path / "not-a-directory" + blocked.write_text("synthetic") + recorder = FakeRecorder() + orchestrator = _make_orchestrator( + tmp_paths, recorder=recorder, config=Config(audio_storage_dir=str(blocked)) + ) + orchestrator.toggle() + assert orchestrator.state == RecordingState.IDLE + assert not list(tmp_paths.sessions_dir.glob("*/source.wav")) + orchestrator.shutdown() diff --git a/tests/unit/test_session_store.py b/tests/unit/test_session_store.py index 5056683..004befa 100644 --- a/tests/unit/test_session_store.py +++ b/tests/unit/test_session_store.py @@ -47,3 +47,49 @@ def test_interrupted_recording_is_pending_when_wav_exists(tmp_paths: AppPaths) - audio_path.write_bytes(b"RIFF interrupted audio") assert store.pending() == [audio_path.parent] + + +def test_custom_storage_retains_discovery_after_location_changes(tmp_path): + from voice_dictation.core.session_store import SessionStore + + default = tmp_path / "default" + custom = tmp_path / "external" + later = tmp_path / "later" + store = SessionStore(default) + old_audio = store.create() + old_audio.write_bytes(b"synthetic") + custom_audio = store.create(custom) + custom_audio.write_bytes(b"synthetic") + assert custom_audio.parent.parent == custom.resolve() + last_audio = store.create(later) + last_audio.write_bytes(b"synthetic") + recovered = SessionStore(default).pending() + assert set(recovered) == {old_audio.parent, custom_audio.parent, last_audio.parent} + + +def test_final_output_separate_from_raw_transcript(tmp_path): + from voice_dictation.core.session_store import SessionStore + + store = SessionStore(tmp_path) + audio = store.create() + store.complete(audio.parent, "raw", ()) + store.save_final_output(audio.parent, "processed", 1.2, str(audio)) + assert (audio.parent / "transcript.txt").read_text() == "raw" + assert (audio.parent / "final.txt").read_text() == "processed" + assert store.read(audio.parent)["processing_sec"] == 1.2 + + +def test_custom_storage_never_cleans_unrelated_directories(tmp_path): + import json + + store = SessionStore(tmp_path / "default") + custom = tmp_path / "custom" + store.create(custom) + unrelated = custom / "another-app" + unrelated.mkdir() + (unrelated / "source.wav").write_bytes(b"unrelated") + (unrelated / "manifest.json").write_text( + json.dumps({"status": "completed", "completed_at": "2000-01-01T00:00:00+00:00"}) + ) + assert store.cleanup_completed_audio(1) == 0 + assert (unrelated / "source.wav").read_bytes() == b"unrelated" diff --git a/tests/unit/test_stats_helpers.py b/tests/unit/test_stats_helpers.py new file mode 100644 index 0000000..5b71ff6 --- /dev/null +++ b/tests/unit/test_stats_helpers.py @@ -0,0 +1,56 @@ +"""Statistics preserve unknown legacy values and literal file paths.""" + +from datetime import UTC, datetime +from decimal import Decimal +from pathlib import Path +from unittest.mock import Mock + +import pytest + +from voice_dictation.core.models import UsageRecord +from voice_dictation.ui import stats_helpers + + +def test_legacy_processing_is_unknown() -> None: + record = UsageRecord(None, datetime.now(UTC), 12.5, Decimal("0.1"), "model", "line1\nline2") + values = stats_helpers.record_values(record, UTC) + assert values[2:] == ("12.5 с", "—", "$0.1000", "line1 line2") + + +def test_zero_processing_is_known() -> None: + record = UsageRecord( + None, datetime.now(UTC), 1, Decimal(0), "local:model", "", processing_sec=0 + ) + assert stats_helpers.record_values(record, UTC)[3] == "0.0 с" + + +@pytest.mark.parametrize("platform, command", [("darwin", "open"), ("linux", "xdg-open")]) +def test_directory_open_uses_literal_argument( + monkeypatch: pytest.MonkeyPatch, platform: str, command: str +) -> None: + launch = Mock() + monkeypatch.setattr(stats_helpers.sys, "platform", platform) + monkeypatch.setattr(stats_helpers.subprocess, "Popen", launch) + directory = Path("/tmp/audio folder;literal") + stats_helpers.open_directory(directory) + launch.assert_called_once_with([command, str(directory)]) + + +def test_copy_uses_native_persistent_clipboard(monkeypatch: pytest.MonkeyPatch) -> None: + from voice_dictation.platform.macos.clipboard import MacClipboard + + copy = Mock() + monkeypatch.setattr(stats_helpers.sys, "platform", "darwin") + monkeypatch.setattr(MacClipboard, "copy", copy) + stats_helpers.copy_saved_text("Полный текст") + copy.assert_called_once_with("Полный текст") + + +def test_cached_exchange_rate_never_fetches(monkeypatch: pytest.MonkeyPatch) -> None: + from voice_dictation.core import fx + + request = Mock(side_effect=AssertionError("No network")) + monkeypatch.setattr(fx.httpx, "get", request) + monkeypatch.setattr(fx._singleton, "_rate", Decimal("90.50")) + assert fx.get_cached_rate() == Decimal("90.50") + request.assert_not_called() diff --git a/tests/unit/test_usage_db.py b/tests/unit/test_usage_db.py index 4029b3d..07f7872 100644 --- a/tests/unit/test_usage_db.py +++ b/tests/unit/test_usage_db.py @@ -74,3 +74,48 @@ def test_month_stats_filters_correctly(tmp_paths: AppPaths) -> None: stats = db.month_stats(2026, 4, tz=UTC) assert stats.count == 1 assert stats.total_duration_sec == 10.0 + + +def test_v1_migration_retains_old_rows_and_unknown_processing(tmp_path): + import sqlite3 + + from voice_dictation.core.usage_db import _SCHEMA_V1 + + path = tmp_path / "legacy.db" + with sqlite3.connect(path) as connection: + connection.executescript(_SCHEMA_V1) + connection.execute("PRAGMA user_version = 1") + connection.execute( + "INSERT INTO usage(created_at, duration_sec, cost_usd, model, text_preview) " + "VALUES (?, ?, ?, ?, ?)", + (datetime.now(UTC).isoformat(), 5, "0.01", "legacy", "old snippet"), + ) + db = UsageDB(path) + old = db.recent()[0] + assert old.text_preview == "old snippet" + assert old.full_text == "" + assert old.processing_sec is None + assert old.audio_path == "" + assert UsageDB(path).recent() == [old] # repeat initialization is idempotent + with sqlite3.connect(path) as connection: + assert connection.execute("PRAGMA user_version").fetchone()[0] == 2 + + +def test_complete_history_record_roundtrips_untruncated(tmp_paths): + from dataclasses import replace + + db = UsageDB(tmp_paths.usage_db) + full_text = "Полный итоговый текст. " * 100 + record = replace( + _record(datetime.now(UTC)), + full_text=full_text, + text_preview=full_text, + processing_sec=2.75, + audio_path="/synthetic/session/source.ogg", + ) + inserted = db.insert(record) + assert inserted == db.recent()[0] + assert inserted.full_text == full_text + assert inserted.text_preview == full_text[:80] + assert inserted.processing_sec == 2.75 + assert inserted.audio_path == "/synthetic/session/source.ogg"