diff --git a/.forgejo/workflows/checks.yml b/.forgejo/workflows/checks.yml new file mode 100644 index 0000000..19f2076 --- /dev/null +++ b/.forgejo/workflows/checks.yml @@ -0,0 +1,22 @@ +name: Checks +on: + pull_request: + push: + branches: [main] +jobs: + checks: + # The CI image is built from ci/Dockerfile on OME. + runs-on: docker + container: + image: voice-dictation-ci:py313-node20-20261019 + timeout-minutes: 20 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + - name: Prepare Python 3.13 environment + run: | + python3 -c 'import sys; assert sys.version_info[:2] == (3, 13)' + python3 -m venv .venv + - name: Install development dependencies + run: .venv/bin/python -m pip install -e '.[dev]' + - name: Lint, types and unit tests + run: PATH="$PWD/.venv/bin:$PATH" make check diff --git a/.gitignore b/.gitignore index a3cc944..6714cd9 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,33 @@ assets/sounds/custom/ # Сборка инсталлятора (идёт в релиз, не в git) installer_output/ *_log.txt + +# Developer caches and private runtime/model artifacts +.mypy_cache/ +.pytest_cache/ +.ruff_cache/ +.coverage +htmlcov/ +.env.* +!.env.example +*.ogg +*.opus +*.mp3 +*.m4a +*.flac +*.webm +*.gguf +*.bin +*.safetensors +models/ +recordings/ +*.zip +*.dmg +*.exe + +# Also ignore an optional local environment symlink +.venv + +# Private user credentials +credentials.json +.credentials-* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..306cb68 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,62 @@ +# Voice Dictation — инструкции для AI-агентов + +## Назначение и источники истины + +Desktop-приложение для диктовки: глобальный хоткей → запись → распознавание → +буфер обмена и вставка в активное приложение. Есть OpenAI API и локальные +Whisper/GigaAM. Свой сервер и автоматическое обновление пока в плане. + +- `README.md` — возможности и ограничения продукта. +- `CONTRIBUTING.md` — окружение, проверки, сборка и Git-процесс. +- `ARCHITECTURE.md` — архитектура; сверять описание с актуальным кодом. +- `docs/README.md` — навигация по документации; `docs/roadmap.md` — будущие работы. +- `CLAUDE.md` — подробный исторический контекст; старые версии и статусы не + считать подтверждением текущего поведения. + +## Карта кода + +- `src/voice_dictation/core/` — конфигурация, сессии, оркестратор, движки, + загрузка моделей, история и стоимость. Не добавлять сюда платформенные API. +- `platform/` — интерфейсы и реализации macOS/Windows: хоткей, буфер, вставка. +- `ui/` — tray, настройки, мастер запуска и локальные диагностические сценарии. + На macOS Tk-окна работают в отдельном процессе от tray/AppKit. +- `infrastructure/` — логи, секреты профиля, PID-блокировка и загрузка окружения. +- `tests/` — модульные проверки; `.forgejo/workflows/checks.yml` — Linux CI. + +## Правила изменений + +1. Работать в ветке через PR. Не сливать и не публиковать без разрешения + пользователя. Проверять CI именно для последнего SHA, а не старого коммита. +2. Python 3.11+, типизированные контракты и платформенные Protocol-интерфейсы. + Перед PR выполнять `make check`: Ruff, форматирование, strict mypy, pytest. +3. После изменения ввода проверять отдельно: разрешения ОС, хоткей start/stop, + распознавание, буфер и вставку. Не посылать Backspace/Delete для компенсации + хоткея: это удаляет пользовательский текст. +4. Не менять установленное приложение, его профиль или общую виртуальную среду + без явного запроса. Для тестов использовать отдельный профиль через + `VOICE_DICTATION_HOME` и отдельный каталог сборки. Обычный build-скрипт может + очищать `dist/` и `build/`: сначала проверить его перед запуском. +5. Перед остановкой беты убедиться, что запись закончена. Перед заменой + установленной версии сохранить предыдущую сборку и настройки для отката. +6. Секреты, `.env`, credentials, аудио, транскрипты, модели, runtime и сборки не + коммитить и не выводить в логи/ответы. Наличие ключа проверять без его вывода. +7. Локальный режим не должен отправлять аудио/текст в облако или автоматически + переключаться на API при ошибке. Реальные API-тесты и отправка сохранённых + записей требуют явного разрешения пользователя. +8. В описании результата разделять: unit/CI, нативную сборку, реальное API и + ручную проверку. Будущие возможности не описывать как реализованные. + +## Статус платформ + +**Текущая beta развивается и проверяется прежде всего на macOS arm64.** +Windows-код и инструкции сборки сохранены, есть отдельные compatibility-тесты, +но текущая Windows-сборка нативно не тестировалась. Адаптация новых возможностей +для Windows не завершена. Не обещать поддержку, исправность GUI, локальных +моделей, микрофона, хоткеев или вставки на Windows до отдельной проверки. +Linux CI не подтверждает ни Windows, ни macOS GUI. + +## Связанные документы + +- [Разработка](CONTRIBUTING.md) +- [Тестирование беты](docs/beta-testing.md) +- [Windows: историческая инструкция сборки](BUILD_WINDOWS.md) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6ee36d1..a7da0e4 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -145,6 +145,13 @@ class Config: dictionary_path: Path | None = None auto_paste: bool = True paste_delay_ms: int = 80 + chunk_duration_sec: float = 180.0 + chunk_overlap_sec: float = 4.0 + vad_enabled: bool = True + vad_search_window_sec: float = 12.0 + vad_min_silence_sec: float = 0.35 + vad_noise_db: float = -35.0 + audio_retention_days: int = 30 class ConfigStore: def __init__(self, path: Path) -> None: ... @@ -166,6 +173,9 @@ class AppPaths: pid_file: Path # ~/.dictate/dictate.pid tmp_dir: Path # ~/.dictate/tmp/ + @property + def sessions_dir(self) -> Path: ... # ~/.dictate/sessions/ + @classmethod def default(cls) -> "AppPaths": ... def ensure_exists(self) -> None: ... @@ -190,7 +200,16 @@ class WhisperModel(StrEnum): GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe" ``` -**`core/recorder.py`** — Protocol + `SoxRecorder` (subprocess Popen). `shutil.which("sox")` check в `__init__`. При stop — SIGTERM + wait. Возвращает `RecordingResult(path, duration_sec)`. +**`core/recorder.py`** — `SoxRecorder` (имя сохранено для совместимости) поверх +`sounddevice.RawInputStream`. Отдельный writer-поток сразу пишет WAV на диск и +каждые 5 секунд обновляет заголовок, поэтому авария не уничтожает всю запись. + +**`core/session_store.py`** — атомарный `manifest.json`, checkpoint каждого +ответа API, итоговый `transcript.txt`, восстановление незавершённых сессий и +retention только для аудио завершённых сессий. + +**`core/text_stitcher.py`** — консервативно удаляет уверенно совпавший текст на +стыке соседних фрагментов; при сомнении оставляет дубль вместо потери слов. **`core/transcriber.py`** — `WhisperTranscriber` через `httpx.Client`. Multipart upload к `POST /v1/audio/transcriptions`. Параметры: `model`, `language`, `prompt`, `response_format=verbose_json` (для duration). Retries=2 на 5xx. Поднимает `TranscriptionError`. @@ -293,7 +312,8 @@ DictationError state: IDLE → RECORDING ├── SoundPlayer.play(start_sound) ├── state_listener(RECORDING) → tray icon red - └── SoxRecorder.start(tmp.wav) + ├── SessionStore.create() + └── SoxRecorder.start(sessions//source.wav) ... user speaks ... @@ -306,8 +326,17 @@ DictationError │ (sanity: duration<0.3s OR size<4KB → skip, no API call) │ └── ThreadPoolExecutor submit: - ├── prompt = Dictionary.build_prompt() - ├── result = Transcriber.transcribe(wav, prompt, language) + ├── AudioCompressor.compress(source.wav → source.ogg) + ├── ffmpeg silencedetect (паузы >=0.35с, threshold=-35dB) + ├── AudioCompressor.split(180с, overlap=4с) + │ ├── ищет паузу в последние 12с перед границей + │ ├── двигает границу только назад + │ └── при ошибке VAD использует фиксированную нарезку + ├── для каждого чанка: + │ ├── Transcriber.transcribe(chunk, prompt, language) + │ └── SessionStore.save_chunk_result(...) + ├── stitch_transcripts(parts) + ├── SessionStore.complete(transcript.txt) ├── UsageDB.insert(UsageRecord(...)) ├── Clipboard.copy(result.text) ├── AutoPaste.paste() (имитирует ⌘V/Ctrl+V) @@ -319,7 +348,8 @@ DictationError - Main: pystray/Tk mainloop - Hotkey: pynput внутренний - Worker: ThreadPoolExecutor (Whisper API) -- Sox: отдельный subprocess +- Audio writer: отдельный поток +- ffmpeg: короткие subprocess для архива и фрагментов --- @@ -356,7 +386,13 @@ CREATE INDEX idx_tx_created ON transcriptions(created_at); ├── app.log ├── dictate.pid ├── sounds/ # custom sounds -└── tmp/ # session_*.wav, чистится при старте >1ч +├── tmp/ # legacy/temp +└── sessions/ + └── / + ├── manifest.json + ├── source.ogg # компактный восстанавливаемый оригинал + ├── transcripts/ # raw checkpoint каждого API-вызова + └── transcript.txt # итоговая склейка ``` --- @@ -395,7 +431,6 @@ CREATE INDEX idx_tx_created ON transcriptions(created_at); ## 6. Точки расширения - **Локальный whisper.cpp** — `Transcriber(Protocol)` + `LocalWhisperTranscriber` -- **Streaming-транскрипция** — `StreamingSoxRecorder.chunks() -> AsyncIterator[bytes]` - **Post-processing GPT** — `PostProcessor(Protocol)` между transcribe и copy - **Workflows** — `Config.workflows: dict[str, WorkflowConfig]`, switch через tray @@ -412,12 +447,15 @@ CREATE INDEX idx_tx_created ON transcriptions(created_at); | Race condition PID-файла | `os.open(O_CREAT\|O_EXCL)` + `psutil.pid_exists`; на win `msvcrt.locking` | | Race condition в toggle | `threading.Lock`; повторный toggle в PROCESSING игнорируется | | Admin API Key утечка | Только `.env`; маскирование в логах `sk-admin-***` | -| sox не установлен | `shutil.which("sox")` на старте; фатальный диалог | +| ffmpeg не установлен | Короткие WAV работают; длинная запись сохраняется для повтора | | Тишина / короткая запись | `duration<0.3s` или `size<4KB` → skip, нет API-вызова | | OpenAI rate-limit/сеть | `httpx` retries=2 на 5xx/timeout | | Zombie sox-процесс | `__del__` + `atexit` шлют SIGTERM/kill | | customtkinter + pystray main thread | pystray на main, Tk-действия через `root.after(0, ...)` | | Длинный транскрипт в чат | `>10000 chars` → только copy, без autopaste, toast | +| Ответ API оборвался / сеть упала | 180-секундные чанки, raw checkpoint каждого ответа, resume при старте | +| VAD не нашёл паузу или ffmpeg-анализ упал | Фиксированная граница; режим и диагностика записываются в manifest | +| Падение во время записи | Потоковый WAV и обновление заголовка каждые 5 секунд | | Хоткей конфликт | `register` возвращает bool; fallback на `cmd+shift+d` | | Словарь >224 токенов | `build_prompt` берёт хвост; UI счётчик `N/224` | diff --git a/BUILD_WINDOWS.md b/BUILD_WINDOWS.md index a9592ba..5b1ca94 100644 --- a/BUILD_WINDOWS.md +++ b/BUILD_WINDOWS.md @@ -1,5 +1,11 @@ # Voice Dictation — сборка под Windows (инструкция для Claude Code) +> **Статус текущей версии:** нативное тестирование Windows не проводилось. +> Адаптация новых возможностей beta под Windows не завершена. Эта инструкция +> сохранена как отправная точка для разработки и не подтверждает готовность +> текущей Windows-сборки. Актуальные ограничения — в [CONTRIBUTING.md](CONTRIBUTING.md). + + **Привет, Claude Code!** Эта инструкция адресована тебе. Выполняй шаги последовательно. Комментируй прогресс, на каждом шаге проверяй результат. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..db1611e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,264 @@ +# Voice Dictation — правила для Claude + +Десктоп-приложение голосовой диктовки. Хоткей → запись с микрофона через `sounddevice` (in-memory PCM, без потерь на длинных записях) → OGG/Opus сжатие через ffmpeg → OpenAI Whisper → опционально post-processing через `gpt-4o-mini` (пресет) → автовставка / буфер. Живёт в системном трее. Кроссплатформенный код, native-сборки под macOS и Windows. + +## Контур + +- **Слой OME:** артефакт-продукт (десктоп-утилита для конечного пользователя). НЕ «рука» в смысле OME — это не MCP/CLI/бот для агентских действий, а инструмент, которым пользуется человек. +- **Репозиторий:** https://git.flowmasters.ru/Soschen/voice-dictation +- **Рабочая копия:** `~/voice-dictation/`. Исходная папка `personal/voice-dictation/` сохранена для работающей установки; дальнейшая разработка ведётся здесь. +- **Авторы:** Викентий (исходный код, macOS-сборка, OGG/Opus, splash, пресеты), Женя Князев (Windows-портирование, sounddevice recorder, Summary mode, Inno Setup). +- **Пользователи:** Викентий (Mac, прод), Варвара (Windows, пилот). + +## Куда смотреть в первую очередь + +1. **[README.md](README.md)** — установка, запуск, конфигурация, troubleshooting. +2. **[ARCHITECTURE.md](ARCHITECTURE.md)** — структура модулей, контракты, data flow, риски, этапы разработки. +3. **[BUILD_WINDOWS.md](BUILD_WINDOWS.md)** — пошаговая инструкция сборки .exe через PyInstaller (адресована Claude Code на стороне Жени). +4. **[pyproject.toml](pyproject.toml)** — зависимости, ruff/mypy/pytest конфиг. +5. **[Makefile](Makefile)** — `make run / test / lint / typecheck / check / clean`. + +## Текущий статус + +| Платформа | Версия | Где живёт | Кто ведёт | Состояние | +|-----------|--------|-----------|-----------|-----------| +| macOS | 0.2.0 (merged) | `dist/Voice Dictation.app` | Викентий | свежая сборка для теста (2026-04-30) | +| Windows | 0.1.1 | `VoiceDictator-Setup.exe` (Inno Setup), у Жени | Женя | пилот для Варвары; может расходиться с merged-веткой | + +Имя на Windows-сборке — **Voice Dictator** (Женя предложил, Викентию нравится). Имя проекта в коде/папке пока остаётся **Voice Dictation**. Решение «переименовывать ли всё целиком» — открытый вопрос. + +### v0.2.0 — что слили из ветки Жени (2026-04-30) + +| Фича | Где | +|------|-----| +| `sounddevice` recorder (in-memory PCM frames → WAV; не теряет данные на длинных записях) | `core/recorder.py` (класс `SoxRecorder` оставлен для совместимости импортов) | +| frozen-aware env_loader (`.env` рядом с exe для PyInstaller-сборки) | `infrastructure/env_loader.py` | +| Summary post-processing через активный пресет (на смену прежнему single `summary_mode`) | `core/orchestrator.py:_summarize` + `core/config.py:SummaryPreset` | +| `MAX_AUTOPASTE_CHARS = 10_000` (длинный текст только в буфер + notify) | `core/orchestrator.py` | +| Радио-submenu пресетов в Tray + toggle splash | `ui/tray.py` | + +### Что НЕ брали из ветки Жени + +| Что | Почему | +|------|--------| +| `installer.iss`, BMP wizard'а, `VoiceDictation.spec` Жени, `sox_ng.exe` | Win-only; Mac не нужны | +| `platform/windows/autopaste.py` keybd_event | Mac не использует; Win-сборку перельём отдельным шагом | +| Default hotkey Жени (`ctrl+space`) | После merge установили общий default `cmd+alt+d`; на Win нужна нормализация cmd→ctrl | + +### Точечные фиксы macOS после merge (2026-05-01) + +| Фикс | Файл | Зачем | +|------|------|-------| +| NSEvent global monitor регистрируется на main thread через `AppHelper.callAfter` | `platform/macos/hotkey_listener.py:start()` | Без этого callbacks не доходили — pystray держит main runloop, монитор в worker-потоке немой | +| `CGEventSetFlags(event, 0)` + задержка 120 мс перед Backspace-eraser | `platform/macos/hotkey_listener.py:_send_backspace_via_quartz()` | Раньше Backspace уходил с зажатым Cmd → `Cmd+Backspace` стирал всю строку. Теперь — один символ | +| Default hotkey `cmd+alt+d` | `core/config.py` + `tests/unit/test_config.py` | `cmd+space` конфликтует с системным Spotlight на свежих macOS | +| `usage_db.today_total/month_stats` принимают `tzinfo | None` (раньше strict `timezone`) | `core/usage_db.py` | mypy --strict теперь зелёный | +| `winsound`/PyObjC модули в mypy overrides | `pyproject.toml` | `make check` зелёный целиком | + +### Что сохранили нашим (Mac-приоритет) + +| Фича | Где | +|------|-----| +| OGG/Opus сжатие через ffmpeg (Opus 24 kbps mono, ~3 МБ / 20 мин) | `core/compressor.py` + интеграция в orchestrator | +| `select_model_for_duration` (whisper-1 для >23 мин) | `core/compressor.py` | +| Splash-окно с DALL-E плакатом | `ui/splash.py` + `assets/splash/dictator.png` | +| 4 пресета в Config | `core/config.py:_default_presets()` | +| Mac-сборка | `scripts/voice_dictation.spec`, `scripts/build_macos.sh` | + +## Архитектурные правила (обязательные) + +Из [ARCHITECTURE.md §8](ARCHITECTURE.md): + +- Python 3.11+, `from __future__ import annotations` во всех файлах. +- **mypy --strict clean**, без `Any`. +- Google-style docstrings на публичных классах/функциях. +- Dataclasses (`frozen=True, slots=True` где возможно) для структур данных. +- **Protocol-based platform abstraction** — кроссплатформенные интерфейсы в `platform/protocols.py`, реализации в `platform/macos/` и `platform/windows/`. +- Pathlib вместо os.path, logging вместо print, Enum для констант. +- SRP — каждый модуль одно дело. +- ruff + mypy --strict + pre-commit; `make check` зелёный. + +## Структура src/voice_dictation/ + +``` +core/ # Бизнес-логика, не знает про UI и ОС + models.py # TranscriptionResult, UsageRecord, SoundTheme, BalanceInfo + config.py # Config + ConfigStore + paths.py # AppPaths (~/.dictate/...) + enums.py # RecordingState, SoundKind, WhisperModel + recorder.py # AudioRecorder Protocol + SoxRecorder + transcriber.py # WhisperTranscriber через httpx + dictionary.py # build_prompt() для Whisper + usage_db.py # SQLite CRUD, миграции через PRAGMA user_version + pricing.py # PriceCalculator (Decimal) + balance.py # OpenAI Admin API + orchestrator.py # DictationOrchestrator — главная state-machine + +platform/ # Platform abstraction (Protocol + factory) + protocols.py + factory.py # build_platform() → PlatformBundle + macos/ # afplay, pync, pbcopy, pynput Cmd+V, /System/Library/Sounds/ + windows/ # winsound, winotify, pyperclip, pynput/keybd_event Ctrl+V + +ui/ # pystray + customtkinter + tray.py + settings_window.py + tabs/{general,sound,dictionary,statistics,balance}_tab.py + widgets/{sound_picker,hotkey_input}.py + +infrastructure/ # logging, single_instance (PID lock), env_loader, errors + +cli/headless.py # запуск без tray +``` + +**Иерархия исключений:** `DictationError` → `RecorderError`/`TranscriptionError`/`ConfigError`/`PlatformError`/`BalanceError`. + +## Конфиг и данные пользователя + +Всё в `~/.dictate/`: + +``` +~/.dictate/ +├── config.json # сериализованный Config +├── usage.db # SQLite, таблица transcriptions, индекс по created_at +├── dictionary.txt # подсказки для Whisper, # — комментарии +├── app.log # RotatingFileHandler 5MB × 3 +├── dictate.pid # single-instance lock +├── sounds/ # custom sounds +└── tmp/ # session_*.wav, чистится при старте >1ч +``` + +## Точки входа + +- `python -m voice_dictation` — tray-режим (pystray + customtkinter). +- `python -m voice_dictation headless` — без tray, для отладки/автозапуска. +- `python -m voice_dictation stats` — сводка использования за сегодня. +- `python -m voice_dictation.cli.headless` — то же что headless. + +Хоткей: `Cmd+Alt+D` (macOS) / `Ctrl+Alt+D` (Windows). Меняется в `~/.dictate/config.json` или через Settings → Общие. + +## Сборка + +### macOS +```bash +make install-dev +./scripts/build_macos.sh +# результат: dist/Voice Dictation.app +``` + +Автозапуск через LaunchAgent: `./scripts/install_autostart_macos.sh`. + +### Windows +Подробно в **[BUILD_WINDOWS.md](BUILD_WINDOWS.md)**. Кратко: +- PowerShell, Python 3.11+, sox в PATH. +- `pip install -e ".[dev]" pyinstaller`. +- `pyinstaller --windowed --name VoiceDictation --paths src ...` (флаги в инструкции). +- Inno Setup упаковывает `dist/VoiceDictation/` в `VoiceDictator-Setup.exe`. + +## Что делать / не делать + +### Делать +- Любые изменения через Protocol-абстракции (`platform/protocols.py`). Не вызывать платформенные API из `core/` напрямую. +- Поддерживать `mypy --strict` зелёным. Если новый код требует `Any` — обосновать в комменте. +- При добавлении нового Whisper-модели — обновить `core/pricing.py:PriceCalculator.PRICES_PER_MINUTE` и `core/enums.py:WhisperModel`. +- Перед деплоем (новый dmg/exe) — `make check` (lint + typecheck + test). +- При изменении платформенного слоя — править ОБЕ реализации (macos + windows), не оставлять одну отстающей. + +### Не делать +- Не коммитить `.env` (ключи OpenAI). Шаблон — `.env.example`. +- Не редактировать README/ARCHITECTURE/BUILD_WINDOWS «по памяти» — это документация авторов с конкретными PyInstaller-флагами и инструкциями для Жени. +- Не плодить inline-конфиг — всё через `Config` dataclass и `~/.dictate/config.json`. +- Не использовать `print` — только `logging` (с маскированием API-ключей). +- Не мешать Mac- и Windows-сборки в одном dist-коммите без явного запроса — Mac у Викентия в проде, поломки чувствительны. + +## Splash screen + +Пасхалка под имя «Voice Dictator»: при старте показывается плакат-пропаганда (диктатор с мегафоном) + опциональная музыка Soviet March из Red Alert 3. + +**По умолчанию ВКЛЮЧЁН** (`splash_enabled = True`, `splash_audio_enabled = True`). Длительность 5 сек. + +### Управление +- **Tray → «Splash при старте»** — toggle (галочка). Сохраняется в `~/.dictate/config.json`. +- **Альтернативно** в `config.json`: + ```json + { + "splash_enabled": true, + "splash_audio_enabled": true, + "splash_duration_sec": 5.0 + } + ``` + +### Ассеты в `~/.dictate/splash/` +- **Картинка:** `dictator.png` — есть готовая в `assets/splash/dictator.png` (DALL-E, советский плакат с цитатами «ДИКТУЙ ЧЁТКО!», «ГОЛОС — ОРУЖИЕ!» и т.п.). Копируется вручную: `cp assets/splash/dictator.png ~/.dictate/splash/`. +- **Музыка:** `soviet_march.mp3` (Mac) / `soviet_march.wav` (Windows). **Не в репо** — `Soviet March` (Red Alert 3, James Hannigan, ©EA Games), коммерческая музыка. Положить руками. На Mac `afplay` принимает mp3/m4a/wav/aiff/ogg; на Windows `winsound` только `.wav` (конвертить `ffmpeg -i in.mp3 out.wav`). + +### Тест без полного запуска +```bash +python -m voice_dictation splash +``` +Borderless-окно по центру экрана, 5 сек, закрывается по Esc/клику или таймеру. + +### Точки в коде +- `ui/splash.py` — Tk-окно (`overrideredirect`, topmost), audio через `afplay` / `winsound`. +- `__main__.py:_show_splash_for_paths()` — поиск ассетов в `~/.dictate/splash/`, фильтр по `splash_audio_enabled`. +- `core/config.py:Config.splash_enabled / splash_audio_enabled / splash_duration_sec`. + +## Пресеты промтов (post-processing) + +После транскрипции текст опционально проходит через `gpt-4o-mini` по выбранному пресету. Переключение через **Tray → «Режим»** (radio). + +### Дефолтные пресеты (`core/config.py:_default_presets()`) + +| Имя | Что делает | +|-----|------------| +| **Диктовка** | no-op. Текст идёт в буфер/автовставку как из Whisper. Default. | +| **Чистка от паразитов** | Убирает «эээ», повторы, незаконченные фразы. Сохраняет ВСЕ факты, имена, числа, даты. | +| **Структура (markdown)** | Преобразует в markdown с `##` заголовками, маркированными списками, **жирным** на ключевом. | +| **Тезисы** | Сжимает в 5–7 ключевых тезисов (буллеты). | + +### Поведение +- Активный пресет хранится в `Config.active_preset` (по имени). +- Если пресет имеет пустой `prompt` или `model` — orchestrator пропускает summary, ничего не вызывает. +- При ошибке OpenAI orchestrator вставляет оригинальный текст транскрипции (fail-safe в `_on_transcription_success`). +- **MAX_AUTOPASTE_CHARS = 10_000** проверяется на FINAL тексте (после summary): если длинно — только буфер + notify «Cmd+V вручную». + +### Добавить свой пресет +Отредактировать `~/.dictate/config.json` → массив `summary_presets`: +```json +{ + "summary_presets": [ + {"name": "Диктовка", "model": "", "prompt": ""}, + {"name": "Мой пресет", "model": "gpt-4o-mini", "prompt": "..."} + ], + "active_preset": "Мой пресет" +} +``` +После рестарта появится в Tray-меню. + +## Большое аудио + +Связка устроена так, чтобы длина диктовки не превращалась в единую точку отказа: + +1. **`sounddevice` recorder** потоково пишет WAV в `~/.dictate/sessions//` и периодически обновляет заголовок, поэтому авария не уничтожает всю запись. +2. **`AudioCompressor`** сохраняет компактный OGG/Opus-оригинал, который остаётся после успешной обработки и удаляется только по retention. +3. Аудио режется на фрагменты с перекрытием. При включённом VAD граница переносится назад на ближайшую паузу в заданном окне; ошибка анализа или отсутствие паузы дают фиксированную границу. +4. Ответ каждого API-вызова атомарно сохраняется отдельно. После сети, крэша или рестарта обработка продолжается с первого отсутствующего фрагмента. +5. **`text_stitcher`** удаляет только уверенно совпавшее перекрытие; при сомнении оставляет возможный дубль вместо потери текста. +6. **MAX_AUTOPASTE_CHARS = 10_000** не пытается автовставить длинный текст в чужое окно — кладёт его в буфер и показывает уведомление. + +ffmpeg должен быть в PATH (`brew install ffmpeg` на Mac). Если его нет, исходный WAV и manifest остаются в незавершённой сессии для последующего восстановления. + +## Открытые вопросы + +1. **Имя.** Voice Dictation (код, папка) vs Voice Dictator (Windows-билд). Унифицировать или оставить как есть. +2. **Win-ветка Жени отстала от merged-Mac (v0.2.0).** Когда Женя продолжит Win-сборку — нужно слить из нашей: `compressor.py`, splash, пресеты. Через Protocol-абстракции — Win-recorder может остаться его, Win-autopaste его keybd_event. +3. **Локальный whisper.cpp** как fallback (см. ARCHITECTURE.md §6) — CLI и Metal-inference проверены на сохранённой записи, но движок ещё не встроен. Текущая `large-v3-turbo-q5_0` чувствительна к длине чанка; перед выбором нужны полный минутный benchmark и сравнение с `large-v3-q5_0`. Практический запуск и ограничения → [README.md](README.md#локальная-транскрибация-whispercpp). +4. **Размер боевого чанка.** Реализация по умолчанию использует 180 секунд и 4 секунды перекрытия, но локальный benchmark показал крупный пропуск на одном трёхминутном фрагменте. Перед окончательной настройкой нужен полный прогон того же файла равномерными минутными чанками. + +## План развития + +Канонический план: [docs/roadmap.md](docs/roadmap.md). Перенос текущей macOS-версии не доказывает совместимость с Windows-версией из main; перед слиянием необходима проверка Windows-функций. + +## Beta 0.3.0b1 + +Локальный Whisper реализован в ветке `feature/local-transcription`: `core/transcription.py`, `core/local_transcriber.py`, `core/model_manager.py`, `ui/recognition_tab.py`. Документация beta: [docs/beta-testing.md](docs/beta-testing.md). Beta bundle и данные изолированы от production. Старые описания runtime выше относятся к исходной OpenAI-версии. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..08a4f19 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,119 @@ +# Разработка + +Канонический репозиторий: https://git.flowmasters.ru/Soschen/voice-dictation. +Изменения оформляем отдельными ветками и PR. Архивы не являются источником истины. + +```bash +git clone https://git.flowmasters.ru/Soschen/voice-dictation.git +cd voice-dictation +python3 -m venv .venv +source .venv/bin/activate +pip install -e '.[dev]' +cp .env.example .env +make check +``` + +На Windows активируйте `.venv\Scripts\activate`. Для работы текущего приложения +заполните локальный `.env`; для unit-тестов ключ не нужен. Нужны Python 3.11+ +и ffmpeg для обработки аудио. Секреты, аудиозаписи, модели и пользовательская +папка `~/.dictate/` не коммитятся. Сборки распространяются отдельно от исходников. + +Проверки: ruff, форматирование, mypy --strict и pytest через `make check`. +Для изменений платформенного кода дополнительно проверяем реальную сборку +и микрофонный сценарий на соответствующей ОС. В PR указываем выполненные +проверки и ограничения. Перенос исходников не означает выпуск новой сборки. + +## Статус Windows + +Нативная проверка текущей Windows-версии не проводилась. Адаптация новых +возможностей под Windows не завершена; сохранившийся код и compatibility-тесты +не подтверждают работоспособность установленного приложения. Перед Windows- +релизом нужны отдельные сборка и проверки GUI, микрофона, хоткея, отмены, +локальных моделей и вставки. Этот пробел не скрывать в PR или описании релиза. + +## Связанные документы + +- [Инструкции для AI-агентов](AGENTS.md) +- [Документация](docs/README.md) +- [План развития](docs/roadmap.md) +- [Windows-сборка](BUILD_WINDOWS.md) + +## Проверки PR и выпуск + +`.forgejo/workflows/checks.yml` запускает `make check` на Linux/Python 3.13 +при PR и push в main. Метка `docker` соответствует существующему ome-runner; +Actions включены для репозитория. До первого успешного запуска workflow +наличие файла не считается работающим CI. Статические проверки и unit-тесты +не скачивают модели и не обращаются в облако. Изменения проходят независимое +ревью; merge и публикация релиза выполняются отдельными действиями. +Настройка обязательного статуса ветки выполняется после первого прогона. + +Реальные модели проверяются отдельно на одинаковых неперсональных записях +с фиксацией модели, версии движка, железа, качества и времени обработки. +Для релиза нужны отдельные нативные сборки и ручная проверка микрофона, +хоткея, распознавания и вставки. Linux CI не подтверждает macOS/Windows GUI. + +## Изолированная macOS beta + +Единственный источник версии — `voice_dictation.__version__` (сейчас `0.3.0b9`). +Метаданные пакета и macOS bundle берут версию оттуда; CFBundleShortVersionString +содержит `0.3.0`, CFBundleVersion — `0.3.0.9`. + +```bash +# В собственной .venv; не менять venv работающей установки. +python -m pip install -e '.[dev]' pyinstaller +LOCAL_WHISPER_CLI=/absolute/path/to/whisper-cli \ +LOCAL_WHISPER_LIB_DIRS=/absolute/path/to/runtime/lib:/absolute/path/to/runtime/libexec \ +./scripts/build_macos.sh +``` + +Результат — `dist/Voice Dictation Beta.app`, bundle ID +`ru.flowmasters.voicedictation.beta`. Скрипт только собирает, установленное +приложение не заменяет и процессы не останавливает. Без LOCAL_WHISPER_CLI +движок не включается. Исполняемый файл доступен приложению как +`Path(sys._MEIPASS) / "bin" / "whisper-cli"`; dylib и динамические ggml-плагины +из LOCAL_WHISPER_LIB_DIRS лежат рядом. При запуске движка задавайте +`GGML_BACKEND_PATH` на эту папку: плагины `.so` не всегда обнаруживаются по +статическим dylib-зависимостям. Архитектура движка должна совпадать с bundle. +Homebrew-зависимости сборщика не являются зависимостями пользователя: +готовый bundle надо проверить на отсутствие внешних абсолютных ссылок. + +Сборка подписана локальной ad-hoc подписью, без Apple Developer ID и +notarization; Gatekeeper может потребовать ручное разрешение. Это тестовая +beta, не канал автоматических обновлений. Sparkle и подписи релизов пока +не реализованы. Модели, runtime-данные и сборки в Git не включаются. + +Для автономной beta используйте закреплённый upstream runtime вместо Homebrew: + +```bash +# Нужны git, cmake и Apple Command Line Tools; системная установка не выполняется. +./scripts/build_whisper_runtime.sh /tmp/voice-whisper-runtime +LOCAL_WHISPER_CLI=/tmp/voice-whisper-runtime/build/bin/whisper-cli \ +LOCAL_WHISPER_LICENSE_DIR=/tmp/voice-whisper-runtime \ +./scripts/build_macos.sh +``` + +Скрипт проверяет commit v1.9.2, отключает динамические backend-плагины, +собирает статические библиотеки и встраивает Metal. `GGML_NATIVE=OFF` +исключает оптимизацию только под CPU сборщика. Результат всё ещё требует +проверки на целевых версиях macOS и архитектуре; текущая сборка — arm64. +Лицензии Whisper и ggml включаются в bundle автоматически. Homebrew-runtime +может обращаться к зашитому пути libexec даже при GGML_BACKEND_PATH; +наличие dylib внутри bundle само по себе не доказывает автономность. + +CI использует локальный образ `voice-dictation-ci:py313-node20-20261019`, +собираемый из `ci/Dockerfile`. Оба базовых образа закреплены digest и уже +кэшированы на OME; сборка не скачивает пакеты. Образ содержит Node для checkout +и Python с pip/venv; apt при каждом PR не запускается. + +```bash +DOCKER_BUILDKIT=0 docker build --pull=false --network=none \ + -t voice-dictation-ci:py313-node20-20261019 -f ci/Dockerfile . +``` + +В конфигурации runner обязательно `container.network: forgejo_forgejo_default`, +чтобы внутреннее имя Forgejo разрешалось внутри job. Runner запускается с +явным `--config /data/config.yaml`. Workflow `container.options --network` +игнорируется используемым runner/act и не заменяет настройку daemon. На другом +runner нужны тот же образ и подходящая настройка сети. macOS-разработка +и требования пакета остаются Python 3.11+; обязательный CI сейчас проверяет 3.13. diff --git a/README.md b/README.md index d829978..8642649 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,45 @@ # Voice Dictation -Desktop-приложение для голосовой диктовки. Хоткей → запись с микрофона → Whisper API → автовставка текста в активное окно. +Desktop-приложение для голосовой диктовки: хоткей → запись с микрофона → +распознавание через OpenAI API или локальную модель → вставка в активное окно. + +Репозиторий: [Forgejo](https://git.flowmasters.ru/Soschen/voice-dictation). +[Документация](docs/README.md) · [План развития](docs/roadmap.md) · +[Инструкции для AI-агентов](AGENTS.md) + +В macOS beta доступны OpenAI с выбором модели и вводом ключа, локальные Whisper +с загрузкой моделей, экспериментальный GigaAM, мастер настройки, история +распознаваний с копированием текста и учётом времени/расчётной стоимости. +Свой сервер и автоматические обновления пока запланированы. +Инструкция: [тестирование beta](docs/beta-testing.md). + +**Статус платформ:** текущая beta проверяется прежде всего на **macOS arm64**. +**Windows для текущей версии нативно не тестировалась и ещё не доведена до +поддержки новых возможностей.** Наличие Windows-кода и compatibility-тестов +не означает готовую рабочую Windows-сборку. Linux CI проверяет код и unit-тесты, +а не работу микрофона, GUI, хоткеев или вставки на конкретной ОС. ## Требования - Python 3.11+ -- `sox` — для записи с микрофона -- OpenAI API Key +- `ffmpeg` — для сжатия и нарезки длинных записей +- OpenAI API Key — только для облачного режима -## Установка sox +## Установка ffmpeg **macOS:** ```bash -brew install sox +brew install ffmpeg ``` **Windows:** ``` -choco install sox -# или скачать с https://sourceforge.net/projects/sox/ +choco install ffmpeg ``` -## Установка приложения +## Разработка и установка из исходников -```bash -cd personal/voice-dictation - -# Создать виртуальное окружение -python3 -m venv .venv -source .venv/bin/activate # macOS/Linux -# .venv\Scripts\activate # Windows - -# Установить зависимости -pip install -e ".[dev]" - -# Скопировать и заполнить .env -cp .env.example .env -# Открыть .env и вставить OPENAI_API_KEY -``` +Инструкции находятся в [CONTRIBUTING.md](CONTRIBUTING.md). ## Запуск @@ -61,7 +63,7 @@ python -m voice_dictation headless python -m voice_dictation stats ``` -Хоткей по умолчанию: `Cmd+Space` (macOS) / `Ctrl+Alt+D` (Windows). Можно сменить +Хоткей по умолчанию: `Cmd+Alt+D` (macOS) / `Ctrl+Alt+D` (Windows). Можно сменить в окне настроек (Tray → Настройки → Общие) или вручную в `~/.dictate/config.json`. Первое нажатие — начало записи. Второе — остановка, транскрипция, вставка в активное окно. @@ -85,7 +87,7 @@ python -m voice_dictation stats ## Разрешения на macOS ### Микрофон -При первом запуске macOS запросит разрешение на доступ к микрофону для `sox`. +При первом запуске macOS запросит разрешение на доступ к микрофону. Если разрешение не появилось: **Системные настройки → Конфиденциальность и безопасность → Микрофон** → включить Terminal/iTerm. ### Accessibility (для автовставки Cmd+V) @@ -111,12 +113,65 @@ python -m voice_dictation stats "notifications_enabled": true, "show_cost_in_notification": true, "sounds_enabled": true, - "volume": 0.6 + "volume": 0.6, + "chunk_duration_sec": 180.0, + "chunk_overlap_sec": 4.0, + "vad_enabled": true, + "vad_search_window_sec": 12.0, + "vad_min_silence_sec": 0.35, + "vad_noise_db": -35.0, + "audio_retention_days": 30 } ``` Статистика и история сохраняются в SQLite `~/.dictate/usage.db`. +## Длинные записи и восстановление + +Каждая запись с первой секунды потоково сохраняется в отдельную папку +`~/.dictate/sessions//`. После остановки приложение: + +1. сохраняет компактный архив `source.ogg`; +2. режет длинное аудио на трёхминутные фрагменты с перекрытием 4 секунды, + перенося границы на ближайшие паузы перед плановой отсечкой; +3. сохраняет ответ API для каждого готового фрагмента; +4. удаляет только уверенно найденные дубли на стыках и пишет `transcript.txt`. + +Если анализ пауз через ffmpeg не сработал или рядом с отсечкой нет тишины, +приложение автоматически использует фиксированную границу. Выбранный режим, +число найденных пауз и перенесённых границ сохраняются в `manifest.json`. + +Если сеть или приложение оборвались, исходное аудио и готовые фрагменты не +удаляются. При следующем запуске обработка продолжается с первого отсутствующего +ответа. После успеха WAV и временные фрагменты удаляются, но компактный OGG, +ответы по фрагментам и итоговый текст остаются. Аудио завершённых сессий хранится +30 дней по умолчанию; текст и manifest не удаляются. + +## Локальная транскрибация whisper.cpp + +`whisper-cli` проверен как ручной offline-fallback и инструмент benchmark, но пока +не встроен в приложение. На Apple Silicon используется Metal, авторизация не +требуется, а модели хранятся отдельно в `~/.dictate/models/`. + +Надёжный вход для установленной Homebrew-сборки — WAV 16 кГц mono: декодирование +сохранённого OGG/Opus в проведённом тесте завершилось ошибкой до распознавания. + +```bash +ffmpeg -i ~/.dictate/sessions//source.ogg \ + -ar 16000 -ac 1 /tmp/voice-dictation.wav + +/opt/homebrew/bin/whisper-cli \ + -m ~/.dictate/models/ggml-large-v3-turbo-q5_0.bin \ + -l ru -f /tmp/voice-dictation.wav -otxt +``` + +Smoke-test на русской записи 10:36 подтвердил работу Metal и локального inference. +При этом цельный файл потерял большие участки речи, а короткие перекрывающиеся +фрагменты дали существенно более полный текст. Поэтому перед интеграцией нужны +равномерный benchmark на минутных чанках и сравнение с полной `large-v3-q5_0`. +Облачный результат в текущем benchmark является только псевдоэталоном, а не +доказанной ручной расшифровкой. + ## Словарь (подсказки для Whisper) Создайте файл `~/.dictate/dictionary.txt` — слова и фразы, которые Whisper должен правильно распознавать: @@ -145,7 +200,8 @@ LaunchAgent запустит `python -m voice_dictation` при логине, п ## Troubleshooting -**`sox: command not found`** — установите sox через brew/choco. +**`ffmpeg не найден`** — установите ffmpeg через brew/choco. Короткие записи +продолжат работать, длинные останутся сохранёнными до установки ffmpeg. **Запись не останавливается** — проверьте разрешение микрофона. diff --git a/assets/icons/AppIcon.icns b/assets/icons/AppIcon.icns index a0ccf97..95f6b5f 100644 Binary files a/assets/icons/AppIcon.icns and b/assets/icons/AppIcon.icns differ diff --git a/assets/splash/dictator.png b/assets/splash/dictator.png new file mode 100644 index 0000000..2635924 Binary files /dev/null and b/assets/splash/dictator.png differ diff --git a/ci/Dockerfile b/ci/Dockerfile new file mode 100644 index 0000000..a928a23 --- /dev/null +++ b/ci/Dockerfile @@ -0,0 +1,4 @@ +# Cached OME images pinned by digest; build requires no network or apt packages. +FROM node:20-bookworm@sha256:8f693eaa7e0a8e71560c9a82b55fd54c2ae920a2ba5d2cde28bac7d1c01c9ba5 AS node +FROM python:3.13-bookworm@sha256:073ffebb96ae4d0ed73ccad59f08c47bd84af8a79f5258130f8458ac50ad9ff4 +COPY --from=node /usr/local/bin/node /usr/local/bin/node diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..4016ce9 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,10 @@ +# Документация + +- [Тестирование 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) +- [Описание приложения](../README.md) diff --git a/docs/beta-testing.md b/docs/beta-testing.md new file mode 100644 index 0000000..d4a6669 --- /dev/null +++ b/docs/beta-testing.md @@ -0,0 +1,116 @@ +# Тестовая macOS beta 0.3.0b1 + +Эта версия добавляет локальный Whisper и загрузку моделей в приложении. +GigaAM, наш сервер и автоматические обновления пока не реализованы. + +## Запуск + +Сборка находится в `dist/Voice Dictation Beta.app`. Откройте её отдельно, +не заменяя основную Voice Dictation. Это arm64-сборка для Apple Silicon, +macOS 13+. Подпись локальная ad-hoc, Apple notarization не выполнялась. + +Beta имеет отдельный bundle ID `ru.flowmasters.voicedictation.beta`, папку +`~/.dictate-beta/` и начальный хоткей `Cmd+Alt+Shift+D`. Настройки, записи, +модели, PID и статистика основной установки `~/.dictate/` не используются. +Разрешения микрофона и Accessibility для beta выдаются пользователем отдельно. +Не запускайте production installer script для этой сборки. + +## Локальное распознавание + +1. В меню beta откройте Настройки → Распознавание. +2. Выберите «Локально» и модель Base, Small или Large v3 Turbo Q5. +3. Нажмите «Скачать». После загрузки проверяются размер и SHA256. +4. Нажмите «Использовать выбранный режим и модель». +5. Проверьте диктовку с отключённой сетью. Хоткей начинает и завершает запись. + +Для подготовленной на Mac тестовой установки Base уже загружена в beta-папку. +Модели не включены в `.app` и переживают замену сборки. Можно проверить +установленную модель, отменить загрузку или удалить её; во время обработки +удаление блокируется. Незавершённая загрузка не считается установленной. +Для новых WAV-записей ffmpeg не нужен: приложение использует lossless PCM +фрагменты до 60 секунд с перекрытием. Локальный режим отключает облачные стили +постобработки и сетевой запрос курса валют; ошибок облачным fallback не исправляет. +Режим фиксируется при начале записи. Изменение настроек действует на следующую. +Старые сессии без сохранённых настроек не отправляются автоматически никуда. + +## Что проверить вручную + +- Короткая русская диктовка с именами, числами и техническими словами. +- Паузы и запись длиннее минуты; отсутствие пропавших фрагментов. +- Вставка в тестовый текстовый документ; для длинного текста — буфер обмена. +- Перезапуск beta: модель и настройки сохранились. +- Отмена загрузки, повтор, переключение моделей. + +Результат синтетического файла не доказывает качество живого микрофона. +Windows-совместимость проверена unit-тестами, настоящая Windows-сборка ещё +требует отдельной проверки. Base — компактный вариант для запуска, не победитель +сравнения качества. GigaAM сравним отдельно на тех же записях с эталоном человека. + +## Выбор облачной модели + +Во вкладке «Распознавание» выберите OpenAI API: здесь же выбирается облачная +модель. Для локального режима показан отдельный список скачиваемых моделей. +В «Общих» больше нет второго выбора облачной модели. Сохранение действует +для следующей записи; уже начатая запись использует свой снимок настроек. + +Добавлен gpt-transcribe: стоимость оценивается по $0.0045 за минуту, +языковая подсказка передаётся через languages[], а прежние модели продолжают +использовать language. Выбранная ранее облачная модель автоматически не меняется. +Новые запросы проверены синтетическими HTTP-ответами; доступность модели на +реальном аккаунте и качество требуют отдельного облачного теста по выбору пользователя. + +OpenAI объявил отключение whisper-1, gpt-4o-transcribe, +gpt-4o-mini-transcribe и gpt-4o-transcribe-diarize 26 февраля 2027 года. +[Официальное объявление](https://developers.openai.com/api/docs/deprecations#2026-08-26-transcription-models). +Для готовых записей рекомендован gpt-transcribe; gpt-live-transcribe относится +к отдельному сценарию распознавания живого потока и в бету не добавлен. +[Выбор сценария](https://developers.openai.com/api/docs/guides/transcription). + +## Экспериментальный GigaAM + +В списке моделей добавлены GigaAM v3 E2E CTC и Multilingual Large CTC. +Веса скачиваются в приложении, runtime пока устанавливается отдельно. +На тестовом Mac он уже установлен в профиле беты. Это CPU-эксперимент: +каждая обработка заново загружает модель; выигрыш в скорости не обещается. +Инструкция и проверенные замеры — [GigaAM для разработки](gigaam-development.md). + +## История диктовок и папка аудио + +В «Настройки → Статистика» выберите строку: «Копировать полный текст» копирует +итоговый текст после обработки, «Открыть папку аудио» открывает каталог записи. +В строке отдельно показаны длительность аудио, время обработки и стоимость. +Время обработки измеряется от остановки записи до готового итогового текста, +включая подготовку аудио и постобработку; ожидание вставки в него не входит. +Локальная модель показывает нулевую API-стоимость, а время остаётся измеряемым. +Старым строкам без измерений соответствует «—»; полный текст из короткого +предпросмотра не восстанавливается. + +В «Общие → Папка аудио» можно выбрать каталог новых записей. Старые записи +автоматически не перемещаются. Папка содержит сессии с аудио, расшифровкой +и данными восстановления; прежние каталоги продолжают использоваться для +поиска незавершённых сессий. Правила срока хранения действуют и в новом каталоге. +Если файл уже удалён, статистика сообщит, что аудио отсутствует. + +Проверка: сделать короткую диктовку, обновить статистику, сравнить скопированный +текст со вставленным, открыть папку; выбрать другой каталог и повторить. +Проверить, что новые файлы появились там, а старые остались на месте. + +## Сборка разработчиком + +```bash +./scripts/build_whisper_runtime.sh /tmp/voice-whisper-runtime +LOCAL_WHISPER_CLI=/tmp/voice-whisper-runtime/build/bin/whisper-cli \ +LOCAL_WHISPER_LICENSE_DIR=/tmp/voice-whisper-runtime \ +./scripts/build_macos.sh +``` + +Нужны CMake, Apple Command Line Tools и Python-окружение из CONTRIBUTING. +Runtime закреплён на whisper.cpp v1.9.2, исходный commit +`306c88f4d1286aec1bf96e544632897886af5501`. Он собран со статическими библиотеками +и встроенными Metal-ресурсами; Homebrew runtime plugins не нужны. + +## Связанные документы + +- [Навигация](README.md) +- [План](roadmap.md) +- [Разработка](../CONTRIBUTING.md) 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..bd887a6 --- /dev/null +++ b/docs/issues/model-catalog-research.md @@ -0,0 +1,23 @@ +# Исследовать и сравнить локальные ASR-модели для выбора в приложении + +Forgejo issue: [#3](https://git.flowmasters.ru/Soschen/voice-dictation/issues/3). + +## Задача +Расширить выбор локальных моделей распознавания: пользователь скачивает модели внутри приложения, сравнивает их на своей задаче и выбирает подходящую. + +## Исследование +- Составить каталог моделей и движков помимо 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/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..98d7e38 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,82 @@ +# План развития Voice Dictation + +Согласован 19 октября 2026 года. Этот документ описывает будущую реализацию. +В ветке `feature/local-transcription` реализована тестовая beta: OpenAI, локальный +Whisper и проверяемая загрузка моделей внутри приложения. Серверный режим, GigaAM +и автообновления ещё не реализованы. Приёмка живого микрофона и Windows остаётся +отдельной: [инструкция beta](beta-testing.md). + +## Целевая модель + +В приложении выбираются независимо место выполнения и совместимая модель: + +| Режим | Где обрабатывается запись | Настройки | +| --- | --- | --- | +| Облачный API | Внешний провайдер, первоначально OpenAI | Провайдер, ключ, модель | +| Наш сервер | Управляемый нами сервер распознавания | URL, авторизация, доступная модель | +| Локально | Компьютер пользователя | Совместимая модель, загрузка и управление файлами | + +Единый контракт транскрибатора отделяет запись, интерфейс и автовставку от +движка. Whisper не является обязательным форматом для всех реализаций. +Модель, версия и runtime сохраняются в метаданных результата и сессии. +При восстановлении сессии нельзя незаметно менять движок или модель. + +## Локальный режим: реализация beta и критерии приёмки + +1. Ввести общий интерфейс транскрибатора и фабрику движков, сохранив OpenAI. + Конфигурация старой установки мигрирует без потери настроек. +2. Реализовать локальный адаптер; whisper.cpp — первоначальный кандидат. + До фиксации runtime проверить актуальные официальные требования, лицензии, + платформы и способы распространения. GigaAM включить в сравнение кандидатов; + заранее победителя не выбирать. +3. Добавить настройки места выполнения и совместимой модели. OpenAI-ключ + не требуется для локального распознавания. +4. Встроить каталог моделей: размер, совместимость с ОС/архитектурой и требования + к памяти. Кнопки скачать, отменить, выбрать и удалить; прогресс и ошибки. + Загрузка идёт во временный файл, проверяется checksum, затем файл атомарно + становится доступен. Неисправная/неполная модель не запускается. +5. После скачивания распознавание работает без сети. Отсутствующий runtime, + нехватка места и повреждённая модель дают понятную ошибку. Секреты и модели + не попадают в Git и диагностические сообщения. +6. Постобработка настраивается отдельно: отключена, внешний API либо будущий + локальный движок. Полностью офлайн-режим исключает сетевую постобработку. + Автоматического перехода в облако при ошибке локального режима нет. +7. Сохранить длинные записи, checkpoint/resume, словарь там, где он поддерживается, + буфер и автовставку. Неподдерживаемые возможности показывать явно. + +### Приёмка и сравнение + +- Одни и те же разрешённые русские записи для Whisper, GigaAM и облачного baseline; + аудио и расшифровки остаются вне репозитория. +- Эталон исправлен человеком. Проверяем пропуски, замены, имена, числа и термины; + облачный результат не считается эталоном автоматически. +- Замеряем полное время, время загрузки модели отдельно, RAM/VRAM, CPU/GPU и + поведение на длинной записи. Фиксируем железо, ОС, runtime, версию модели, + квантование и параметры нарезки. Неподдерживаемые конфигурации отмечаем явно. +- Проверяем офлайн-работу после загрузки, отмену/повтор скачивания, checksum, + отсутствие ключа OpenAI и отсутствие скрытой передачи аудио наружу. +- Автоматические проверки плюс ручной микрофонный тест на целевых платформах. + +## Затем: наш сервер + +Отдельный PR: серверный контракт и клиентский адаптер с выбором URL/модели, +авторизацией, TLS, ограничением размера, таймаутами, отменой и понятными ошибками. +Зафиксировать политику удаления аудио и исключить аудио/текст из обычных логов. +Секреты сервера хранятся вне Git. Производительность проверяется на фактическом +сервере; модель и железо пока не выбраны. Развёртывание — отдельный этап. + +## Перенос исходников + +Продолжаем существующий приватный репозиторий `Soschen/voice-dictation`. +Ветка переноса сохраняет текущую локальную версию; main содержит отличающуюся +Windows-версию (исходный commit `70a5dce`). Windows installer/spec и история сохранены. +В beta исправлены миграция стилей/режимов и поиск прежнего ffmpeg. +Перед слиянием на реальной Windows сверить режимы обработки, шесть кастомных стилей, загрузку ffmpeg, +автовставку и упаковку Windows. Прохождение unit-тестов на macOS не заменяет эту +проверку. Исходная рабочая установка не перемещалась и не пересобиралась. + +## Связанные документы + +- [Навигация](README.md) +- [Работа с репозиторием](../CONTRIBUTING.md) +- [Архитектура текущей версии](../ARCHITECTURE.md) diff --git a/pyproject.toml b/pyproject.toml index 6f64385..b8d6c4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "voice-dictation" -version = "0.2.0" +dynamic = ["version"] description = "Desktop голосовая диктовка через Whisper API" requires-python = ">=3.11" readme = "README.md" @@ -19,7 +19,11 @@ dependencies = [ "pystray>=0.19.5", "Pillow>=10.0.0", "customtkinter>=5.2.0", + "sounddevice>=0.4.6", + "openai>=1.40.0", "winotify>=1.1.0; sys_platform == 'win32'", + "pyobjc-framework-Cocoa>=10.3; sys_platform == 'darwin'", + "pyobjc-framework-Quartz>=10.3; sys_platform == 'darwin'", ] [project.optional-dependencies] @@ -36,6 +40,9 @@ voice-dictation = "voice_dictation.__main__:main" voice-dictation-headless = "voice_dictation.cli.headless:main" voice-dictation-tray = "voice_dictation.__main__:main" +[tool.setuptools.dynamic] +version = {attr = "voice_dictation.__version__"} + [tool.setuptools.packages.find] where = ["src"] @@ -92,6 +99,14 @@ module = [ "pynput.*", "pyperclip.*", "psutil.*", + "sounddevice.*", + "pystray.*", + "customtkinter.*", + "AppKit.*", + "ApplicationServices.*", + "Quartz.*", + "Foundation.*", + "PyObjCTools.*", ] ignore_missing_imports = true 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/build_macos.sh b/scripts/build_macos.sh old mode 100644 new mode 100755 index 96479df..a9b10dd --- a/scripts/build_macos.sh +++ b/scripts/build_macos.sh @@ -39,7 +39,7 @@ rm -rf dist/ build/ echo "[ШАГ 2/3] Запуск PyInstaller..." pyinstaller scripts/voice_dictation.spec --noconfirm -APP_PATH="dist/Voice Dictation.app" +APP_PATH="dist/Voice Dictation Beta.app" if [[ ! -d "${APP_PATH}" ]]; then echo "[ОШИБКА] Сборка не удалась — нет ${APP_PATH}" exit 1 @@ -55,7 +55,7 @@ SYS_TCL_SCRIPTS="${PY_FRAMEWORKS}/Tcl.framework/Versions/8.6/Resources/Scripts" BUNDLE_TK_DATA="${APP_PATH}/Contents/Frameworks/_tk_data" BUNDLE_TCL_DATA="${APP_PATH}/Contents/Frameworks/_tcl_data" -if [[ -d "${SYS_TK_SCRIPTS}" && -d "${BUNDLE_TK_DATA}" ]]; then +if [[ -d "${SYS_TK_SCRIPTS}" ]]; then rm -rf "${BUNDLE_TK_DATA}" cp -R "${SYS_TK_SCRIPTS}" "${BUNDLE_TK_DATA}" echo " tk: ${SYS_TK_SCRIPTS} -> ${BUNDLE_TK_DATA}" @@ -63,25 +63,31 @@ fi if [[ -d "${SYS_TCL_SCRIPTS}" && -d "${BUNDLE_TCL_DATA}" ]]; then rm -rf "${BUNDLE_TCL_DATA}" cp -R "${SYS_TCL_SCRIPTS}" "${BUNDLE_TCL_DATA}" + # Эти необязательные Tcl-пакеты имеют расширение в имени директории; + # codesign принимает их за вложенные bundle. Voice Dictation их не использует. + rm -rf "${BUNDLE_TCL_DATA}/opt0.4" "${BUNDLE_TCL_DATA}/http1.0" echo " tcl: ${SYS_TCL_SCRIPTS} -> ${BUNDLE_TCL_DATA}" fi -# Пере-подписать app после изменений (ad-hoc, чтобы Gatekeeper не заплакал) -codesign --force --deep --sign - "${APP_PATH}" 2>/dev/null || true +# Пере-подписать app после изменений (локальная ad-hoc подпись). +xattr -cr "${APP_PATH}" +codesign --force --deep --sign - "${APP_PATH}" +codesign --verify --deep --strict "${APP_PATH}" echo "[ШАГ 3/3] Готово!" echo echo " ${APP_PATH}" echo echo "Запуск: open \"${APP_PATH}\"" -echo "Установка: mv \"${APP_PATH}\" /Applications/" +echo "Тестовая сборка: установка выполняется отдельно вручную." echo "Размер: $(du -sh "${APP_PATH}" | cut -f1)" echo # DMG (опционально) if [[ "${1:-}" == "dmg" ]]; then echo "[ДОП] Сборка DMG..." - DMG_PATH="dist/VoiceDictation-0.1.0.dmg" + VERSION="$(python -c 'from voice_dictation import __version__; print(__version__)')" + DMG_PATH="dist/VoiceDictation-Beta-${VERSION}.dmg" rm -f "${DMG_PATH}" if command -v create-dmg >/dev/null 2>&1; then @@ -90,7 +96,7 @@ if [[ "${1:-}" == "dmg" ]]; then --window-pos 200 120 \ --window-size 600 400 \ --icon-size 96 \ - --icon "Voice Dictation.app" 175 200 \ + --icon "Voice Dictation Beta.app" 175 200 \ --hide-extension "Voice Dictation.app" \ --app-drop-link 425 200 \ "${DMG_PATH}" \ diff --git a/scripts/build_whisper_runtime.sh b/scripts/build_whisper_runtime.sh new file mode 100755 index 0000000..7a5ec2a --- /dev/null +++ b/scripts/build_whisper_runtime.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Standalone runtime from pinned upstream source; no system installation. +set -euo pipefail +WHISPER_COMMIT="306c88f4d1286aec1bf96e544632897886af5501" # v1.9.2 +RUNTIME_ROOT="${1:-/tmp/voice-whisper-runtime}" +CMAKE_BIN="${CMAKE_BIN:-cmake}" +if [[ ! -d "${RUNTIME_ROOT}/.git" ]]; then + git clone --depth 1 --branch v1.9.2 https://github.com/ggml-org/whisper.cpp.git "${RUNTIME_ROOT}" +fi +ACTUAL_COMMIT="$(git -C "${RUNTIME_ROOT}" rev-parse HEAD)" +if [[ "${ACTUAL_COMMIT}" != "${WHISPER_COMMIT}" ]]; then + echo "Runtime source does not match pinned upstream commit" >&2 + exit 1 +fi +if [[ -n "$(git -C "${RUNTIME_ROOT}" status --porcelain --untracked-files=no)" ]]; then + echo "Runtime source has tracked modifications" >&2 + exit 1 +fi +"${CMAKE_BIN}" -S "${RUNTIME_ROOT}" -B "${RUNTIME_ROOT}/build" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 \ + -DBUILD_SHARED_LIBS=OFF \ + -DGGML_BACKEND_DL=OFF \ + -DGGML_NATIVE=OFF \ + -DGGML_METAL_EMBED_LIBRARY=ON \ + -DGGML_BLAS=OFF \ + -DWHISPER_BUILD_TESTS=OFF \ + -DWHISPER_BUILD_EXAMPLES=ON +"${CMAKE_BIN}" --build "${RUNTIME_ROOT}/build" --config Release \ + --target whisper-cli --parallel "${BUILD_JOBS:-4}" +# Review output: only Apple/system libraries are expected for the macOS runtime. +otool -L "${RUNTIME_ROOT}/build/bin/whisper-cli" +echo "LOCAL_WHISPER_CLI=${RUNTIME_ROOT}/build/bin/whisper-cli" +echo "LOCAL_WHISPER_LICENSE_DIR=${RUNTIME_ROOT}" diff --git a/scripts/com.vickenty.voicedictation.plist.template b/scripts/com.vickenty.voicedictation.plist.template index 7d353d5..da948ce 100644 --- a/scripts/com.vickenty.voicedictation.plist.template +++ b/scripts/com.vickenty.voicedictation.plist.template @@ -7,9 +7,7 @@ ProgramArguments - {{PYTHON_BIN}} - -m - voice_dictation + {{APP_EXECUTABLE}} WorkingDirectory diff --git a/scripts/install_autostart_macos.sh b/scripts/install_autostart_macos.sh old mode 100644 new mode 100755 index a34b4d4..40392bc --- a/scripts/install_autostart_macos.sh +++ b/scripts/install_autostart_macos.sh @@ -9,8 +9,8 @@ set -euo pipefail LABEL="com.vickenty.voicedictation" PLIST_DEST="$HOME/Library/LaunchAgents/${LABEL}.plist" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" TEMPLATE="${SCRIPT_DIR}/com.vickenty.voicedictation.plist.template" +APP_EXECUTABLE="${VOICE_DICTATION_APP_EXECUTABLE:-/Applications/Voice Dictation.app/Contents/MacOS/VoiceDictation}" if [[ "${1:-}" == "uninstall" ]]; then launchctl unload "${PLIST_DEST}" 2>/dev/null || true @@ -19,17 +19,15 @@ if [[ "${1:-}" == "uninstall" ]]; then exit 0 fi -# Найти python из venv проекта (приоритет) или системный python3 -if [[ -x "${PROJECT_DIR}/.venv/bin/python" ]]; then - PYTHON_BIN="${PROJECT_DIR}/.venv/bin/python" -else - PYTHON_BIN="$(command -v python3)" +if [[ ! -x "${APP_EXECUTABLE}" ]]; then + echo "[ОШИБКА] Не найдено установленное приложение: ${APP_EXECUTABLE}" + exit 1 fi mkdir -p "$(dirname "${PLIST_DEST}")" sed \ - -e "s|{{PYTHON_BIN}}|${PYTHON_BIN}|g" \ - -e "s|{{WORKING_DIR}}|${PROJECT_DIR}|g" \ + -e "s|{{APP_EXECUTABLE}}|${APP_EXECUTABLE}|g" \ + -e "s|{{WORKING_DIR}}|${HOME}/.dictate|g" \ -e "s|{{HOME}}|${HOME}|g" \ "${TEMPLATE}" > "${PLIST_DEST}" @@ -37,8 +35,7 @@ launchctl unload "${PLIST_DEST}" 2>/dev/null || true launchctl load "${PLIST_DEST}" echo "Установлено: ${PLIST_DEST}" -echo "Python: ${PYTHON_BIN}" -echo "Проект: ${PROJECT_DIR}" +echo "Приложение: ${APP_EXECUTABLE}" echo echo "Управление:" echo " launchctl unload ${PLIST_DEST} # остановить" 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/scripts/install_macos_app.sh b/scripts/install_macos_app.sh new file mode 100755 index 0000000..6d12634 --- /dev/null +++ b/scripts/install_macos_app.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Устанавливает собранный bundle в /Applications с recoverable backup. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +SOURCE_APP="${1:-${PROJECT_DIR}/dist/Voice Dictation.app}" +DEST_APP="/Applications/Voice Dictation.app" + +if [[ ! -d "${SOURCE_APP}" ]]; then + echo "[ОШИБКА] Не найдена сборка: ${SOURCE_APP}" + exit 1 +fi + +pkill -TERM -x VoiceDictation 2>/dev/null || true +for _attempt in 1 2 3 4 5; do + if ! pgrep -x VoiceDictation >/dev/null 2>&1; then + break + fi + sleep 1 +done +if pgrep -x VoiceDictation >/dev/null 2>&1; then + pkill -KILL -x VoiceDictation + sleep 1 +fi + +if [[ -d "${DEST_APP}" ]]; then + BACKUP_APP="${HOME}/.Trash/Voice Dictation before $(date +%Y%m%d-%H%M%S).app" + mv "${DEST_APP}" "${BACKUP_APP}" + echo "Резервная копия: ${BACKUP_APP}" +fi + +/usr/bin/ditto "${SOURCE_APP}" "${DEST_APP}" + +codesign --verify --deep --strict "${DEST_APP}" +/usr/bin/open "${DEST_APP}" + +echo "Установлено: ${DEST_APP}" diff --git a/scripts/pyi_rth_tk.py b/scripts/pyi_rth_tk.py index b390764..6db4b61 100644 --- a/scripts/pyi_rth_tk.py +++ b/scripts/pyi_rth_tk.py @@ -1,17 +1,17 @@ -"""Runtime hook для PyInstaller: указывает Tcl/Tk на упакованные библиотеки. - -PyInstaller на Python 3.13 + Tk 8.6 на macOS неправильно прописывает -TCL_LIBRARY/TK_LIBRARY — приходится делать руками. -""" +"""Point Tcl/Tk at bundled scripts rather than build-machine installations.""" import os import sys +from pathlib import Path if hasattr(sys, "_MEIPASS"): - base = sys._MEIPASS - tcl_dir = os.path.join(base, "tcl") - tk_dir = os.path.join(base, "tk") - if os.path.isdir(tcl_dir): - os.environ["TCL_LIBRARY"] = tcl_dir - if os.path.isdir(tk_dir): - os.environ["TK_LIBRARY"] = tk_dir + base = Path(sys._MEIPASS) + for variable, candidates in ( + ("TCL_LIBRARY", ("_tcl_data", "tcl")), + ("TK_LIBRARY", ("_tk_data", "tk")), + ): + for name in candidates: + directory = base / name + if directory.is_dir(): + os.environ[variable] = str(directory) + break diff --git a/scripts/voice_dictation.spec b/scripts/voice_dictation.spec index c96d512..dede5d1 100644 --- a/scripts/voice_dictation.spec +++ b/scripts/voice_dictation.spec @@ -10,6 +10,8 @@ dist/Voice Dictation.app """ +import os +import runpy from pathlib import Path PROJECT_ROOT = Path(SPECPATH).parent @@ -17,14 +19,51 @@ SRC = PROJECT_ROOT / "src" ICON = PROJECT_ROOT / "assets" / "icons" / "AppIcon.icns" RT_HOOK_TK = PROJECT_ROOT / "scripts" / "pyi_rth_tk.py" +VERSION = runpy.run_path(str(SRC / "voice_dictation" / "__init__.py"))["__version__"] +# CFBundleShortVersionString accepts numeric release components only. +MAC_VERSION = VERSION.split("b")[0] +BUILD_VERSION = MAC_VERSION + "." + VERSION.split("b")[1] +LOCAL_WHISPER_CLI = os.environ.get("LOCAL_WHISPER_CLI") +NATIVE_BINARIES = [] +NATIVE_LICENSES = [] +if LOCAL_WHISPER_CLI: + executable = Path(LOCAL_WHISPER_CLI).expanduser().resolve(strict=True) + NATIVE_BINARIES.append((str(executable), "bin")) + license_root = Path(os.environ.get( + "LOCAL_WHISPER_LICENSE_DIR", str(executable.parent.parent.parent) + )).expanduser().resolve() + for license_file, destination in ( + (license_root / "LICENSE", "licenses/whisper.cpp"), + (license_root / "ggml" / "LICENSE", "licenses/ggml"), + ): + if not license_file.is_file(): + if destination == "licenses/ggml": + # Pinned whisper.cpp vendors ggml under the root ggml-authors license. + continue + raise FileNotFoundError( + f"Missing runtime license {license_file}; set LOCAL_WHISPER_LICENSE_DIR" + ) + NATIVE_LICENSES.append((str(license_file), destination)) + # Keep adjacent runtime dylibs together; PyInstaller also scans dependencies. + library_dirs = [executable.parent, executable.parent.parent / "lib"] + library_dirs.extend( + Path(directory).expanduser().resolve(strict=True) + for directory in os.environ.get("LOCAL_WHISPER_LIB_DIRS", "").split(os.pathsep) + if directory + ) + for directory in library_dirs: + for pattern in ("*.dylib", "*.so"): + for library in sorted(directory.glob(pattern)): + NATIVE_BINARIES.append((str(library), "bin")) + block_cipher = None a = Analysis( [str(SRC / "voice_dictation" / "__main__.py")], pathex=[str(SRC)], - binaries=[], - datas=[], + binaries=NATIVE_BINARIES, + datas=NATIVE_LICENSES, hiddenimports=[ "voice_dictation", "voice_dictation.cli.headless", @@ -32,6 +71,7 @@ a = Analysis( "voice_dictation.ui.settings_window", "voice_dictation.ui.tray", "voice_dictation.ui.icons", + "voice_dictation.ui.splash", "voice_dictation.platform.macos.autopaste", "voice_dictation.platform.macos.clipboard", "voice_dictation.platform.macos.hotkey_listener", @@ -45,6 +85,7 @@ a = Analysis( "voice_dictation.platform.windows.sound_player", "voice_dictation.platform.windows.system_sounds_scanner", "voice_dictation.core.balance", + "voice_dictation.core.compressor", "voice_dictation.core.fx", "voice_dictation.core.usage_db", "pkg_resources", @@ -53,6 +94,8 @@ a = Analysis( "darkdetect", "pystray._darwin", "PIL._tkinter_finder", + "sounddevice", + "openai", ], hookspath=[], hooksconfig={}, @@ -103,26 +146,26 @@ coll = COLLECT( app = BUNDLE( coll, - name="Voice Dictation.app", + name="Voice Dictation Beta.app", icon=str(ICON), - bundle_identifier="ru.flowmasters.voicedictation", - version="0.1.0", + bundle_identifier="ru.flowmasters.voicedictation.beta", + version=MAC_VERSION, info_plist={ - "CFBundleName": "Voice Dictation", - "CFBundleDisplayName": "Voice Dictation", - "CFBundleShortVersionString": "0.1.0", - "CFBundleVersion": "0.1.0", - "CFBundleIdentifier": "ru.flowmasters.voicedictation", + "CFBundleName": "Voice Dictation Beta", + "CFBundleDisplayName": "Voice Dictation Beta", + "CFBundleShortVersionString": MAC_VERSION, + "CFBundleVersion": BUILD_VERSION, + "CFBundleIdentifier": "ru.flowmasters.voicedictation.beta", "CFBundleExecutable": "VoiceDictation", # LSUIElement=true — приложение живёт только в трее, без иконки в Dock "LSUIElement": True, "NSHighResolutionCapable": True, # Минимальная версия macOS (universal2 рантайм) - "LSMinimumSystemVersion": "11.0", + "LSMinimumSystemVersion": "13.0", # Permissions — пояснения для пользователя "NSMicrophoneUsageDescription": ( "Voice Dictation использует микрофон для записи речи и её " - "транскрипции через OpenAI Whisper API." + "транскрипции локально или через выбранного провайдера." ), "NSAppleEventsUsageDescription": ( "Voice Dictation использует AppleScript для показа уведомлений " diff --git a/src/voice_dictation/__init__.py b/src/voice_dictation/__init__.py index 0a3981a..b1a7f2e 100644 --- a/src/voice_dictation/__init__.py +++ b/src/voice_dictation/__init__.py @@ -2,4 +2,4 @@ from __future__ import annotations -__version__ = "0.2.0" +__version__ = "0.3.0b9" diff --git a/src/voice_dictation/__main__.py b/src/voice_dictation/__main__.py index cd0b9f6..5dbb57f 100644 --- a/src/voice_dictation/__main__.py +++ b/src/voice_dictation/__main__.py @@ -7,34 +7,71 @@ import signal import sys import threading from datetime import datetime +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from voice_dictation.core.paths import AppPaths logger = logging.getLogger(__name__) -def _format_hotkey(hotkey: str) -> str: - """Человекочитаемое отображение хоткея под текущую ОС. - - На macOS — символы клавиш (⌘⌥⌃⇧), на Windows/Linux — словами (Ctrl + Shift + Space). - """ - if sys.platform == "darwin": - return ( - hotkey.replace("cmd", "⌘") - .replace("alt", "⌥") - .replace("ctrl", "⌃") - .replace("shift", "⇧") - ) - return " + ".join(part.capitalize() for part in hotkey.split("+")) - - def main() -> None: """Tray-режим: иконка в строке меню + хоткей. Если в argv передана подкоманда `headless` или `stats` — делегирует CLI. """ + if len(sys.argv) == 3 and sys.argv[1] == "input-safety-check": + from pathlib import Path + + from voice_dictation.ui.hotkey_acceptance import run_input_check + + run_input_check(Path(sys.argv[2])) + return + + if len(sys.argv) > 1 and sys.argv[1] == "transcribe-file": + from voice_dictation.cli.transcribe_file import main as transcribe_main + + transcribe_main(sys.argv[2:]) + return + + if len(sys.argv) > 1 and sys.argv[1] == "setup": + from voice_dictation.core.config import ConfigStore + from voice_dictation.core.paths import AppPaths + from voice_dictation.ui.setup_wizard import run_setup + + if "--smoke-test" in sys.argv: + import tempfile + from pathlib import Path + + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + with ( + synthetic_clipboard(), + tempfile.TemporaryDirectory(prefix="voice-setup-smoke-") as directory, + ): + test_root = Path(directory) + if not run_setup( + test_root, ConfigStore(test_root / "config.json"), smoke_test=True + ): + raise RuntimeError("Setup smoke test failed to save synthetic settings") + return + setup_paths = AppPaths.default().ensure_exists() + if "--startup-setup-test" in sys.argv: + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + with synthetic_clipboard(): + if not run_setup( + setup_paths.root, ConfigStore(setup_paths.config_file), smoke_test=True + ): + raise RuntimeError("Startup setup test failed") + else: + run_setup(setup_paths.root, ConfigStore(setup_paths.config_file)) + return + if len(sys.argv) > 1 and sys.argv[1] == "settings": from voice_dictation.ui.settings_cli import main as settings_main - settings_main() + settings_main(smoke_test="--smoke-test" in sys.argv) return if len(sys.argv) > 1 and sys.argv[1] in {"headless", "stats"}: @@ -46,6 +83,10 @@ def main() -> None: cli_main() return + if len(sys.argv) > 1 and sys.argv[1] == "splash": + _run_splash_test() + return + from voice_dictation.infrastructure.env_loader import load_env try: @@ -73,8 +114,45 @@ def main() -> None: config_store = ConfigStore(paths.config_file) config = config_store.load() + if not paths.config_file.exists() and paths.root.name == ".dictate-beta": + config.transcription_backend = "local" + config.hotkey = "cmd+alt+shift+d" + config.splash_enabled = False + config_store.save(config) + if not (paths.root / "setup-complete").exists(): + import os + import subprocess + + # Tk and pystray/AppKit must not share a process on macOS. + setup_command = ( + [sys.executable, "setup"] + if getattr(sys, "frozen", False) + else [sys.executable, "-m", "voice_dictation", "setup"] + ) + if "--startup-smoke-test" in sys.argv: + setup_command.append("--startup-setup-test") + setup_env = os.environ.copy() + setup_env["VOICE_DICTATION_HOME"] = str(paths.root) + try: + setup_result = subprocess.run(setup_command, env=setup_env, check=False) + except OSError: + logger.error("Не удалось открыть мастер настройки") + lock.release() + return + if setup_result.returncode or not (paths.root / "setup-complete").exists(): + lock.release() + return + config = config_store.load() + env = load_env() logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model) + if config.splash_enabled: + _show_splash_for_paths( + paths, + config.splash_duration_sec, + audio_enabled=config.splash_audio_enabled, + ) + from voice_dictation.infrastructure.errors import ( SoxNotFoundError, UnsupportedPlatformError, @@ -91,15 +169,21 @@ def main() -> None: from voice_dictation.core.recorder import SoxRecorder try: - recorder = SoxRecorder(sample_rate=16000, bin_dir=paths.bin_dir) + recorder = SoxRecorder(sample_rate=16000) except SoxNotFoundError as exc: logger.error("%s", exc) print(f"[ОШИБКА] {exc}", file=sys.stderr) sys.exit(1) - from voice_dictation.core.transcriber import WhisperTranscriber + from voice_dictation.core.transcription import RoutingTranscriber - transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model) + transcriber = RoutingTranscriber(api_key=env.api_key, models_dir=paths.models_dir) + + from voice_dictation.core.compressor import AudioCompressor + + compressor = AudioCompressor() + if not compressor.is_available(): + logger.warning("ffmpeg не найден — сжатие аудио отключено, шлём WAV как есть") from voice_dictation.core.dictionary import Dictionary @@ -129,10 +213,11 @@ def main() -> None: auto_paste=platform_bundle.auto_paste, sound_player=platform_bundle.sound_player, notifier=platform_bundle.notifier, - config_provider=config_store.current, + config_provider=config_store.load, paths=paths, state_listener=_state_changed, usage_db=usage_db, + compressor=compressor, ) # Проверяем Accessibility — без неё NSEvent global monitor не получает событий @@ -157,6 +242,13 @@ def main() -> None: logger.warning("Не удалось зарегистрировать %s, fallback %s", config.hotkey, fallback) platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle) + recovered = orchestrator.resume_pending_sessions() + if recovered: + platform_bundle.notifier.show( + "Voice Dictation", + f"Продолжаю незавершённых записей: {recovered}", + ) + def _show_stats() -> None: tz = datetime.now().astimezone().tzinfo today = usage_db.today_total(tz=tz) @@ -198,31 +290,41 @@ def main() -> None: def _quit() -> None: shutdown_event.set() - from voice_dictation.core.modes import all_specs, get_mode - - def _list_modes() -> list[tuple[str, str]]: - cfg = config_store.current() - return [(m.key, m.label) for m in all_specs(cfg.custom_modes)] - - def _select_mode(key: str) -> None: - cfg = config_store.current() - cfg.mode = key + def _select_preset(name: str) -> None: + cfg = config_store.load() + cfg.active_preset = name config_store.save(cfg) - spec = get_mode(key, cfg.custom_modes) - platform_bundle.notifier.show("Voice Dictator", f"Режим: {spec.label}") - logger.info("Режим переключён: mode=%s", key) + platform_bundle.notifier.show("Voice Dictation", f"Режим: {name}") + logger.info("Preset выбран: %s", name) - def _get_mode() -> str: - return config_store.current().mode + def _get_active_preset() -> str: + return config_store.load().active_preset + + def _get_preset_names() -> list[str]: + return [p.name for p in config_store.load().summary_presets] + + def _toggle_splash() -> bool: + cfg = config_store.load() + cfg.splash_enabled = not cfg.splash_enabled + config_store.save(cfg) + state = "включён" if cfg.splash_enabled else "выключен" + platform_bundle.notifier.show("Voice Dictation", f"Splash {state}") + logger.info("Splash переключён: enabled=%s", cfg.splash_enabled) + return cfg.splash_enabled + + def _get_splash_state() -> bool: + return config_store.load().splash_enabled tray = TrayApp( on_toggle=orchestrator.toggle, on_settings=_show_settings, on_stats=_show_stats, on_quit=_quit, - modes_provider=_list_modes, - on_mode_select=_select_mode, - current_mode=_get_mode, + on_preset_select=_select_preset, + get_active_preset=_get_active_preset, + get_preset_names=_get_preset_names, + on_splash_toggle=_toggle_splash, + get_splash_state=_get_splash_state, ) tray_holder["tray"] = tray @@ -248,9 +350,12 @@ def main() -> None: threading.Thread(target=_watchdog, name="shutdown-watchdog", daemon=True).start() - hotkey_display = _format_hotkey(config.hotkey) + hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃") print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}") + if "--startup-smoke-test" in sys.argv: + threading.Timer(2.0, _quit).start() + try: tray.run() finally: @@ -261,5 +366,48 @@ def main() -> None: logger.info("Voice Dictation остановлен") +def _show_splash_for_paths( + paths: AppPaths, + duration_sec: float, + audio_enabled: bool = True, +) -> None: + """Ищет splash-ассеты в ~/.dictate/splash/ и показывает окно. + + Args: + paths: AppPaths приложения. + duration_sec: Сколько секунд показывать splash. + audio_enabled: Если False — splash будет тихим, даже если файл есть. + + Картинка: dictator.png. Аудио: soviet_march.mp3 (Mac) / soviet_march.wav (Win). + Если ассетов нет — splash тихо пропускается, лог в DEBUG. + """ + from pathlib import Path + + from voice_dictation.ui.splash import show_splash + + splash_dir = paths.root / "splash" + image_path = splash_dir / "dictator.png" + audio_path: Path | None = None + if audio_enabled: + for candidate_name in ("soviet_march.mp3", "soviet_march.wav", "soviet_march.ogg"): + candidate = splash_dir / candidate_name + if candidate.exists(): + audio_path = candidate + break + + show_splash(image_path, audio_path, duration_sec=duration_sec) + + +def _run_splash_test() -> None: + """`python -m voice_dictation splash` — показать splash без запуска tray.""" + from voice_dictation.core.paths import AppPaths + from voice_dictation.infrastructure.logging_setup import configure_logging + + paths = AppPaths.default().ensure_exists() + configure_logging(paths, verbose=True) + logger.info("Splash test: ищу ассеты в %s/splash/", paths.root) + _show_splash_for_paths(paths, duration_sec=5.0, audio_enabled=True) + + if __name__ == "__main__": main() diff --git a/src/voice_dictation/cli/headless.py b/src/voice_dictation/cli/headless.py index df643f5..f79c5e6 100644 --- a/src/voice_dictation/cli/headless.py +++ b/src/voice_dictation/cli/headless.py @@ -51,6 +51,11 @@ def main() -> None: config_store = ConfigStore(paths.config_file) config = config_store.load() + if not paths.config_file.exists() and paths.root.name == ".dictate-beta": + config.transcription_backend = "local" + config.hotkey = "cmd+alt+shift+d" + config.splash_enabled = False + config_store.save(config) logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model) # 6. Платформенные компоненты @@ -76,9 +81,16 @@ def main() -> None: sys.exit(1) # 8. Transcriber - from voice_dictation.core.transcriber import WhisperTranscriber + from voice_dictation.core.transcription import RoutingTranscriber - transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model) + transcriber = RoutingTranscriber(api_key=env.api_key, models_dir=paths.models_dir) + + # 8.1. Audio compressor (опционально — если ffmpeg есть) + from voice_dictation.core.compressor import AudioCompressor + + compressor = AudioCompressor() + if not compressor.is_available(): + logger.warning("ffmpeg не найден — сжатие аудио отключено, шлём WAV как есть") # 9. Dictionary from voice_dictation.core.dictionary import Dictionary @@ -104,10 +116,11 @@ def main() -> None: auto_paste=platform_bundle.auto_paste, sound_player=platform_bundle.sound_player, notifier=platform_bundle.notifier, - config_provider=config_store.current, + config_provider=config_store.load, paths=paths, state_listener=_state_changed, usage_db=usage_db, + compressor=compressor, ) # 11. Регистрация хоткея @@ -117,6 +130,8 @@ def main() -> None: fallback = "cmd+shift+d" if sys.platform == "darwin" else "ctrl+shift+d" platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle) + orchestrator.resume_pending_sessions() + # 12. Обработчик сигналов для graceful shutdown def _shutdown(signum: int, frame: object) -> None: logger.info("Получен сигнал %d, завершение...", signum) @@ -128,15 +143,7 @@ def main() -> None: signal.signal(signal.SIGTERM, _shutdown) signal.signal(signal.SIGINT, _shutdown) - if sys.platform == "darwin": - hotkey_display = ( - config.hotkey.replace("cmd", "⌘") - .replace("alt", "⌥") - .replace("ctrl", "⌃") - .replace("shift", "⇧") - ) - else: - hotkey_display = " + ".join(part.capitalize() for part in config.hotkey.split("+")) + hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃") print( f"Voice Dictation запущен. Хоткей: {hotkey_display}\n" "Нажмите хоткей для начала записи, ещё раз — для остановки и транскрипции.\n" diff --git a/src/voice_dictation/cli/transcribe_file.py b/src/voice_dictation/cli/transcribe_file.py new file mode 100644 index 0000000..59a7101 --- /dev/null +++ b/src/voice_dictation/cli/transcribe_file.py @@ -0,0 +1,30 @@ +"""Explicit offline file transcription for beta diagnostics and benchmarks.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +from voice_dictation.core.model_manager import CATALOG, ModelManager +from voice_dictation.core.paths import AppPaths +from voice_dictation.core.transcription import RoutingTranscriber + + +def main(arguments: list[str] | None = None) -> None: + """Transcribe a user-selected file locally, without loading cloud keys.""" + parser = argparse.ArgumentParser(description="Локально распознать выбранный файл") + parser.add_argument("audio", type=Path) + parser.add_argument("--model", choices=[m.id for m in CATALOG], default="whisper-base") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--download", action="store_true", help="Скачать модель при необходимости") + args = parser.parse_args(arguments) + paths = AppPaths.default().ensure_exists() + manager = ModelManager(paths.models_dir) + if args.download and not manager.is_installed(args.model): + manager.download(args.model) + result = RoutingTranscriber("", paths.models_dir).transcribe( + args.audio, model=f"local:{args.model}", language="ru" + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(result.text, encoding="utf-8") + print(f"Локальная транскрипция завершена: {args.output}") diff --git a/src/voice_dictation/core/compressor.py b/src/voice_dictation/core/compressor.py new file mode 100644 index 0000000..d1f3681 --- /dev/null +++ b/src/voice_dictation/core/compressor.py @@ -0,0 +1,418 @@ +"""Сжатие аудио через ffmpeg в Opus/Ogg и выбор модели по длительности.""" + +from __future__ import annotations + +import logging +import os +import re +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from voice_dictation.infrastructure.errors import CompressionError + +logger = logging.getLogger(__name__) + +_FFMPEG_FALLBACK_PATHS = ( + "/opt/homebrew/bin/ffmpeg", + "/usr/local/bin/ffmpeg", + "/usr/bin/ffmpeg", + "/opt/local/bin/ffmpeg", +) + +# OpenAI Whisper API: лимит 25 МБ на файл. +WHISPER_FILE_SIZE_LIMIT_BYTES = 25 * 1024 * 1024 + +# gpt-4o-transcribe и gpt-4o-mini-transcribe не принимают аудио длиннее ~1500 сек. +# Используем запас безопасности 1400 сек (23 мин 20 сек). +GPT4O_MAX_DURATION_SEC = 1400.0 + +_GPT4O_MODELS = frozenset({"gpt-4o-transcribe", "gpt-4o-mini-transcribe"}) + + +@dataclass(frozen=True, slots=True) +class AudioChunk: + """Фрагмент аудио с точным положением на общей временной шкале.""" + + index: int + path: Path + start_sec: float + duration_sec: float + + +@dataclass(frozen=True, slots=True) +class SilenceInterval: + """Интервал тишины, найденный ffmpeg silencedetect.""" + + start_sec: float + end_sec: float + + +@dataclass(frozen=True, slots=True) +class ChunkingResult: + """Нарезанные фрагменты и диагностика выбранных границ.""" + + chunks: tuple[AudioChunk, ...] + mode: str + detected_silences: int + adjusted_boundaries: int + + +_SILENCE_START_RE = re.compile(r"silence_start:\s*(-?\d+(?:\.\d+)?)") +_SILENCE_END_RE = re.compile(r"silence_end:\s*(-?\d+(?:\.\d+)?)") + + +def parse_silence_intervals(output: str) -> tuple[SilenceInterval, ...]: + """Разбирает диагностический вывод фильтра ffmpeg silencedetect.""" + intervals: list[SilenceInterval] = [] + pending_start: float | None = None + for line in output.splitlines(): + start_match = _SILENCE_START_RE.search(line) + if start_match is not None: + pending_start = max(0.0, float(start_match.group(1))) + + end_match = _SILENCE_END_RE.search(line) + if end_match is not None and pending_start is not None: + end_sec = max(pending_start, float(end_match.group(1))) + intervals.append(SilenceInterval(pending_start, end_sec)) + pending_start = None + return tuple(intervals) + + +def plan_chunk_ranges( + total_duration_sec: float, + chunk_duration_sec: float, + overlap_sec: float, + silences: tuple[SilenceInterval, ...] = (), + search_window_sec: float = 12.0, +) -> tuple[tuple[tuple[float, float], ...], int]: + """Планирует перекрывающиеся диапазоны, предпочитая границы в тишине. + + Точку разреза разрешено двигать только назад от номинальной границы. Поэтому + длительность фрагмента не превышает ``chunk_duration_sec``. Если подходящей + паузы нет, используется номинальная граница. + """ + if total_duration_sec <= 0: + raise CompressionError("total_duration_sec должен быть больше нуля") + if chunk_duration_sec <= 0: + raise CompressionError("chunk_duration_sec должен быть больше нуля") + if overlap_sec < 0 or overlap_sec >= chunk_duration_sec: + raise CompressionError("chunk_overlap_sec должен быть от 0 до размера чанка") + if search_window_sec < 0: + raise CompressionError("vad_search_window_sec не может быть отрицательным") + if total_duration_sec <= chunk_duration_sec: + return (((0.0, total_duration_sec),), 0) + + stride_sec = chunk_duration_sec - overlap_sec + cut_points = [0.0] + adjusted_boundaries = 0 + cursor_sec = 0.0 + + while True: + nominal_sec = cursor_sec + stride_sec + if nominal_sec >= total_duration_sec: + break + + lower_bound_sec = max(cursor_sec + overlap_sec, nominal_sec - search_window_sec) + candidates: list[float] = [] + for silence in silences: + if silence.end_sec < lower_bound_sec or silence.start_sec > nominal_sec: + continue + midpoint_sec = (silence.start_sec + silence.end_sec) / 2 + candidates.append(min(nominal_sec, max(lower_bound_sec, midpoint_sec))) + + cut_sec = max(candidates, default=nominal_sec) + if cut_sec < nominal_sec - 0.001: + adjusted_boundaries += 1 + cut_points.append(cut_sec) + cursor_sec = cut_sec + + cut_points.append(total_duration_sec) + half_overlap_sec = overlap_sec / 2 + ranges: list[tuple[float, float]] = [] + for index in range(len(cut_points) - 1): + start_sec = 0.0 if index == 0 else cut_points[index] - half_overlap_sec + end_sec = ( + total_duration_sec + if index == len(cut_points) - 2 + else cut_points[index + 1] + half_overlap_sec + ) + ranges.append((max(0.0, start_sec), min(total_duration_sec, end_sec))) + return (tuple(ranges), adjusted_boundaries) + + +def _find_ffmpeg() -> str | None: + """Ищет ffmpeg: сначала PATH, потом стандартные локации homebrew/macports.""" + from voice_dictation.core.ffmpeg_setup import find_ffmpeg + from voice_dictation.core.paths import AppPaths + + found = find_ffmpeg(AppPaths.default().bin_dir) + if found: + return found + for path in _FFMPEG_FALLBACK_PATHS: + if Path(path).is_file() and os.access(path, os.X_OK): + return path + return None + + +class AudioCompressor: + """Сжимает WAV в Opus (Ogg) через ffmpeg. + + Opus 24 kbps mono — оптимально для речи: сохраняет разборчивость, даёт + ~3 МБ на 20 минут (WAV 16kHz/16bit был бы ~38 МБ). Часовая запись + укладывается в ~11 МБ — спокойно влезает в 25 МБ лимит Whisper API. + + Args: + bitrate_kbps: Целевой битрейт в кбит/с (по умолчанию 24). + """ + + def __init__(self, bitrate_kbps: int = 24) -> None: + self._ffmpeg_bin = _find_ffmpeg() + self._bitrate_kbps = bitrate_kbps + + def is_available(self) -> bool: + """True, если ffmpeg найден и компрессия возможна.""" + return self._ffmpeg_bin is not None + + def compress(self, src: Path, dst: Path) -> Path: + """Сжимает аудио в Opus/Ogg. + + Args: + src: Исходный файл (любой формат, который читает ffmpeg). + dst: Путь для сохранения .ogg. + + Returns: + Путь к созданному .ogg файлу (тот же dst). + + Raises: + CompressionError: Если ffmpeg недоступен, упал или не создал файл. + """ + if self._ffmpeg_bin is None: + raise CompressionError("ffmpeg не найден в PATH") + + dst.parent.mkdir(parents=True, exist_ok=True) + cmd = [ + self._ffmpeg_bin, + "-hide_banner", + "-loglevel", + "error", + "-y", + "-i", + str(src), + "-c:a", + "libopus", + "-b:a", + f"{self._bitrate_kbps}k", + "-ac", + "1", + "-application", + "voip", + "-vbr", + "on", + str(dst), + ] + try: + result = subprocess.run( # noqa: S603 — аргументы полностью контролируемые + cmd, + check=False, + capture_output=True, + timeout=300, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise CompressionError(f"ffmpeg упал: {exc}") from exc + + if result.returncode != 0: + stderr = result.stderr.decode("utf-8", errors="replace")[:500] + raise CompressionError(f"ffmpeg вернул {result.returncode}: {stderr}") + + if not dst.exists() or dst.stat().st_size == 0: + raise CompressionError(f"ffmpeg не создал выходной файл: {dst}") + + return dst + + def split( + self, + src: Path, + output_dir: Path, + total_duration_sec: float, + chunk_duration_sec: float, + overlap_sec: float, + *, + vad_enabled: bool = True, + vad_search_window_sec: float = 12.0, + vad_min_silence_sec: float = 0.35, + vad_noise_db: float = -35.0, + ) -> ChunkingResult: + """Режет запись на Opus-фрагменты с паузами и перекрытием. + + По возможности граница переносится на ближайшую предшествующую паузу. + Перекрытие страхует слова у границы, а итоговые тексты дедуплицируются + локальным stitcher-ом. Ошибка анализа пауз не мешает фиксированной + нарезке. + """ + if self._ffmpeg_bin is None: + raise CompressionError("ffmpeg не найден в PATH") + + output_dir.mkdir(parents=True, exist_ok=True) + silences: tuple[SilenceInterval, ...] = () + detection_failed = False + if vad_enabled: + try: + silences = self._detect_silences( + src, + total_duration_sec, + vad_min_silence_sec, + vad_noise_db, + ) + except CompressionError as exc: + detection_failed = True + logger.warning("Анализ пауз не удался, использую фиксированную нарезку: %s", exc) + + ranges, adjusted_boundaries = plan_chunk_ranges( + total_duration_sec, + chunk_duration_sec, + overlap_sec, + silences, + vad_search_window_sec, + ) + if not vad_enabled: + mode = "fixed" + elif detection_failed: + mode = "fixed_fallback" + elif adjusted_boundaries: + mode = "silence_aware" + else: + mode = "fixed_no_nearby_silence" + + chunks: list[AudioChunk] = [] + for index, (start_sec, end_sec) in enumerate(ranges): + duration_sec = end_sec - start_sec + dst = output_dir / f"chunk_{index:04d}.ogg" + if not dst.exists() or dst.stat().st_size == 0: + self._encode_slice(src, dst, start_sec, duration_sec) + chunks.append( + AudioChunk( + index=index, + path=dst, + start_sec=start_sec, + duration_sec=duration_sec, + ) + ) + logger.info( + "Нарезка: mode=%s, пауз=%d, границ перенесено=%d, чанков=%d", + mode, + len(silences), + adjusted_boundaries, + len(chunks), + ) + return ChunkingResult( + chunks=tuple(chunks), + mode=mode, + detected_silences=len(silences), + adjusted_boundaries=adjusted_boundaries, + ) + + def _detect_silences( + self, + src: Path, + total_duration_sec: float, + min_silence_sec: float, + noise_db: float, + ) -> tuple[SilenceInterval, ...]: + """Находит паузы через ffmpeg silencedetect без изменения аудио.""" + assert self._ffmpeg_bin is not None + if min_silence_sec <= 0: + raise CompressionError("vad_min_silence_sec должен быть больше нуля") + cmd = [ + self._ffmpeg_bin, + "-hide_banner", + "-nostats", + "-i", + str(src), + "-af", + f"silencedetect=noise={noise_db:g}dB:d={min_silence_sec:g}", + "-f", + "null", + "-", + ] + timeout_sec = max(60.0, min(300.0, total_duration_sec * 0.2 + 30.0)) + try: + result = subprocess.run( # noqa: S603 — аргументы полностью контролируемые + cmd, + check=False, + capture_output=True, + timeout=timeout_sec, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise CompressionError(f"ffmpeg silencedetect упал: {exc}") from exc + if result.returncode != 0: + stderr = result.stderr.decode("utf-8", errors="replace")[-500:] + raise CompressionError(f"ffmpeg silencedetect вернул {result.returncode}: {stderr}") + stderr = result.stderr.decode("utf-8", errors="replace") + return parse_silence_intervals(stderr) + + def _encode_slice(self, src: Path, dst: Path, start_sec: float, duration_sec: float) -> None: + """Кодирует один временной диапазон в Opus.""" + assert self._ffmpeg_bin is not None + cmd = [ + self._ffmpeg_bin, + "-hide_banner", + "-loglevel", + "error", + "-y", + "-ss", + f"{start_sec:.3f}", + "-i", + str(src), + "-t", + f"{duration_sec:.3f}", + "-c:a", + "libopus", + "-b:a", + f"{self._bitrate_kbps}k", + "-ac", + "1", + "-application", + "voip", + "-vbr", + "on", + str(dst), + ] + try: + result = subprocess.run( # noqa: S603 — аргументы полностью контролируемые + cmd, + check=False, + capture_output=True, + timeout=300, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + raise CompressionError(f"ffmpeg упал на фрагменте {start_sec:.1f}с: {exc}") from exc + if result.returncode != 0 or not dst.exists() or dst.stat().st_size == 0: + stderr = result.stderr.decode("utf-8", errors="replace")[:500] + raise CompressionError( + f"ffmpeg не создал фрагмент {start_sec:.1f}с (код {result.returncode}): {stderr}" + ) + + +def select_model_for_duration(duration_sec: float, configured_model: str) -> str: + """Выбирает модель с учётом лимита длительности у gpt-4o-*-transcribe. + + Если сконфигурирована gpt-4o-* модель, но аудио длиннее их лимита (~25 мин), + автоматически переключается на whisper-1 (у него такого лимита нет). + + Args: + duration_sec: Длительность аудио в секундах. + configured_model: Модель из конфига. + + Returns: + Имя модели, которую стоит использовать для этого аудио. + """ + if configured_model in _GPT4O_MODELS and duration_sec > GPT4O_MAX_DURATION_SEC: + logger.info( + "Длительность %.1fс превышает лимит %s (~%.0fс), переключаюсь на whisper-1", + duration_sec, + configured_model, + GPT4O_MAX_DURATION_SEC, + ) + return "whisper-1" + return configured_model diff --git a/src/voice_dictation/core/config.py b/src/voice_dictation/core/config.py index 029ff62..37ca340 100644 --- a/src/voice_dictation/core/config.py +++ b/src/voice_dictation/core/config.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import json import logging from dataclasses import asdict, dataclass, field @@ -10,6 +11,57 @@ from pathlib import Path logger = logging.getLogger(__name__) +@dataclass(frozen=True, slots=True) +class SummaryPreset: + """Пресет post-processing промта для расшифровки. + + Args: + name: Уникальное имя пресета (показывается в Tray-меню). + model: OpenAI-модель для post-processing. Пустая строка → no-op. + prompt: Системный промт. Пустой → no-op (текст идёт без обработки). + """ + + name: str + model: str + prompt: str + + +def _default_presets() -> list[SummaryPreset]: + """Дефолтные пресеты, которые ставятся в Config при первом запуске.""" + return [ + SummaryPreset(name="Диктовка", model="", prompt=""), + SummaryPreset( + name="Чистка от паразитов", + model="gpt-4o-mini", + prompt=( + "Очисти расшифровку речи от мусора. Сохрани ВСЕ факты, имена, " + "решения, числа, даты и технические детали. Убери только " + "слова-паразиты, повторы и незаконченные фразы. " + "Результат на русском, без вступлений и комментариев:" + ), + ), + SummaryPreset( + name="Структура (markdown)", + model="gpt-4o-mini", + prompt=( + "Преобразуй расшифровку речи в структурированный markdown с " + "заголовками `##`, маркированными списками и **жирным** на " + "ключевых моментах. Сохрани все факты и порядок изложения. " + "Не добавляй ничего от себя:" + ), + ), + SummaryPreset( + name="Тезисы", + model="gpt-4o-mini", + prompt=( + "Сделай краткое summary расшифровки в виде 5–7 ключевых " + "тезисов (маркированный список, начинающийся с `-`). " + "Только суть, без воды. На русском:" + ), + ), + ] + + @dataclass(slots=True) class Config: """Конфигурация приложения. @@ -28,10 +80,24 @@ class Config: dictionary_path: Путь к словарю (None — стандартный). auto_paste: Автоматически вставлять текст после транскрипции. paste_delay_ms: Задержка перед вставкой в миллисекундах. + summary_presets: Список пресетов post-processing. + active_preset: Имя активного пресета (matches name из summary_presets). + splash_enabled: Показывать splash-окно при старте приложения. + splash_audio_enabled: Играть аудио на splash (если файл есть). + splash_duration_sec: Сколько показывать splash в секундах. + chunk_duration_sec: Размер одного API-фрагмента аудио в секундах. + chunk_overlap_sec: Перекрытие соседних фрагментов в секундах. + vad_enabled: Переносить границы фрагментов на ближайшие паузы. + vad_search_window_sec: Глубина поиска паузы перед плановой границей. + vad_min_silence_sec: Минимальная длительность паузы для переноса границы. + vad_noise_db: Порог тишины ffmpeg silencedetect в децибелах. + audio_retention_days: Сколько дней хранить аудио завершённых сессий. """ - hotkey: str = "ctrl+space" + hotkey: str = "cmd+alt+d" model: str = "gpt-4o-mini-transcribe" + transcription_backend: str = "openai" + local_model: str = "whisper-base" language: str | None = "ru" notifications_enabled: bool = True show_cost_in_notification: bool = True @@ -43,9 +109,19 @@ class Config: dictionary_path: Path | None = None auto_paste: bool = True paste_delay_ms: int = 80 - mode: str = "raw" # ключ режима постобработки из core.modes - proc_model: str = "gpt-4o-mini" # модель LLM для режимов постобработки - custom_modes: dict[str, str] = field(default_factory=dict) # {название: промпт} + summary_presets: list[SummaryPreset] = field(default_factory=_default_presets) + active_preset: str = "Диктовка" + splash_enabled: bool = True + splash_audio_enabled: bool = True + splash_duration_sec: float = 5.0 + chunk_duration_sec: float = 180.0 + chunk_overlap_sec: float = 4.0 + vad_enabled: bool = True + 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-сериализацию _path: Path | None = field(default=None, repr=False, compare=False) @@ -54,7 +130,6 @@ class Config: def _config_to_dict(config: Config) -> dict[str, object]: """Сериализует Config в dict для JSON, конвертируя Path в строки.""" d = asdict(config) - # Убираем приватное поле d.pop("_path", None) for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"): if d[key] is not None: @@ -67,20 +142,55 @@ def _config_from_dict(data: dict[str, object]) -> Config: kwargs: dict[str, object] = dict(data) kwargs.pop("_path", None) - # Миграция со старой схемы (summary_mode/summary_model) на mode/proc_model. - # Делается ДО фильтрации неизвестных ключей, иначе старые поля потеряются. - if "mode" not in kwargs and kwargs.get("summary_mode") is True: - kwargs["mode"] = "summary" - if "proc_model" not in kwargs and isinstance(kwargs.get("summary_model"), str): - kwargs["proc_model"] = kwargs["summary_model"] - for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"): val = kwargs.get(key) if val is not None and isinstance(val, str): kwargs[key] = Path(val) - # Игнорируем неизвестные ключи из будущих версий конфига - import dataclasses + # Upgrade Windows mode-based settings before filtering obsolete keys. + if "summary_presets" not in kwargs and any( + key in kwargs for key in ("mode", "custom_modes", "summary_mode") + ): + from voice_dictation.core.modes import DEFAULT_MODES + + model = str(kwargs.get("proc_model", kwargs.get("summary_model", "gpt-4o-mini"))) + selected = str(kwargs.get("mode", "summary" if kwargs.get("summary_mode") else "raw")) + presets = [ + SummaryPreset(spec.label, model if spec.prompt else "", spec.prompt) + for spec in DEFAULT_MODES + ] + selected_name = next( + (spec.label for spec in DEFAULT_MODES if spec.key == selected), presets[0].name + ) + custom = kwargs.get("custom_modes") + if isinstance(custom, dict): + for name, prompt in custom.items(): + if not isinstance(name, str) or not isinstance(prompt, str): + continue + # A custom label may equal a built-in label; keep both unambiguously. + label = name + while any(preset.name == label for preset in presets): + label += " (свой)" + presets.append(SummaryPreset(label, model, prompt)) + if selected == f"custom:{name}": + selected_name = label + kwargs["summary_presets"] = [dataclasses.asdict(preset) for preset in presets] + kwargs.setdefault("active_preset", selected_name) + + presets_raw = kwargs.get("summary_presets") + if isinstance(presets_raw, list): + kwargs["summary_presets"] = [ + SummaryPreset( + name=str(item.get("name", "")), + model=str(item.get("model", "")), + prompt=str(item.get("prompt", "")), + ) + for item in presets_raw + if isinstance(item, dict) + ] + + if kwargs.get("transcription_backend", "openai") not in {"openai", "local"}: + raise ValueError("Неизвестный движок распознавания") known = {f.name for f in dataclasses.fields(Config)} filtered = {k: v for k, v in kwargs.items() if k in known} return Config(**filtered) # type: ignore[arg-type] @@ -107,12 +217,22 @@ class ConfigStore: try: with self._path.open(encoding="utf-8") as fh: data = json.load(fh) + if not isinstance(data, dict): + raise TypeError("Конфигурация должна быть JSON-объектом") self._current = _config_from_dict(data) - except (json.JSONDecodeError, TypeError) as exc: - logger.warning("Не удалось загрузить конфиг, использую дефолтный: %s", exc) - self._current = Config() + except (OSError, ValueError, TypeError) as exc: + logger.warning( + "Не удалось загрузить конфиг, сохраняю безопасные настройки: %s", exc + ) + self._current = self._current or Config(transcription_backend="local") else: - self._current = Config() + self._current = ( + Config( + transcription_backend="local", hotkey="cmd+alt+shift+d", splash_enabled=False + ) + if self._path.parent.name == ".dictate-beta" + else Config() + ) return self._current def save(self, config: Config) -> None: @@ -123,8 +243,10 @@ class ConfigStore: """ self._path.parent.mkdir(parents=True, exist_ok=True) data = _config_to_dict(config) - with self._path.open("w", encoding="utf-8") as fh: + temporary = self._path.with_suffix(".json.tmp") + with temporary.open("w", encoding="utf-8") as fh: json.dump(data, fh, indent=2, ensure_ascii=False) + temporary.replace(self._path) self._current = config logger.debug("Конфиг сохранён в %s", self._path) diff --git a/src/voice_dictation/core/enums.py b/src/voice_dictation/core/enums.py index b325d1a..64bcd8b 100644 --- a/src/voice_dictation/core/enums.py +++ b/src/voice_dictation/core/enums.py @@ -25,6 +25,7 @@ class SoundKind(Enum): class WhisperModel(StrEnum): """Доступные модели транскрипции Whisper API.""" + GPT_TRANSCRIBE = "gpt-transcribe" WHISPER_1 = "whisper-1" GPT_4O_TRANSCRIBE = "gpt-4o-transcribe" GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe" 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/local_transcriber.py b/src/voice_dictation/core/local_transcriber.py new file mode 100644 index 0000000..f067bb8 --- /dev/null +++ b/src/voice_dictation/core/local_transcriber.py @@ -0,0 +1,172 @@ +"""Local whisper.cpp subprocess adapter; never falls back to a network service.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import wave +from datetime import UTC, datetime +from decimal import Decimal +from pathlib import Path + +from voice_dictation.core.models import TranscriptionResult +from voice_dictation.infrastructure.errors import TranscriptionError + + +def discover_executable(name: str) -> Path: + """Find a bundled runtime first, then PATH and standard Homebrew prefixes.""" + filename = f"{name}.exe" if sys.platform == "win32" else name + bundle_root = Path(getattr(sys, "_MEIPASS", Path(sys.executable).parent)) + candidates = [ + bundle_root / "bin" / filename, + bundle_root / filename, + Path(sys.executable).parent.parent / "Resources" / "bin" / filename, + ] + from voice_dictation.core.paths import AppPaths + + candidates.append(AppPaths.default().root / "bin" / filename) + found = shutil.which(filename) + if found: + candidates.append(Path(found)) + candidates.extend([Path("/opt/homebrew/bin") / filename, Path("/usr/local/bin") / filename]) + for candidate in candidates: + if candidate.is_file() and os.access(candidate, os.X_OK): + return candidate + raise TranscriptionError( + f"Не найден {filename}. Установите whisper.cpp и ffmpeg или используйте сборку с движком." + ) + + +class LocalTranscriber: + """Transcribe with a managed model and a separately discovered whisper-cli.""" + + def __init__(self, model_path: Path, executable: Path | None = None) -> None: + self._model_path = model_path + self._executable = executable + + def transcribe( + self, + audio_path: Path, + prompt: str = "", + language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, + ) -> TranscriptionResult: + """Convert to 16 kHz mono PCM, run locally and parse whisper.cpp JSON.""" + requested_at = datetime.now(tz=UTC) + if not self._model_path.is_file(): + raise TranscriptionError("Локальная модель не установлена. Скачайте её в настройках") + executable = self._executable or discover_executable("whisper-cli") + if not executable.is_file(): + raise TranscriptionError("Не найден исполняемый файл whisper-cli") + timeout = max(120.0, (duration_sec or 0.0) * 10 + 60) + try: + with tempfile.TemporaryDirectory(prefix="voice-local-") as temporary: + root = Path(temporary) + wav = audio_path + if not self._is_pcm_wav(audio_path): + wav = root / "audio.wav" + self._run( + [ + str(discover_executable("ffmpeg")), + "-nostdin", + "-v", + "error", + "-y", + "-i", + str(audio_path), + "-ar", + "16000", + "-ac", + "1", + "-c:a", + "pcm_s16le", + str(wav), + ], + timeout, + ) + output = root / "result" + command = [ + str(executable), + "-m", + str(self._model_path), + "-f", + str(wav), + "-l", + language or "auto", + "-oj", + "-of", + str(output), + ] + if prompt: + command.extend(["--prompt", prompt]) + self._run(command, timeout) + payload = json.loads(output.with_suffix(".json").read_text(encoding="utf-8")) + if not isinstance(payload, dict): + raise ValueError("Expected JSON object") + segments = payload.get("transcription") + if not isinstance(segments, list) or any( + not isinstance(segment, dict) or not isinstance(segment.get("text"), str) + for segment in segments + ): + raise ValueError("Missing transcription segments") + text = " ".join(segment["text"].strip() for segment in segments).strip() + result_metadata = payload.get("result", {}) + detected_language = ( + result_metadata.get("language") if isinstance(result_metadata, dict) else None + ) + return TranscriptionResult( + text=text, + duration_sec=duration_sec if duration_sec is not None else self._duration(wav), + model=model or self._model_path.stem, + language=detected_language if isinstance(detected_language, str) else language, + prompt_used=prompt or None, + requested_at=requested_at, + cost_usd=Decimal("0"), + ) + except (OSError, ValueError, KeyError, TypeError) as exc: + raise TranscriptionError( + "Не удалось прочитать результат локального распознавания" + ) from exc + + @staticmethod + def _run(command: list[str], timeout: float) -> None: + try: + environment = os.environ.copy() + if hasattr(sys, "_MEIPASS"): + environment["GGML_BACKEND_PATH"] = str(Path(sys._MEIPASS) / "bin") + completed = subprocess.run( + command, capture_output=True, timeout=timeout, check=False, env=environment + ) + except subprocess.TimeoutExpired as exc: + raise TranscriptionError("Локальное распознавание превысило время ожидания") from exc + except OSError as exc: + raise TranscriptionError("Не удалось запустить локальный движок или ffmpeg") from exc + if completed.returncode: + # Runtime stderr may contain transcript, prompts or local paths: don't expose it. + raise TranscriptionError(f"Локальный движок завершился с кодом {completed.returncode}") + + @staticmethod + def _is_pcm_wav(path: Path) -> bool: + try: + with wave.open(str(path), "rb") as audio: + return ( + audio.getnchannels() == 1 + and audio.getframerate() == 16000 + and audio.getsampwidth() == 2 + and audio.getcomptype() == "NONE" + ) + except (wave.Error, EOFError, OSError): + return False + + @staticmethod + def _duration(path: Path) -> float: + with wave.open(str(path), "rb") as audio: + return audio.getnframes() / audio.getframerate() + + def close(self) -> None: + """No persistent process or network client to close.""" diff --git a/src/voice_dictation/core/model_manager.py b/src/voice_dictation/core/model_manager.py new file mode 100644 index 0000000..d8ba3f6 --- /dev/null +++ b/src/voice_dictation/core/model_manager.py @@ -0,0 +1,371 @@ +"""Verified local model downloads, independent of the application bundle.""" + +from __future__ import annotations + +import asyncio +import hashlib +import logging +import shutil +import sys +import threading +import time +from collections.abc import Callable, Iterator +from contextlib import ExitStack, contextmanager, suppress +from dataclasses import dataclass +from pathlib import Path +from typing import BinaryIO +from uuid import uuid4 + +import httpx + +logger = logging.getLogger(__name__) + + +class ModelError(RuntimeError): + """A model operation failed safely.""" + + +class DownloadCancelled(ModelError): # noqa: N818 - public cancellation event name + """The user cancelled a model download.""" + + +@dataclass(frozen=True, slots=True) +class ModelSpec: + """Pinned model metadata from the upstream Hugging Face LFS tree.""" + + id: str + name: str + url: str + size: int + sha256: str + dependencies: tuple[str, ...] = () + selectable: bool = True + + @property + def size_bytes(self) -> int: + """Expected download size in bytes.""" + return self.size + + +# SHA256 and exact size verified 2026-10-19 against the official LFS metadata: +# https://huggingface.co/api/models/ggerganov/whisper.cpp/tree/main +# Hash verification pins the content even if upstream main changes later. +CATALOG: tuple[ModelSpec, ...] = ( + ModelSpec( + "whisper-base", + "Whisper Base · 148 MB", + "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin", + 147951465, + "60ed5bc3dd14eea856493d334349b405782ddcaf0028d4b5df4088345fba2efe", + ), + ModelSpec( + "whisper-small", + "Whisper Small · 488 MB", + "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin", + 487601967, + "1be3a9b2063867b937e64e2ec7483364a79917e157fa98c5d94b5c1fffea987b", + ), + ModelSpec( + "whisper-turbo-q5", + "Whisper Large v3 Turbo Q5 · 574 MB", + "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3-turbo-q5_0.bin", + 574041195, + "394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2", + ), + # 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", + ), +) + + +class ModelManager: + """Manage explicitly requested downloads with integrity and process-safe locks.""" + + def __init__(self, models_dir: Path) -> None: + self.models_dir = models_dir + + @staticmethod + def _spec(model_id: str) -> ModelSpec: + for spec in CATALOG: + if spec.id == model_id: + return spec + raise ModelError(f"Неизвестная локальная модель: {model_id!r}") + + def path_for(self, model_id: str) -> Path: + """Return the managed path, rejecting arbitrary filenames and symlinks.""" + spec = self._spec(model_id) + path = self.models_dir / f"{spec.id}.bin" + if path.is_symlink(): + raise ModelError("Путь модели не должен быть символической ссылкой") + return path + + def is_installed(self, model_id: str) -> bool: + """Check size and SHA256; partial or corrupted files are never installed.""" + spec = self._spec(model_id) + path = self.path_for(model_id) + return self._valid(path, spec) and all( + self.is_installed(dependency) for dependency in spec.dependencies + ) + + @staticmethod + def _valid(path: Path, spec: ModelSpec) -> bool: + if not path.is_file() or path.stat().st_size != spec.size: + return False + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() == spec.sha256 + + @contextmanager + def _lock(self, model_id: str) -> Iterator[None]: + self.models_dir.mkdir(parents=True, exist_ok=True) + lock = self.models_dir / f".{model_id}.lock" + if lock.is_symlink(): + raise ModelError("Путь блокировки не должен быть символической ссылкой") + # The file stays on disk; the OS releases its advisory lock on process exit. + # Unlinking a lock file would let another process lock a different inode. + with lock.open("a+b") as stream: + try: + self._acquire(stream) + except OSError as exc: + raise ModelError("Модель используется в другом окне или процессе") from exc + try: + yield + finally: + self._release(stream) + + @staticmethod + def _acquire(stream: BinaryIO) -> None: + if sys.platform == "win32": + import msvcrt + + stream.seek(0, 2) + if stream.tell() == 0: + stream.write(b"0") + stream.flush() + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + + @staticmethod + def _release(stream: BinaryIO) -> None: + if sys.platform == "win32": + import msvcrt + + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + + @contextmanager + def use(self, model_id: str) -> Iterator[Path]: + """Hold a process-safe inference lease, preventing deletion/replacement.""" + path = self.path_for(model_id) + with 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 + + def download( + self, + model_id: str, + 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. + + A cancelled/failed download removes only its own partial file. Existing + installed models remain untouched. OS locks release even after a crash. + ``stage`` receives checking, connecting, downloading and verifying. The + synchronous API is intended for a worker thread, not an active asyncio loop. + """ + spec = self._spec(model_id) + operation = uuid4().hex[:12] + started = time.monotonic() + + def notify(value: str) -> None: + logger.info( + "model.download.stage operation=%s model=%s stage=%s", operation, spec.id, value + ) + if stage is not None: + stage(value) + + def check_cancel() -> None: + if cancel is not None and cancel.is_set(): + raise DownloadCancelled("Скачивание отменено") + + logger.info("model.download.started operation=%s model=%s", operation, spec.id) + try: + path = self.path_for(model_id) + with self._lock(model_id): + check_cancel() + notify("checking") + if self._valid_cancellable(path, spec, check_cancel): + logger.info("model.download.cached operation=%s model=%s", operation, spec.id) + return path + if shutil.disk_usage(self.models_dir).free < spec.size + 16 * 1024 * 1024: + raise ModelError("Недостаточно свободного места для скачивания модели") + partial = path.with_suffix(".bin.part") + if partial.is_symlink(): + raise ModelError("Временный путь модели не должен быть символической ссылкой") + try: + loop = asyncio.new_event_loop() + try: + loop.run_until_complete( + self._download_async(spec, partial, progress, cancel, notify) + ) + finally: + loop.run_until_complete(loop.shutdown_asyncgens()) + # Unlike asyncio.run(), do not wait for a cancelled OS DNS + # resolver thread. The transfer task and client are already + # fully closed; a resolver cannot resume the download. + loop.close() + check_cancel() + notify("verifying") + if not self._valid_cancellable(partial, spec, check_cancel): + raise ModelError("Проверка размера или SHA256 модели не пройдена") + check_cancel() + partial.replace(path) + logger.info( + "model.download.completed operation=%s model=%s bytes=%d elapsed_ms=%d", + operation, + spec.id, + spec.size, + int((time.monotonic() - started) * 1000), + ) + return path + finally: + partial.unlink(missing_ok=True) + except DownloadCancelled: + logger.info( + "model.download.cancelled operation=%s model=%s elapsed_ms=%d", + operation, + spec.id, + int((time.monotonic() - started) * 1000), + ) + raise + except Exception as exc: + # Exception text may contain signed redirect URLs or local user paths. + logger.warning( + "model.download.failed operation=%s model=%s error_type=%s", + operation, + spec.id, + type(exc).__name__, + ) + if isinstance(exc, httpx.HTTPError): + raise ModelError( + "Не удалось скачать модель. Проверьте соединение и повторите" + ) from None + raise + + @staticmethod + def _valid_cancellable(path: Path, spec: ModelSpec, check_cancel: Callable[[], None]) -> bool: + if not path.is_file() or path.stat().st_size != spec.size: + return False + digest = hashlib.sha256() + with path.open("rb") as stream: + while block := stream.read(1024 * 1024): + check_cancel() + digest.update(block) + check_cancel() + return digest.hexdigest() == spec.sha256 + + @staticmethod + async def _download_async( + spec: ModelSpec, + partial: Path, + progress: Callable[[int, int], None] | None, + cancel: threading.Event | None, + notify: Callable[[str], None], + ) -> None: + """Cancel pending socket awaits; await shutdown before returning to caller. + + The sync API runs on the existing downloader worker. It owns this event + loop and never leaves a background download or writer after cancellation. + """ + + async def transfer() -> None: + notify("connecting") + timeout = httpx.Timeout(30.0, connect=10.0) + async with ( + httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client, + client.stream("GET", spec.url) as response, + ): + response.raise_for_status() + notify("downloading") + received = 0 + with partial.open("wb") as output: + # No chunk-size buffer: surface each available network block. + async for block in response.aiter_bytes(): + if cancel is not None and cancel.is_set(): + raise DownloadCancelled("Скачивание отменено") + received += len(block) + if received > spec.size: + raise ModelError("Размер модели превышает ожидаемый") + output.write(block) + if progress is not None: + progress(received, spec.size) + # Cached transports may yield synchronously; let cancellation run. + await asyncio.sleep(0) + + task = asyncio.create_task(transfer()) + try: + while not task.done(): + if cancel is not None and cancel.is_set(): + task.cancel() + with suppress(asyncio.CancelledError): + await task + raise DownloadCancelled("Скачивание отменено") + await asyncio.wait({task}, timeout=0.1) + await task + finally: + if not task.done(): + task.cancel() + with suppress(asyncio.CancelledError): + await task + + def delete(self, model_id: str) -> None: + """Remove a managed model, refusing to race with a download.""" + path = self.path_for(model_id) + with self._lock(model_id): + path.unlink(missing_ok=True) 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 253746e..4752f31 100644 --- a/src/voice_dictation/core/orchestrator.py +++ b/src/voice_dictation/core/orchestrator.py @@ -4,22 +4,43 @@ from __future__ import annotations import contextlib import logging +import shutil import threading import time +import wave from collections.abc import Callable from concurrent.futures import Future, ThreadPoolExecutor -from datetime import datetime +from datetime import UTC, datetime +from decimal import Decimal +from pathlib import Path from typing import TYPE_CHECKING -from voice_dictation.core.config import Config +from voice_dictation.core.compressor import ( + WHISPER_FILE_SIZE_LIMIT_BYTES, + AudioChunk, + AudioCompressor, + ChunkingResult, + plan_chunk_ranges, +) +from voice_dictation.core.config import ( + Config, + SummaryPreset, + _config_from_dict, + _config_to_dict, +) from voice_dictation.core.dictionary import Dictionary from voice_dictation.core.enums import RecordingState, SoundKind from voice_dictation.core.models import RecordingResult, TranscriptionResult, UsageRecord -from voice_dictation.core.modes import get_mode from voice_dictation.core.paths import AppPaths -from voice_dictation.core.transcriber import WhisperTranscriber +from voice_dictation.core.session_store import SessionStore +from voice_dictation.core.text_stitcher import stitch_transcripts +from voice_dictation.core.transcription import Transcriber from voice_dictation.core.usage_db import UsageDB -from voice_dictation.infrastructure.errors import RecorderError, TranscriptionError +from voice_dictation.infrastructure.errors import ( + CompressionError, + RecorderError, + TranscriptionError, +) if TYPE_CHECKING: from voice_dictation.platform.protocols import ( @@ -58,7 +79,7 @@ class DictationOrchestrator: def __init__( self, recorder: AudioRecorder, - transcriber: WhisperTranscriber, + transcriber: Transcriber, dictionary: Dictionary, clipboard: Clipboard, auto_paste: AutoPaste, @@ -68,6 +89,8 @@ class DictationOrchestrator: paths: AppPaths, state_listener: Callable[[RecordingState], None] | None = None, usage_db: UsageDB | None = None, + compressor: AudioCompressor | None = None, + session_store: SessionStore | None = None, ) -> None: self._recorder = recorder self._transcriber = transcriber @@ -80,11 +103,19 @@ class DictationOrchestrator: self._paths = paths self._state_listener = state_listener self._usage_db = usage_db + self._compressor = compressor + self._session_store = session_store or SessionStore(paths.sessions_dir) self._state = RecordingState.IDLE self._lock = threading.Lock() self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="whisper") self._current_future: Future[None] | None = None + self._recording_config: Config | None = None + + config = self._config_provider() + removed = self._session_store.cleanup_completed_audio(config.audio_retention_days) + if removed: + logger.info("Удалено старых аудиоартефактов: %d", removed) @property def state(self) -> RecordingState: @@ -110,18 +141,44 @@ class DictationOrchestrator: with self._lock: if self._state != RecordingState.RECORDING: return - with contextlib.suppress(RecorderError): - self._recorder.stop() + try: + recording = self._recorder.stop() + self._session_store.update( + recording.path.parent, + status="cancelled", + duration_sec=recording.duration_sec, + cancelled_at=datetime.now(tz=UTC).isoformat(), + ) + except RecorderError: + logger.warning("Не удалось корректно сохранить отменённую запись") self._set_state(RecordingState.IDLE) logger.info("Запись отменена") def _start_recording(self) -> None: """Запускает запись (вызывается внутри lock).""" config = self._config_provider() - output_path = self._paths.tmp_dir / f"session_{int(time.time() * 1000)}.wav" + config = _config_from_dict(_config_to_dict(config)) + self._recording_config = config + 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), + ) try: self._recorder.start(output_path) except RecorderError as exc: + self._session_store.mark_failed(output_path.parent, str(exc)) logger.error("Не удалось начать запись: %s", exc) self._set_state(RecordingState.ERROR) self._sound_player.play(SoundKind.ERROR, config=config) @@ -136,7 +193,9 @@ class DictationOrchestrator: def _stop_recording(self) -> None: """Останавливает запись и запускает транскрипцию (вызывается внутри lock).""" - config = self._config_provider() + processing_started = time.monotonic() + config = self._recording_config or self._config_provider() + self._recording_config = None try: recording = self._recorder.stop() except RecorderError as exc: @@ -148,35 +207,380 @@ class DictationOrchestrator: self._set_state(RecordingState.PROCESSING) self._sound_player.play(SoundKind.STOP, config=config) + 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, recording: RecordingResult, config: Config) -> None: + def _process_recording( + self, + recording: RecordingResult, + config: Config, + *, + finalize_state: bool = True, + allow_auto_paste: bool = True, + processing_started: float | None = None, + ) -> None: """Транскрибирует запись и вставляет текст (выполняется в worker-потоке). + Pipeline: архивный Opus → перекрывающиеся фрагменты → API checkpoint-ы + → безопасная склейка. Ни исходник, ни уже полученные ответы при ошибке + не удаляются. + Args: recording: Результат записи. config: Текущая конфигурация. """ + if processing_started is None: + processing_started = time.monotonic() + session_dir = recording.path.parent try: - prompt = self._dictionary.build_prompt() + if config.transcription_backend not in {"local", "openai"}: + raise TranscriptionError("Неизвестный движок: выберите локальный режим или OpenAI") + result = self._transcribe_session(recording, config) + self._on_transcription_success( + result, + 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)) + logger.error("Ошибка транскрипции: %s", exc) + self._on_transcription_error(str(exc), config, finalize_state=finalize_state) + except Exception as exc: + self._session_store.mark_failed(session_dir, str(exc)) + logger.exception("Неожиданная ошибка при транскрипции: %s", exc) + self._on_transcription_error( + f"Неожиданная ошибка: {exc}", + config, + finalize_state=finalize_state, + ) + + def resume_pending_sessions(self) -> int: + """Продолжает незавершённые сессии с последнего сохранённого чанка.""" + with self._lock: + if self._state != RecordingState.IDLE: + return 0 + pending = self._session_store.pending() + if not pending: + return 0 + self._set_state(RecordingState.PROCESSING) + config = self._config_provider() + self._current_future = self._executor.submit( + self._recover_sessions, + pending, + config, + ) + logger.info("Восстанавливаю незавершённых сессий: %d", len(pending)) + return len(pending) + + def _recover_sessions(self, session_dirs: list[Path], config: Config) -> None: + for session_dir in session_dirs: + manifest = self._session_store.read(session_dir) + saved_config = manifest.get("recording_config") + if not isinstance(saved_config, dict): + self._session_store.mark_failed( + session_dir, + "Сессия без настроек происхождения: автоматическое восстановление запрещено", + ) + continue + try: + session_config = _config_from_dict(saved_config) + except (TypeError, ValueError): + self._session_store.mark_failed(session_dir, "Повреждены настройки сессии") + continue + source_wav = session_dir / "source.wav" + source_ogg = session_dir / "source.ogg" + source = source_wav if source_wav.exists() else source_ogg + try: + duration_sec = float(manifest["duration_sec"]) + except (KeyError, TypeError, ValueError): + duration_sec = self._wav_duration(source) + if duration_sec <= 0: + self._session_store.mark_failed( + session_dir, + "Не удалось восстановить длительность незавершённой записи", + ) + continue + self._process_recording( + RecordingResult(path=source, duration_sec=duration_sec), + session_config, + finalize_state=False, + allow_auto_paste=False, + ) + self._set_state(RecordingState.IDLE) + + @staticmethod + def _wav_duration(path: Path) -> float: + if path.suffix.lower() != ".wav": + return 0.0 + try: + with wave.open(str(path), "rb") as wav_file: + sample_rate = wav_file.getframerate() + return wav_file.getnframes() / sample_rate if sample_rate else 0.0 + except (OSError, EOFError, wave.Error): + return 0.0 + + def _transcribe_session( + self, + recording: RecordingResult, + config: Config, + ) -> TranscriptionResult: + """Транскрибирует сессию по частям и сохраняет каждый успешный ответ.""" + session_dir = recording.path.parent + archive_path = session_dir / "source.ogg" + local = config.transcription_backend == "local" + effective_model = f"local:{config.local_model}" if local else config.model + audio_source = recording.path + + if not local and archive_path.exists() and archive_path.stat().st_size > 0: + audio_source = archive_path + elif not local and self._compressor is not None and self._compressor.is_available(): + self._compressor.compress(recording.path, archive_path) + wav_size = recording.path.stat().st_size + ogg_size = archive_path.stat().st_size + logger.info( + "Сжатие: %.2f МБ → %.2f МБ (×%.1f)", + wav_size / 1_048_576, + ogg_size / 1_048_576, + wav_size / ogg_size if ogg_size else 1.0, + ) + audio_source = archive_path + + if local: + from dataclasses import replace + + 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, + "chunk_duration_sec": config.chunk_duration_sec, + "chunk_overlap_sec": config.chunk_overlap_sec, + "vad_enabled": config.vad_enabled, + "vad_search_window_sec": config.vad_search_window_sec, + "vad_min_silence_sec": config.vad_min_silence_sec, + "vad_noise_db": config.vad_noise_db, + "dictionary": self._dictionary.build_prompt(), + } + if local: + from voice_dictation.core.model_manager import CATALOG + + spec = next((item for item in CATALOG if item.id == config.local_model), None) + if spec is None: + raise TranscriptionError("Неизвестная локальная модель") + identity["model_sha256"] = spec.sha256 + 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: + raise TranscriptionError( + "Настройки незавершённой сессии изменились. Верните прежний движок, " + "модель и настройки нарезки для безопасного продолжения. Аудио сохранено." + ) + if old_identity is None and previous.get("chunks"): + raise TranscriptionError( + "Старая сессия без идентификатора движка: автоматическое продолжение " + "отключено. Аудио сохранено для ручного восстановления." + ) + chunking = self._prepare_chunks(recording, audio_source, config) + chunks = chunking.chunks + self._session_store.update( + session_dir, + status="processing", + transcription_identity=identity, + model=effective_model, + chunk_duration_sec=config.chunk_duration_sec, + chunk_overlap_sec=config.chunk_overlap_sec, + chunking_mode=chunking.mode, + detected_silences=chunking.detected_silences, + adjusted_boundaries=chunking.adjusted_boundaries, + chunks=[ + { + "index": chunk.index, + "file": str(chunk.path.relative_to(session_dir)), + "start_sec": chunk.start_sec, + "duration_sec": chunk.duration_sec, + } + for chunk in chunks + ], + ) + + results: list[TranscriptionResult] = [] + base_prompt = self._dictionary.build_prompt() + for chunk in chunks: + cached = self._session_store.load_chunk_result(session_dir, chunk.index) + if cached is not None: + logger.info( + "Чанк %d/%d уже готов, использую checkpoint", + chunk.index + 1, + len(chunks), + ) + results.append(cached) + continue + + prompt = self._chunk_prompt(base_prompt, results[-1].text if results else "") + logger.info( + "Транскрипция чанка %d/%d: %.1f–%.1fс", + chunk.index + 1, + len(chunks), + chunk.start_sec, + chunk.start_sec + chunk.duration_sec, + ) result = self._transcriber.transcribe( - recording.path, + chunk.path, prompt=prompt, language=config.language, + model=effective_model, + duration_sec=chunk.duration_sec, ) - self._on_transcription_success(result, config) - except TranscriptionError as exc: - logger.error("Ошибка транскрипции: %s", exc) - self._on_transcription_error(str(exc), config) - except Exception as exc: - logger.exception("Неожиданная ошибка при транскрипции: %s", exc) - self._on_transcription_error(f"Неожиданная ошибка: {exc}", config) - finally: - recording.path.unlink(missing_ok=True) + self._session_store.save_chunk_result(session_dir, chunk.index, result) + results.append(result) - def _on_transcription_success(self, result: TranscriptionResult, config: Config) -> None: + stitch = stitch_transcripts([result.text for result in results]) + if not stitch.text: + raise TranscriptionError("Все аудиофрагменты вернули пустой текст") + + self._session_store.complete(session_dir, stitch.text, stitch.removed_prefix_words) + self._cleanup_successful_session(session_dir, archive_path) + if effective_model == "gpt-transcribe": + languages = {result.language for result in results} + detected_language = next(iter(languages)) if len(languages) == 1 else None + else: + detected_language = next( + (result.language for result in results if result.language), config.language + ) + return TranscriptionResult( + text=stitch.text, + duration_sec=recording.duration_sec, + model=effective_model, + language=detected_language, + prompt_used=base_prompt or None, + requested_at=min( + (result.requested_at for result in results), + default=datetime.now(tz=UTC), + ), + cost_usd=sum((result.cost_usd for result in results), start=Decimal("0")), + ) + + def _prepare_chunks( + self, + recording: RecordingResult, + audio_source: Path, + config: Config, + ) -> ChunkingResult: + if config.transcription_backend == "local" and audio_source.suffix.lower() == ".wav": + return self._local_pcm_chunks(recording, audio_source, config) + if recording.duration_sec <= config.chunk_duration_sec: + if ( + config.transcription_backend != "local" + and audio_source.stat().st_size > WHISPER_FILE_SIZE_LIMIT_BYTES + ): + raise CompressionError("Аудиофайл больше 25 МБ, а нарезка не была выполнена") + return ChunkingResult( + chunks=(AudioChunk(0, audio_source, 0.0, recording.duration_sec),), + mode="single", + detected_silences=0, + adjusted_boundaries=0, + ) + + if self._compressor is None or not self._compressor.is_available(): + raise CompressionError( + "Для записи длиннее одного чанка нужен ffmpeg; аудио сохранено для повтора" + ) + split_source = recording.path if recording.path.exists() else audio_source + return self._compressor.split( + split_source, + recording.path.parent / "chunks", + recording.duration_sec, + config.chunk_duration_sec, + config.chunk_overlap_sec, + vad_enabled=config.vad_enabled, + vad_search_window_sec=config.vad_search_window_sec, + vad_min_silence_sec=config.vad_min_silence_sec, + vad_noise_db=config.vad_noise_db, + ) + + @staticmethod + def _local_pcm_chunks( + recording: RecordingResult, + source: Path, + config: Config, + ) -> ChunkingResult: + """Slice lossless recorder WAV locally without an ffmpeg installation.""" + if recording.duration_sec <= config.chunk_duration_sec: + return ChunkingResult( + (AudioChunk(0, source, 0, recording.duration_sec),), "local_pcm_single", 0, 0 + ) + ranges, _ = plan_chunk_ranges( + recording.duration_sec, + config.chunk_duration_sec, + config.chunk_overlap_sec, + ) + output_dir = source.parent / "chunks" + output_dir.mkdir(parents=True, exist_ok=True) + chunks: list[AudioChunk] = [] + try: + with wave.open(str(source), "rb") as reader: + rate = reader.getframerate() + for index, (start, end) in enumerate(ranges): + destination = output_dir / f"chunk_{index:04d}.wav" + # Rewrite atomically: never reuse partial chunks after a crash. + temporary = destination.with_suffix(".wav.part") + reader.setpos(min(int(start * rate), reader.getnframes())) + with wave.open(str(temporary), "wb") as writer: + writer.setparams(reader.getparams()) + writer.writeframes(reader.readframes(int((end - start) * rate))) + temporary.replace(destination) + chunks.append(AudioChunk(index, destination, start, end - start)) + except (OSError, EOFError, wave.Error) as exc: + raise CompressionError("Не удалось нарезать локальный WAV; исходник сохранён") from exc + return ChunkingResult(tuple(chunks), "local_pcm_fixed", 0, 0) + + @staticmethod + def _chunk_prompt(base_prompt: str, previous_text: str) -> str: + if not previous_text: + return base_prompt + previous_tail = previous_text[-700:] + context = ( + "Контекст конца предыдущего аудиофрагмента; используй только для связности " + f"и не добавляй отсутствующие слова: {previous_tail}" + ) + return "\n\n".join(part for part in (base_prompt, context) if part)[-1600:] + + @staticmethod + def _cleanup_successful_session(session_dir: Path, archive_path: Path) -> None: + """После успеха оставляет компактный архив Opus и все тексты.""" + if archive_path.exists(): + (session_dir / "source.wav").unlink(missing_ok=True) + chunks_dir = session_dir / "chunks" + if chunks_dir.exists(): + shutil.rmtree(chunks_dir) + + def _on_transcription_success( + self, + result: TranscriptionResult, + config: Config, + *, + finalize_state: bool = True, + allow_auto_paste: bool = True, + processing_started: float | None = None, + session_dir: Path | None = None, + ) -> None: """Обрабатывает успешную транскрипцию. Args: @@ -185,7 +589,8 @@ class DictationOrchestrator: """ if not result.text: logger.info("Транскрипция вернула пустой текст") - self._set_state(RecordingState.IDLE) + if finalize_state: + self._set_state(RecordingState.IDLE) return logger.info( @@ -195,6 +600,46 @@ class DictationOrchestrator: len(result.text), ) + # Post-processing через активный пресет (если есть и не пустой) + final_text = result.text + active = self._resolve_active_preset(config) + if ( + config.transcription_backend != "local" + and active is not None + and active.prompt.strip() + and active.model.strip() + ): + try: + final_text = self._summarize(result.text, active) + logger.info( + "Summary (%s): %d → %d символов", + active.name, + len(result.text), + len(final_text), + ) + except Exception as exc: + logger.error( + "Ошибка summary (preset=%s): %s, вставляю оригинал", + active.name, + exc, + ) + 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: @@ -205,7 +650,10 @@ class DictationOrchestrator: duration_sec=result.duration_sec, cost_usd=result.cost_usd, model=result.model, - text_preview=result.text[:80], + text_preview=final_text[:80], + full_text=final_text, + processing_sec=processing_sec, + audio_path=audio_path, ) ) tz = datetime.now().astimezone().tzinfo @@ -213,29 +661,16 @@ class DictationOrchestrator: except Exception as exc: logger.warning("Не удалось записать UsageRecord: %s", exc) - # Постобработка: гоним текст через LLM по выбранному режиму - final_text = result.text - mode = get_mode(config.mode, config.custom_modes) - if mode.uses_llm: - try: - final_text = self._post_process(result.text, mode.prompt, config) - logger.info( - "Режим '%s' готов: %d → %d символов", - mode.key, - len(result.text), - len(final_text), - ) - except Exception as exc: - logger.error("Ошибка постобработки (%s): %s, вставляю оригинал", mode.key, exc) - self._clipboard.copy(final_text) if config.notifications_enabled: from voice_dictation.core.fx import get_rate, usd_to_rub - chars = len(result.text) + chars = len(final_text) summary_parts = [f"{result.duration_sec:.1f}с · {chars} симв."] - if config.show_cost_in_notification: + if config.transcription_backend == "local": + summary_parts.append("локально · без API") + elif config.show_cost_in_notification: rate = get_rate() cost_rub = usd_to_rub(result.cost_usd, rate) cost_part = f"${result.cost_usd:.4f}" @@ -250,45 +685,50 @@ class DictationOrchestrator: summary_parts.append(today_part) self._notifier.show("Диктовка готова", " · ".join(summary_parts)) - if config.auto_paste and len(result.text) <= _MAX_AUTOPASTE_CHARS: + if allow_auto_paste and config.auto_paste and len(final_text) <= _MAX_AUTOPASTE_CHARS: if config.paste_delay_ms > 0: time.sleep(config.paste_delay_ms / 1000) self._auto_paste.paste() - elif len(result.text) > _MAX_AUTOPASTE_CHARS: - # Слишком длинный текст — только буфер, без вставки - chars = len(result.text) + elif len(final_text) > _MAX_AUTOPASTE_CHARS: self._notifier.show( "Текст скопирован", - f"Слишком длинный для автовставки ({chars} символов). Вставьте вручную Cmd+V.", + f"Слишком длинный для автовставки ({len(final_text)} симв.). Вставьте вручную ⌘V.", ) - self._set_state(RecordingState.IDLE) + if finalize_state: + self._set_state(RecordingState.IDLE) @staticmethod - def _post_process(text: str, prompt: str, config: Config) -> str: - """Прогоняет текст через LLM с заданным промптом режима. + def _resolve_active_preset(config: Config) -> SummaryPreset | None: + """Находит активный пресет по имени из config.active_preset.""" + for preset in config.summary_presets: + if preset.name == config.active_preset: + return preset + return None - Args: - text: Исходная транскрипция. - prompt: Системная инструкция режима. - config: Конфигурация (модель в proc_model). - - Returns: - Обработанный текст; исходный, если LLM вернул пусто. - """ + @staticmethod + def _summarize(text: str, preset: SummaryPreset) -> str: + """Отправляет текст в OpenAI для post-processing по пресету.""" from openai import OpenAI client = OpenAI() resp = client.chat.completions.create( - model=config.proc_model, + model=preset.model, messages=[ - {"role": "user", "content": f"{prompt}\n\n{text}"} + {"role": "user", "content": f"{preset.prompt}\n\n{text}"}, ], - max_tokens=2000, + max_tokens=4000, ) - return resp.choices[0].message.content or text + choice = resp.choices[0].message.content if resp.choices else None + return choice or text - def _on_transcription_error(self, message: str, config: Config) -> None: + def _on_transcription_error( + self, + message: str, + config: Config, + *, + finalize_state: bool = True, + ) -> None: """Обрабатывает ошибку транскрипции. Args: @@ -297,7 +737,8 @@ class DictationOrchestrator: """ self._sound_player.play(SoundKind.ERROR, config=config) self._notifier.show("Ошибка транскрипции", message) - self._set_state(RecordingState.IDLE) + if finalize_state: + self._set_state(RecordingState.IDLE) def _set_state(self, new_state: RecordingState) -> None: """Устанавливает новое состояние и уведомляет слушателя. diff --git a/src/voice_dictation/core/paths.py b/src/voice_dictation/core/paths.py index cb23add..ecdd17a 100644 --- a/src/voice_dictation/core/paths.py +++ b/src/voice_dictation/core/paths.py @@ -2,9 +2,14 @@ from __future__ import annotations +import os +import re +import sys from dataclasses import dataclass from pathlib import Path +from voice_dictation import __version__ + @dataclass(frozen=True, slots=True) class AppPaths: @@ -29,7 +34,6 @@ class AppPaths: log_file: Path pid_file: Path tmp_dir: Path - bin_dir: Path @classmethod def default(cls) -> AppPaths: @@ -38,7 +42,16 @@ class AppPaths: Returns: AppPaths с путями в ~/.dictate/. """ - root = Path.home() / ".dictate" + override = os.environ.get("VOICE_DICTATION_HOME") + # Build identity must survive renaming or moving the .app bundle. + beta = bool(getattr(sys, "frozen", False)) and bool( + re.search(r"(?:a|b|rc|\.dev)\d", __version__) + ) + root = ( + Path(override).expanduser() + if override + else Path.home() / (".dictate-beta" if beta else ".dictate") + ) return cls( root=root, config_file=root / "config.json", @@ -48,7 +61,6 @@ class AppPaths: log_file=root / "app.log", pid_file=root / "dictate.pid", tmp_dir=root / "tmp", - bin_dir=root / "bin", ) def ensure_exists(self) -> AppPaths: @@ -57,6 +69,27 @@ class AppPaths: Returns: self для удобства цепочки вызовов. """ - for directory in (self.root, self.custom_sounds_dir, self.tmp_dir, self.bin_dir): + for directory in ( + self.root, + self.custom_sounds_dir, + self.tmp_dir, + self.sessions_dir, + self.bin_dir, + ): directory.mkdir(parents=True, exist_ok=True) return self + + @property + def sessions_dir(self) -> Path: + """Постоянные аудиосессии и промежуточные результаты транскрипции.""" + return self.root / "sessions" + + @property + def bin_dir(self) -> Path: + """Downloaded helper binaries, preserved across application updates.""" + return self.root / "bin" + + @property + def models_dir(self) -> Path: + """Downloaded models are independent of the application bundle.""" + return self.root / "models" diff --git a/src/voice_dictation/core/pricing.py b/src/voice_dictation/core/pricing.py index 0361c75..e7e6326 100644 --- a/src/voice_dictation/core/pricing.py +++ b/src/voice_dictation/core/pricing.py @@ -17,6 +17,7 @@ class PriceCalculator: PRICES_PER_MINUTE: Final[Mapping[str, Decimal]] = MappingProxyType( { + "gpt-transcribe": Decimal("0.0045"), "gpt-4o-mini-transcribe": Decimal("0.003"), "gpt-4o-transcribe": Decimal("0.006"), "whisper-1": Decimal("0.006"), diff --git a/src/voice_dictation/core/recorder.py b/src/voice_dictation/core/recorder.py index fa41e2d..2cd889f 100644 --- a/src/voice_dictation/core/recorder.py +++ b/src/voice_dictation/core/recorder.py @@ -1,51 +1,75 @@ -"""Запись аудио с микрофона через sounddevice (кроссплатформенно).""" +"""Запись аудио с микрофона через sounddevice (in-memory frames → WAV). + +Sounddevice держит фреймы в памяти и собирает WAV в момент `stop()` — это +надёжнее, чем sox через subprocess (terminate ломал WAV-заголовок при длинных +записях, особенно на Windows). OGG/Opus сжатие делает orchestrator через +`AudioCompressor`, recorder сохраняет только WAV. +""" from __future__ import annotations import logging +import queue import struct import threading import time from pathlib import Path +from typing import TYPE_CHECKING, Any from voice_dictation.core.models import RecordingResult from voice_dictation.infrastructure.errors import RecorderError +if TYPE_CHECKING: + pass + logger = logging.getLogger(__name__) _MIN_DURATION_SEC = 0.3 _MIN_FILE_SIZE_BYTES = 4 * 1024 # 4 KB +_BLOCKSIZE = 1024 +_SAMPLE_WIDTH_BYTES = 2 # 16-bit PCM +_HEADER_SIZE_BYTES = 44 +_CHECKPOINT_INTERVAL_SEC = 5.0 class SoxRecorder: - """Запись WAV с микрофона через sounddevice. + """Запись WAV с микрофона через `sounddevice.RawInputStream`. + + Имя класса оставлено для обратной совместимости с импортами в `__main__` + и тестах. Sox больше не используется. Args: - sample_rate: Частота дискретизации (по умолчанию 16000 Гц). + sample_rate: Частота дискретизации в Гц (по умолчанию 16000). channels: Количество каналов (по умолчанию 1 — моно). - bin_dir: Каталог докачанных бинарников (для поиска ffmpeg). """ - def __init__( - self, sample_rate: int = 16000, channels: int = 1, bin_dir: Path | None = None - ) -> None: + def __init__(self, sample_rate: int = 16000, channels: int = 1) -> None: try: import sounddevice # noqa: F401 - except ImportError: + except ImportError as exc: raise RecorderError( - "sounddevice не установлен. pip install sounddevice" - ) + 'sounddevice не установлен. Запустите `pip install -e ".[dev]"`', + ) from exc self._sample_rate = sample_rate self._channels = channels - self._bin_dir = bin_dir - self._frames: list[bytes] = [] - self._stream = None + self._stream: Any = None self._output_path: Path | None = None self._start_time: float | None = None self._lock = threading.Lock() + self._write_queue: queue.SimpleQueue[bytes | None] | None = None + self._writer_thread: threading.Thread | None = None + self._writer_error: Exception | None = None + self._data_size = 0 def start(self, output_path: Path) -> None: - """Начинает запись в указанный файл.""" + """Начинает запись в указанный файл. + + Args: + output_path: Путь для сохранения WAV-файла. + + Raises: + RecorderError: Если запись уже идёт или поток не запустился. + """ import sounddevice as sd with self._lock: @@ -53,13 +77,24 @@ class SoxRecorder: raise RecorderError("Запись уже запущена") output_path.parent.mkdir(parents=True, exist_ok=True) - self._frames = [] self._output_path = output_path + self._write_queue = queue.SimpleQueue() + self._writer_error = None + self._data_size = 0 + self._writer_thread = threading.Thread( + target=self._write_stream, + args=(output_path, self._write_queue), + name="audio-writer", + daemon=True, + ) + self._writer_thread.start() - def callback(indata, frames, time_info, status): + def callback(indata: Any, _frames: int, _time_info: Any, status: Any) -> None: if status: logger.warning("sounddevice status: %s", status) - self._frames.append(bytes(indata)) + write_queue = self._write_queue + if write_queue is not None: + write_queue.put(bytes(indata)) try: self._stream = sd.RawInputStream( @@ -67,18 +102,28 @@ class SoxRecorder: channels=self._channels, dtype="int16", callback=callback, - blocksize=1024, + blocksize=_BLOCKSIZE, ) self._stream.start() except Exception as exc: self._stream = None + self._finish_writer() + output_path.unlink(missing_ok=True) raise RecorderError(f"Не удалось начать запись: {exc}") from exc self._start_time = time.monotonic() logger.debug("Запись начата: %s", output_path) def stop(self) -> RecordingResult: - """Останавливает запись и возвращает результат.""" + """Останавливает запись и возвращает результат. + + Returns: + RecordingResult с путём к WAV и длительностью. + + Raises: + RecorderError: Если запись не была запущена, нет данных, + запись слишком короткая или файл слишком маленький. + """ with self._lock: if self._stream is None or self._output_path is None: raise RecorderError("Запись не запущена") @@ -94,105 +139,110 @@ class SoxRecorder: self._stream = None self._output_path = None - elapsed = time.monotonic() - (self._start_time or 0) self._start_time = None + self._finish_writer() - # Собираем все фреймы в один буфер - audio_data = b"".join(self._frames) - self._frames = [] - - if not audio_data: + if self._writer_error is not None: + raise RecorderError(f"Ошибка записи WAV на диск: {self._writer_error}") + if self._data_size == 0: raise RecorderError("Нет записанных данных") - duration_sec = len(audio_data) / (self._sample_rate * self._channels * 2) - - # Конвертируем в OGG/Opus — ~10x сжатие - ogg_path = output_path.with_suffix(".ogg") - try: - self._write_ogg(audio_data, ogg_path) - output_path = ogg_path - logger.debug("Конвертировано в OGG: %d байт", ogg_path.stat().st_size) - except Exception as exc: - logger.warning("OGG конвертация не удалась, пишем WAV: %s", exc) - self._write_wav(output_path, audio_data) - + duration_sec = self._data_size / ( + self._sample_rate * self._channels * _SAMPLE_WIDTH_BYTES + ) file_size = output_path.stat().st_size if duration_sec < _MIN_DURATION_SEC: output_path.unlink(missing_ok=True) raise RecorderError( - f"Запись слишком короткая: {duration_sec:.2f}с" + f"Запись слишком короткая: {duration_sec:.2f}с (минимум {_MIN_DURATION_SEC}с)", ) if file_size < _MIN_FILE_SIZE_BYTES: output_path.unlink(missing_ok=True) raise RecorderError( - f"Файл слишком маленький: {file_size} байт" + f"Файл слишком маленький: {file_size} байт (минимум {_MIN_FILE_SIZE_BYTES})", ) logger.debug("Запись остановлена: %.2fс, %d байт", duration_sec, file_size) return RecordingResult(path=output_path, duration_sec=duration_sec) - def _write_wav(self, path: Path, data: bytes) -> None: - """Записывает корректный WAV-файл.""" + def _write_stream( + self, + path: Path, + write_queue: queue.SimpleQueue[bytes | None], + ) -> None: + """Потоково пишет PCM и каждые пять секунд чинит WAV-заголовок.""" + data_size = 0 + last_checkpoint = time.monotonic() + try: + with path.open("w+b") as fh: + fh.write(self._wav_header(0)) + fh.flush() + while True: + block = write_queue.get() + if block is None: + break + fh.seek(0, 2) + fh.write(block) + data_size += len(block) + if time.monotonic() - last_checkpoint >= _CHECKPOINT_INTERVAL_SEC: + self._checkpoint_header(fh, data_size) + last_checkpoint = time.monotonic() + self._checkpoint_header(fh, data_size) + except Exception as exc: + self._writer_error = exc + finally: + self._data_size = data_size + + def _finish_writer(self) -> None: + write_queue = self._write_queue + writer_thread = self._writer_thread + self._write_queue = None + self._writer_thread = None + if write_queue is not None: + write_queue.put(None) + if writer_thread is not None: + writer_thread.join(timeout=30) + if writer_thread.is_alive() and self._writer_error is None: + self._writer_error = RuntimeError("audio-writer не завершился за 30 секунд") + + def _checkpoint_header(self, fh: Any, data_size: int) -> None: + fh.seek(0) + fh.write(self._wav_header(data_size)) + fh.flush() + fh.seek(_HEADER_SIZE_BYTES + data_size) + + def _wav_header(self, data_size: int) -> bytes: + """Собирает 44-байтовый PCM WAV-заголовок.""" num_channels = self._channels - sample_width = 2 # 16-bit + sample_width = _SAMPLE_WIDTH_BYTES byte_rate = self._sample_rate * num_channels * sample_width block_align = num_channels * sample_width - data_size = len(data) file_size = 36 + data_size - - with open(path, "wb") as f: - # RIFF header - f.write(b"RIFF") - f.write(struct.pack(" None: - """Конвертирует PCM-данные в OGG/Opus через ffmpeg.""" - import subprocess as sp - import os as _os - - from voice_dictation.core.ffmpeg_setup import find_ffmpeg - - ffmpeg = find_ffmpeg(self._bin_dir) - if not ffmpeg: - raise RuntimeError("ffmpeg не найден") - - cmd = [ - ffmpeg, "-y", - "-f", "s16le", - "-ar", str(self._sample_rate), - "-ac", str(self._channels), - "-i", "-", - "-c:a", "libopus", - "-b:a", "32k", - str(path), - ] - kw: dict = dict(stdout=sp.DEVNULL, stderr=sp.DEVNULL) - if _os.name == "nt": - kw["creationflags"] = sp.CREATE_NO_WINDOW - proc = sp.Popen(cmd, stdin=sp.PIPE, **kw) - proc.communicate(input=data, timeout=30) - if proc.returncode != 0: - raise RuntimeError(f"ffmpeg exit code {proc.returncode}") + return b"".join( + ( + b"RIFF", + struct.pack(" None: + """Гарантированно останавливает stream при уничтожении объекта.""" if self._stream is not None: try: self._stream.stop() self._stream.close() except Exception: pass + self._finish_writer() diff --git a/src/voice_dictation/core/session_store.py b/src/voice_dictation/core/session_store.py new file mode 100644 index 0000000..3d46e7e --- /dev/null +++ b/src/voice_dictation/core/session_store.py @@ -0,0 +1,242 @@ +"""Долговечное хранилище аудиосессий и checkpoint-ов транскрипции.""" + +from __future__ import annotations + +import json +import logging +import re +import shutil +from datetime import UTC, datetime, timedelta +from decimal import Decimal +from pathlib import Path +from typing import Any +from uuid import uuid4 + +from voice_dictation.core.models import TranscriptionResult + +logger = logging.getLogger(__name__) + +_MANIFEST_NAME = "manifest.json" +_PENDING_STATUSES = frozenset({"recording", "recorded", "processing", "failed"}) + + +class SessionStore: + """Пишет состояние сессии атомарно в ``~/.dictate/sessions``.""" + + def __init__(self, sessions_dir: Path) -> None: + self._sessions_dir = sessions_dir + self._sessions_dir.mkdir(parents=True, exist_ok=True) + + 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]}" + 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, + version=1, + session_id=session_id, + status="recording", + created_at=now.isoformat(), + source_wav="source.wav", + chunks=[], + ) + return session_dir / "source.wav" + + def update(self, session_dir: Path, **values: object) -> dict[str, Any]: + """Обновляет manifest через временный файл и atomic replace.""" + manifest = self.read(session_dir) + manifest.update(values) + manifest["updated_at"] = datetime.now(tz=UTC).isoformat() + self._write_json(session_dir / _MANIFEST_NAME, manifest) + return manifest + + def read(self, session_dir: Path) -> dict[str, Any]: + """Читает manifest; для новой сессии возвращает пустой словарь.""" + path = session_dir / _MANIFEST_NAME + if not path.exists(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + logger.warning("Не удалось прочитать manifest %s: %s", path, exc) + return {} + return data if isinstance(data, dict) else {} + + def mark_recorded(self, audio_path: Path, duration_sec: float) -> None: + """Фиксирует успешно завершённую запись.""" + self.update( + audio_path.parent, + status="recorded", + duration_sec=duration_sec, + recorded_at=datetime.now(tz=UTC).isoformat(), + ) + + def mark_failed(self, session_dir: Path, error: str) -> None: + """Фиксирует ошибку, не удаляя ни аудио, ни checkpoint-ы.""" + self.update(session_dir, status="failed", last_error=error) + + def save_chunk_result( + self, + session_dir: Path, + index: int, + result: TranscriptionResult, + ) -> None: + """Сохраняет ответ API отдельным checkpoint-файлом.""" + result_path = session_dir / "transcripts" / f"chunk_{index:04d}.json" + payload = { + "index": index, + "text": result.text, + "duration_sec": result.duration_sec, + "model": result.model, + "language": result.language, + "prompt_used": result.prompt_used, + "requested_at": result.requested_at.isoformat(), + "cost_usd": str(result.cost_usd), + } + self._write_json(result_path, payload) + + def load_chunk_result(self, session_dir: Path, index: int) -> TranscriptionResult | None: + """Возвращает готовый checkpoint, чтобы не платить за него повторно.""" + path = session_dir / "transcripts" / f"chunk_{index:04d}.json" + if not path.exists(): + return None + try: + payload = json.loads(path.read_text(encoding="utf-8")) + return TranscriptionResult( + text=str(payload["text"]), + duration_sec=float(payload["duration_sec"]), + model=str(payload["model"]), + language=(str(payload["language"]) if payload.get("language") else None), + prompt_used=(str(payload["prompt_used"]) if payload.get("prompt_used") else None), + requested_at=datetime.fromisoformat(str(payload["requested_at"])), + cost_usd=Decimal(str(payload["cost_usd"])), + ) + except (KeyError, TypeError, ValueError, OSError, json.JSONDecodeError) as exc: + logger.warning("Повреждён checkpoint %s: %s", path, exc) + return None + + def complete( + self, + session_dir: Path, + text: str, + removed_prefix_words: tuple[int, ...], + ) -> None: + """Атомарно сохраняет итоговый текст и помечает сессию завершённой.""" + self._write_text(session_dir / "transcript.txt", text) + self.update( + session_dir, + status="completed", + completed_at=datetime.now(tz=UTC).isoformat(), + transcript_file="transcript.txt", + stitch_removed_prefix_words=list(removed_prefix_words), + 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 self._session_directories(): + if not session_dir.is_dir(): + continue + manifest = self.read(session_dir) + if manifest.get("status") not in _PENDING_STATUSES: + continue + if (session_dir / "source.wav").exists() or (session_dir / "source.ogg").exists(): + pending.append(session_dir) + return pending + + def cleanup_completed_audio(self, retention_days: int) -> int: + """Удаляет только аудио старых завершённых сессий, сохраняя текст и manifest.""" + if retention_days < 1: + return 0 + cutoff = datetime.now(tz=UTC) - timedelta(days=retention_days) + removed = 0 + for session_dir in self._session_directories(): + if not session_dir.is_dir(): + continue + manifest = self.read(session_dir) + if manifest.get("status") != "completed": + continue + try: + completed_at = datetime.fromisoformat(str(manifest["completed_at"])) + except (KeyError, ValueError): + continue + if completed_at >= cutoff: + continue + for name in ("source.wav", "source.ogg"): + path = session_dir / name + if path.exists(): + path.unlink() + removed += 1 + chunks_dir = session_dir / "chunks" + if chunks_dir.exists(): + shutil.rmtree(chunks_dir) + removed += 1 + return removed + + @staticmethod + def _write_json(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temp_path = path.with_suffix(path.suffix + ".tmp") + temp_path.write_text( + json.dumps(payload, indent=2, ensure_ascii=False), + encoding="utf-8", + ) + temp_path.replace(path) + + @staticmethod + def _write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temp_path = path.with_suffix(path.suffix + ".tmp") + temp_path.write_text(text, encoding="utf-8") + temp_path.replace(path) diff --git a/src/voice_dictation/core/text_stitcher.py b/src/voice_dictation/core/text_stitcher.py new file mode 100644 index 0000000..c3a8b39 --- /dev/null +++ b/src/voice_dictation/core/text_stitcher.py @@ -0,0 +1,67 @@ +"""Безопасная склейка транскриптов перекрывающихся аудиофрагментов.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from difflib import SequenceMatcher + +_TOKEN_RE = re.compile(r"\S+") +_NORMALIZE_RE = re.compile(r"[^\w]+", flags=re.UNICODE) +_MAX_OVERLAP_WORDS = 100 +_MIN_FUZZY_WORDS = 4 +_FUZZY_THRESHOLD = 0.88 + + +@dataclass(frozen=True, slots=True) +class StitchResult: + """Итоговая строка и число удалённых слов в каждом следующем фрагменте.""" + + text: str + removed_prefix_words: tuple[int, ...] + + +def _normalize(token: str) -> str: + return _NORMALIZE_RE.sub("", token.casefold()) + + +def _tokens(text: str) -> list[str]: + return _TOKEN_RE.findall(text.strip()) + + +def _overlap_size(left: list[str], right: list[str]) -> int: + limit = min(len(left), len(right), _MAX_OVERLAP_WORDS) + left_normalized = [_normalize(token) for token in left] + right_normalized = [_normalize(token) for token in right] + + for size in range(limit, 1, -1): + if left_normalized[-size:] == right_normalized[:size]: + return size + + for size in range(limit, _MIN_FUZZY_WORDS - 1, -1): + left_part = " ".join(left_normalized[-size:]) + right_part = " ".join(right_normalized[:size]) + if SequenceMatcher(None, left_part, right_part).ratio() >= _FUZZY_THRESHOLD: + return size + + return 0 + + +def stitch_transcripts(parts: list[str]) -> StitchResult: + """Склеивает части, удаляя только уверенно распознанное перекрытие. + + При сомнении сохраняет оба текста. Небольшой дубль безопаснее потери слов. + """ + non_empty = [part.strip() for part in parts if part.strip()] + if not non_empty: + return StitchResult(text="", removed_prefix_words=()) + + merged_tokens = _tokens(non_empty[0]) + removed: list[int] = [] + for part in non_empty[1:]: + next_tokens = _tokens(part) + overlap = _overlap_size(merged_tokens, next_tokens) + removed.append(overlap) + merged_tokens.extend(next_tokens[overlap:]) + + return StitchResult(text=" ".join(merged_tokens), removed_prefix_words=tuple(removed)) diff --git a/src/voice_dictation/core/transcriber.py b/src/voice_dictation/core/transcriber.py index cae5fd9..1edf836 100644 --- a/src/voice_dictation/core/transcriber.py +++ b/src/voice_dictation/core/transcriber.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import math import wave from datetime import UTC, datetime from decimal import Decimal @@ -17,9 +18,32 @@ from voice_dictation.infrastructure.errors import TranscriptionError, WhisperAPI logger = logging.getLogger(__name__) _API_URL = "https://api.openai.com/v1/audio/transcriptions" -_TIMEOUT_SEC = 60.0 +# Базовый таймаут для коротких записей. Для длинных используется duration_sec × множитель. +_BASE_TIMEOUT_SEC = 120.0 +_TIMEOUT_PER_AUDIO_SEC = 0.5 # 30 мин аудио → +15 мин таймаут _MAX_RETRIES = 2 +# Content-type по расширению: Whisper принимает wav/ogg/mp3/m4a/flac/webm. +_CONTENT_TYPE_BY_SUFFIX = { + ".wav": "audio/wav", + ".ogg": "audio/ogg", + ".opus": "audio/ogg", + ".mp3": "audio/mpeg", + ".m4a": "audio/mp4", + ".flac": "audio/flac", + ".webm": "audio/webm", +} + + +def _compute_timeout(duration_sec: float | None) -> float: + if duration_sec is None or duration_sec <= 0: + return _BASE_TIMEOUT_SEC + return max(_BASE_TIMEOUT_SEC, duration_sec * _TIMEOUT_PER_AUDIO_SEC + 60.0) + + +def _content_type_for(path: Path) -> str: + return _CONTENT_TYPE_BY_SUFFIX.get(path.suffix.lower(), "application/octet-stream") + class WhisperTranscriber: """Транскрипция WAV-файлов через OpenAI Whisper API. @@ -32,23 +56,25 @@ class WhisperTranscriber: def __init__(self, api_key: str, model: str = "gpt-4o-mini-transcribe") -> None: self._api_key = api_key self._model = model - self._client = httpx.Client( - headers={"Authorization": f"Bearer {api_key}"}, - timeout=_TIMEOUT_SEC, - ) + # Клиент без статического timeout — таймаут задаётся на каждый запрос по длине аудио. + self._client = httpx.Client(headers={"Authorization": f"Bearer {api_key}"}) def transcribe( self, audio_path: Path, prompt: str = "", language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, ) -> TranscriptionResult: - """Отправляет WAV в Whisper API и возвращает результат. + """Отправляет аудио в Whisper API и возвращает результат. Args: - audio_path: Путь к WAV-файлу. + audio_path: Путь к аудио-файлу (wav/ogg/mp3/m4a/flac/webm). prompt: Подсказка со специальными словами. language: Код языка (None — автоопределение). + model: Переопределяет модель на этот один вызов (None — использует self._model). + duration_sec: Длительность аудио для расчёта таймаута. Returns: TranscriptionResult с текстом и метаданными. @@ -58,11 +84,21 @@ class WhisperTranscriber: WhisperAPIError: При HTTP-ошибке от API. """ requested_at = datetime.now(tz=UTC) + effective_model = model or self._model + timeout = _compute_timeout(duration_sec) last_exc: Exception | None = None for attempt in range(_MAX_RETRIES + 1): try: - result = self._do_request(audio_path, prompt, language, requested_at) + result = self._do_request( + audio_path, + prompt, + language, + requested_at, + effective_model, + timeout, + duration_sec, + ) return result except WhisperAPIError as exc: # Не ретраим 4xx — это клиентские ошибки @@ -91,14 +127,19 @@ class WhisperTranscriber: prompt: str, language: str | None, requested_at: datetime, + model: str, + timeout: float, + duration_hint: float | None, ) -> TranscriptionResult: """Выполняет один HTTP-запрос к Whisper API. Args: - audio_path: Путь к WAV. + audio_path: Путь к аудио-файлу. prompt: Подсказка. language: Код языка. requested_at: Время запроса. + model: Модель для этого запроса. + timeout: Таймаут HTTP-запроса. Returns: TranscriptionResult. @@ -107,22 +148,26 @@ class WhisperTranscriber: WhisperAPIError: При HTTP-ошибке. TranscriptionError: При сетевой ошибке или невалидном JSON. """ - response_format = "verbose_json" if self._model == "whisper-1" else "json" + response_format = "verbose_json" if model == "whisper-1" else "json" data: dict[str, str] = { - "model": self._model, + "model": model, "response_format": response_format, } if language: - data["language"] = language + # GPT-Transcribe uses repeated multipart languages[] hints. + data["languages[]" if model == "gpt-transcribe" else "language"] = language if prompt: data["prompt"] = prompt + content_type = _content_type_for(audio_path) + try: with audio_path.open("rb") as audio_file: response = self._client.post( _API_URL, data=data, - files={"file": (audio_path.name, audio_file, "audio/ogg" if audio_path.suffix == ".ogg" else "audio/wav")}, + files={"file": (audio_path.name, audio_file, content_type)}, + timeout=timeout, ) except httpx.TimeoutException as exc: raise TranscriptionError(f"Timeout при запросе к Whisper API: {exc}") from exc @@ -140,20 +185,53 @@ class WhisperTranscriber: except Exception as exc: raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc - text: str = body.get("text", "").strip() - duration_sec: float = float(body.get("duration", 0.0)) or _wav_duration(audio_path) - detected_language: str | None = body.get("language") or language + if not isinstance(body, dict) or not isinstance(body.get("text"), str): + raise TranscriptionError("Невалидная структура ответа транскрипции") + text = body["text"].strip() + duration_value: object = body.get("duration", 0.0) + if model == "gpt-transcribe": + usage = body.get("usage") + if isinstance(usage, dict) and usage.get("type") == "duration": + duration_value = usage.get("seconds", 0.0) + if ( + isinstance(duration_value, bool) + or not isinstance(duration_value, (float, int)) + or not math.isfinite(duration_value) + or duration_value < 0 + ): + raise TranscriptionError("Невалидная длительность в ответе транскрипции") + api_duration = float(duration_value) + duration_sec = ( + api_duration + or (duration_hint if duration_hint and duration_hint > 0 else 0.0) + or _wav_duration(audio_path) + ) + detected_language: str | None + if model == "gpt-transcribe": + detected = body.get("languages", []) + if not isinstance(detected, list) or any( + not isinstance(item, dict) + or not isinstance(item.get("code"), str) + or not item["code"].strip() + for item in detected + ): + raise TranscriptionError("Невалидные языки в ответе транскрипции") + # The current result schema is singular: do not misrepresent multiple + # detected languages, an empty array or a requested hint as detection. + detected_language = detected[0]["code"] if len(detected) == 1 else None + else: + detected_language = body.get("language") or language - cost = PriceCalculator.cost(self._model, duration_sec) + cost = PriceCalculator.cost(model, duration_sec) return TranscriptionResult( text=text, duration_sec=duration_sec, - model=self._model, + model=model, language=detected_language, prompt_used=prompt or None, requested_at=requested_at, - cost_usd=cost if cost != Decimal("0") else PriceCalculator.cost(self._model, 1.0), + cost_usd=cost if cost != Decimal("0") else PriceCalculator.cost(model, 1.0), ) def close(self) -> None: diff --git a/src/voice_dictation/core/transcription.py b/src/voice_dictation/core/transcription.py new file mode 100644 index 0000000..bf83971 --- /dev/null +++ b/src/voice_dictation/core/transcription.py @@ -0,0 +1,86 @@ +"""Engine-neutral transcription contract and explicit local/cloud routing.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Protocol + +from voice_dictation.core.models import TranscriptionResult +from voice_dictation.infrastructure.errors import TranscriptionError + + +class Transcriber(Protocol): + """Recognize an audio file using an explicitly selected model.""" + + def transcribe( + self, + audio_path: Path, + prompt: str = "", + language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, + ) -> TranscriptionResult: + """Return recognized text or raise a transcription error.""" + ... + + def close(self) -> None: + """Release resources.""" + ... + + +class RoutingTranscriber: + """Dispatch by model identity; local failures never fall back to cloud.""" + + def __init__(self, api_key: str, models_dir: Path) -> None: + self._api_key = api_key + self._models_dir = models_dir + + def transcribe( + self, + audio_path: Path, + prompt: str = "", + language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, + ) -> TranscriptionResult: + """Recognize locally for local: model IDs, otherwise use OpenAI.""" + if model is None: + raise TranscriptionError("Не выбрана модель распознавания") + engine: Transcriber + if model.startswith("local:"): + from voice_dictation.core.local_transcriber import LocalTranscriber + from voice_dictation.core.model_manager import ModelManager + + manager = ModelManager(self._models_dir) + model_id = model.removeprefix("local:") + try: + with manager.use(model_id) as 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 + ) + except RuntimeError as exc: + raise TranscriptionError(str(exc)) from exc + else: + from voice_dictation.core.transcriber import WhisperTranscriber + from voice_dictation.infrastructure.credentials import read_api_key + + api_key = read_api_key(self._models_dir.parent) or self._api_key + if not api_key: + raise TranscriptionError( + "Для OpenAI укажите OPENAI_API_KEY или выберите локальный режим" + ) + engine = WhisperTranscriber(api_key=api_key, model=model) + try: + return engine.transcribe(audio_path, prompt, language, model, duration_sec) + finally: + # Both concrete implementations own disposable resources. + engine.close() + + def close(self) -> None: + """Each recognition call closes its own concrete engine.""" diff --git a/src/voice_dictation/core/usage_db.py b/src/voice_dictation/core/usage_db.py index 036df27..590d949 100644 --- a/src/voice_dictation/core/usage_db.py +++ b/src/voice_dictation/core/usage_db.py @@ -8,7 +8,7 @@ import threading from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass -from datetime import UTC, date, datetime, time, timedelta, timezone +from datetime import UTC, date, datetime, time, timedelta, tzinfo from decimal import Decimal from pathlib import Path @@ -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,19 +118,23 @@ 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: timezone = UTC) -> UsageStats: + def today_total(self, tz: tzinfo | None = None) -> UsageStats: """Статистика за сегодня в указанной TZ. Args: - tz: Часовой пояс для определения "сегодня". + tz: Часовой пояс для определения "сегодня". None → UTC. Returns: UsageStats за текущий день. """ - now_local = datetime.now(tz) - start_local = datetime.combine(now_local.date(), time.min, tzinfo=tz) + effective_tz: tzinfo = tz if tz is not None else UTC + now_local = datetime.now(effective_tz) + start_local = datetime.combine(now_local.date(), time.min, tzinfo=effective_tz) end_local = start_local + timedelta(days=1) return self.stats(start_local, end_local) @@ -161,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() @@ -173,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 ] @@ -196,20 +214,21 @@ class UsageDB: total_cost_usd=Decimal(str(total_cost)).quantize(Decimal("0.000001")), ) - def month_stats(self, year: int, month: int, tz: timezone = UTC) -> UsageStats: + def month_stats(self, year: int, month: int, tz: tzinfo | None = None) -> UsageStats: """Статистика за месяц. Args: year: Год. month: Месяц (1-12). - tz: Часовой пояс. + tz: Часовой пояс. None → UTC. Returns: UsageStats за указанный месяц. """ - start = datetime.combine(date(year, month, 1), time.min, tzinfo=tz) + effective_tz: tzinfo = tz if tz is not None else UTC + start = datetime.combine(date(year, month, 1), time.min, tzinfo=effective_tz) if month == 12: - end = datetime.combine(date(year + 1, 1, 1), time.min, tzinfo=tz) + end = datetime.combine(date(year + 1, 1, 1), time.min, tzinfo=effective_tz) else: - end = datetime.combine(date(year, month + 1, 1), time.min, tzinfo=tz) + end = datetime.combine(date(year, month + 1, 1), time.min, tzinfo=effective_tz) return self.stats(start, end) diff --git a/src/voice_dictation/infrastructure/credentials.py b/src/voice_dictation/infrastructure/credentials.py new file mode 100644 index 0000000..a4ac8d9 --- /dev/null +++ b/src/voice_dictation/infrastructure/credentials.py @@ -0,0 +1,66 @@ +"""Profile-scoped API credentials, separate from exported preferences.""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +from io import StringIO +from pathlib import Path + +from dotenv import dotenv_values + + +def read_api_key(root: Path) -> str: + """Read a saved key without logging its contents.""" + try: + data = json.loads((root / "credentials.json").read_text()) + value = data.get("openai_api_key", "") if isinstance(data, dict) else "" + return value if isinstance(value, str) else "" + except (OSError, ValueError): + return "" + + +def normalize_api_key(value: str) -> str: + """Accept a key or one OPENAI_API_KEY assignment pasted from dotenv.""" + candidate = value.strip().lstrip("\ufeff") + assignment = re.match(r"^(?:export\s+)?OPENAI_API_KEY\s*=", candidate) + if assignment: + candidate = "OPENAI_API_KEY=" + candidate[assignment.end() :] + parsed = dotenv_values(stream=StringIO(candidate), interpolate=False) + if set(parsed) != {"OPENAI_API_KEY"}: + raise ValueError("Скопировано несколько настроек. Нужна только строка OPENAI_API_KEY.") + candidate = (parsed.get("OPENAI_API_KEY") or "").strip() + quote_pairs = {'"': '"', "'": "'", "“": "”", "«": "»"} + if len(candidate) >= 2 and quote_pairs.get(candidate[0]) == candidate[-1]: + candidate = candidate[1:-1].strip() + if not candidate: + raise ValueError("Поле ключа пустое. Вставьте значение OPENAI_API_KEY из .env.") + # Long keys are sometimes copied with visual line wrapping or invisible separators. + compact = "".join( + char for char in candidate if not char.isspace() and char not in "\u200b\ufeff" + ) + if compact.startswith("sk-") and re.fullmatch(r"[A-Za-z0-9_-]+", compact): + candidate = compact + if any(char.isspace() for char in candidate): + raise ValueError( + "В ключе остались пробелы или лишние строки. Скопируйте только значение после =." + ) + if "=" in candidate: + raise ValueError("Не удалось разобрать строку. Ожидается OPENAI_API_KEY=значение.") + return candidate + + +def save_api_key(root: Path, key: str) -> None: + """Atomically save a private credentials file (0600 on POSIX).""" + key = normalize_api_key(key) + root.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".credentials-", dir=root) + temporary = Path(name) + try: + with os.fdopen(fd, "w") as stream: + json.dump({"openai_api_key": key}, stream) + temporary.replace(root / "credentials.json") + finally: + temporary.unlink(missing_ok=True) diff --git a/src/voice_dictation/infrastructure/env_loader.py b/src/voice_dictation/infrastructure/env_loader.py index 0d78d7a..cd6e928 100644 --- a/src/voice_dictation/infrastructure/env_loader.py +++ b/src/voice_dictation/infrastructure/env_loader.py @@ -3,20 +3,19 @@ from __future__ import annotations import os +import sys from dataclasses import dataclass from pathlib import Path from dotenv import load_dotenv -from voice_dictation.infrastructure.errors import ConfigError - @dataclass(frozen=True, slots=True) class EnvConfig: """Конфигурация из переменных окружения. Args: - api_key: OpenAI API ключ (обязательный). + api_key: OpenAI API ключ; пустой допустим для локального режима. admin_api_key: OpenAI Admin API ключ (опциональный, для баланса). """ @@ -33,17 +32,20 @@ def load_env() -> EnvConfig: Returns: EnvConfig с ключами API. - Raises: - ConfigError: Если OPENAI_API_KEY не задан или пустой. """ - # Ищем .env: рядом с exe → cwd → ~/.dictate/ - import sys - exe_dir = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path.cwd() - candidates = [ - exe_dir / ".env", - Path.cwd() / ".env", - Path.home() / ".dictate" / ".env", - ] + from voice_dictation.core.paths import AppPaths + + # Ищем .env: рядом с exe (для PyInstaller-сборки) → cwd → ~/.dictate/ + is_frozen = bool(getattr(sys, "frozen", False)) + candidates = [] + if is_frozen: + candidates.append(Path(sys.executable).parent / ".env") + candidates.extend( + [ + Path.cwd() / ".env", + AppPaths.default().root / ".env", + ] + ) for candidate in candidates: if candidate.exists(): load_dotenv(candidate, override=False) @@ -52,13 +54,9 @@ def load_env() -> EnvConfig: # .env не найден — используем существующие переменные окружения pass - api_key = os.environ.get("OPENAI_API_KEY", "").strip() - if not api_key: - raise ConfigError( - "OPENAI_API_KEY не задан. Создайте файл .env на основе .env.example " - "и укажите ключ: OPENAI_API_KEY=sk-..." - ) + from voice_dictation.infrastructure.credentials import read_api_key + api_key = read_api_key(AppPaths.default().root) or os.environ.get("OPENAI_API_KEY", "").strip() admin_key = os.environ.get("OPENAI_ADMIN_API_KEY", "").strip() or None return EnvConfig(api_key=api_key, admin_api_key=admin_key) diff --git a/src/voice_dictation/infrastructure/errors.py b/src/voice_dictation/infrastructure/errors.py index e1a2392..d183956 100644 --- a/src/voice_dictation/infrastructure/errors.py +++ b/src/voice_dictation/infrastructure/errors.py @@ -15,6 +15,10 @@ class SoxNotFoundError(RecorderError): """sox не найден в системном PATH.""" +class CompressionError(DictationError): + """Ошибка сжатия аудио (ffmpeg недоступен/упал).""" + + class TranscriptionError(DictationError): """Ошибка транскрипции (сеть, парсинг).""" diff --git a/src/voice_dictation/infrastructure/logging_setup.py b/src/voice_dictation/infrastructure/logging_setup.py index 231bbe6..a0d6243 100644 --- a/src/voice_dictation/infrastructure/logging_setup.py +++ b/src/voice_dictation/infrastructure/logging_setup.py @@ -53,6 +53,9 @@ def configure_logging(paths: AppPaths, verbose: bool = False) -> None: paths: Пути приложения (для log_file). verbose: Если True — уровень DEBUG, иначе INFO. """ + # HTTP redirects may include signed query parameters. + for dependency in ("httpx", "httpcore"): + logging.getLogger(dependency).setLevel(logging.WARNING) level = logging.DEBUG if verbose else logging.INFO root_logger = logging.getLogger() diff --git a/src/voice_dictation/platform/macos/hotkey_listener.py b/src/voice_dictation/platform/macos/hotkey_listener.py index 860b3e7..362da56 100644 --- a/src/voice_dictation/platform/macos/hotkey_listener.py +++ b/src/voice_dictation/platform/macos/hotkey_listener.py @@ -10,7 +10,6 @@ from __future__ import annotations import logging import re import threading -import time from collections.abc import Callable from typing import Any @@ -20,25 +19,71 @@ logger = logging.getLogger(__name__) # Карта имён клавиш в virtual key codes macOS _KEY_CODES: dict[str, int] = { - "a": 0x00, "s": 0x01, "d": 0x02, "f": 0x03, "h": 0x04, "g": 0x05, - "z": 0x06, "x": 0x07, "c": 0x08, "v": 0x09, "b": 0x0B, "q": 0x0C, - "w": 0x0D, "e": 0x0E, "r": 0x0F, "y": 0x10, "t": 0x11, - "1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17, - "9": 0x19, "7": 0x1A, "8": 0x1C, "0": 0x1D, - "o": 0x1F, "u": 0x20, "i": 0x22, "p": 0x23, - "l": 0x25, "j": 0x26, "k": 0x28, "n": 0x2D, "m": 0x2E, - "space": 0x31, "tab": 0x30, "enter": 0x24, "return": 0x24, - "escape": 0x35, "esc": 0x35, "delete": 0x33, "backspace": 0x33, - "f1": 0x7A, "f2": 0x78, "f3": 0x63, "f4": 0x76, "f5": 0x60, - "f6": 0x61, "f7": 0x62, "f8": 0x64, "f9": 0x65, "f10": 0x6D, - "f11": 0x67, "f12": 0x6F, - "left": 0x7B, "right": 0x7C, "down": 0x7D, "up": 0x7E, + "a": 0x00, + "s": 0x01, + "d": 0x02, + "f": 0x03, + "h": 0x04, + "g": 0x05, + "z": 0x06, + "x": 0x07, + "c": 0x08, + "v": 0x09, + "b": 0x0B, + "q": 0x0C, + "w": 0x0D, + "e": 0x0E, + "r": 0x0F, + "y": 0x10, + "t": 0x11, + "1": 0x12, + "2": 0x13, + "3": 0x14, + "4": 0x15, + "6": 0x16, + "5": 0x17, + "9": 0x19, + "7": 0x1A, + "8": 0x1C, + "0": 0x1D, + "o": 0x1F, + "u": 0x20, + "i": 0x22, + "p": 0x23, + "l": 0x25, + "j": 0x26, + "k": 0x28, + "n": 0x2D, + "m": 0x2E, + "space": 0x31, + "tab": 0x30, + "enter": 0x24, + "return": 0x24, + "escape": 0x35, + "esc": 0x35, + "delete": 0x33, + "backspace": 0x33, + "f1": 0x7A, + "f2": 0x78, + "f3": 0x63, + "f4": 0x76, + "f5": 0x60, + "f6": 0x61, + "f7": 0x62, + "f8": 0x64, + "f9": 0x65, + "f10": 0x6D, + "f11": 0x67, + "f12": 0x6F, + "left": 0x7B, + "right": 0x7C, + "down": 0x7D, + "up": 0x7E, } _MODIFIER_TOKENS = {"cmd", "command", "ctrl", "control", "alt", "option", "shift", "super"} # Печатные клавиши, после которых надо стереть символ из активного поля -_PRINTABLE_MAIN_KEYS = {"space", "tab", "enter", "return"} def _parse_hotkey(hotkey: str) -> tuple[set[str], str]: @@ -140,67 +185,45 @@ class MacHotkeyListener: logger.warning("Неизвестная клавиша '%s' в хоткее '%s'", main, hotkey) return False - wrapped = self._wrap_with_backspace(callback, main) mods_mask = _modifier_mask(mods) keycode = _KEY_CODES[main] for i, (m, k, *_) in enumerate(self._hotkeys): if m == mods and k == main: - self._hotkeys[i] = (mods, main, mods_mask, keycode, wrapped) + self._hotkeys[i] = (mods, main, mods_mask, keycode, callback) return True - self._hotkeys.append((mods, main, mods_mask, keycode, wrapped)) + self._hotkeys.append((mods, main, mods_mask, keycode, callback)) logger.debug("Хоткей зарегистрирован: %s -> mods=%s, key=%s", hotkey, sorted(mods), main) return True - def _wrap_with_backspace( - self, callback: Callable[[], None], main_key: str - ) -> Callable[[], None]: - """Если хоткей с печатной клавишей — после нажатия шлём Backspace. - - macOS успевает вставить пробел/таб в активное поле до перехвата хоткея - через NSEvent global monitor (он не блокирует событие, только наблюдает). - Стираем лишний символ, чтобы поле осталось чистым. - """ - if main_key not in _PRINTABLE_MAIN_KEYS: - return callback - - def _runner() -> None: - try: - # Маленькая задержка, чтобы система успела вставить символ - time.sleep(0.02) - _send_backspace_via_quartz() - except Exception as exc: - logger.debug("Не удалось послать Backspace: %s", exc) - - def _wrapped() -> None: - threading.Thread(target=_runner, name="bs-eraser", daemon=True).start() - callback() - - return _wrapped - def start(self) -> None: - """Регистрирует NSEvent monitor и блокирует поток до stop(). + """Регистрирует NSEvent global monitor на main thread (non-blocking). - В этом методе крутится NSRunLoop текущего потока. Если callback нужен - в главном потоке (например, для AppKit), вызывайте start() из главного. + NSEvent.addGlobalMonitorForEventsMatchingMask_handler_ требует, чтобы + callback приходил на main run loop. Если регистрировать в worker-потоке, + события не доставляются в наш handler (main runloop занят pystray). + Поэтому регистрация откладывается на main через AppHelper.callAfter — + как только pystray.run() запустит main runloop, регистрация выполнится + и callbacks пойдут в этот же runloop. + + Метод non-blocking: возвращает управление сразу. Raises: - PlatformError: Если нет хоткеев или AppKit недоступен. + PlatformError: Если нет хоткеев или AppKit/PyObjC недоступны. """ if not self._hotkeys: raise PlatformError("Нет зарегистрированных хоткеев") try: from AppKit import NSEvent, NSEventMaskKeyDown - from Foundation import NSDate, NSDefaultRunLoopMode, NSRunLoop + from PyObjCTools import AppHelper except ImportError as exc: - raise PlatformError("AppKit/Foundation недоступны (PyObjC)") from exc + raise PlatformError("AppKit/PyObjC недоступны") from exc all_mods = _all_modifier_flags() - registered = [(sorted(mods), main) for (mods, main, *_) in self._hotkeys] - logger.info("Запуск слушателя хоткеев: %s", registered) + logger.info("Регистрация хоткеев на main thread: %s", registered) def _handler(event: Any) -> None: try: @@ -216,45 +239,38 @@ class MacHotkeyListener: except Exception as exc: logger.exception("Ошибка в NSEvent handler: %s", exc) - self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_( - NSEventMaskKeyDown, _handler - ) - - if self._monitor is None: - raise PlatformError( - "Не удалось создать NSEvent global monitor — нужны права Accessibility" + def _do_register() -> None: + self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_( + NSEventMaskKeyDown, _handler ) + if self._monitor is None: + logger.error( + "NSEvent global monitor не создался — нужны Accessibility + Input Monitoring", + ) + else: + logger.info("NSEvent global monitor зарегистрирован на main thread") - # Блокируем поток, пока не вызовут stop() - run_loop = NSRunLoop.currentRunLoop() - while not self._stop_event.is_set(): - run_loop.runMode_beforeDate_( - NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow_(0.5) - ) + AppHelper.callAfter(_do_register) def stop(self) -> None: - """Останавливает слушатель.""" + """Снимает NSEvent monitor (на main thread).""" self._stop_event.set() - if self._monitor is not None: - try: - from AppKit import NSEvent + if self._monitor is None: + return + try: + from AppKit import NSEvent + from PyObjCTools import AppHelper - NSEvent.removeMonitor_(self._monitor) - except Exception as exc: - logger.debug("Ошибка снятия NSEvent monitor: %s", exc) + monitor = self._monitor + + def _do_remove() -> None: + try: + NSEvent.removeMonitor_(monitor) + except Exception as exc: + logger.debug("Ошибка снятия NSEvent monitor: %s", exc) + + AppHelper.callAfter(_do_remove) + except Exception as exc: + logger.debug("stop() error: %s", exc) + finally: self._monitor = None - - -def _send_backspace_via_quartz() -> None: - """Эмулирует нажатие Backspace через Quartz CGEvent (без pynput).""" - from Quartz import ( - CGEventCreateKeyboardEvent, - CGEventPost, - kCGHIDEventTap, - ) - - keycode = 0x33 # Backspace virtual key code - down = CGEventCreateKeyboardEvent(None, keycode, True) - up = CGEventCreateKeyboardEvent(None, keycode, False) - CGEventPost(kCGHIDEventTap, down) - CGEventPost(kCGHIDEventTap, up) diff --git a/src/voice_dictation/platform/windows/autopaste.py b/src/voice_dictation/platform/windows/autopaste.py index e81408a..e7b7e8c 100644 --- a/src/voice_dictation/platform/windows/autopaste.py +++ b/src/voice_dictation/platform/windows/autopaste.py @@ -10,13 +10,9 @@ from voice_dictation.infrastructure.errors import PlatformError logger = logging.getLogger(__name__) -VK_CONTROL = 0x11 -VK_V = 0x56 -KEYEVENTF_KEYUP = 0x0002 - class WinAutoPaste: - """Имитирует Ctrl+V через Win32 keybd_event. + """Имитирует Ctrl+V в активном окне через Win32. Args: paste_delay_ms: Дополнительная задержка перед вставкой (мс). @@ -26,26 +22,27 @@ class WinAutoPaste: self._paste_delay_ms = paste_delay_ms def paste(self) -> None: - """Нажимает Ctrl+V в активном окне.""" + """Нажимает Ctrl+V в активном окне. + + Raises: + PlatformError: Если Win32 не может отправить событие. + """ if self._paste_delay_ms > 0: time.sleep(self._paste_delay_ms / 1000) try: - # Отпускаем все модификаторы которые могут быть зажаты - ctypes.windll.user32.keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0) - ctypes.windll.user32.keybd_event(0x12, 0, KEYEVENTF_KEYUP, 0) # Alt - ctypes.windll.user32.keybd_event(0x10, 0, KEYEVENTF_KEYUP, 0) # Shift - ctypes.windll.user32.keybd_event(0x20, 0, KEYEVENTF_KEYUP, 0) # Space + send = ctypes.windll.user32.keybd_event # type: ignore[attr-defined] + for key in (0x11, 0x12, 0x10, 0x20): + send(key, 0, 0x0002, 0) time.sleep(0.5) - - # Ctrl+V - ctypes.windll.user32.keybd_event(VK_CONTROL, 0, 0, 0) + send(0x11, 0, 0, 0) time.sleep(0.05) - ctypes.windll.user32.keybd_event(VK_V, 0, 0, 0) - time.sleep(0.05) - ctypes.windll.user32.keybd_event(VK_V, 0, KEYEVENTF_KEYUP, 0) - time.sleep(0.05) - ctypes.windll.user32.keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0) + try: + send(0x56, 0, 0, 0) + time.sleep(0.05) + finally: + send(0x56, 0, 0x0002, 0) + send(0x11, 0, 0x0002, 0) except Exception as exc: raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc diff --git a/src/voice_dictation/platform/windows/sound_player.py b/src/voice_dictation/platform/windows/sound_player.py index 4444859..0e9bddf 100644 --- a/src/voice_dictation/platform/windows/sound_player.py +++ b/src/voice_dictation/platform/windows/sound_player.py @@ -56,6 +56,9 @@ def _play_file(path: Path) -> None: try: import winsound - winsound.PlaySound(str(path), winsound.SND_FILENAME | winsound.SND_ASYNC) + winsound.PlaySound( # type: ignore[attr-defined] + str(path), + winsound.SND_FILENAME | winsound.SND_ASYNC, # type: ignore[attr-defined] + ) except Exception as exc: logger.warning("winsound не удалось воспроизвести %s: %s", path, exc) diff --git a/src/voice_dictation/ui/entry_shortcuts.py b/src/voice_dictation/ui/entry_shortcuts.py new file mode 100644 index 0000000..1c27146 --- /dev/null +++ b/src/voice_dictation/ui/entry_shortcuts.py @@ -0,0 +1,44 @@ +"""Explicit paste bindings for packaged Tk entry widgets on macOS.""" + +from __future__ import annotations + +import sys +import tkinter as tk +from collections.abc import Callable + +import customtkinter as ctk + + +def paste_into(entry: ctk.CTkEntry, reader: Callable[[], str] | None = None) -> str: + """Paste without exposing clipboard data, replacing the current selection.""" + try: + if reader is not None: + value = reader() + elif sys.platform == "darwin": + from AppKit import NSPasteboard, NSPasteboardTypeString + + native_value = NSPasteboard.generalPasteboard().stringForType_(NSPasteboardTypeString) + if native_value is None: + return "break" + value = str(native_value) + else: + value = entry.clipboard_get() + if entry.select_present(): + entry.delete("sel.first", "sel.last") + entry.insert("insert", value) + except tk.TclError: + pass # An empty/non-text clipboard is harmless. + return "break" + + +def bind_paste(entry: ctk.CTkEntry, reader: Callable[[], str] | None = None) -> None: + """Handle Command-V in English and Russian layouts on macOS.""" + if sys.platform != "darwin": + return + + def on_command(event: tk.Event[tk.Misc]) -> str | None: + if event.keysym in {"v", "V", "Cyrillic_em", "Cyrillic_EM", "м", "М"}: + return paste_into(entry, reader) + return None + + entry.bind("", on_command) diff --git a/src/voice_dictation/ui/hotkey_acceptance.py b/src/voice_dictation/ui/hotkey_acceptance.py new file mode 100644 index 0000000..e6ec645 --- /dev/null +++ b/src/voice_dictation/ui/hotkey_acceptance.py @@ -0,0 +1,57 @@ +"""Manual native input acceptance, without microphone, API, or profile changes.""" + +from __future__ import annotations + +import json +from pathlib import Path + + +def run_input_check(output: Path) -> None: + """Observe two real hotkeys and paste a fixed marker after the second one.""" + from AppKit import NSApplication + from ApplicationServices import AXIsProcessTrusted + from PyObjCTools import AppHelper + + from voice_dictation.platform.macos.autopaste import MacAutoPaste + from voice_dictation.platform.macos.hotkey_listener import MacHotkeyListener + from voice_dictation.ui.setup_acceptance import synthetic_clipboard + + trusted = bool(AXIsProcessTrusted()) + presses = 0 + + def report(stage: str) -> None: + output.write_text(json.dumps({"stage": stage, "trusted": trusted, "presses": presses})) + + if not trusted: + report("permission_required") + return + NSApplication.sharedApplication() + listener = MacHotkeyListener() + + def paste() -> None: + MacAutoPaste().paste() + report("pasted") + + def toggle() -> None: + nonlocal presses + presses += 1 + report("hotkey") + if presses == 2: + AppHelper.callLater(0.3, paste) + + listener.register("cmd+space", toggle) + with synthetic_clipboard("[DICTATION]"): + listener.start() + AppHelper.callLater(0.5, report, "ready") + if output.name.startswith("auto-"): + # Invoke the exact registered callbacks; native paste still goes to the editor. + registered_callback = listener._hotkeys[0][-1] + AppHelper.callLater(2.0, registered_callback) + AppHelper.callLater(3.0, registered_callback) + AppHelper.callLater(5.0, AppHelper.stopEventLoop) + else: + AppHelper.callLater(45, AppHelper.stopEventLoop) + try: + AppHelper.runEventLoop() + finally: + listener.stop() diff --git a/src/voice_dictation/ui/recognition_tab.py b/src/voice_dictation/ui/recognition_tab.py new file mode 100644 index 0000000..f45ff0b --- /dev/null +++ b/src/voice_dictation/ui/recognition_tab.py @@ -0,0 +1,328 @@ +"""Recognition preferences and asynchronous model downloads.""" + +from __future__ import annotations + +import queue +import threading +import time +from collections.abc import Callable +from dataclasses import replace +from datetime import datetime + +import customtkinter as ctk + +from voice_dictation.core.config import ConfigStore +from voice_dictation.core.model_manager import CATALOG, DownloadCancelled, ModelError, ModelManager +from voice_dictation.core.paths import AppPaths + +CLOUD_MODELS = ("gpt-transcribe", "gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1") + + +def build_recognition_tab( + parent: ctk.CTkFrame, + store: ConfigStore, + paths: AppPaths, + toast: Callable[[str], None], +) -> None: + """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 if m.selectable} + initial_label = next( + (k for k, v in labels.items() if v == config.local_model), next(iter(labels)) + ) + backend = ctk.StringVar( + value="Локально" if config.transcription_backend == "local" else "OpenAI API" + ) + selected = ctk.StringVar(value=initial_label) + ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4)) + backend_menu = ctk.CTkOptionMenu( + parent, + values=["Локально", "OpenAI API"], + variable=backend, + command=lambda _: show_backend(), + ) + backend_menu.pack(anchor="w", padx=12) + privacy = ctk.CTkLabel(parent, text="", justify="left", wraplength=620) + privacy.pack(anchor="w", padx=12, pady=8) + engine_area = ctk.CTkFrame(parent, fg_color="transparent") + engine_area.pack(fill="both", expand=True) + cloud_frame = ctk.CTkFrame(engine_area, fg_color="transparent") + cloud_model = ctk.StringVar(value=config.model) + cloud_values = list(CLOUD_MODELS) + if config.model not in cloud_values: + cloud_values.append(config.model) + ctk.CTkLabel(cloud_frame, text="Модель OpenAI:").pack(anchor="w", padx=12, pady=6) + cloud_menu = ctk.CTkOptionMenu( + cloud_frame, values=cloud_values, variable=cloud_model, width=460 + ) + cloud_menu.pack(anchor="w", padx=12, pady=6) + ctk.CTkLabel( + cloud_frame, + text="gpt-transcribe — новая рекомендуемая модель для аудиофайлов.\n" + "Прежние модели будут отключены 26.02.2027.\n" + "Сохранённая модель меняется только по вашему выбору.", + justify="left", + wraplength=620, + ).pack(anchor="w", padx=12, pady=8) + from voice_dictation.infrastructure.credentials import read_api_key, save_api_key + + key_entry = ctk.CTkEntry(cloud_frame, show="•", width=460, placeholder_text="OpenAI API-ключ") + key_entry.pack(anchor="w", padx=12, pady=4) + from voice_dictation.ui.entry_shortcuts import bind_paste, paste_into + + bind_paste(key_entry) + ctk.CTkButton(cloud_frame, text="Вставить ключ", command=lambda: paste_into(key_entry)).pack( + anchor="w", padx=12, pady=4 + ) + key_status = ctk.CTkLabel( + cloud_frame, + text="Ключ сохранён" + if read_api_key(paths.root) + else "Ключ можно вставить здесь (или использовать прежний .env).", + ) + key_status.pack(anchor="w", padx=12) + + def save_key() -> None: + try: + save_api_key(paths.root, key_entry.get()) + except (ValueError, OSError): + key_status.configure( + text="Не удалось сохранить ключ. Проверьте ввод и доступ к профилю." + ) + return + key_entry.delete(0, "end") + key_status.configure( + text="Ключ сохранён. Распознавание использует его со следующей записи." + ) + + ctk.CTkButton(cloud_frame, text="Сохранить API-ключ", command=save_key).pack( + anchor="w", padx=12, pady=4 + ) + + def open_setup() -> None: + import subprocess + import sys + + args = ( + [sys.executable, "setup"] + if getattr(sys, "frozen", False) + else [sys.executable, "-m", "voice_dictation", "setup"] + ) + subprocess.Popen(args, start_new_session=True) + toast("После изменения хоткея в мастере перезапустите приложение.") + + ctk.CTkButton(parent, text="Мастер настройки", command=open_setup).pack( + anchor="w", padx=12, pady=4 + ) + local_frame = ctk.CTkFrame(engine_area, fg_color="transparent") + + def show_backend() -> None: + local_frame.pack_forget() + cloud_frame.pack_forget() + if backend.get() == "Локально": + local_frame.pack(fill="both", expand=True) + privacy.configure( + text="Локально: аудио и текст не отправляются в облако.\n" + "Облачные стили обработки отключены." + ) + else: + cloud_frame.pack(fill="both", expand=True) + privacy.configure( + text="OpenAI API: запись отправляется в OpenAI для распознавания.\n" + "Выбранные облачные стили могут также отправлять текст на обработку." + ) + + ctk.CTkLabel( + local_frame, text="Локальная модель (Whisper CPU/Metal; GigaAM CPU — отдельный runtime):" + ).pack(anchor="w", padx=12) + local_menu = ctk.CTkOptionMenu(local_frame, values=list(labels), variable=selected, width=460) + local_menu.pack(anchor="w", padx=12, pady=6) + status = ctk.CTkLabel( + local_frame, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620 + ) + status.pack(anchor="w", padx=12, pady=6) + bar = ctk.CTkProgressBar(local_frame, width=460) + bar.set(0) + bar.pack(anchor="w", padx=12, pady=6) + events: queue.Queue[tuple[str, float]] = queue.Queue() + cancel = threading.Event() + busy = False + started = 0.0 + received = 0 + total_bytes = 0 + last_update = 0.0 + buttons: list[ctk.CTkButton] = [] + + journal = ctk.CTkTextbox(local_frame, width=620, height=100) + journal.pack(anchor="w", padx=12, pady=6) + journal.configure(state="disabled") + + def note(message: str) -> None: + journal.configure(state="normal") + journal.insert("end", f"{datetime.now():%H:%M:%S} {message}\n") + if int(journal.index("end-1c").split(".")[0]) > 100: + journal.delete("1.0", "2.0") + journal.see("end") + journal.configure(state="disabled") + + stages = { + "checking": "Проверяю установленную модель…", + "connecting": "Подключаюсь к серверу моделей…", + "downloading": "Получаю файл модели…", + "verifying": "Проверяю целостность скачанного файла…", + } + + def progress(done: int, total: int) -> None: + nonlocal received, total_bytes, last_update + received, total_bytes = done, total + now = time.monotonic() + if now - last_update >= 0.2 or done == total: + events.put(("progress", done / total if total else 0)) + last_update = now + + def worker(action: str, model_id: str) -> None: + try: + if action == "download": + manager.download( + model_id, + progress=progress, + stage=lambda name: events.put((stages[name], -2)), + cancel=cancel, + ) + message = ( + "Веса GigaAM проверены. Для распознавания требуется отдельный runtime." + if model_id.startswith("gigaam-") + else "Модель скачана и проверена. Можно использовать." + ) + events.put((message, 1)) + elif action == "delete": + manager.delete(model_id) + events.put(("Модель удалена.", 0)) + else: + installed = manager.is_installed(model_id) + events.put( + ( + "Модель установлена и проверена." + if installed + else "Модель ещё не скачана.", + 1 if installed else 0, + ) + ) + except DownloadCancelled: + events.put(("Загрузка отменена. Незавершённый файл удалён.", 0)) + except ModelError as exc: + events.put((str(exc), -1)) + except Exception: + events.put(("Не удалось выполнить операцию. Подробности — в журнале приложения.", -1)) + + def start(action: str) -> None: + nonlocal busy, started, received, total_bytes, last_update + if busy: + return + busy = True + started = time.monotonic() + received = total_bytes = 0 + last_update = 0.0 + cancel.clear() + cancel_button.configure(state="normal" if action == "download" else "disabled") + for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button): + control.configure(state="disabled") + message = { + "check": "Проверяю модель…", + "download": "Подготавливаю загрузку…", + "delete": "Удаляю модель…", + }[action] + status.configure(text=message) + bar.set(0) + note(f"{selected.get()}: {message}") + threading.Thread(target=worker, args=(action, labels[selected.get()]), daemon=True).start() + + def poll() -> None: + nonlocal busy + if not parent.winfo_exists(): + cancel.set() + return + try: + while True: + message, value = events.get_nowait() + if message == "progress": + bar.set(value) + elapsed = max(0.1, time.monotonic() - started) + if not cancel.is_set(): + status.configure( + text=f"Скачивание: {value:.1%} · {received / 1_000_000:.1f} / " + f"{total_bytes / 1_000_000:.1f} МБ · " + f"{received / elapsed / 1_000_000:.1f} МБ/с" + ) + elif value == -2: + note(message) + if not cancel.is_set(): + status.configure(text=message) + else: + note(message) + cancel_button.configure(state="disabled") + status.configure(text=message) + bar.set(max(0, value)) + busy = False + for control in (*buttons, backend_menu, local_menu, cloud_menu, save_button): + control.configure(state="normal") + except queue.Empty: + pass + parent.after(100, poll) + + row = ctk.CTkFrame(local_frame, fg_color="transparent") + row.pack(anchor="w", padx=12, pady=6) + for title, action in [("Скачать", "download"), ("Проверить", "check"), ("Удалить", "delete")]: + button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a)) + button.pack(side="left", padx=(0, 6)) + buttons.append(button) + + def request_cancel() -> None: + if not busy or cancel.is_set(): + return + cancel.set() + status.configure(text="Отменяю загрузку… Закрываю соединение и удаляю временный файл.") + note("Отмена запрошена; ожидаю завершения операции…") + cancel_button.configure(state="disabled") + + cancel_button = ctk.CTkButton( + row, text="Отменить", width=100, command=request_cancel, state="disabled" + ) + cancel_button.pack(side="left") + + def save() -> None: + if busy: + return + 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", + local_model=labels[selected.get()], + model=cloud_model.get(), + ) + store.save(updated) + toast("Сохранено. Новый режим применяется к следующей записи.") + + save_button = ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save) + save_button.pack(anchor="w", padx=12, pady=12) + ctk.CTkLabel( + local_frame, + text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}", + justify="left", + wraplength=620, + ).pack(anchor="w", padx=12) + parent.bind( + "", lambda event: cancel.set() if event.widget == parent else None, add="+" + ) + parent.after(100, poll) + + show_backend() diff --git a/src/voice_dictation/ui/settings_cli.py b/src/voice_dictation/ui/settings_cli.py index b98723a..3e557f7 100644 --- a/src/voice_dictation/ui/settings_cli.py +++ b/src/voice_dictation/ui/settings_cli.py @@ -14,7 +14,7 @@ import sys logger = logging.getLogger(__name__) -def main() -> None: +def main(smoke_test: bool = False) -> None: """Точка входа подпроцесса для окна настроек.""" from voice_dictation.core.config import ConfigStore from voice_dictation.core.paths import AppPaths @@ -50,7 +50,7 @@ def main() -> None: usage_db=usage_db, system_sounds_scanner=platform_bundle.system_sounds_scanner, ) - window.run() + window.run(smoke_test=smoke_test) if __name__ == "__main__": diff --git a/src/voice_dictation/ui/settings_window.py b/src/voice_dictation/ui/settings_window.py index 0cbd8c0..d2dd89c 100644 --- a/src/voice_dictation/ui/settings_window.py +++ b/src/voice_dictation/ui/settings_window.py @@ -3,12 +3,12 @@ from __future__ import annotations import logging -import sys import threading 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 @@ -22,12 +22,7 @@ if TYPE_CHECKING: from voice_dictation.platform.protocols import HotkeyListener, SystemSoundsScanner -# Пресеты зависят от ОС: на macOS — Cmd-сочетания, на Windows/Linux — Ctrl. -if sys.platform == "darwin": - _HOTKEY_PRESETS = ["cmd+space", "cmd+shift+space", "cmd+alt+d", "cmd+shift+d", "ctrl+alt+d"] -else: - _HOTKEY_PRESETS = ["ctrl+shift+space", "ctrl+alt+d", "ctrl+shift+d", "ctrl+alt+space"] -_MODELS = ["gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1"] +_HOTKEY_PRESETS = ["cmd+space", "cmd+shift+space", "cmd+alt+d", "cmd+shift+d", "ctrl+alt+d"] _LANGUAGES = ["ru", "en", "auto"] _ABOUT_TEXT = """Voice Dictation — голосовая диктовка под macOS / Windows. @@ -43,8 +38,9 @@ Transcription, MacWhisper) либо платные, либо неудобные, ═══ Что под капотом ═══ • Хоткей — pynput GlobalHotKeys (macOS Cmd+Space по умолчанию) -• Запись — sox subprocess, 16 kHz mono WAV -• Транскрипция — OpenAI Whisper API (gpt-4o-mini-transcribe, ~$0.003/мин) +• Запись — sounddevice, потоковый 16 kHz mono WAV +• Надёжность — сессии на диске, чанки с overlap, resume после сбоя +• Транскрипция — OpenAI Audio API (gpt-4o-mini-transcribe, ~$0.003/мин) • Словарь — ~/.dictate/dictionary.txt с подсказками для Whisper • Автовставка — pbcopy + Cmd+V через pynput • Звуки — afplay + системные звуки macOS (Tink/Pop/Basso) @@ -73,7 +69,7 @@ Transcription, MacWhisper) либо платные, либо неудобные, • Этап 4 — tray icon с динамической иконкой • Этап 5 — окно настроек (5 табов на customtkinter) • Этап 6 — баланс OpenAI через Admin API - • Этап 7 — линтер (ruff), 44 теста, README, autostart-скрипт + • Этап 7 — линтер (ruff), тесты, README, autostart-скрипт 4. Багфиксы по ходу: • verbose_json не работает с gpt-4o-mini → переключение на json @@ -117,20 +113,6 @@ personal/voice-dictation/ https://flowmasters.ru/ """ -_CHANGELOG = """═══ Что нового ═══ - -v0.2.0 -• Режимы обработки вместо одной галочки Summary: Чистая диктовка, - Чистовик (без паразитов), Summary, Переводчик RU→EN, Промпт для - LLM, Буллеты, Деловое письмо. Выбор в трее → «Режим обработки». -• Свои стили: таб «Стили» — пишешь название и промпт, режим - появляется в трее. - -v0.1.0 -• Первая версия под Windows: запись, Whisper, автовставка, трей, - звуки, статистика, баланс, установщик. -""" - _window_lock = threading.Lock() _window_holder: dict[str, SettingsWindow] = {} @@ -234,7 +216,7 @@ class SettingsWindow: 100, lambda: self._root.attributes("-topmost", False) if self._root else None ) - def run(self) -> None: + def run(self, smoke_test: bool = False) -> None: config = self._config_store.current() ctk.set_appearance_mode("system") @@ -242,13 +224,15 @@ class SettingsWindow: self._root = ctk.CTk() self._root.title("Voice Dictation — настройки") - self._root.geometry("720x560") + self._root.geometry("820x680") # Принудительно вытаскиваем окно на передний план — иначе в bundle # с LSUIElement=true Tk-окно создаётся, но прячется за активным приложением. _activate_app() self._root.after(50, self._root.lift) - self._root.after(50, lambda: self._root.attributes("-topmost", True) if self._root else None) + self._root.after( + 50, lambda: self._root.attributes("-topmost", True) if self._root else None + ) self._root.after( 500, lambda: self._root.attributes("-topmost", False) if self._root else None ) @@ -257,6 +241,7 @@ class SettingsWindow: tabs = ctk.CTkTabview(self._root) tabs.pack(fill="both", expand=True, padx=12, pady=12) + recognition_tab = tabs.add("Распознавание") general_tab = tabs.add("Общие") styles_tab = tabs.add("Стили") sound_tab = tabs.add("Звук") @@ -265,6 +250,9 @@ class SettingsWindow: balance_tab = tabs.add("Баланс") about_tab = tabs.add("О проекте") + from voice_dictation.ui.recognition_tab import build_recognition_tab + + build_recognition_tab(recognition_tab, self._config_store, self._paths, self._toast) self._build_general_tab(general_tab, config) self._build_styles_tab(styles_tab, config) self._build_sound_tab(sound_tab, config) @@ -273,6 +261,9 @@ class SettingsWindow: self._build_balance_tab(balance_tab) self._build_about_tab(about_tab) + if smoke_test: + self._root.after(250, self._on_close) + print("Settings smoke: recognition, general, styles and auxiliary tabs created") self._root.protocol("WM_DELETE_WINDOW", self._on_close) self._root.mainloop() @@ -296,13 +287,6 @@ class SettingsWindow: hotkey_box = ctk.CTkComboBox(parent, values=_HOTKEY_PRESETS, variable=hotkey_var, width=240) hotkey_box.grid(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) - model_var = ctk.StringVar(value=config.model) - ctk.CTkComboBox(parent, values=_MODELS, variable=model_var, width=240).grid( - 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) language_var = ctk.StringVar(value=config.language or "auto") @@ -337,23 +321,46 @@ 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: - import dataclasses - language_choice = language_var.get() new_hotkey = hotkey_var.get().strip().lower() - current = self._config_store.current() - updated = dataclasses.replace( + current = self._config_store.load() + updated = replace( current, hotkey=new_hotkey, - model=model_var.get(), language=None if language_choice == "auto" else language_choice, notifications_enabled=notif_var.get(), 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: @@ -365,121 +372,58 @@ class SettingsWindow: row=row, column=0, columnspan=2, pady=14 ) - # --- Ускорение отправки через ffmpeg (опциональная докачка) --- - from voice_dictation.core.ffmpeg_setup import find_ffmpeg - - row += 1 - installed = find_ffmpeg(self._paths.bin_dir) is not None - status_var = ctk.StringVar( - value=( - "✓ ffmpeg установлен — запись сжимается, отправка быстрее" - if installed - else "ffmpeg не установлен — запись отправляется как WAV (работает, но крупнее)" - ) - ) - ctk.CTkLabel( - parent, textvariable=status_var, wraplength=440, justify="left", anchor="w" - ).grid(row=row, column=0, columnspan=3, sticky="w", padx=8, pady=(18, 0)) - - row += 1 - ctk.CTkLabel( - parent, - text="ffmpeg ускоряет отправку примерно в 10× (сжатие в Opus). ~100 МБ, скачивается один раз.", - wraplength=440, - justify="left", - anchor="w", - text_color="gray", - ).grid(row=row, column=0, columnspan=3, sticky="w", padx=8, pady=(0, 4)) - - row += 1 - ff_btn = ctk.CTkButton(parent, text="Скачать ffmpeg") - - def _ui(fn: Callable[[], None]) -> None: - if self._root is not None: - self._root.after(0, fn) - - def _download_ffmpeg() -> None: - ff_btn.configure(state="disabled", text="Скачивание…") - - def _work() -> None: - from voice_dictation.core.ffmpeg_setup import download_ffmpeg - - try: - download_ffmpeg( - self._paths.bin_dir, - progress=lambda m: _ui(lambda: ff_btn.configure(text=m)), - ) - _ui(lambda: ff_btn.configure(text="✓ Установлено")) - _ui(lambda: status_var.set("✓ ffmpeg установлен — запись сжимается, отправка быстрее")) - except Exception as exc: - logger.warning("Скачивание ffmpeg не удалось: %s", exc) - _ui(lambda: ff_btn.configure(state="normal", text="Повторить скачивание")) - _ui(lambda: self._toast(f"Не удалось скачать ffmpeg: {exc}")) - - threading.Thread(target=_work, name="ffmpeg-download", daemon=True).start() - - ff_btn.configure(command=_download_ffmpeg) - if installed: - ff_btn.configure(state="disabled", text="✓ Установлено") - ff_btn.grid(row=row, column=0, columnspan=2, sticky="w", padx=8, pady=(0, 8)) - def _build_styles_tab(self, parent: ctk.CTkFrame, config: object) -> None: - import dataclasses - - from voice_dictation.core.config import Config + from voice_dictation.core.config import Config, SummaryPreset assert isinstance(config, Config) - ctk.CTkLabel( parent, - text=( - "Свои стили обработки. Название появится в меню «Режим обработки» в трее, " - "промпт — это инструкция для LLM (что сделать с надиктованным текстом)." - ), - anchor="w", + text="Редактируйте режимы и добавляйте свои. Пустой промпт — без обработки.", wraplength=660, - justify="left", - ).pack(fill="x", padx=8, pady=(8, 4)) - + ).pack(fill="x", padx=8, pady=8) scroll = ctk.CTkScrollableFrame(parent) scroll.pack(fill="both", expand=True, padx=8, pady=4) - - slots = 6 - existing = list(config.custom_modes.items()) - slot_widgets: list[tuple[ctk.StringVar, ctk.CTkTextbox]] = [] - for i in range(slots): - name = existing[i][0] if i < len(existing) else "" - prompt = existing[i][1] if i < len(existing) else "" - ctk.CTkLabel(scroll, text=f"Стиль {i + 1} — название:", anchor="w").pack( - fill="x", padx=4, pady=(8, 0) + slots: list[tuple[ctk.StringVar, ctk.StringVar, ctk.CTkTextbox]] = [] + for index in range(len(config.summary_presets) + 6): + preset = ( + config.summary_presets[index] + if index < len(config.summary_presets) + else SummaryPreset("", "gpt-4o-mini", "") ) - name_var = ctk.StringVar(value=name) - ctk.CTkEntry(scroll, textvariable=name_var).pack(fill="x", padx=4, pady=2) - ctk.CTkLabel(scroll, text="Промпт:", anchor="w").pack(fill="x", padx=4, pady=(4, 0)) - prompt_box = ctk.CTkTextbox(scroll, height=70, wrap="word") - prompt_box.pack(fill="x", padx=4, pady=2) - if prompt: - prompt_box.insert("1.0", prompt) - slot_widgets.append((name_var, prompt_box)) + ctk.CTkLabel(scroll, text=f"Стиль {index + 1}: название / модель").pack(anchor="w") + name = ctk.StringVar(value=preset.name) + model = ctk.StringVar(value=preset.model) + ctk.CTkEntry(scroll, textvariable=name).pack(fill="x", pady=2) + ctk.CTkEntry(scroll, textvariable=model).pack(fill="x", pady=2) + prompt = ctk.CTkTextbox(scroll, height=70, wrap="word") + prompt.pack(fill="x", pady=(2, 8)) + prompt.insert("1.0", preset.prompt) + slots.append((name, model, prompt)) def _save_styles() -> None: - from voice_dictation.core.modes import CUSTOM_PREFIX, get_mode - - custom: dict[str, str] = {} - for name_var, prompt_box in slot_widgets: - name = name_var.get().strip() - prompt = prompt_box.get("1.0", "end").strip() - if name and prompt: - custom[name] = prompt + presets = [ + SummaryPreset( + name.get().strip(), model.get().strip(), prompt.get("1.0", "end").strip() + ) + for name, model, prompt in slots + if name.get().strip() + ] + if not presets or len({preset.name for preset in presets}) != len(presets): + self._toast("Нужен хотя бы один стиль; названия должны быть уникальными.") + return current = self._config_store.current() - updated = dataclasses.replace(current, custom_modes=custom) - # Активный кастомный стиль удалили/переименовали — откат на «Чистая диктовка». - if updated.mode.startswith(CUSTOM_PREFIX) and get_mode(updated.mode, custom).key != updated.mode: - updated = dataclasses.replace(updated, mode="raw") - self._config_store.save(updated) + active = current.active_preset + # Preserve selection when an existing style is renamed in its slot. + for index, preset in enumerate(config.summary_presets): + if preset.name == active and slots[index][0].get().strip(): + active = slots[index][0].get().strip() + break + if active not in {preset.name for preset in presets}: + active = presets[0].name + self._config_store.save(replace(current, summary_presets=presets, active_preset=active)) self._toast("Стили сохранены. Доступны в меню трея.") - ctk.CTkButton(parent, text="Сохранить", command=_save_styles).pack(pady=10) + ctk.CTkButton(parent, text="Сохранить стили", command=_save_styles).pack(pady=10) def _build_sound_tab(self, parent: ctk.CTkFrame, config: object) -> None: from voice_dictation.core.config import Config @@ -508,14 +452,6 @@ class SettingsWindow: stop_var = ctk.StringVar(value=_name_of(config.stop_sound_path)) error_var = ctk.StringVar(value=_name_of(config.error_sound_path)) - def _resolve(name: str) -> Path | None: - if name == sound_options[0]: - return None - for s in self._system_sounds: - if s.name == name: - return s.path - return None - for row, (label, var) in enumerate( [("Старт записи:", start_var), ("Остановка:", stop_var), ("Ошибка:", error_var)], start=2, @@ -524,18 +460,18 @@ class SettingsWindow: ctk.CTkComboBox(parent, values=sound_options, variable=var, width=240).grid( row=row, column=1, sticky="w", padx=8, pady=8 ) - ctk.CTkButton( - parent, - text="▶", - width=36, - command=lambda v=var: self._preview_sound(_resolve(v.get())), - ).grid(row=row, column=2, sticky="w", padx=4, pady=8) + + def _resolve(name: str) -> Path | None: + if name == sound_options[0]: + return None + for s in self._system_sounds: + if s.name == name: + return s.path + return None def _save_sound() -> None: - import dataclasses - current = self._config_store.current() - updated = dataclasses.replace( + updated = replace( current, sounds_enabled=sounds_enabled_var.get(), volume=float(volume_var.get()), @@ -587,55 +523,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( @@ -698,18 +707,9 @@ class SettingsWindow: ctk.CTkButton(parent, text="Получить баланс", command=_fetch).pack(padx=8, pady=8) def _build_about_tab(self, parent: ctk.CTkFrame) -> None: - from voice_dictation import __version__ - - ctk.CTkLabel( - parent, - text=f"Voice Dictation v{__version__}", - anchor="w", - font=("", 14, "bold"), - ).pack(fill="x", padx=8, pady=(8, 0)) - text_widget = ctk.CTkTextbox(parent, wrap="word") text_widget.pack(fill="both", expand=True, padx=8, pady=8) - text_widget.insert("1.0", _CHANGELOG + "\n" + _ABOUT_TEXT) + text_widget.insert("1.0", _ABOUT_TEXT) text_widget.configure(state="disabled") controls = ctk.CTkFrame(parent, fg_color="transparent") @@ -720,9 +720,7 @@ class SettingsWindow: webbrowser.open("https://flowmasters.ru/") - ctk.CTkButton(controls, text="flowmasters.ru", command=_open_site).pack( - side="left", padx=4 - ) + ctk.CTkButton(controls, text="flowmasters.ru", command=_open_site).pack(side="left", padx=4) # ------------------------------------------------------------------ helpers @@ -738,34 +736,6 @@ class SettingsWindow: except Exception as exc: logger.warning("Не удалось перерегистрировать хоткей: %s", exc) - def _preview_sound(self, path: Path | None) -> None: - """Проигрывает звук для предпрослушки (кроссплатформенно, в фоне). - - Args: - path: Путь к звуку; None — системный звук по умолчанию. - """ - - def _run() -> None: - try: - if sys.platform == "darwin": - import subprocess - - target = str(path) if path else "/System/Library/Sounds/Ping.aiff" - subprocess.run(["afplay", target], timeout=10, check=False) - else: - import winsound - - if path is not None and path.exists(): - winsound.PlaySound( - str(path), winsound.SND_FILENAME | winsound.SND_ASYNC - ) - else: - winsound.MessageBeep() - except Exception as exc: - logger.warning("Не удалось проиграть звук %s: %s", path, exc) - - threading.Thread(target=_run, name="sound-preview", daemon=True).start() - def _toast(self, message: str) -> None: if self._root is None: return diff --git a/src/voice_dictation/ui/setup_acceptance.py b/src/voice_dictation/ui/setup_acceptance.py new file mode 100644 index 0000000..e96c0e6 --- /dev/null +++ b/src/voice_dictation/ui/setup_acceptance.py @@ -0,0 +1,33 @@ +"""Native setup acceptance helpers using synthetic clipboard content only.""" + +from __future__ import annotations + +import sys +from collections.abc import Iterator +from contextlib import contextmanager + + +@contextmanager +def synthetic_clipboard(text: str = "sk-test-not-a-real-key") -> Iterator[None]: + """Temporarily replace and restore every native pasteboard representation.""" + if sys.platform != "darwin": + raise RuntimeError("Native clipboard acceptance currently requires macOS") + from AppKit import NSPasteboard, NSPasteboardItem, NSPasteboardTypeString + + board = NSPasteboard.generalPasteboard() + saved = [] + for item in board.pasteboardItems() or []: + restored = NSPasteboardItem.alloc().init() + for kind in item.types(): + data = item.dataForType_(kind) + if data is not None: + restored.setData_forType_(data, kind) + saved.append(restored) + board.clearContents() + board.setString_forType_(text, NSPasteboardTypeString) + try: + yield + finally: + board.clearContents() + if saved: + board.writeObjects_(saved) diff --git a/src/voice_dictation/ui/setup_wizard.py b/src/voice_dictation/ui/setup_wizard.py new file mode 100644 index 0000000..c600050 --- /dev/null +++ b/src/voice_dictation/ui/setup_wizard.py @@ -0,0 +1,188 @@ +"""Interactive first-launch setup; never sends audio or validates keys online.""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path +from tkinter import messagebox + +import customtkinter as ctk + +from voice_dictation.core.config import ConfigStore +from voice_dictation.infrastructure.credentials import read_api_key, save_api_key +from voice_dictation.ui.entry_shortcuts import bind_paste, paste_into + + +def run_setup(root: Path, store: ConfigStore, *, smoke_test: bool = False) -> bool: + """Show setup before tray startup; return whether the user finished it.""" + window = ctk.CTk() + window.title("Voice Dictation — первый запуск") + window.geometry("720x650") + from voice_dictation.ui.settings_window import _activate_app + + _activate_app() + content = ctk.CTkScrollableFrame(window) + content.pack(fill="both", expand=True) + completed = False + config = store.load() + ctk.CTkLabel(content, text="Настроим диктовку", font=("Arial", 23)).pack(pady=12) + ctk.CTkLabel(content, text="1. Где распознавать запись?").pack() + backend = ctk.StringVar( + value="Локально" if config.transcription_backend == "local" else "OpenAI API" + ) + ctk.CTkOptionMenu(content, values=["Локально", "OpenAI API"], variable=backend).pack(pady=6) + ctk.CTkLabel(content, text="OpenAI API-ключ или строка OPENAI_API_KEY=…:").pack() + key = ctk.CTkEntry(content, show="•", width=540, placeholder_text="Вставьте ключ здесь") + key.pack(pady=6) + bind_paste(key) + paste_button = ctk.CTkButton(content, text="Вставить ключ", command=lambda: paste_into(key)) + paste_button.pack(pady=4) + ctk.CTkLabel( + content, + text="Ключ сохраняется отдельно в вашем профиле с правами 0600.\n" + "Пустое поле оставляет прежний ключ. Проверки через интернет здесь нет.", + ).pack() + ctk.CTkLabel(content, text="2. Разрешения macOS: микрофон и Универсальный доступ").pack( + pady=(16, 4) + ) + status = ctk.CTkLabel(content, text="") + status.pack() + + def refresh() -> None: + if sys.platform == "darwin": + from ApplicationServices import AXIsProcessTrusted + + access = "разрешено" if AXIsProcessTrusted() else "нет доступа" + status.configure( + text=f"Управление клавиатурой: {access}\n" + "Микрофон проверяется отдельной кнопкой ниже." + ) + else: + status.configure(text="Разрешите микрофон в настройках конфиденциальности Windows.") + + def permissions(section: str) -> None: + if sys.platform == "darwin": + subprocess.Popen( + [ + "/usr/bin/open", + f"x-apple.systempreferences:com.apple.preference.security?Privacy_{section}", + ] + ) + elif sys.platform == "win32": + subprocess.Popen(["explorer.exe", "ms-settings:privacy-microphone"]) + + def test_microphone() -> None: + import sounddevice as sd + + try: + with sd.RawInputStream(samplerate=16000, channels=1, dtype="int16") as stream: + stream.read(1600) + status.configure(text="Микрофон: запись доступна. Аудио не сохранено и не отправлено.") + except Exception: + status.configure( + text="Нет доступа к микрофону или устройство недоступно. Проверьте разрешения." + ) + + ctk.CTkButton(content, text="Проверить микрофон", command=test_microphone).pack(pady=4) + ctk.CTkButton( + content, text="Открыть Универсальный доступ", command=lambda: permissions("Accessibility") + ).pack(pady=4) + ctk.CTkButton( + content, text="Открыть настройки микрофона", command=lambda: permissions("Microphone") + ).pack(pady=4) + ctk.CTkButton(content, text="Проверить разрешения снова", command=refresh).pack(pady=4) + ctk.CTkLabel(content, text="3. Хоткей (⌘Space часто занят Spotlight)").pack(pady=(12, 4)) + hotkey = ctk.CTkEntry(content, width=400) + hotkey.insert(0, config.hotkey) + hotkey.pack() + bind_paste(hotkey) + message = ctk.CTkLabel( + content, + text="После запуска: хоткей → фраза → хоткей → проверьте вставку.\n" + "Локальную модель можно скачать в Настройки → Распознавание.", + wraplength=650, + ) + message.pack(pady=10) + + def finish() -> None: + nonlocal completed + from voice_dictation.infrastructure.env_loader import load_env + + try: + from pynput.keyboard import HotKey + + combination = hotkey.get().strip().lower() + HotKey.parse( + "+".join(f"<{part}>" if len(part) > 1 else part for part in combination.split("+")) + ) + if "+" not in combination: + raise ValueError("Укажите сочетание клавиш, например cmd+alt+d") + except ValueError: + message.configure(text="Не удалось разобрать хоткей. Попробуйте cmd+alt+d.") + return + try: + if key.get().strip(): + save_api_key(root, key.get()) + except ValueError as exc: + message.configure(text=str(exc)) + messagebox.showerror("Ключ не сохранён", str(exc), parent=window) + key.focus_set() + return + except OSError: + message.configure( + text="Не удалось записать ключ в папку профиля. Проверьте права доступа." + ) + return + if backend.get() == "OpenAI API" and not (read_api_key(root) or load_env().api_key): + message.configure(text="Введите OpenAI API-ключ или выберите локальный режим.") + return + try: + updated = store.load() + updated.transcription_backend = "local" if backend.get() == "Локально" else "openai" + updated.hotkey = hotkey.get().strip() + store.save(updated) + (root / "setup-complete").touch(mode=0o600) + except (ValueError, OSError): + message.configure(text="Не удалось записать настройки в папку профиля.") + return + completed = True + window.destroy() + + ctk.CTkButton(content, text="Сохранить и запустить диктовку", command=finish).pack(pady=8) + refresh() + if smoke_test: + backend.set("OpenAI API") + + def test_paste() -> None: + paste_button.invoke() + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Native clipboard button test failed before keyboard test") + key.delete(0, "end") + window.focus_force() + key.focus_set() + window.update() + focused = window.focus_get() + if focused is not None: + focused.event_generate("") + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Synthetic Command-V test failed") + key.select_range(0, "end") + if focused is not None: + focused.event_generate("") + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Russian layout paste/selection test failed") + key.delete(0, "end") + paste_button.invoke() + if key.get() != "sk-test-not-a-real-key": + raise RuntimeError("Native clipboard button test failed") + finish() + if completed and read_api_key(root) != "sk-test-not-a-real-key": + raise RuntimeError("Saved key mismatch") + + hotkey.delete(0, "end") + hotkey.insert(0, "cmd+space") + window.after(300, test_paste) + window.after(700, window.destroy) + window.mainloop() + return completed diff --git a/src/voice_dictation/ui/splash.py b/src/voice_dictation/ui/splash.py new file mode 100644 index 0000000..af12075 --- /dev/null +++ b/src/voice_dictation/ui/splash.py @@ -0,0 +1,154 @@ +"""Splash screen на старте: плакат с диктатором + опциональная музыка.""" + +from __future__ import annotations + +import contextlib +import logging +import shutil +import subprocess +import sys +import tkinter as tk +from pathlib import Path + +logger = logging.getLogger(__name__) + +_MAX_IMAGE_SIDE_PX = 600 + + +def show_splash( + image_path: Path, + audio_path: Path | None, + duration_sec: float = 5.0, +) -> None: + """Показывает splash-окно на duration_sec секунд (blocking). + + Окно без рамки, поверх всех, кликабельно для досрочного закрытия (Esc / клик). + Если картинка не найдена — функция возвращает управление сразу. Если аудио + не найдено или формат не поддерживается платформой — splash показывается без + звука. + + Args: + image_path: PNG/JPG для splash. Если файла нет — splash не показывается. + audio_path: Опциональный аудиофайл. На macOS играется через `afplay` + (mp3/m4a/wav/aiff/ogg). На Windows используется `winsound`, который + принимает только `.wav`. Прочее — игнорируется с warning'ом в логе. + duration_sec: Сколько показывать (5 сек по умолчанию). + """ + if not image_path.exists(): + logger.warning("Splash: картинка не найдена: %s", image_path) + return + + audio_proc = _play_audio_async(audio_path) if audio_path is not None else None + + try: + _run_tk_window(image_path, duration_sec) + finally: + _stop_audio(audio_proc) + + +def _run_tk_window(image_path: Path, duration_sec: float) -> None: + """Создаёт borderless Tk-окно с картинкой по центру экрана.""" + try: + from PIL import Image, ImageTk + except ImportError as exc: + logger.warning("Splash: Pillow недоступен (%s), пропускаю", exc) + return + + root = tk.Tk() + root.title("Voice Dictator") + root.attributes("-topmost", True) + with contextlib.suppress(tk.TclError): + root.overrideredirect(True) + + try: + img = Image.open(image_path) + img.thumbnail((_MAX_IMAGE_SIDE_PX, _MAX_IMAGE_SIDE_PX), Image.Resampling.LANCZOS) + photo = ImageTk.PhotoImage(img) + except Exception as exc: + logger.warning("Splash: не удалось открыть картинку: %s", exc) + with contextlib.suppress(tk.TclError): + root.destroy() + return + + label = tk.Label(root, image=photo, borderwidth=0, highlightthickness=0) + label.image = photo # type: ignore[attr-defined] + label.pack() + + root.update_idletasks() + width = root.winfo_width() + height = root.winfo_height() + screen_w = root.winfo_screenwidth() + screen_h = root.winfo_screenheight() + x = (screen_w - width) // 2 + y = (screen_h - height) // 2 + root.geometry(f"+{x}+{y}") + + def _close(_event: object = None) -> None: + with contextlib.suppress(tk.TclError): + root.destroy() + + root.after(int(duration_sec * 1000), _close) + root.bind("", _close) + root.bind("", _close) + + with contextlib.suppress(Exception): + root.mainloop() + + +def _play_audio_async(path: Path) -> subprocess.Popen[bytes] | None: + """Стартует воспроизведение в фоне. Возвращает процесс (для terminate) или None.""" + if not path.exists(): + logger.debug("Splash audio: файл не найден: %s", path) + return None + + if sys.platform == "darwin": + return _play_audio_macos(path) + if sys.platform == "win32": + _play_audio_windows(path) + return None + logger.debug("Splash audio: платформа %s не поддержана", sys.platform) + return None + + +def _play_audio_macos(path: Path) -> subprocess.Popen[bytes] | None: + afplay = shutil.which("afplay") or "/usr/bin/afplay" + try: + return subprocess.Popen( + [afplay, str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + except OSError as exc: + logger.warning("Splash audio: afplay не запустился: %s", exc) + return None + + +def _play_audio_windows(path: Path) -> None: + if path.suffix.lower() != ".wav": + logger.warning( + "Splash audio: на Windows поддерживается только .wav, получено %s", + path.suffix, + ) + return + try: + import winsound + + winsound.PlaySound( # type: ignore[attr-defined] + str(path), + winsound.SND_FILENAME | winsound.SND_ASYNC, # type: ignore[attr-defined] + ) + except Exception as exc: + logger.warning("Splash audio: winsound не запустился: %s", exc) + + +def _stop_audio(proc: subprocess.Popen[bytes] | None) -> None: + """Останавливает audio (Mac terminate, Win winsound.PURGE).""" + if proc is not None: + with contextlib.suppress(Exception): + proc.terminate() + if sys.platform == "win32": + with contextlib.suppress(Exception): + import winsound + + winsound.PlaySound(None, winsound.SND_PURGE) # type: ignore[attr-defined] 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/src/voice_dictation/ui/tray.py b/src/voice_dictation/ui/tray.py index 3689f86..cc7138c 100644 --- a/src/voice_dictation/ui/tray.py +++ b/src/voice_dictation/ui/tray.py @@ -2,6 +2,7 @@ from __future__ import annotations +import functools import logging import threading from collections.abc import Callable @@ -24,6 +25,11 @@ class TrayApp: on_stats: Колбэк при клике "Статистика". on_quit: Колбэк при клике "Выход". title: Заголовок tray (tooltip). + on_preset_select: Колбэк выбора пресета по имени (опционально). + get_active_preset: Геттер имени активного пресета (опционально). + get_preset_names: Геттер списка имён всех пресетов (опционально). + on_splash_toggle: Колбэк toggle splash при старте (опционально). + get_splash_state: Геттер текущего состояния splash (опционально). """ def __init__( @@ -32,21 +38,26 @@ class TrayApp: on_settings: Callable[[], None], on_stats: Callable[[], None], on_quit: Callable[[], None], - modes_provider: Callable[[], list[tuple[str, str]]] | None = None, - on_mode_select: Callable[[str], None] | None = None, - current_mode: Callable[[], str] | None = None, title: str = "Voice Dictation", + on_preset_select: Callable[[str], None] | None = None, + get_active_preset: Callable[[], str] | None = None, + get_preset_names: Callable[[], list[str]] | None = None, + on_splash_toggle: Callable[[], bool] | None = None, + get_splash_state: Callable[[], bool] | None = None, ) -> None: self._on_toggle = on_toggle self._on_settings = on_settings self._on_stats = on_stats self._on_quit = on_quit - self._modes_provider = modes_provider - self._on_mode_select = on_mode_select - self._current_mode = current_mode self._title = title self._state = RecordingState.IDLE + self._on_preset_select = on_preset_select + self._get_active_preset = get_active_preset + self._get_preset_names = get_preset_names + self._on_splash_toggle = on_splash_toggle + self._get_splash_state = get_splash_state + self._icon = pystray.Icon( "voice_dictation", icon=make_icon(self._state), @@ -55,47 +66,47 @@ class TrayApp: ) def _build_menu(self) -> pystray.Menu: - items = [ + items: list[MenuItem] = [ MenuItem(self._toggle_label, self._handle_toggle, default=True), ] - if self._modes_provider is not None and self._on_mode_select is not None: - items.append(MenuItem("Режим обработки", self._build_mode_submenu())) - items.extend([ - MenuItem("Статистика", self._handle_stats), - MenuItem("Настройки", self._handle_settings), - pystray.Menu.SEPARATOR, - MenuItem("Выход", self._handle_quit), - ]) + + if self._on_preset_select is not None and self._get_preset_names is not None: + items.append(MenuItem("Режим", self._build_presets_submenu())) + + if self._on_splash_toggle is not None and self._get_splash_state is not None: + items.append( + MenuItem( + "Splash при старте", + self._handle_splash_toggle, + checked=self._splash_checked, + ), + ) + + items.extend( + [ + MenuItem("Статистика", self._handle_stats), + MenuItem("Настройки", self._handle_settings), + pystray.Menu.SEPARATOR, + MenuItem("Выход", self._handle_quit), + ] + ) + return pystray.Menu(*items) - def _build_mode_submenu(self) -> pystray.Menu: - """Строит подменю выбора режима с радио-галочками.""" - sub_items = [] - modes = self._modes_provider() if self._modes_provider is not None else [] - for key, label in modes: - sub_items.append( - MenuItem( - label, - self._make_mode_handler(key), - checked=self._make_mode_checked(key), - radio=True, - ) + def _build_presets_submenu(self) -> pystray.Menu: + """Строит submenu с радио-кнопками по списку имён пресетов.""" + assert self._get_preset_names is not None + names = self._get_preset_names() + preset_items = [ + MenuItem( + name, + functools.partial(self._handle_preset_select, name), + checked=functools.partial(self._preset_checked, name), + radio=True, ) - return pystray.Menu(*sub_items) - - def _make_mode_handler(self, key: str) -> Callable[..., None]: - def handler(*_args: object) -> None: - if self._on_mode_select is not None: - self._on_mode_select(key) - self.update_state(self._state) # перерисовать галочки - return handler - - def _make_mode_checked(self, key: str) -> Callable[[object], bool]: - def checked(_item: object) -> bool: - if self._current_mode is not None: - return self._current_mode() == key - return False - return checked + for name in names + ] + return pystray.Menu(*preset_items) def _toggle_label(self, _item: object) -> str: if self._state == RecordingState.RECORDING: @@ -104,6 +115,16 @@ class TrayApp: return "Обработка..." return "Начать запись" + def _preset_checked(self, name: str, _item: object) -> bool: + if self._get_active_preset is None: + return False + return self._get_active_preset() == name + + def _splash_checked(self, _item: object) -> bool: + if self._get_splash_state is None: + return False + return self._get_splash_state() + def _handle_toggle(self, *_args: object) -> None: self._on_toggle() @@ -117,6 +138,24 @@ class TrayApp: self._on_quit() self._icon.stop() + def _handle_preset_select(self, name: str, *_args: object) -> None: + if self._on_preset_select is None: + return + self._on_preset_select(name) + try: + self._icon.update_menu() + except Exception as exc: + logger.debug("Не удалось обновить меню после выбора пресета: %s", exc) + + def _handle_splash_toggle(self, *_args: object) -> None: + if self._on_splash_toggle is None: + return + self._on_splash_toggle() + try: + self._icon.update_menu() + except Exception as exc: + logger.debug("Не удалось обновить меню после splash toggle: %s", exc) + def update_state(self, state: RecordingState) -> None: """Обновляет иконку и меню в соответствии с состоянием. diff --git a/tests/conftest.py b/tests/conftest.py index c859c42..19f6a26 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -27,7 +27,19 @@ def tmp_paths(tmp_path: pytest.TempPathFactory) -> AppPaths: log_file=root / "app.log", pid_file=root / "dictate.pid", tmp_dir=root / "tmp", - bin_dir=root / "bin", ) paths.ensure_exists() return paths + + +@pytest.fixture(autouse=True) +def offline_unit_environment(monkeypatch): + """Unit checks never depend on exchange-rate services or network access.""" + import socket + from decimal import Decimal + + def reject_connection(*args, **kwargs): + raise AssertionError("Unit tests must use an explicit network fake") + + monkeypatch.setattr(socket, "create_connection", reject_connection) + monkeypatch.setattr("voice_dictation.core.fx.get_rate", lambda: Decimal("100")) diff --git a/tests/fakes/fake_components.py b/tests/fakes/fake_components.py index 49e2702..95189af 100644 --- a/tests/fakes/fake_components.py +++ b/tests/fakes/fake_components.py @@ -62,9 +62,17 @@ class FakeTranscriber: fail: Если True — transcribe() бросит TranscriptionError. """ - def __init__(self, text: str = "Тестовый текст", fail: bool = False) -> None: + def __init__( + self, + text: str = "Тестовый текст", + fail: bool = False, + texts: list[str] | None = None, + fail_on_call: int | None = None, + ) -> None: self.text = text self.fail = fail + self.texts = texts + self.fail_on_call = fail_on_call self.calls: list[tuple[Path, str, str | None]] = [] def transcribe( @@ -72,14 +80,19 @@ class FakeTranscriber: audio_path: Path, prompt: str = "", language: str | None = None, + model: str | None = None, + duration_sec: float | None = None, ) -> TranscriptionResult: self.calls.append((audio_path, prompt, language)) - if self.fail: + if self.fail or self.fail_on_call == len(self.calls): raise TranscriptionError("FakeTranscriber: принудительная ошибка") + text = self.text + if self.texts: + text = self.texts[min(len(self.calls) - 1, len(self.texts) - 1)] return TranscriptionResult( - text=self.text, - duration_sec=2.0, - model="gpt-4o-mini-transcribe", + text=text, + duration_sec=duration_sec or 2.0, + model=model or "gpt-4o-mini-transcribe", language=language or "ru", prompt_used=prompt or None, requested_at=datetime.now(tz=UTC), diff --git a/tests/unit/test_compressor.py b/tests/unit/test_compressor.py new file mode 100644 index 0000000..7d5d166 --- /dev/null +++ b/tests/unit/test_compressor.py @@ -0,0 +1,104 @@ +"""Тесты планирования чанков и разбора ffmpeg silencedetect.""" + +from __future__ import annotations + +from itertools import pairwise + +import pytest + +from voice_dictation.core.compressor import ( + AudioCompressor, + SilenceInterval, + parse_silence_intervals, + plan_chunk_ranges, +) +from voice_dictation.infrastructure.errors import CompressionError + + +def test_parse_silence_intervals_from_ffmpeg_output() -> None: + output = """ +[silencedetect @ 0x1] silence_start: 168.4 +[silencedetect @ 0x1] silence_end: 169.2 | silence_duration: 0.8 +[silencedetect @ 0x1] silence_start: 341.0 +[silencedetect @ 0x1] silence_end: 341.5 | silence_duration: 0.5 +""" + + assert parse_silence_intervals(output) == ( + SilenceInterval(168.4, 169.2), + SilenceInterval(341.0, 341.5), + ) + + +def test_plan_moves_boundary_to_nearest_preceding_pause() -> None: + ranges, adjusted = plan_chunk_ranges( + total_duration_sec=400.0, + chunk_duration_sec=180.0, + overlap_sec=4.0, + silences=(SilenceInterval(168.0, 170.0), SilenceInterval(338.0, 340.0)), + search_window_sec=12.0, + ) + + assert adjusted == 2 + expected = ((0.0, 171.0), (167.0, 341.0), (337.0, 400.0)) + for actual_range, expected_range in zip(ranges, expected, strict=True): + assert actual_range == pytest.approx(expected_range) + assert all(end - start <= 180.0 for start, end in ranges) + + +def test_plan_keeps_fixed_boundaries_without_nearby_pause() -> None: + ranges, adjusted = plan_chunk_ranges( + total_duration_sec=400.0, + chunk_duration_sec=180.0, + overlap_sec=4.0, + silences=(SilenceInterval(100.0, 101.0),), + search_window_sec=12.0, + ) + + assert adjusted == 0 + expected = ((0.0, 178.0), (174.0, 354.0), (350.0, 400.0)) + for actual_range, expected_range in zip(ranges, expected, strict=True): + assert actual_range == pytest.approx(expected_range) + + +def test_plan_preserves_four_second_overlap() -> None: + ranges, _ = plan_chunk_ranges( + total_duration_sec=750.0, + chunk_duration_sec=180.0, + overlap_sec=4.0, + silences=(SilenceInterval(170.0, 171.0),), + ) + + for left, right in pairwise(ranges): + assert left[1] - right[0] == pytest.approx(4.0) + + +def test_split_falls_back_when_silence_detection_fails( + tmp_path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + compressor = AudioCompressor() + monkeypatch.setattr(compressor, "_ffmpeg_bin", "ffmpeg") + + def fail_detection(*args: object, **kwargs: object) -> tuple[SilenceInterval, ...]: + del args, kwargs + raise CompressionError("silencedetect unavailable") + + def write_slice( + _self: AudioCompressor, + _src, + dst, + _start_sec: float, + _duration_sec: float, + ) -> None: + dst.write_bytes(b"ogg") + + monkeypatch.setattr(AudioCompressor, "_detect_silences", fail_detection) + monkeypatch.setattr(AudioCompressor, "_encode_slice", write_slice) + source = tmp_path / "source.wav" + source.write_bytes(b"wav") + + result = compressor.split(source, tmp_path / "chunks", 400.0, 180.0, 4.0) + + assert result.mode == "fixed_fallback" + assert result.adjusted_boundaries == 0 + assert len(result.chunks) == 3 diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index a89a392..d03700a 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -14,19 +14,26 @@ from voice_dictation.core.paths import AppPaths def test_default_config_values() -> None: """Дефолтный конфиг имеет правильные значения.""" config = Config() - assert config.hotkey == "cmd+space" + assert config.hotkey == "cmd+alt+d" assert config.model == "gpt-4o-mini-transcribe" assert config.language == "ru" assert config.auto_paste is True assert config.paste_delay_ms == 80 assert config.volume == 0.6 + assert config.chunk_duration_sec == 180.0 + assert config.chunk_overlap_sec == 4.0 + assert config.vad_enabled is True + assert config.vad_search_window_sec == 12.0 + assert config.vad_min_silence_sec == 0.35 + assert config.vad_noise_db == -35.0 + assert config.audio_retention_days == 30 def test_load_missing_file_returns_defaults(tmp_paths: AppPaths) -> None: """Загрузка несуществующего файла возвращает дефолтный конфиг.""" store = ConfigStore(tmp_paths.config_file) config = store.load() - assert config.hotkey == "cmd+space" + assert config.hotkey == "cmd+alt+d" assert config.model == "gpt-4o-mini-transcribe" @@ -38,6 +45,13 @@ def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None: language="en", auto_paste=False, paste_delay_ms=150, + chunk_duration_sec=240.0, + chunk_overlap_sec=5.0, + vad_enabled=False, + vad_search_window_sec=15.0, + vad_min_silence_sec=0.5, + vad_noise_db=-32.0, + audio_retention_days=60, ) store = ConfigStore(tmp_paths.config_file) store.save(original) @@ -50,6 +64,13 @@ def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None: assert loaded.language == "en" assert loaded.auto_paste is False assert loaded.paste_delay_ms == 150 + assert loaded.chunk_duration_sec == 240.0 + assert loaded.chunk_overlap_sec == 5.0 + assert loaded.vad_enabled is False + assert loaded.vad_search_window_sec == 15.0 + assert loaded.vad_min_silence_sec == 0.5 + assert loaded.vad_noise_db == -32.0 + assert loaded.audio_retention_days == 60 def test_save_with_path_fields(tmp_paths: AppPaths) -> None: @@ -95,4 +116,53 @@ def test_load_corrupted_json_returns_defaults(tmp_paths: AppPaths) -> None: tmp_paths.config_file.write_text("{ NOT VALID JSON }") store = ConfigStore(tmp_paths.config_file) config = store.load() - assert config.hotkey == "cmd+space" + assert config.hotkey == "cmd+alt+d" + + +@pytest.mark.parametrize("mode", ["raw", "summary", "translate_en", "email", "custom:Мой"]) +def test_windows_modes_migrate_and_round_trip(tmp_path: Path, mode: str) -> None: + """Upgrading and saving preserves legacy prompts, model, and selected mode.""" + from voice_dictation.core.modes import DEFAULT_MODES + + path = tmp_path / "config.json" + path.write_text( + json.dumps( + { + "mode": mode, + "proc_model": "my-model", + "custom_modes": {"Мой": "Keep all facts", "Деловое письмо": "Custom collision"}, + } + ) + ) + store = ConfigStore(path) + config = store.load() + expected = ( + "Мой" + if mode == "custom:Мой" + else next(spec.label for spec in DEFAULT_MODES if spec.key == mode) + ) + assert config.active_preset == expected + assert len(config.summary_presets) == len(DEFAULT_MODES) + 2 + assert config.summary_presets[-1].name != "Деловое письмо" + assert config.summary_presets[-1].prompt == "Custom collision" + assert all(p.model == "my-model" for p in config.summary_presets if p.prompt) + store.save(config) + assert ConfigStore(path).load() == config + + +def test_older_summary_toggle_migrates(tmp_path: Path) -> None: + path = tmp_path / "config.json" + path.write_text('{"summary_mode": true, "summary_model": "legacy-model"}') + config = ConfigStore(path).load() + assert config.active_preset == "Summary (структурировать)" + assert ( + 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_credentials.py b/tests/unit/test_credentials.py new file mode 100644 index 0000000..5f40918 --- /dev/null +++ b/tests/unit/test_credentials.py @@ -0,0 +1,70 @@ +"""Private profile credentials must not leak into preferences or other profiles.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from voice_dictation.infrastructure.credentials import read_api_key, save_api_key + + +def test_key_roundtrip_private_and_isolated(tmp_path: Path) -> None: + beta = tmp_path / "beta" + save_api_key(beta, "test-key-not-real") + assert read_api_key(beta) == "test-key-not-real" + assert read_api_key(tmp_path / "main") == "" + if os.name == "posix": + assert (beta / "credentials.json").stat().st_mode & 0o777 == 0o600 + save_api_key(beta, "replacement-not-real") + assert read_api_key(beta) == "replacement-not-real" + assert not list(beta.glob(".credentials-*")) + + +def test_invalid_key_preserves_previous(tmp_path: Path) -> None: + save_api_key(tmp_path, "test-key-not-real") + with pytest.raises(ValueError): + save_api_key(tmp_path, "bad key") + assert read_api_key(tmp_path) == "test-key-not-real" + + +def test_invalid_file_does_not_crash(tmp_path: Path) -> None: + (tmp_path / "credentials.json").write_text("[]") + assert read_api_key(tmp_path) == "" + + +@pytest.mark.parametrize( + "value", + [ + " sk-test-not-real ", + '"sk-test-not-real"', + "OPENAI_API_KEY=sk-test-not-real", + 'OPENAI_API_KEY = "sk-test-not-real"', + "export OPENAI_API_KEY=sk-test-not-real", + ], +) +def test_paste_from_dotenv(tmp_path: Path, value: str) -> None: + save_api_key(tmp_path, value) + assert read_api_key(tmp_path) == "sk-test-not-real" + + +def test_multiple_env_values_rejected(tmp_path: Path) -> None: + with pytest.raises(ValueError): + save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test") + assert not (tmp_path / "credentials.json").exists() + + +@pytest.mark.parametrize( + "value", + [ + "OPENAI_API_KEY\t=sk-test-not-real", + "export OPENAI_API_KEY = sk-test-not-real", + "sk-test-\nnot-real", + "“sk-test-not-real”", + "sk-test-\u200bnot-real", + ], +) +def test_copy_formatting_is_normalized(tmp_path: Path, value: str) -> None: + save_api_key(tmp_path, value) + assert read_api_key(tmp_path) == "sk-test-not-real" 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 new file mode 100644 index 0000000..255cdb9 --- /dev/null +++ b/tests/unit/test_local_pipeline.py @@ -0,0 +1,193 @@ +"""Offline guarantees across routing, recovery and the full success path.""" + +from __future__ import annotations + +import json +import socket +from pathlib import Path + +import httpx +import pytest + +from tests.fakes.fake_components import FakeClipboard, FakeTranscriber +from tests.unit.test_orchestrator import _make_orchestrator +from voice_dictation.core.config import Config, ConfigStore +from voice_dictation.core.paths import AppPaths +from voice_dictation.core.transcription import RoutingTranscriber +from voice_dictation.infrastructure.env_loader import load_env +from voice_dictation.infrastructure.errors import TranscriptionError + + +def _wait(orchestrator): + if orchestrator._current_future: + orchestrator._current_future.result(timeout=5) + + +def _no_network(*args, **kwargs): + raise AssertionError("Offline scenario attempted network access") + + +def test_local_success_never_calls_network_or_postprocessing(tmp_paths, monkeypatch): + monkeypatch.setattr(socket, "create_connection", _no_network) + monkeypatch.setattr(httpx.Client, "send", _no_network) + clipboard = FakeClipboard() + config = Config(transcription_backend="local", active_preset="Тезисы", paste_delay_ms=0) + orchestrator = _make_orchestrator(tmp_paths, clipboard=clipboard, config=config) + monkeypatch.setattr(orchestrator, "_summarize", _no_network) + monkeypatch.setattr("voice_dictation.core.fx.get_rate", _no_network) + orchestrator.toggle() + orchestrator.toggle() + _wait(orchestrator) + assert clipboard.copy_calls == ["Тестовый текст"] + orchestrator.shutdown() + + +def test_local_recording_keeps_mode_when_settings_change(tmp_paths): + config = Config(transcription_backend="local", paste_delay_ms=0) + engine = FakeTranscriber() + orchestrator = _make_orchestrator(tmp_paths, transcriber=engine, config=config) + orchestrator.toggle() + # Simulate separate settings process returning a new config object. + orchestrator._config_provider = lambda: Config(transcription_backend="openai") + orchestrator.toggle() + _wait(orchestrator) + manifest = next(tmp_paths.sessions_dir.glob("*/manifest.json")) + saved = json.loads(manifest.read_text()) + assert saved["transcription_identity"]["engine"] == "local" + assert saved["recording_config"]["transcription_backend"] == "local" + orchestrator.shutdown() + + +def test_recovery_uses_recording_config_not_current_cloud(tmp_paths, monkeypatch): + config = Config(transcription_backend="local", paste_delay_ms=0) + first = _make_orchestrator(tmp_paths, config=config) + first.toggle() + # Simulate interrupted process with an intact source WAV. + session = next(tmp_paths.sessions_dir.iterdir()) + first._session_store.mark_recorded(session / "source.wav", 2.0) + second = _make_orchestrator(tmp_paths, config=Config(transcription_backend="openai")) + monkeypatch.setattr(second, "_summarize", _no_network) + assert second.resume_pending_sessions() == 1 + _wait(second) + saved = second._session_store.read(session) + assert saved["transcription_identity"]["engine"] == "local" + first.shutdown() + second.shutdown() + + +def test_legacy_recording_never_automatically_uploaded(tmp_paths): + engine = FakeTranscriber() + orchestrator = _make_orchestrator(tmp_paths, transcriber=engine) + source = orchestrator._session_store.create() + source.write_bytes(b"audio") + orchestrator._session_store.mark_recorded(source, 2.0) + assert orchestrator.resume_pending_sessions() == 1 + _wait(orchestrator) + assert not engine.calls + assert "автоматическое" in orchestrator._session_store.read(source.parent)["last_error"] + orchestrator.shutdown() + + +def test_local_missing_model_cannot_construct_cloud(tmp_path, monkeypatch): + monkeypatch.setattr("voice_dictation.core.transcriber.WhisperTranscriber", _no_network) + with pytest.raises(TranscriptionError): + RoutingTranscriber("", tmp_path).transcribe( + tmp_path / "audio.wav", model="local:whisper-base" + ) + + +def test_cloud_missing_key_is_actionable(tmp_path): + with pytest.raises(TranscriptionError, match="OPENAI_API_KEY"): + RoutingTranscriber("", tmp_path).transcribe(tmp_path / "audio.wav", model="whisper-1") + + +def test_keyless_env_and_beta_paths_are_isolated(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + monkeypatch.setenv("VOICE_DICTATION_HOME", str(tmp_path / "beta")) + assert load_env().api_key == "" + assert AppPaths.default().root == tmp_path / "beta" + + +def test_settings_file_changes_are_loaded_for_next_recording(tmp_path): + store = ConfigStore(tmp_path / "config.json") + store.save(Config(transcription_backend="openai")) + other = ConfigStore(store._path) + other.save(Config(transcription_backend="local")) + assert store.load().transcription_backend == "local" + + +def test_corrupt_local_config_never_switches_to_cloud(tmp_path): + path = tmp_path / "config.json" + store = ConfigStore(path) + store.save(Config(transcription_backend="local")) + path.write_text("{broken") + assert store.load().transcription_backend == "local" + assert ConfigStore(path).load().transcription_backend == "local" + path.write_text('{"transcription_backend": "server"}') + assert ConfigStore(path).load().transcription_backend == "local" + + +def test_local_long_wav_splits_without_ffmpeg(tmp_paths): + import wave + + from voice_dictation.core.models import RecordingResult + + config = Config(transcription_backend="local", chunk_duration_sec=60) + orchestrator = _make_orchestrator(tmp_paths, config=config) + source = orchestrator._session_store.create() + with wave.open(str(source), "wb") as audio: + audio.setparams((1, 2, 16000, 0, "NONE", "not compressed")) + audio.writeframes(b"\0\0" * 16000 * 125) + chunks = orchestrator._prepare_chunks(RecordingResult(source, 125), source, config) + assert len(chunks.chunks) == 3 + assert chunks.mode == "local_pcm_fixed" + for chunk in chunks.chunks: + with wave.open(str(chunk.path), "rb") as audio: + assert audio.getnframes() / audio.getframerate() <= 60.001 + orchestrator.shutdown() + + +def test_checkpoint_model_change_is_rejected(tmp_paths): + from voice_dictation.core.models import RecordingResult + + engine = FakeTranscriber() + config = Config(transcription_backend="local", paste_delay_ms=0) + orchestrator = _make_orchestrator(tmp_paths, transcriber=engine, config=config) + source = orchestrator._session_store.create() + source.write_bytes(b"audio") + recording = RecordingResult(source, 2) + orchestrator._transcribe_session(recording, config) + with pytest.raises(TranscriptionError, match="изменились"): + orchestrator._transcribe_session( + recording, Config(transcription_backend="local", local_model="whisper-small") + ) + orchestrator.shutdown() + + +def test_renamed_beta_bundle_still_cannot_use_production_profile(tmp_path, monkeypatch): + import sys + + monkeypatch.delenv("VOICE_DICTATION_HOME", raising=False) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.setattr(sys, "frozen", True, raising=False) + 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_local_transcriber.py b/tests/unit/test_local_transcriber.py new file mode 100644 index 0000000..640bda4 --- /dev/null +++ b/tests/unit/test_local_transcriber.py @@ -0,0 +1,135 @@ +"""Subprocess adapter tests with synthetic silence and fake CLI output.""" + +from __future__ import annotations + +import json +import subprocess +import wave +from decimal import Decimal +from pathlib import Path +from unittest.mock import patch + +import pytest + +from voice_dictation.core.local_transcriber import LocalTranscriber +from voice_dictation.infrastructure.errors import TranscriptionError + + +@pytest.fixture +def local_setup(tmp_path): + model = tmp_path / "model.bin" + model.write_bytes(b"fake") + executable = tmp_path / "whisper-cli" + executable.touch() + audio = tmp_path / "silence.wav" + with wave.open(str(audio), "wb") as stream: + stream.setnchannels(1) + stream.setsampwidth(2) + stream.setframerate(16000) + stream.writeframes(b"\x00\x00" * 16000) + return LocalTranscriber(model, executable), audio + + +def test_pcm_wav_transcription_is_local(local_setup): + transcriber, audio = local_setup + calls = [] + + def run(command, **kwargs): + calls.append(command) + output = Path(command[command.index("-of") + 1]).with_suffix(".json") + output.write_text( + json.dumps( + { + "transcription": [{"text": " Привет "}, {"text": " мир "}], + "result": {"language": "ru"}, + } + ) + ) + return subprocess.CompletedProcess(command, 0) + + with patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run): + result = transcriber.transcribe(audio, prompt="terms", model="whisper-base") + assert result.text == "Привет мир" + assert result.cost_usd == Decimal("0") + assert result.duration_sec == 1.0 + assert result.language == "ru" + assert result.model == "whisper-base" + assert result.prompt_used == "terms" + assert len(calls) == 1 + assert "--prompt" in calls[0] + assert calls[0][calls[0].index("-l") + 1] == "auto" + assert not Path(calls[0][calls[0].index("-of") + 1]).parent.exists() + + +def test_missing_model_no_process(tmp_path): + with patch("voice_dictation.core.local_transcriber.subprocess.run") as run: + with pytest.raises(TranscriptionError, match="не установлена"): + LocalTranscriber(tmp_path / "absent").transcribe(tmp_path / "audio") + run.assert_not_called() + + +def test_timeout_no_fallback(local_setup): + transcriber, audio = local_setup + with ( + patch( + "voice_dictation.core.local_transcriber.subprocess.run", + side_effect=subprocess.TimeoutExpired("whisper-cli", 120), + ), + pytest.raises(TranscriptionError, match="время ожидания"), + ): + transcriber.transcribe(audio) + + +def test_failure_does_not_expose_stderr(local_setup): + transcriber, audio = local_setup + with ( + patch( + "voice_dictation.core.local_transcriber.subprocess.run", + return_value=subprocess.CompletedProcess([], 1, stderr=b"PRIVATE TRANSCRIPT"), + ), + pytest.raises(TranscriptionError, match="кодом 1") as exc, + ): + transcriber.transcribe(audio) + assert "PRIVATE" not in str(exc.value) + + +def test_invalid_json(local_setup): + transcriber, audio = local_setup + + def run(command, **kwargs): + Path(command[command.index("-of") + 1]).with_suffix(".json").write_text("[]") + return subprocess.CompletedProcess(command, 0) + + with ( + patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run), + pytest.raises(TranscriptionError, match="результат"), + ): + transcriber.transcribe(audio) + + +def test_opus_converted_before_inference(local_setup, tmp_path): + transcriber, source = local_setup + audio = tmp_path / "audio.ogg" + audio.write_bytes(b"fake ogg") + calls = [] + + def run(command, **kwargs): + calls.append(command) + if "-of" in command: + Path(command[command.index("-of") + 1]).with_suffix(".json").write_text( + '{"transcription": [{"text": "ok"}]}' + ) + else: + Path(command[-1]).write_bytes(source.read_bytes()) + return subprocess.CompletedProcess(command, 0) + + with ( + patch("voice_dictation.core.local_transcriber.subprocess.run", side_effect=run), + patch( + "voice_dictation.core.local_transcriber.discover_executable", + return_value=Path("/fake/ffmpeg"), + ), + ): + assert transcriber.transcribe(audio).text == "ok" + assert len(calls) == 2 + assert "pcm_s16le" in calls[0] diff --git a/tests/unit/test_macos_input_safety.py b/tests/unit/test_macos_input_safety.py new file mode 100644 index 0000000..8e062f4 --- /dev/null +++ b/tests/unit/test_macos_input_safety.py @@ -0,0 +1,46 @@ +"""Hotkeys must never repair the user's text by synthesizing deletion keys.""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import pytest + +from voice_dictation.platform.macos import autopaste, hotkey_listener + + +@pytest.mark.parametrize("hotkey", ["cmd+space", "cmd+tab", "cmd+enter", "cmd+alt+d"]) +def test_start_and_stop_hotkeys_do_not_edit_text( + hotkey: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(hotkey_listener, "_modifier_mask", lambda _: 0) + + def forbidden_thread(*args: object, **kwargs: object) -> None: + pytest.fail("Hotkey spawned an unsolicited background input operation") + + monkeypatch.setattr(hotkey_listener.threading, "Thread", forbidden_thread) + calls: list[str] = [] + + def callback() -> None: + calls.append("toggle") + + listener = hotkey_listener.MacHotkeyListener() + assert listener.register(hotkey, callback) + for _ in range(2): + listener._hotkeys[0][-1]() + assert calls == ["toggle", "toggle"] + + +def test_paste_posts_only_command_v(monkeypatch: pytest.MonkeyPatch) -> None: + events: list[tuple[int, bool]] = [] + quartz = SimpleNamespace( + CGEventCreateKeyboardEvent=lambda source, key, down: (key, down), + CGEventPost=lambda tap, event: events.append(event), + CGEventSetFlags=lambda event, flags: None, + kCGEventFlagMaskCommand=1, + kCGHIDEventTap=0, + ) + monkeypatch.setitem(sys.modules, "Quartz", quartz) + autopaste.MacAutoPaste().paste() + assert events == [(0x09, True), (0x09, False)] diff --git a/tests/unit/test_model_manager.py b/tests/unit/test_model_manager.py new file mode 100644 index 0000000..bbc92da --- /dev/null +++ b/tests/unit/test_model_manager.py @@ -0,0 +1,245 @@ +"""Model installation invariants without network or real model downloads.""" + +from __future__ import annotations + +import hashlib +import threading +from unittest.mock import AsyncMock, MagicMock + +import httpx +import pytest + +from voice_dictation.core import model_manager as module +from voice_dictation.core.model_manager import ( + DownloadCancelled, + ModelError, + ModelManager, + ModelSpec, +) + + +@pytest.fixture +def fixture_model(monkeypatch): + content = b"small synthetic model bytes" + spec = ModelSpec( + "test", + "Test", + "https://example.invalid/model", + len(content), + hashlib.sha256(content).hexdigest(), + ) + monkeypatch.setattr(module, "CATALOG", (spec,)) + response = MagicMock() + response.blocks = [content[:8], content[8:]] + + async def chunks(): + for block in response.blocks: + yield block + + response.aiter_bytes = chunks + stream = MagicMock() + stream.__aenter__ = AsyncMock(return_value=response) + stream.__aexit__ = AsyncMock(return_value=False) + client = MagicMock() + client.stream.return_value = stream + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=False) + monkeypatch.setattr(module.httpx, "AsyncClient", lambda *a, **kw: client) + return spec, content, response + + +def test_verified_atomic_download(tmp_path, fixture_model): + spec, content, _ = fixture_model + manager = ModelManager(tmp_path) + progress = [] + path = manager.download(spec.id, lambda done, total: progress.append((done, total))) + assert path.read_bytes() == content + assert manager.is_installed(spec.id) + assert progress[-1] == (len(content), len(content)) + assert not list(tmp_path.glob("*.part")) + manager.delete(spec.id) + assert not manager.is_installed(spec.id) + + +def test_corrupt_download_never_installed(tmp_path, fixture_model): + spec, _, response = fixture_model + response.blocks = [b"corrupt"] + manager = ModelManager(tmp_path) + with pytest.raises(ModelError, match="SHA256"): + manager.download(spec.id) + assert not manager.is_installed(spec.id) + assert not list(tmp_path.glob("*.part")) + + +def test_cancel_removes_partial(tmp_path, fixture_model): + spec, _, _ = fixture_model + cancel = threading.Event() + manager = ModelManager(tmp_path) + with pytest.raises(DownloadCancelled): + manager.download(spec.id, lambda *_: cancel.set(), cancel) + assert not manager.path_for(spec.id).exists() + assert not list(tmp_path.glob("*.part")) + + +def test_concurrent_download_and_delete_rejected(tmp_path, fixture_model): + spec, _, _ = fixture_model + manager = ModelManager(tmp_path) + with manager._lock(spec.id): + with pytest.raises(ModelError, match="другом окне"): + ModelManager(tmp_path).download(spec.id) + with pytest.raises(ModelError, match="другом окне"): + ModelManager(tmp_path).delete(spec.id) + + +def test_network_failure_preserves_old_model(tmp_path, fixture_model): + spec, content, response = fixture_model + manager = ModelManager(tmp_path) + path = manager.path_for(spec.id) + path.write_bytes(b"previous corrupt model") + response.raise_for_status.side_effect = httpx.ConnectError("failed") + with pytest.raises(ModelError): + manager.download(spec.id) + assert path.read_bytes() == b"previous corrupt model" + assert not list(tmp_path.glob("*.part")) + path.write_bytes(content) + assert manager.download(spec.id) == path + + +@pytest.mark.parametrize("model_id", ["../escape", "/tmp/escape", "unknown", "test/../../escape"]) +def test_unknown_ids_rejected(tmp_path, fixture_model, model_id): + with pytest.raises(ModelError): + ModelManager(tmp_path).download(model_id) + + +def test_symlink_rejected(tmp_path, fixture_model): + target = tmp_path / "target" + target.write_bytes(b"keep") + (tmp_path / "test.bin").symlink_to(target) + with pytest.raises(ModelError, match="ссылкой"): + ModelManager(tmp_path).delete("test") + assert target.read_bytes() == b"keep" + + +def test_inference_lease_blocks_delete_and_releases(tmp_path, fixture_model): + spec, content, _ = fixture_model + manager = ModelManager(tmp_path) + manager.path_for(spec.id).write_bytes(content) + with manager.use(spec.id) as path: + assert path.read_bytes() == content + with pytest.raises(ModelError, match="другом окне"): + ModelManager(tmp_path).delete(spec.id) + manager.delete(spec.id) + assert not manager.is_installed(spec.id) + + +@pytest.mark.parametrize("oversize", [False, True]) +def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize): + spec, content, response = fixture_model + response.blocks = [b"x" * (len(content) + int(oversize))] + manager = ModelManager(tmp_path) + with pytest.raises(ModelError): + manager.download(spec.id) + assert not manager.path_for(spec.id).exists() + assert not list(tmp_path.glob("*.part")) + + +def test_precancelled_download_makes_no_request(tmp_path, fixture_model, monkeypatch): + spec, _, _ = fixture_model + request = MagicMock() + monkeypatch.setattr(module.httpx, "AsyncClient", request) + cancel = threading.Event() + cancel.set() + with pytest.raises(DownloadCancelled): + ModelManager(tmp_path).download(spec.id, cancel=cancel) + request.assert_not_called() + + +def test_partial_symlink_cannot_overwrite_target(tmp_path, fixture_model): + spec, _, _ = fixture_model + target = tmp_path / "target" + target.write_bytes(b"keep") + (tmp_path / "test.bin.part").symlink_to(target) + with pytest.raises(ModelError, match="ссылкой"): + ModelManager(tmp_path).download(spec.id) + assert target.read_bytes() == b"keep" + + +@pytest.mark.parametrize("blocked_stage", ["connecting", "downloading"]) +def test_cancel_interrupts_blocked_socket_and_finishes_cleanup( + tmp_path, fixture_model, monkeypatch, blocked_stage +): + import asyncio + import time + + spec, _, response = fixture_model + entered = threading.Event() + cleaned = threading.Event() + cancel = threading.Event() + + class BlockedStream: + async def __aenter__(self): + if blocked_stage == "connecting": + entered.set() + try: + await asyncio.sleep(60) + finally: + cleaned.set() + return response + + async def __aexit__(self, *args): + cleaned.set() + + async def slow_bytes(): + entered.set() + await asyncio.sleep(60) + yield b"never delivered" + + response.aiter_bytes = slow_bytes + client = MagicMock() + client.stream.return_value = BlockedStream() + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=False) + monkeypatch.setattr(module.httpx, "AsyncClient", lambda **kwargs: client) + + def trigger_cancel(): + assert entered.wait(2) + cancel.set() + + trigger = threading.Thread(target=trigger_cancel) + trigger.start() + started = time.monotonic() + with pytest.raises(DownloadCancelled): + ModelManager(tmp_path).download(spec.id, cancel=cancel) + elapsed = time.monotonic() - started + trigger.join(2) + assert elapsed < 1.0 + assert cleaned.is_set() + assert not list(tmp_path.glob("*.part")) + assert not ModelManager(tmp_path).path_for(spec.id).exists() + client.__aexit__.assert_awaited_once() + # Lock release proves no downloader continues owning the operation. + with ModelManager(tmp_path)._lock(spec.id): + pass + + +def test_stage_order_and_safe_operation_logs(tmp_path, fixture_model, caplog): + import logging + + spec, _, _ = fixture_model + stages = [] + with caplog.at_level(logging.INFO, logger=module.__name__): + ModelManager(tmp_path).download(spec.id, stage=stages.append) + assert stages == ["checking", "connecting", "downloading", "verifying"] + assert "model.download.started" in caplog.text + assert "model.download.completed" in caplog.text + assert "operation=" in caplog.text + assert spec.url not in caplog.text + + +def test_failure_log_does_not_expose_network_exception(tmp_path, fixture_model, caplog): + spec, _, response = fixture_model + response.raise_for_status.side_effect = httpx.ConnectError("SECRET SIGNED URL") + with pytest.raises(ModelError): + ModelManager(tmp_path).download(spec.id) + assert "model.download.failed" in caplog.text + assert "SECRET" not in caplog.text diff --git a/tests/unit/test_orchestrator.py b/tests/unit/test_orchestrator.py index e4d4aa4..7764232 100644 --- a/tests/unit/test_orchestrator.py +++ b/tests/unit/test_orchestrator.py @@ -3,6 +3,9 @@ from __future__ import annotations import time +from pathlib import Path + +import pytest from tests.fakes.fake_components import ( FakeAutoPaste, @@ -12,6 +15,7 @@ from tests.fakes.fake_components import ( FakeSoundPlayer, FakeTranscriber, ) +from voice_dictation.core.compressor import AudioChunk, ChunkingResult from voice_dictation.core.config import Config from voice_dictation.core.dictionary import Dictionary from voice_dictation.core.enums import RecordingState, SoundKind @@ -28,6 +32,7 @@ def _make_orchestrator( sound_player: FakeSoundPlayer | None = None, notifier: FakeNotifier | None = None, config: Config | None = None, + compressor=None, ) -> DictationOrchestrator: """Вспомогательная функция — создаёт оркестратор с фейками.""" cfg = config or Config() @@ -41,9 +46,46 @@ def _make_orchestrator( notifier=notifier or FakeNotifier(), config_provider=lambda: cfg, paths=tmp_paths, + compressor=compressor, ) +class _FakeChunkCompressor: + def is_available(self) -> bool: + return True + + def compress(self, src: Path, dst: Path) -> Path: + dst.write_bytes(src.read_bytes()) + return dst + + def split( + self, + src: Path, + output_dir: Path, + total_duration_sec: float, + chunk_duration_sec: float, + overlap_sec: float, + **kwargs: object, + ) -> ChunkingResult: + del src + del kwargs + output_dir.mkdir(parents=True, exist_ok=True) + chunks: list[AudioChunk] = [] + start = 0.0 + step = chunk_duration_sec - overlap_sec + index = 0 + while start < total_duration_sec: + duration = min(chunk_duration_sec, total_duration_sec - start) + path = output_dir / f"chunk_{index:04d}.ogg" + path.write_bytes(b"chunk") + chunks.append(AudioChunk(index, path, start, duration)) + if start + duration >= total_duration_sec: + break + start += step + index += 1 + return ChunkingResult(tuple(chunks), "fake", 0, 0) + + def test_initial_state_is_idle(tmp_paths: AppPaths) -> None: """Начальное состояние — IDLE.""" o = _make_orchestrator(tmp_paths) @@ -206,9 +248,13 @@ def test_cancel_stops_recording(tmp_paths: AppPaths) -> None: assert o.state == RecordingState.IDLE -def test_autopaste_skipped_for_long_text(tmp_paths: AppPaths) -> None: - """Автовставка не выполняется если текст длиннее 10000 символов.""" - long_text = "а" * 15000 +def test_autopaste_skipped_for_very_long_text(tmp_paths: AppPaths) -> None: + """Текст >10000 символов автоматически НЕ вставляется (только буфер). + + После merge с веткой Жени: при превышении MAX_AUTOPASTE_CHARS показываем + notify «вставьте вручную ⌘V», autopaste не вызываем. + """ + long_text = "а" * 50_000 transcriber = FakeTranscriber(text=long_text) auto_paste = FakeAutoPaste() o = _make_orchestrator(tmp_paths, transcriber=transcriber, auto_paste=auto_paste) @@ -220,3 +266,175 @@ def test_autopaste_skipped_for_long_text(tmp_paths: AppPaths) -> None: time.sleep(0.05) assert auto_paste.paste_count == 0 + + +def test_long_recording_is_chunked_stitched_and_archived(tmp_paths: AppPaths) -> None: + clipboard = FakeClipboard() + transcriber = FakeTranscriber( + texts=[ + "раз два три четыре", + "три четыре пять шесть", + "пять шесть семь", + ] + ) + config = Config(chunk_duration_sec=3.0, chunk_overlap_sec=1.0, paste_delay_ms=0) + o = _make_orchestrator( + tmp_paths, + recorder=FakeRecorder(duration_sec=7.0), + transcriber=transcriber, + clipboard=clipboard, + config=config, + compressor=_FakeChunkCompressor(), + ) + + o.toggle() + o.toggle() + deadline = time.time() + 5 + while o.state != RecordingState.IDLE and time.time() < deadline: + time.sleep(0.05) + + assert len(transcriber.calls) == 3 + assert clipboard.copy_calls == ["раз два три четыре пять шесть семь"] + session_dir = next(tmp_paths.sessions_dir.iterdir()) + assert (session_dir / "source.ogg").exists() + assert not (session_dir / "source.wav").exists() + assert not (session_dir / "chunks").exists() + assert (session_dir / "transcript.txt").read_text(encoding="utf-8") == clipboard.copy_calls[0] + + +def test_restart_resumes_from_saved_chunk_checkpoint(tmp_paths: AppPaths) -> None: + config = Config(chunk_duration_sec=3.0, chunk_overlap_sec=1.0, paste_delay_ms=0) + failing = FakeTranscriber(texts=["раз два три четыре"], fail_on_call=2) + first = _make_orchestrator( + tmp_paths, + recorder=FakeRecorder(duration_sec=7.0), + transcriber=failing, + config=config, + compressor=_FakeChunkCompressor(), + ) + first.toggle() + first.toggle() + deadline = time.time() + 5 + while first.state != RecordingState.IDLE and time.time() < deadline: + time.sleep(0.05) + + session_dir = next(tmp_paths.sessions_dir.iterdir()) + assert (session_dir / "transcripts" / "chunk_0000.json").exists() + assert (session_dir / "source.wav").exists() + + clipboard = FakeClipboard() + resumed_transcriber = FakeTranscriber(texts=["три четыре пять шесть", "пять шесть семь"]) + resumed = _make_orchestrator( + tmp_paths, + transcriber=resumed_transcriber, + clipboard=clipboard, + config=config, + compressor=_FakeChunkCompressor(), + ) + assert resumed.resume_pending_sessions() == 1 + deadline = time.time() + 5 + while resumed.state != RecordingState.IDLE and time.time() < deadline: + time.sleep(0.05) + + 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() + + +@pytest.mark.parametrize( + ("model", "languages", "expected"), + [ + ("gpt-transcribe", ["ru", "ru", "ru"], "ru"), + ("gpt-transcribe", ["ru", None, "ru"], None), + ("gpt-transcribe", ["ru", "en", "ru"], None), + ("gpt-transcribe", [None, None, None], None), + ("gpt-4o-mini-transcribe", [None, None, None], "ru"), + ("gpt-4o-mini-transcribe", [None, "en", "ru"], "en"), + ], +) +def test_chunk_language_aggregation_preserves_unknown_and_legacy( + tmp_paths, monkeypatch, model, languages, expected +): + from dataclasses import replace + + from voice_dictation.core.models import RecordingResult + + transcriber = FakeTranscriber() + original = transcriber.transcribe + detected = iter(languages) + + def respond(*args, **kwargs): + return replace(original(*args, **kwargs), language=next(detected)) + + monkeypatch.setattr(transcriber, "transcribe", respond) + config = Config(model=model, language="ru", chunk_duration_sec=3, chunk_overlap_sec=1) + orchestrator = _make_orchestrator( + tmp_paths, transcriber=transcriber, config=config, compressor=_FakeChunkCompressor() + ) + audio = orchestrator._session_store.create() + audio.write_bytes(b"synthetic") + result = orchestrator._transcribe_session(RecordingResult(audio, 7), config) + assert result.language == expected + assert len(transcriber.calls) == 3 + orchestrator.shutdown() diff --git a/tests/unit/test_pricing.py b/tests/unit/test_pricing.py index e31285b..84c2c4d 100644 --- a/tests/unit/test_pricing.py +++ b/tests/unit/test_pricing.py @@ -60,3 +60,7 @@ def test_prices_immutable() -> None: """PRICES_PER_MINUTE нельзя изменить (MappingProxyType).""" with pytest.raises(TypeError): PriceCalculator.PRICES_PER_MINUTE["new-model"] = Decimal("1.0") # type: ignore[index] + + +def test_gpt_transcribe_one_minute(): + assert PriceCalculator.cost("gpt-transcribe", 60) == Decimal("0.004500") diff --git a/tests/unit/test_session_store.py b/tests/unit/test_session_store.py new file mode 100644 index 0000000..004befa --- /dev/null +++ b/tests/unit/test_session_store.py @@ -0,0 +1,95 @@ +"""Тесты долговечных сессий и checkpoint-файлов.""" + +from datetime import UTC, datetime +from decimal import Decimal + +from voice_dictation.core.models import TranscriptionResult +from voice_dictation.core.paths import AppPaths +from voice_dictation.core.session_store import SessionStore + + +def test_chunk_checkpoint_roundtrip(tmp_paths: AppPaths) -> None: + store = SessionStore(tmp_paths.sessions_dir) + audio_path = store.create() + audio_path.write_bytes(b"audio") + store.mark_recorded(audio_path, 12.5) + expected = TranscriptionResult( + text="полный текст чанка", + duration_sec=12.5, + model="gpt-4o-mini-transcribe", + language="ru", + prompt_used="словарь", + requested_at=datetime.now(tz=UTC), + cost_usd=Decimal("0.00123"), + ) + + store.save_chunk_result(audio_path.parent, 0, expected) + actual = store.load_chunk_result(audio_path.parent, 0) + + assert actual == expected + assert store.pending() == [audio_path.parent] + + +def test_completed_session_is_not_pending(tmp_paths: AppPaths) -> None: + store = SessionStore(tmp_paths.sessions_dir) + audio_path = store.create() + audio_path.write_bytes(b"audio") + store.mark_recorded(audio_path, 1.0) + store.complete(audio_path.parent, "готово", ()) + + assert store.pending() == [] + assert (audio_path.parent / "transcript.txt").read_text(encoding="utf-8") == "готово" + + +def test_interrupted_recording_is_pending_when_wav_exists(tmp_paths: AppPaths) -> None: + store = SessionStore(tmp_paths.sessions_dir) + audio_path = store.create() + 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_text_stitcher.py b/tests/unit/test_text_stitcher.py new file mode 100644 index 0000000..10328c2 --- /dev/null +++ b/tests/unit/test_text_stitcher.py @@ -0,0 +1,35 @@ +"""Тесты склейки перекрывающихся транскриптов.""" + +from voice_dictation.core.text_stitcher import stitch_transcripts + + +def test_stitch_removes_exact_overlap() -> None: + result = stitch_transcripts( + [ + "Раз два три четыре.", + "три четыре пять шесть", + "пять шесть семь", + ] + ) + + assert result.text == "Раз два три четыре. пять шесть семь" + assert result.removed_prefix_words == (2, 2) + + +def test_stitch_keeps_both_parts_when_overlap_is_uncertain() -> None: + result = stitch_transcripts(["первая независимая мысль", "совсем другой абзац"]) + + assert result.text == "первая независимая мысль совсем другой абзац" + assert result.removed_prefix_words == (0,) + + +def test_stitch_accepts_small_asr_variation_in_long_overlap() -> None: + result = stitch_transcripts( + [ + "до границы мы обсуждали сохранение всей исходной аудиозаписи", + "обсуждали сохранение всей исходной аудио записи после границы", + ] + ) + + assert result.text.endswith("после границы") + assert result.removed_prefix_words[0] >= 4 diff --git a/tests/unit/test_transcriber.py b/tests/unit/test_transcriber.py new file mode 100644 index 0000000..af3bd5d --- /dev/null +++ b/tests/unit/test_transcriber.py @@ -0,0 +1,110 @@ +"""HTTP contracts with synthetic bytes and MockTransport only.""" + +from __future__ import annotations + +from decimal import Decimal + +import httpx +import pytest + +from voice_dictation.core.transcriber import WhisperTranscriber +from voice_dictation.infrastructure.errors import TranscriptionError + + +def _engine(payload, model="gpt-transcribe"): + requests = [] + + def respond(request): + requests.append(request.read()) + return httpx.Response(200, json=payload) + + engine = WhisperTranscriber("synthetic-key", model=model) + engine._client.close() + engine._client = httpx.Client(transport=httpx.MockTransport(respond)) + return engine, requests + + +def test_gpt_transcribe_multipart_language_and_duration_price(tmp_path): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic audio placeholder") + engine, requests = _engine( + { + "text": " Test ", + "languages": [{"code": "ru"}], + "usage": {"type": "duration", "seconds": 60.0}, + } + ) + try: + result = engine.transcribe(audio, language="ru", prompt="domain context", duration_sec=20) + finally: + engine.close() + body = requests[0] + assert b'name="languages[]"\r\n\r\nru' in body + assert b'name="language"' not in body + assert b'name="keywords[]"' not in body + assert b'name="prompt"\r\n\r\ndomain context' in body + assert b'name="response_format"\r\n\r\njson' in body + assert result.text == "Test" + assert result.language == "ru" + assert result.duration_sec == 60 + assert result.cost_usd == Decimal("0.004500") + + +@pytest.mark.parametrize("model", ["whisper-1", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"]) +def test_existing_models_keep_singular_language(tmp_path, model): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, requests = _engine({"text": "test"}, model=model) + try: + result = engine.transcribe(audio, language="ru", duration_sec=60) + finally: + engine.close() + assert b'name="language"\r\n\r\nru' in requests[0] + assert b'name="languages[]"' not in requests[0] + assert result.language == "ru" + expected = Decimal("0.003000") if model == "gpt-4o-mini-transcribe" else Decimal("0.006000") + assert result.cost_usd == expected + + +@pytest.mark.parametrize("languages", [[], [{"code": "ru"}, {"code": "en"}]]) +def test_language_hint_is_not_reported_as_detected(tmp_path, languages): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, _ = _engine({"text": "text", "languages": languages}) + try: + assert engine.transcribe(audio, language="ru", duration_sec=1).language is None + finally: + engine.close() + + +@pytest.mark.parametrize( + "payload", + [ + [], + {"text": None}, + {"text": "x", "languages": ["ru"]}, + {"text": "x", "usage": {"type": "duration", "seconds": True}}, + ], +) +def test_invalid_response_rejected(tmp_path, payload): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, _ = _engine(payload) + try: + with pytest.raises(TranscriptionError): + engine.transcribe(audio) + finally: + engine.close() + + +def test_auto_language_omits_hints_and_uses_audio_duration_hint(tmp_path): + audio = tmp_path / "synthetic.wav" + audio.write_bytes(b"synthetic") + engine, requests = _engine({"text": "test", "languages": []}) + try: + result = engine.transcribe(audio, language=None, duration_sec=30) + finally: + engine.close() + assert b'name="languages[]"' not in requests[0] + assert result.duration_sec == 30 + assert result.cost_usd == Decimal("0.002250") 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" diff --git a/tests/unit/test_windows_compat.py b/tests/unit/test_windows_compat.py new file mode 100644 index 0000000..7bf1921 --- /dev/null +++ b/tests/unit/test_windows_compat.py @@ -0,0 +1,35 @@ +"""Cross-platform checks of Windows compatibility contracts.""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +def test_downloaded_ffmpeg_is_discovered(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + from voice_dictation.core import compressor + from voice_dictation.core.ffmpeg_setup import _EXE_NAME + + helper = tmp_path / ".dictate" / "bin" / _EXE_NAME + helper.parent.mkdir(parents=True) + helper.write_text("helper") + monkeypatch.setattr(Path, "home", lambda: tmp_path) + assert compressor._find_ffmpeg() == str(helper) + + +def test_autopaste_releases_hotkey_modifiers(monkeypatch: pytest.MonkeyPatch) -> None: + from voice_dictation.platform.windows import autopaste + + events: list[tuple[int, int, int, int]] = [] + monkeypatch.setattr( + autopaste.ctypes, + "windll", + SimpleNamespace(user32=SimpleNamespace(keybd_event=lambda *args: events.append(args))), + raising=False, + ) + monkeypatch.setattr(autopaste.time, "sleep", lambda _: None) + autopaste.WinAutoPaste().paste() + assert events[:4] == [(key, 0, 2, 0) for key in (0x11, 0x12, 0x10, 0x20)] + assert events[4:] == [(0x11, 0, 0, 0), (0x56, 0, 0, 0), (0x56, 0, 2, 0), (0x11, 0, 2, 0)]