Import current desktop app with resumable long recordings
This commit is contained in:
parent
70a5dce682
commit
8a6fd2e281
39 changed files with 2649 additions and 596 deletions
23
.gitignore
vendored
23
.gitignore
vendored
|
|
@ -42,3 +42,26 @@ assets/sounds/custom/
|
||||||
# Сборка инсталлятора (идёт в релиз, не в git)
|
# Сборка инсталлятора (идёт в релиз, не в git)
|
||||||
installer_output/
|
installer_output/
|
||||||
*_log.txt
|
*_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
|
||||||
|
|
|
||||||
|
|
@ -145,6 +145,13 @@ class Config:
|
||||||
dictionary_path: Path | None = None
|
dictionary_path: Path | None = None
|
||||||
auto_paste: bool = True
|
auto_paste: bool = True
|
||||||
paste_delay_ms: int = 80
|
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:
|
class ConfigStore:
|
||||||
def __init__(self, path: Path) -> None: ...
|
def __init__(self, path: Path) -> None: ...
|
||||||
|
|
@ -166,6 +173,9 @@ class AppPaths:
|
||||||
pid_file: Path # ~/.dictate/dictate.pid
|
pid_file: Path # ~/.dictate/dictate.pid
|
||||||
tmp_dir: Path # ~/.dictate/tmp/
|
tmp_dir: Path # ~/.dictate/tmp/
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sessions_dir(self) -> Path: ... # ~/.dictate/sessions/
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def default(cls) -> "AppPaths": ...
|
def default(cls) -> "AppPaths": ...
|
||||||
def ensure_exists(self) -> None: ...
|
def ensure_exists(self) -> None: ...
|
||||||
|
|
@ -190,7 +200,16 @@ class WhisperModel(StrEnum):
|
||||||
GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe"
|
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`.
|
**`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
|
state: IDLE → RECORDING
|
||||||
├── SoundPlayer.play(start_sound)
|
├── SoundPlayer.play(start_sound)
|
||||||
├── state_listener(RECORDING) → tray icon red
|
├── state_listener(RECORDING) → tray icon red
|
||||||
└── SoxRecorder.start(tmp.wav)
|
├── SessionStore.create()
|
||||||
|
└── SoxRecorder.start(sessions/<id>/source.wav)
|
||||||
|
|
||||||
... user speaks ...
|
... user speaks ...
|
||||||
|
|
||||||
|
|
@ -306,8 +326,17 @@ DictationError
|
||||||
│ (sanity: duration<0.3s OR size<4KB → skip, no API call)
|
│ (sanity: duration<0.3s OR size<4KB → skip, no API call)
|
||||||
│
|
│
|
||||||
└── ThreadPoolExecutor submit:
|
└── ThreadPoolExecutor submit:
|
||||||
├── prompt = Dictionary.build_prompt()
|
├── AudioCompressor.compress(source.wav → source.ogg)
|
||||||
├── result = Transcriber.transcribe(wav, prompt, language)
|
├── 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(...))
|
├── UsageDB.insert(UsageRecord(...))
|
||||||
├── Clipboard.copy(result.text)
|
├── Clipboard.copy(result.text)
|
||||||
├── AutoPaste.paste() (имитирует ⌘V/Ctrl+V)
|
├── AutoPaste.paste() (имитирует ⌘V/Ctrl+V)
|
||||||
|
|
@ -319,7 +348,8 @@ DictationError
|
||||||
- Main: pystray/Tk mainloop
|
- Main: pystray/Tk mainloop
|
||||||
- Hotkey: pynput внутренний
|
- Hotkey: pynput внутренний
|
||||||
- Worker: ThreadPoolExecutor (Whisper API)
|
- 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
|
├── app.log
|
||||||
├── dictate.pid
|
├── dictate.pid
|
||||||
├── sounds/ # custom sounds
|
├── sounds/ # custom sounds
|
||||||
└── tmp/ # session_*.wav, чистится при старте >1ч
|
├── tmp/ # legacy/temp
|
||||||
|
└── sessions/
|
||||||
|
└── <session-id>/
|
||||||
|
├── manifest.json
|
||||||
|
├── source.ogg # компактный восстанавливаемый оригинал
|
||||||
|
├── transcripts/ # raw checkpoint каждого API-вызова
|
||||||
|
└── transcript.txt # итоговая склейка
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
@ -395,7 +431,6 @@ CREATE INDEX idx_tx_created ON transcriptions(created_at);
|
||||||
## 6. Точки расширения
|
## 6. Точки расширения
|
||||||
|
|
||||||
- **Локальный whisper.cpp** — `Transcriber(Protocol)` + `LocalWhisperTranscriber`
|
- **Локальный whisper.cpp** — `Transcriber(Protocol)` + `LocalWhisperTranscriber`
|
||||||
- **Streaming-транскрипция** — `StreamingSoxRecorder.chunks() -> AsyncIterator[bytes]`
|
|
||||||
- **Post-processing GPT** — `PostProcessor(Protocol)` между transcribe и copy
|
- **Post-processing GPT** — `PostProcessor(Protocol)` между transcribe и copy
|
||||||
- **Workflows** — `Config.workflows: dict[str, WorkflowConfig]`, switch через tray
|
- **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 PID-файла | `os.open(O_CREAT\|O_EXCL)` + `psutil.pid_exists`; на win `msvcrt.locking` |
|
||||||
| Race condition в toggle | `threading.Lock`; повторный toggle в PROCESSING игнорируется |
|
| Race condition в toggle | `threading.Lock`; повторный toggle в PROCESSING игнорируется |
|
||||||
| Admin API Key утечка | Только `.env`; маскирование в логах `sk-admin-***` |
|
| Admin API Key утечка | Только `.env`; маскирование в логах `sk-admin-***` |
|
||||||
| sox не установлен | `shutil.which("sox")` на старте; фатальный диалог |
|
| ffmpeg не установлен | Короткие WAV работают; длинная запись сохраняется для повтора |
|
||||||
| Тишина / короткая запись | `duration<0.3s` или `size<4KB` → skip, нет API-вызова |
|
| Тишина / короткая запись | `duration<0.3s` или `size<4KB` → skip, нет API-вызова |
|
||||||
| OpenAI rate-limit/сеть | `httpx` retries=2 на 5xx/timeout |
|
| OpenAI rate-limit/сеть | `httpx` retries=2 на 5xx/timeout |
|
||||||
| Zombie sox-процесс | `__del__` + `atexit` шлют SIGTERM/kill |
|
| Zombie sox-процесс | `__del__` + `atexit` шлют SIGTERM/kill |
|
||||||
| customtkinter + pystray main thread | pystray на main, Tk-действия через `root.after(0, ...)` |
|
| customtkinter + pystray main thread | pystray на main, Tk-действия через `root.after(0, ...)` |
|
||||||
| Длинный транскрипт в чат | `>10000 chars` → только copy, без autopaste, toast |
|
| Длинный транскрипт в чат | `>10000 chars` → только copy, без autopaste, toast |
|
||||||
|
| Ответ API оборвался / сеть упала | 180-секундные чанки, raw checkpoint каждого ответа, resume при старте |
|
||||||
|
| VAD не нашёл паузу или ffmpeg-анализ упал | Фиксированная граница; режим и диагностика записываются в manifest |
|
||||||
|
| Падение во время записи | Потоковый WAV и обновление заголовка каждые 5 секунд |
|
||||||
| Хоткей конфликт | `register` возвращает bool; fallback на `cmd+shift+d` |
|
| Хоткей конфликт | `register` возвращает bool; fallback на `cmd+shift+d` |
|
||||||
| Словарь >224 токенов | `build_prompt` берёт хвост; UI счётчик `N/224` |
|
| Словарь >224 токенов | `build_prompt` берёт хвост; UI счётчик `N/224` |
|
||||||
|
|
||||||
|
|
|
||||||
260
CLAUDE.md
Normal file
260
CLAUDE.md
Normal file
|
|
@ -0,0 +1,260 @@
|
||||||
|
# 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/<id>/` и периодически обновляет заголовок, поэтому авария не уничтожает всю запись.
|
||||||
|
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-функций.
|
||||||
74
README.md
74
README.md
|
|
@ -1,24 +1,24 @@
|
||||||
# Voice Dictation
|
# Voice Dictation
|
||||||
|
|
||||||
Desktop-приложение для голосовой диктовки. Хоткей → запись с микрофона → Whisper API → автовставка текста в активное окно.
|
Desktop-приложение для голосовой диктовки. Хоткей → запись с микрофона →
|
||||||
|
надёжная транскрипция через OpenAI API → автовставка текста в активное окно.
|
||||||
|
|
||||||
## Требования
|
## Требования
|
||||||
|
|
||||||
- Python 3.11+
|
- Python 3.11+
|
||||||
- `sox` — для записи с микрофона
|
- `ffmpeg` — для сжатия и нарезки длинных записей
|
||||||
- OpenAI API Key
|
- OpenAI API Key
|
||||||
|
|
||||||
## Установка sox
|
## Установка ffmpeg
|
||||||
|
|
||||||
**macOS:**
|
**macOS:**
|
||||||
```bash
|
```bash
|
||||||
brew install sox
|
brew install ffmpeg
|
||||||
```
|
```
|
||||||
|
|
||||||
**Windows:**
|
**Windows:**
|
||||||
```
|
```
|
||||||
choco install sox
|
choco install ffmpeg
|
||||||
# или скачать с https://sourceforge.net/projects/sox/
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Установка приложения
|
## Установка приложения
|
||||||
|
|
@ -61,7 +61,7 @@ python -m voice_dictation headless
|
||||||
python -m voice_dictation stats
|
python -m voice_dictation stats
|
||||||
```
|
```
|
||||||
|
|
||||||
Хоткей по умолчанию: `Cmd+Space` (macOS) / `Ctrl+Alt+D` (Windows). Можно сменить
|
Хоткей по умолчанию: `Cmd+Alt+D` (macOS) / `Ctrl+Alt+D` (Windows). Можно сменить
|
||||||
в окне настроек (Tray → Настройки → Общие) или вручную в `~/.dictate/config.json`.
|
в окне настроек (Tray → Настройки → Общие) или вручную в `~/.dictate/config.json`.
|
||||||
|
|
||||||
Первое нажатие — начало записи. Второе — остановка, транскрипция, вставка в активное окно.
|
Первое нажатие — начало записи. Второе — остановка, транскрипция, вставка в активное окно.
|
||||||
|
|
@ -85,7 +85,7 @@ python -m voice_dictation stats
|
||||||
## Разрешения на macOS
|
## Разрешения на macOS
|
||||||
|
|
||||||
### Микрофон
|
### Микрофон
|
||||||
При первом запуске macOS запросит разрешение на доступ к микрофону для `sox`.
|
При первом запуске macOS запросит разрешение на доступ к микрофону.
|
||||||
Если разрешение не появилось: **Системные настройки → Конфиденциальность и безопасность → Микрофон** → включить Terminal/iTerm.
|
Если разрешение не появилось: **Системные настройки → Конфиденциальность и безопасность → Микрофон** → включить Terminal/iTerm.
|
||||||
|
|
||||||
### Accessibility (для автовставки Cmd+V)
|
### Accessibility (для автовставки Cmd+V)
|
||||||
|
|
@ -111,12 +111,65 @@ python -m voice_dictation stats
|
||||||
"notifications_enabled": true,
|
"notifications_enabled": true,
|
||||||
"show_cost_in_notification": true,
|
"show_cost_in_notification": true,
|
||||||
"sounds_enabled": 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`.
|
Статистика и история сохраняются в SQLite `~/.dictate/usage.db`.
|
||||||
|
|
||||||
|
## Длинные записи и восстановление
|
||||||
|
|
||||||
|
Каждая запись с первой секунды потоково сохраняется в отдельную папку
|
||||||
|
`~/.dictate/sessions/<session-id>/`. После остановки приложение:
|
||||||
|
|
||||||
|
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/<session-id>/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)
|
## Словарь (подсказки для Whisper)
|
||||||
|
|
||||||
Создайте файл `~/.dictate/dictionary.txt` — слова и фразы, которые Whisper должен правильно распознавать:
|
Создайте файл `~/.dictate/dictionary.txt` — слова и фразы, которые Whisper должен правильно распознавать:
|
||||||
|
|
@ -145,7 +198,8 @@ LaunchAgent запустит `python -m voice_dictation` при логине, п
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
**`sox: command not found`** — установите sox через brew/choco.
|
**`ffmpeg не найден`** — установите ffmpeg через brew/choco. Короткие записи
|
||||||
|
продолжат работать, длинные останутся сохранёнными до установки ffmpeg.
|
||||||
|
|
||||||
**Запись не останавливается** — проверьте разрешение микрофона.
|
**Запись не останавливается** — проверьте разрешение микрофона.
|
||||||
|
|
||||||
|
|
|
||||||
Binary file not shown.
BIN
assets/splash/dictator.png
Normal file
BIN
assets/splash/dictator.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
|
|
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "voice-dictation"
|
name = "voice-dictation"
|
||||||
version = "0.2.0"
|
version = "0.1.0"
|
||||||
description = "Desktop голосовая диктовка через Whisper API"
|
description = "Desktop голосовая диктовка через Whisper API"
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
|
@ -19,6 +19,8 @@ dependencies = [
|
||||||
"pystray>=0.19.5",
|
"pystray>=0.19.5",
|
||||||
"Pillow>=10.0.0",
|
"Pillow>=10.0.0",
|
||||||
"customtkinter>=5.2.0",
|
"customtkinter>=5.2.0",
|
||||||
|
"sounddevice>=0.4.6",
|
||||||
|
"openai>=1.40.0",
|
||||||
"winotify>=1.1.0; sys_platform == 'win32'",
|
"winotify>=1.1.0; sys_platform == 'win32'",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -92,6 +94,14 @@ module = [
|
||||||
"pynput.*",
|
"pynput.*",
|
||||||
"pyperclip.*",
|
"pyperclip.*",
|
||||||
"psutil.*",
|
"psutil.*",
|
||||||
|
"sounddevice.*",
|
||||||
|
"pystray.*",
|
||||||
|
"customtkinter.*",
|
||||||
|
"AppKit.*",
|
||||||
|
"ApplicationServices.*",
|
||||||
|
"Quartz.*",
|
||||||
|
"Foundation.*",
|
||||||
|
"PyObjCTools.*",
|
||||||
]
|
]
|
||||||
ignore_missing_imports = true
|
ignore_missing_imports = true
|
||||||
|
|
||||||
|
|
|
||||||
9
scripts/build_macos.sh
Normal file → Executable file
9
scripts/build_macos.sh
Normal file → Executable file
|
|
@ -63,11 +63,16 @@ fi
|
||||||
if [[ -d "${SYS_TCL_SCRIPTS}" && -d "${BUNDLE_TCL_DATA}" ]]; then
|
if [[ -d "${SYS_TCL_SCRIPTS}" && -d "${BUNDLE_TCL_DATA}" ]]; then
|
||||||
rm -rf "${BUNDLE_TCL_DATA}"
|
rm -rf "${BUNDLE_TCL_DATA}"
|
||||||
cp -R "${SYS_TCL_SCRIPTS}" "${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}"
|
echo " tcl: ${SYS_TCL_SCRIPTS} -> ${BUNDLE_TCL_DATA}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Пере-подписать app после изменений (ad-hoc, чтобы Gatekeeper не заплакал)
|
# Пере-подписать app после изменений (локальная ad-hoc подпись).
|
||||||
codesign --force --deep --sign - "${APP_PATH}" 2>/dev/null || true
|
xattr -cr "${APP_PATH}"
|
||||||
|
codesign --force --deep --sign - "${APP_PATH}"
|
||||||
|
codesign --verify --deep --strict "${APP_PATH}"
|
||||||
|
|
||||||
echo "[ШАГ 3/3] Готово!"
|
echo "[ШАГ 3/3] Готово!"
|
||||||
echo
|
echo
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,7 @@
|
||||||
|
|
||||||
<key>ProgramArguments</key>
|
<key>ProgramArguments</key>
|
||||||
<array>
|
<array>
|
||||||
<string>{{PYTHON_BIN}}</string>
|
<string>{{APP_EXECUTABLE}}</string>
|
||||||
<string>-m</string>
|
|
||||||
<string>voice_dictation</string>
|
|
||||||
</array>
|
</array>
|
||||||
|
|
||||||
<key>WorkingDirectory</key>
|
<key>WorkingDirectory</key>
|
||||||
|
|
|
||||||
17
scripts/install_autostart_macos.sh
Normal file → Executable file
17
scripts/install_autostart_macos.sh
Normal file → Executable file
|
|
@ -9,8 +9,8 @@ set -euo pipefail
|
||||||
LABEL="com.vickenty.voicedictation"
|
LABEL="com.vickenty.voicedictation"
|
||||||
PLIST_DEST="$HOME/Library/LaunchAgents/${LABEL}.plist"
|
PLIST_DEST="$HOME/Library/LaunchAgents/${LABEL}.plist"
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
|
||||||
TEMPLATE="${SCRIPT_DIR}/com.vickenty.voicedictation.plist.template"
|
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
|
if [[ "${1:-}" == "uninstall" ]]; then
|
||||||
launchctl unload "${PLIST_DEST}" 2>/dev/null || true
|
launchctl unload "${PLIST_DEST}" 2>/dev/null || true
|
||||||
|
|
@ -19,17 +19,15 @@ if [[ "${1:-}" == "uninstall" ]]; then
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Найти python из venv проекта (приоритет) или системный python3
|
if [[ ! -x "${APP_EXECUTABLE}" ]]; then
|
||||||
if [[ -x "${PROJECT_DIR}/.venv/bin/python" ]]; then
|
echo "[ОШИБКА] Не найдено установленное приложение: ${APP_EXECUTABLE}"
|
||||||
PYTHON_BIN="${PROJECT_DIR}/.venv/bin/python"
|
exit 1
|
||||||
else
|
|
||||||
PYTHON_BIN="$(command -v python3)"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$(dirname "${PLIST_DEST}")"
|
mkdir -p "$(dirname "${PLIST_DEST}")"
|
||||||
sed \
|
sed \
|
||||||
-e "s|{{PYTHON_BIN}}|${PYTHON_BIN}|g" \
|
-e "s|{{APP_EXECUTABLE}}|${APP_EXECUTABLE}|g" \
|
||||||
-e "s|{{WORKING_DIR}}|${PROJECT_DIR}|g" \
|
-e "s|{{WORKING_DIR}}|${HOME}/.dictate|g" \
|
||||||
-e "s|{{HOME}}|${HOME}|g" \
|
-e "s|{{HOME}}|${HOME}|g" \
|
||||||
"${TEMPLATE}" > "${PLIST_DEST}"
|
"${TEMPLATE}" > "${PLIST_DEST}"
|
||||||
|
|
||||||
|
|
@ -37,8 +35,7 @@ launchctl unload "${PLIST_DEST}" 2>/dev/null || true
|
||||||
launchctl load "${PLIST_DEST}"
|
launchctl load "${PLIST_DEST}"
|
||||||
|
|
||||||
echo "Установлено: ${PLIST_DEST}"
|
echo "Установлено: ${PLIST_DEST}"
|
||||||
echo "Python: ${PYTHON_BIN}"
|
echo "Приложение: ${APP_EXECUTABLE}"
|
||||||
echo "Проект: ${PROJECT_DIR}"
|
|
||||||
echo
|
echo
|
||||||
echo "Управление:"
|
echo "Управление:"
|
||||||
echo " launchctl unload ${PLIST_DEST} # остановить"
|
echo " launchctl unload ${PLIST_DEST} # остановить"
|
||||||
|
|
|
||||||
38
scripts/install_macos_app.sh
Executable file
38
scripts/install_macos_app.sh
Executable file
|
|
@ -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}"
|
||||||
|
|
@ -32,6 +32,7 @@ a = Analysis(
|
||||||
"voice_dictation.ui.settings_window",
|
"voice_dictation.ui.settings_window",
|
||||||
"voice_dictation.ui.tray",
|
"voice_dictation.ui.tray",
|
||||||
"voice_dictation.ui.icons",
|
"voice_dictation.ui.icons",
|
||||||
|
"voice_dictation.ui.splash",
|
||||||
"voice_dictation.platform.macos.autopaste",
|
"voice_dictation.platform.macos.autopaste",
|
||||||
"voice_dictation.platform.macos.clipboard",
|
"voice_dictation.platform.macos.clipboard",
|
||||||
"voice_dictation.platform.macos.hotkey_listener",
|
"voice_dictation.platform.macos.hotkey_listener",
|
||||||
|
|
@ -45,6 +46,7 @@ a = Analysis(
|
||||||
"voice_dictation.platform.windows.sound_player",
|
"voice_dictation.platform.windows.sound_player",
|
||||||
"voice_dictation.platform.windows.system_sounds_scanner",
|
"voice_dictation.platform.windows.system_sounds_scanner",
|
||||||
"voice_dictation.core.balance",
|
"voice_dictation.core.balance",
|
||||||
|
"voice_dictation.core.compressor",
|
||||||
"voice_dictation.core.fx",
|
"voice_dictation.core.fx",
|
||||||
"voice_dictation.core.usage_db",
|
"voice_dictation.core.usage_db",
|
||||||
"pkg_resources",
|
"pkg_resources",
|
||||||
|
|
@ -53,6 +55,8 @@ a = Analysis(
|
||||||
"darkdetect",
|
"darkdetect",
|
||||||
"pystray._darwin",
|
"pystray._darwin",
|
||||||
"PIL._tkinter_finder",
|
"PIL._tkinter_finder",
|
||||||
|
"sounddevice",
|
||||||
|
"openai",
|
||||||
],
|
],
|
||||||
hookspath=[],
|
hookspath=[],
|
||||||
hooksconfig={},
|
hooksconfig={},
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,4 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
__version__ = "0.2.0"
|
__version__ = "0.1.0"
|
||||||
|
|
|
||||||
|
|
@ -7,25 +7,14 @@ import signal
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
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:
|
def main() -> None:
|
||||||
"""Tray-режим: иконка в строке меню + хоткей.
|
"""Tray-режим: иконка в строке меню + хоткей.
|
||||||
|
|
||||||
|
|
@ -46,6 +35,10 @@ def main() -> None:
|
||||||
cli_main()
|
cli_main()
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "splash":
|
||||||
|
_run_splash_test()
|
||||||
|
return
|
||||||
|
|
||||||
from voice_dictation.infrastructure.env_loader import load_env
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -75,6 +68,13 @@ def main() -> None:
|
||||||
config = config_store.load()
|
config = config_store.load()
|
||||||
logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model)
|
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 (
|
from voice_dictation.infrastructure.errors import (
|
||||||
SoxNotFoundError,
|
SoxNotFoundError,
|
||||||
UnsupportedPlatformError,
|
UnsupportedPlatformError,
|
||||||
|
|
@ -91,7 +91,7 @@ def main() -> None:
|
||||||
from voice_dictation.core.recorder import SoxRecorder
|
from voice_dictation.core.recorder import SoxRecorder
|
||||||
|
|
||||||
try:
|
try:
|
||||||
recorder = SoxRecorder(sample_rate=16000, bin_dir=paths.bin_dir)
|
recorder = SoxRecorder(sample_rate=16000)
|
||||||
except SoxNotFoundError as exc:
|
except SoxNotFoundError as exc:
|
||||||
logger.error("%s", exc)
|
logger.error("%s", exc)
|
||||||
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
|
@ -101,6 +101,12 @@ def main() -> None:
|
||||||
|
|
||||||
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||||
|
|
||||||
|
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
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
|
||||||
dictionary = Dictionary(paths.dictionary_file)
|
dictionary = Dictionary(paths.dictionary_file)
|
||||||
|
|
@ -133,6 +139,7 @@ def main() -> None:
|
||||||
paths=paths,
|
paths=paths,
|
||||||
state_listener=_state_changed,
|
state_listener=_state_changed,
|
||||||
usage_db=usage_db,
|
usage_db=usage_db,
|
||||||
|
compressor=compressor,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Проверяем Accessibility — без неё NSEvent global monitor не получает событий
|
# Проверяем Accessibility — без неё NSEvent global monitor не получает событий
|
||||||
|
|
@ -157,6 +164,13 @@ def main() -> None:
|
||||||
logger.warning("Не удалось зарегистрировать %s, fallback %s", config.hotkey, fallback)
|
logger.warning("Не удалось зарегистрировать %s, fallback %s", config.hotkey, fallback)
|
||||||
platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle)
|
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:
|
def _show_stats() -> None:
|
||||||
tz = datetime.now().astimezone().tzinfo
|
tz = datetime.now().astimezone().tzinfo
|
||||||
today = usage_db.today_total(tz=tz)
|
today = usage_db.today_total(tz=tz)
|
||||||
|
|
@ -198,31 +212,41 @@ def main() -> None:
|
||||||
def _quit() -> None:
|
def _quit() -> None:
|
||||||
shutdown_event.set()
|
shutdown_event.set()
|
||||||
|
|
||||||
from voice_dictation.core.modes import all_specs, get_mode
|
def _select_preset(name: str) -> None:
|
||||||
|
|
||||||
def _list_modes() -> list[tuple[str, str]]:
|
|
||||||
cfg = config_store.current()
|
cfg = config_store.current()
|
||||||
return [(m.key, m.label) for m in all_specs(cfg.custom_modes)]
|
cfg.active_preset = name
|
||||||
|
|
||||||
def _select_mode(key: str) -> None:
|
|
||||||
cfg = config_store.current()
|
|
||||||
cfg.mode = key
|
|
||||||
config_store.save(cfg)
|
config_store.save(cfg)
|
||||||
spec = get_mode(key, cfg.custom_modes)
|
platform_bundle.notifier.show("Voice Dictation", f"Режим: {name}")
|
||||||
platform_bundle.notifier.show("Voice Dictator", f"Режим: {spec.label}")
|
logger.info("Preset выбран: %s", name)
|
||||||
logger.info("Режим переключён: mode=%s", key)
|
|
||||||
|
|
||||||
def _get_mode() -> str:
|
def _get_active_preset() -> str:
|
||||||
return config_store.current().mode
|
return config_store.current().active_preset
|
||||||
|
|
||||||
|
def _get_preset_names() -> list[str]:
|
||||||
|
return [p.name for p in config_store.current().summary_presets]
|
||||||
|
|
||||||
|
def _toggle_splash() -> bool:
|
||||||
|
cfg = config_store.current()
|
||||||
|
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.current().splash_enabled
|
||||||
|
|
||||||
tray = TrayApp(
|
tray = TrayApp(
|
||||||
on_toggle=orchestrator.toggle,
|
on_toggle=orchestrator.toggle,
|
||||||
on_settings=_show_settings,
|
on_settings=_show_settings,
|
||||||
on_stats=_show_stats,
|
on_stats=_show_stats,
|
||||||
on_quit=_quit,
|
on_quit=_quit,
|
||||||
modes_provider=_list_modes,
|
on_preset_select=_select_preset,
|
||||||
on_mode_select=_select_mode,
|
get_active_preset=_get_active_preset,
|
||||||
current_mode=_get_mode,
|
get_preset_names=_get_preset_names,
|
||||||
|
on_splash_toggle=_toggle_splash,
|
||||||
|
get_splash_state=_get_splash_state,
|
||||||
)
|
)
|
||||||
tray_holder["tray"] = tray
|
tray_holder["tray"] = tray
|
||||||
|
|
||||||
|
|
@ -248,7 +272,7 @@ def main() -> None:
|
||||||
|
|
||||||
threading.Thread(target=_watchdog, name="shutdown-watchdog", daemon=True).start()
|
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}")
|
print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
|
@ -261,5 +285,48 @@ def main() -> None:
|
||||||
logger.info("Voice Dictation остановлен")
|
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__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,13 @@ def main() -> None:
|
||||||
|
|
||||||
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||||
|
|
||||||
|
# 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
|
# 9. Dictionary
|
||||||
from voice_dictation.core.dictionary import Dictionary
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
|
||||||
|
|
@ -108,6 +115,7 @@ def main() -> None:
|
||||||
paths=paths,
|
paths=paths,
|
||||||
state_listener=_state_changed,
|
state_listener=_state_changed,
|
||||||
usage_db=usage_db,
|
usage_db=usage_db,
|
||||||
|
compressor=compressor,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 11. Регистрация хоткея
|
# 11. Регистрация хоткея
|
||||||
|
|
@ -117,6 +125,8 @@ def main() -> None:
|
||||||
fallback = "cmd+shift+d" if sys.platform == "darwin" else "ctrl+shift+d"
|
fallback = "cmd+shift+d" if sys.platform == "darwin" else "ctrl+shift+d"
|
||||||
platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle)
|
platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle)
|
||||||
|
|
||||||
|
orchestrator.resume_pending_sessions()
|
||||||
|
|
||||||
# 12. Обработчик сигналов для graceful shutdown
|
# 12. Обработчик сигналов для graceful shutdown
|
||||||
def _shutdown(signum: int, frame: object) -> None:
|
def _shutdown(signum: int, frame: object) -> None:
|
||||||
logger.info("Получен сигнал %d, завершение...", signum)
|
logger.info("Получен сигнал %d, завершение...", signum)
|
||||||
|
|
@ -128,15 +138,7 @@ def main() -> None:
|
||||||
signal.signal(signal.SIGTERM, _shutdown)
|
signal.signal(signal.SIGTERM, _shutdown)
|
||||||
signal.signal(signal.SIGINT, _shutdown)
|
signal.signal(signal.SIGINT, _shutdown)
|
||||||
|
|
||||||
if sys.platform == "darwin":
|
hotkey_display = config.hotkey.replace("cmd", "⌘").replace("alt", "⌥").replace("ctrl", "⌃")
|
||||||
hotkey_display = (
|
|
||||||
config.hotkey.replace("cmd", "⌘")
|
|
||||||
.replace("alt", "⌥")
|
|
||||||
.replace("ctrl", "⌃")
|
|
||||||
.replace("shift", "⇧")
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
hotkey_display = " + ".join(part.capitalize() for part in config.hotkey.split("+"))
|
|
||||||
print(
|
print(
|
||||||
f"Voice Dictation запущен. Хоткей: {hotkey_display}\n"
|
f"Voice Dictation запущен. Хоткей: {hotkey_display}\n"
|
||||||
"Нажмите хоткей для начала записи, ещё раз — для остановки и транскрипции.\n"
|
"Нажмите хоткей для начала записи, ещё раз — для остановки и транскрипции.\n"
|
||||||
|
|
|
||||||
416
src/voice_dictation/core/compressor.py
Normal file
416
src/voice_dictation/core/compressor.py
Normal file
|
|
@ -0,0 +1,416 @@
|
||||||
|
"""Сжатие аудио через ffmpeg в Opus/Ogg и выбор модели по длительности."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
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."""
|
||||||
|
found = shutil.which("ffmpeg")
|
||||||
|
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
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import dataclasses
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from dataclasses import asdict, dataclass, field
|
from dataclasses import asdict, dataclass, field
|
||||||
|
|
@ -10,6 +11,57 @@ from pathlib import Path
|
||||||
logger = logging.getLogger(__name__)
|
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)
|
@dataclass(slots=True)
|
||||||
class Config:
|
class Config:
|
||||||
"""Конфигурация приложения.
|
"""Конфигурация приложения.
|
||||||
|
|
@ -28,9 +80,21 @@ class Config:
|
||||||
dictionary_path: Путь к словарю (None — стандартный).
|
dictionary_path: Путь к словарю (None — стандартный).
|
||||||
auto_paste: Автоматически вставлять текст после транскрипции.
|
auto_paste: Автоматически вставлять текст после транскрипции.
|
||||||
paste_delay_ms: Задержка перед вставкой в миллисекундах.
|
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"
|
model: str = "gpt-4o-mini-transcribe"
|
||||||
language: str | None = "ru"
|
language: str | None = "ru"
|
||||||
notifications_enabled: bool = True
|
notifications_enabled: bool = True
|
||||||
|
|
@ -43,9 +107,18 @@ class Config:
|
||||||
dictionary_path: Path | None = None
|
dictionary_path: Path | None = None
|
||||||
auto_paste: bool = True
|
auto_paste: bool = True
|
||||||
paste_delay_ms: int = 80
|
paste_delay_ms: int = 80
|
||||||
mode: str = "raw" # ключ режима постобработки из core.modes
|
summary_presets: list[SummaryPreset] = field(default_factory=_default_presets)
|
||||||
proc_model: str = "gpt-4o-mini" # модель LLM для режимов постобработки
|
active_preset: str = "Диктовка"
|
||||||
custom_modes: dict[str, str] = field(default_factory=dict) # {название: промпт}
|
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_retention_days: int = 30
|
||||||
|
|
||||||
# Не включать в JSON-сериализацию
|
# Не включать в JSON-сериализацию
|
||||||
_path: Path | None = field(default=None, repr=False, compare=False)
|
_path: Path | None = field(default=None, repr=False, compare=False)
|
||||||
|
|
@ -54,7 +127,6 @@ class Config:
|
||||||
def _config_to_dict(config: Config) -> dict[str, object]:
|
def _config_to_dict(config: Config) -> dict[str, object]:
|
||||||
"""Сериализует Config в dict для JSON, конвертируя Path в строки."""
|
"""Сериализует Config в dict для JSON, конвертируя Path в строки."""
|
||||||
d = asdict(config)
|
d = asdict(config)
|
||||||
# Убираем приватное поле
|
|
||||||
d.pop("_path", None)
|
d.pop("_path", None)
|
||||||
for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"):
|
for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"):
|
||||||
if d[key] is not None:
|
if d[key] is not None:
|
||||||
|
|
@ -67,19 +139,22 @@ def _config_from_dict(data: dict[str, object]) -> Config:
|
||||||
kwargs: dict[str, object] = dict(data)
|
kwargs: dict[str, object] = dict(data)
|
||||||
kwargs.pop("_path", None)
|
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"):
|
for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"):
|
||||||
val = kwargs.get(key)
|
val = kwargs.get(key)
|
||||||
if val is not None and isinstance(val, str):
|
if val is not None and isinstance(val, str):
|
||||||
kwargs[key] = Path(val)
|
kwargs[key] = Path(val)
|
||||||
# Игнорируем неизвестные ключи из будущих версий конфига
|
|
||||||
import dataclasses
|
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)
|
||||||
|
]
|
||||||
|
|
||||||
known = {f.name for f in dataclasses.fields(Config)}
|
known = {f.name for f in dataclasses.fields(Config)}
|
||||||
filtered = {k: v for k, v in kwargs.items() if k in known}
|
filtered = {k: v for k, v in kwargs.items() if k in known}
|
||||||
|
|
|
||||||
|
|
@ -4,22 +4,37 @@ from __future__ import annotations
|
||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
import logging
|
import logging
|
||||||
|
import shutil
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
import wave
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from concurrent.futures import Future, ThreadPoolExecutor
|
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 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,
|
||||||
|
)
|
||||||
|
from voice_dictation.core.config import Config, SummaryPreset
|
||||||
from voice_dictation.core.dictionary import Dictionary
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
from voice_dictation.core.enums import RecordingState, SoundKind
|
from voice_dictation.core.enums import RecordingState, SoundKind
|
||||||
from voice_dictation.core.models import RecordingResult, TranscriptionResult, UsageRecord
|
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.paths import AppPaths
|
||||||
|
from voice_dictation.core.session_store import SessionStore
|
||||||
|
from voice_dictation.core.text_stitcher import stitch_transcripts
|
||||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
from voice_dictation.core.usage_db import UsageDB
|
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:
|
if TYPE_CHECKING:
|
||||||
from voice_dictation.platform.protocols import (
|
from voice_dictation.platform.protocols import (
|
||||||
|
|
@ -68,6 +83,8 @@ class DictationOrchestrator:
|
||||||
paths: AppPaths,
|
paths: AppPaths,
|
||||||
state_listener: Callable[[RecordingState], None] | None = None,
|
state_listener: Callable[[RecordingState], None] | None = None,
|
||||||
usage_db: UsageDB | None = None,
|
usage_db: UsageDB | None = None,
|
||||||
|
compressor: AudioCompressor | None = None,
|
||||||
|
session_store: SessionStore | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._recorder = recorder
|
self._recorder = recorder
|
||||||
self._transcriber = transcriber
|
self._transcriber = transcriber
|
||||||
|
|
@ -80,12 +97,19 @@ class DictationOrchestrator:
|
||||||
self._paths = paths
|
self._paths = paths
|
||||||
self._state_listener = state_listener
|
self._state_listener = state_listener
|
||||||
self._usage_db = usage_db
|
self._usage_db = usage_db
|
||||||
|
self._compressor = compressor
|
||||||
|
self._session_store = session_store or SessionStore(paths.sessions_dir)
|
||||||
|
|
||||||
self._state = RecordingState.IDLE
|
self._state = RecordingState.IDLE
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="whisper")
|
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="whisper")
|
||||||
self._current_future: Future[None] | None = None
|
self._current_future: Future[None] | None = None
|
||||||
|
|
||||||
|
config = self._config_provider()
|
||||||
|
removed = self._session_store.cleanup_completed_audio(config.audio_retention_days)
|
||||||
|
if removed:
|
||||||
|
logger.info("Удалено старых аудиоартефактов: %d", removed)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self) -> RecordingState:
|
def state(self) -> RecordingState:
|
||||||
"""Текущее состояние оркестратора."""
|
"""Текущее состояние оркестратора."""
|
||||||
|
|
@ -110,18 +134,27 @@ class DictationOrchestrator:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self._state != RecordingState.RECORDING:
|
if self._state != RecordingState.RECORDING:
|
||||||
return
|
return
|
||||||
with contextlib.suppress(RecorderError):
|
try:
|
||||||
self._recorder.stop()
|
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)
|
self._set_state(RecordingState.IDLE)
|
||||||
logger.info("Запись отменена")
|
logger.info("Запись отменена")
|
||||||
|
|
||||||
def _start_recording(self) -> None:
|
def _start_recording(self) -> None:
|
||||||
"""Запускает запись (вызывается внутри lock)."""
|
"""Запускает запись (вызывается внутри lock)."""
|
||||||
config = self._config_provider()
|
config = self._config_provider()
|
||||||
output_path = self._paths.tmp_dir / f"session_{int(time.time() * 1000)}.wav"
|
output_path = self._session_store.create()
|
||||||
try:
|
try:
|
||||||
self._recorder.start(output_path)
|
self._recorder.start(output_path)
|
||||||
except RecorderError as exc:
|
except RecorderError as exc:
|
||||||
|
self._session_store.mark_failed(output_path.parent, str(exc))
|
||||||
logger.error("Не удалось начать запись: %s", exc)
|
logger.error("Не удалось начать запись: %s", exc)
|
||||||
self._set_state(RecordingState.ERROR)
|
self._set_state(RecordingState.ERROR)
|
||||||
self._sound_player.play(SoundKind.ERROR, config=config)
|
self._sound_player.play(SoundKind.ERROR, config=config)
|
||||||
|
|
@ -148,35 +181,264 @@ class DictationOrchestrator:
|
||||||
|
|
||||||
self._set_state(RecordingState.PROCESSING)
|
self._set_state(RecordingState.PROCESSING)
|
||||||
self._sound_player.play(SoundKind.STOP, config=config)
|
self._sound_player.play(SoundKind.STOP, config=config)
|
||||||
|
self._session_store.mark_recorded(recording.path, recording.duration_sec)
|
||||||
|
|
||||||
# Запрос к API — в отдельном потоке, не блокируем hotkey
|
# Запрос к API — в отдельном потоке, не блокируем hotkey
|
||||||
self._current_future = self._executor.submit(self._process_recording, recording, config)
|
self._current_future = self._executor.submit(self._process_recording, recording, config)
|
||||||
|
|
||||||
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,
|
||||||
|
) -> None:
|
||||||
"""Транскрибирует запись и вставляет текст (выполняется в worker-потоке).
|
"""Транскрибирует запись и вставляет текст (выполняется в worker-потоке).
|
||||||
|
|
||||||
|
Pipeline: архивный Opus → перекрывающиеся фрагменты → API checkpoint-ы
|
||||||
|
→ безопасная склейка. Ни исходник, ни уже полученные ответы при ошибке
|
||||||
|
не удаляются.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
recording: Результат записи.
|
recording: Результат записи.
|
||||||
config: Текущая конфигурация.
|
config: Текущая конфигурация.
|
||||||
"""
|
"""
|
||||||
|
session_dir = recording.path.parent
|
||||||
try:
|
try:
|
||||||
prompt = self._dictionary.build_prompt()
|
result = self._transcribe_session(recording, config)
|
||||||
|
self._on_transcription_success(
|
||||||
|
result,
|
||||||
|
config,
|
||||||
|
finalize_state=finalize_state,
|
||||||
|
allow_auto_paste=allow_auto_paste,
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
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),
|
||||||
|
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"
|
||||||
|
audio_source = recording.path
|
||||||
|
|
||||||
|
if archive_path.exists() and archive_path.stat().st_size > 0:
|
||||||
|
audio_source = archive_path
|
||||||
|
elif 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
|
||||||
|
|
||||||
|
chunking = self._prepare_chunks(recording, audio_source, config)
|
||||||
|
chunks = chunking.chunks
|
||||||
|
self._session_store.update(
|
||||||
|
session_dir,
|
||||||
|
status="processing",
|
||||||
|
model=config.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(
|
result = self._transcriber.transcribe(
|
||||||
recording.path,
|
chunk.path,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
language=config.language,
|
language=config.language,
|
||||||
|
model=config.model,
|
||||||
|
duration_sec=chunk.duration_sec,
|
||||||
)
|
)
|
||||||
self._on_transcription_success(result, config)
|
self._session_store.save_chunk_result(session_dir, chunk.index, result)
|
||||||
except TranscriptionError as exc:
|
results.append(result)
|
||||||
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)
|
|
||||||
|
|
||||||
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)
|
||||||
|
return TranscriptionResult(
|
||||||
|
text=stitch.text,
|
||||||
|
duration_sec=recording.duration_sec,
|
||||||
|
model=config.model,
|
||||||
|
language=next(
|
||||||
|
(result.language for result in results if result.language),
|
||||||
|
config.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 recording.duration_sec <= config.chunk_duration_sec:
|
||||||
|
if 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 _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,
|
||||||
|
) -> None:
|
||||||
"""Обрабатывает успешную транскрипцию.
|
"""Обрабатывает успешную транскрипцию.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|
@ -185,6 +447,7 @@ class DictationOrchestrator:
|
||||||
"""
|
"""
|
||||||
if not result.text:
|
if not result.text:
|
||||||
logger.info("Транскрипция вернула пустой текст")
|
logger.info("Транскрипция вернула пустой текст")
|
||||||
|
if finalize_state:
|
||||||
self._set_state(RecordingState.IDLE)
|
self._set_state(RecordingState.IDLE)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -213,27 +476,32 @@ class DictationOrchestrator:
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("Не удалось записать UsageRecord: %s", exc)
|
logger.warning("Не удалось записать UsageRecord: %s", exc)
|
||||||
|
|
||||||
# Постобработка: гоним текст через LLM по выбранному режиму
|
# Post-processing через активный пресет (если есть и не пустой)
|
||||||
final_text = result.text
|
final_text = result.text
|
||||||
mode = get_mode(config.mode, config.custom_modes)
|
active = self._resolve_active_preset(config)
|
||||||
if mode.uses_llm:
|
if active is not None and active.prompt.strip() and active.model.strip():
|
||||||
try:
|
try:
|
||||||
final_text = self._post_process(result.text, mode.prompt, config)
|
final_text = self._summarize(result.text, active)
|
||||||
logger.info(
|
logger.info(
|
||||||
"Режим '%s' готов: %d → %d символов",
|
"Summary (%s): %d → %d символов",
|
||||||
mode.key,
|
active.name,
|
||||||
len(result.text),
|
len(result.text),
|
||||||
len(final_text),
|
len(final_text),
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.error("Ошибка постобработки (%s): %s, вставляю оригинал", mode.key, exc)
|
logger.error(
|
||||||
|
"Ошибка summary (preset=%s): %s, вставляю оригинал",
|
||||||
|
active.name,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
final_text = result.text
|
||||||
|
|
||||||
self._clipboard.copy(final_text)
|
self._clipboard.copy(final_text)
|
||||||
|
|
||||||
if config.notifications_enabled:
|
if config.notifications_enabled:
|
||||||
from voice_dictation.core.fx import get_rate, usd_to_rub
|
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} симв."]
|
summary_parts = [f"{result.duration_sec:.1f}с · {chars} симв."]
|
||||||
if config.show_cost_in_notification:
|
if config.show_cost_in_notification:
|
||||||
rate = get_rate()
|
rate = get_rate()
|
||||||
|
|
@ -250,45 +518,50 @@ class DictationOrchestrator:
|
||||||
summary_parts.append(today_part)
|
summary_parts.append(today_part)
|
||||||
self._notifier.show("Диктовка готова", " · ".join(summary_parts))
|
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:
|
if config.paste_delay_ms > 0:
|
||||||
time.sleep(config.paste_delay_ms / 1000)
|
time.sleep(config.paste_delay_ms / 1000)
|
||||||
self._auto_paste.paste()
|
self._auto_paste.paste()
|
||||||
elif len(result.text) > _MAX_AUTOPASTE_CHARS:
|
elif len(final_text) > _MAX_AUTOPASTE_CHARS:
|
||||||
# Слишком длинный текст — только буфер, без вставки
|
|
||||||
chars = len(result.text)
|
|
||||||
self._notifier.show(
|
self._notifier.show(
|
||||||
"Текст скопирован",
|
"Текст скопирован",
|
||||||
f"Слишком длинный для автовставки ({chars} символов). Вставьте вручную Cmd+V.",
|
f"Слишком длинный для автовставки ({len(final_text)} симв.). Вставьте вручную ⌘V.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if finalize_state:
|
||||||
self._set_state(RecordingState.IDLE)
|
self._set_state(RecordingState.IDLE)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _post_process(text: str, prompt: str, config: Config) -> str:
|
def _resolve_active_preset(config: Config) -> SummaryPreset | None:
|
||||||
"""Прогоняет текст через LLM с заданным промптом режима.
|
"""Находит активный пресет по имени из config.active_preset."""
|
||||||
|
for preset in config.summary_presets:
|
||||||
|
if preset.name == config.active_preset:
|
||||||
|
return preset
|
||||||
|
return None
|
||||||
|
|
||||||
Args:
|
@staticmethod
|
||||||
text: Исходная транскрипция.
|
def _summarize(text: str, preset: SummaryPreset) -> str:
|
||||||
prompt: Системная инструкция режима.
|
"""Отправляет текст в OpenAI для post-processing по пресету."""
|
||||||
config: Конфигурация (модель в proc_model).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Обработанный текст; исходный, если LLM вернул пусто.
|
|
||||||
"""
|
|
||||||
from openai import OpenAI
|
from openai import OpenAI
|
||||||
|
|
||||||
client = OpenAI()
|
client = OpenAI()
|
||||||
resp = client.chat.completions.create(
|
resp = client.chat.completions.create(
|
||||||
model=config.proc_model,
|
model=preset.model,
|
||||||
messages=[
|
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:
|
Args:
|
||||||
|
|
@ -297,6 +570,7 @@ class DictationOrchestrator:
|
||||||
"""
|
"""
|
||||||
self._sound_player.play(SoundKind.ERROR, config=config)
|
self._sound_player.play(SoundKind.ERROR, config=config)
|
||||||
self._notifier.show("Ошибка транскрипции", message)
|
self._notifier.show("Ошибка транскрипции", message)
|
||||||
|
if finalize_state:
|
||||||
self._set_state(RecordingState.IDLE)
|
self._set_state(RecordingState.IDLE)
|
||||||
|
|
||||||
def _set_state(self, new_state: RecordingState) -> None:
|
def _set_state(self, new_state: RecordingState) -> None:
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,6 @@ class AppPaths:
|
||||||
log_file: Path
|
log_file: Path
|
||||||
pid_file: Path
|
pid_file: Path
|
||||||
tmp_dir: Path
|
tmp_dir: Path
|
||||||
bin_dir: Path
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def default(cls) -> AppPaths:
|
def default(cls) -> AppPaths:
|
||||||
|
|
@ -48,7 +47,6 @@ class AppPaths:
|
||||||
log_file=root / "app.log",
|
log_file=root / "app.log",
|
||||||
pid_file=root / "dictate.pid",
|
pid_file=root / "dictate.pid",
|
||||||
tmp_dir=root / "tmp",
|
tmp_dir=root / "tmp",
|
||||||
bin_dir=root / "bin",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def ensure_exists(self) -> AppPaths:
|
def ensure_exists(self) -> AppPaths:
|
||||||
|
|
@ -57,6 +55,16 @@ class AppPaths:
|
||||||
Returns:
|
Returns:
|
||||||
self для удобства цепочки вызовов.
|
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,
|
||||||
|
):
|
||||||
directory.mkdir(parents=True, exist_ok=True)
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sessions_dir(self) -> Path:
|
||||||
|
"""Постоянные аудиосессии и промежуточные результаты транскрипции."""
|
||||||
|
return self.root / "sessions"
|
||||||
|
|
|
||||||
|
|
@ -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
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import queue
|
||||||
import struct
|
import struct
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING, Any
|
||||||
|
|
||||||
from voice_dictation.core.models import RecordingResult
|
from voice_dictation.core.models import RecordingResult
|
||||||
from voice_dictation.infrastructure.errors import RecorderError
|
from voice_dictation.infrastructure.errors import RecorderError
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
pass
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_MIN_DURATION_SEC = 0.3
|
_MIN_DURATION_SEC = 0.3
|
||||||
_MIN_FILE_SIZE_BYTES = 4 * 1024 # 4 KB
|
_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:
|
class SoxRecorder:
|
||||||
"""Запись WAV с микрофона через sounddevice.
|
"""Запись WAV с микрофона через `sounddevice.RawInputStream`.
|
||||||
|
|
||||||
|
Имя класса оставлено для обратной совместимости с импортами в `__main__`
|
||||||
|
и тестах. Sox больше не используется.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
sample_rate: Частота дискретизации (по умолчанию 16000 Гц).
|
sample_rate: Частота дискретизации в Гц (по умолчанию 16000).
|
||||||
channels: Количество каналов (по умолчанию 1 — моно).
|
channels: Количество каналов (по умолчанию 1 — моно).
|
||||||
bin_dir: Каталог докачанных бинарников (для поиска ffmpeg).
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, sample_rate: int = 16000, channels: int = 1) -> None:
|
||||||
self, sample_rate: int = 16000, channels: int = 1, bin_dir: Path | None = None
|
|
||||||
) -> None:
|
|
||||||
try:
|
try:
|
||||||
import sounddevice # noqa: F401
|
import sounddevice # noqa: F401
|
||||||
except ImportError:
|
except ImportError as exc:
|
||||||
raise RecorderError(
|
raise RecorderError(
|
||||||
"sounddevice не установлен. pip install sounddevice"
|
'sounddevice не установлен. Запустите `pip install -e ".[dev]"`',
|
||||||
)
|
) from exc
|
||||||
self._sample_rate = sample_rate
|
self._sample_rate = sample_rate
|
||||||
self._channels = channels
|
self._channels = channels
|
||||||
self._bin_dir = bin_dir
|
self._stream: Any = None
|
||||||
self._frames: list[bytes] = []
|
|
||||||
self._stream = None
|
|
||||||
self._output_path: Path | None = None
|
self._output_path: Path | None = None
|
||||||
self._start_time: float | None = None
|
self._start_time: float | None = None
|
||||||
self._lock = threading.Lock()
|
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:
|
def start(self, output_path: Path) -> None:
|
||||||
"""Начинает запись в указанный файл."""
|
"""Начинает запись в указанный файл.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
output_path: Путь для сохранения WAV-файла.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RecorderError: Если запись уже идёт или поток не запустился.
|
||||||
|
"""
|
||||||
import sounddevice as sd
|
import sounddevice as sd
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
|
|
@ -53,13 +77,24 @@ class SoxRecorder:
|
||||||
raise RecorderError("Запись уже запущена")
|
raise RecorderError("Запись уже запущена")
|
||||||
|
|
||||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
self._frames = []
|
|
||||||
self._output_path = output_path
|
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:
|
if status:
|
||||||
logger.warning("sounddevice status: %s", 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:
|
try:
|
||||||
self._stream = sd.RawInputStream(
|
self._stream = sd.RawInputStream(
|
||||||
|
|
@ -67,18 +102,28 @@ class SoxRecorder:
|
||||||
channels=self._channels,
|
channels=self._channels,
|
||||||
dtype="int16",
|
dtype="int16",
|
||||||
callback=callback,
|
callback=callback,
|
||||||
blocksize=1024,
|
blocksize=_BLOCKSIZE,
|
||||||
)
|
)
|
||||||
self._stream.start()
|
self._stream.start()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._stream = None
|
self._stream = None
|
||||||
|
self._finish_writer()
|
||||||
|
output_path.unlink(missing_ok=True)
|
||||||
raise RecorderError(f"Не удалось начать запись: {exc}") from exc
|
raise RecorderError(f"Не удалось начать запись: {exc}") from exc
|
||||||
|
|
||||||
self._start_time = time.monotonic()
|
self._start_time = time.monotonic()
|
||||||
logger.debug("Запись начата: %s", output_path)
|
logger.debug("Запись начата: %s", output_path)
|
||||||
|
|
||||||
def stop(self) -> RecordingResult:
|
def stop(self) -> RecordingResult:
|
||||||
"""Останавливает запись и возвращает результат."""
|
"""Останавливает запись и возвращает результат.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RecordingResult с путём к WAV и длительностью.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RecorderError: Если запись не была запущена, нет данных,
|
||||||
|
запись слишком короткая или файл слишком маленький.
|
||||||
|
"""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
if self._stream is None or self._output_path is None:
|
if self._stream is None or self._output_path is None:
|
||||||
raise RecorderError("Запись не запущена")
|
raise RecorderError("Запись не запущена")
|
||||||
|
|
@ -94,105 +139,110 @@ class SoxRecorder:
|
||||||
|
|
||||||
self._stream = None
|
self._stream = None
|
||||||
self._output_path = None
|
self._output_path = None
|
||||||
elapsed = time.monotonic() - (self._start_time or 0)
|
|
||||||
self._start_time = None
|
self._start_time = None
|
||||||
|
self._finish_writer()
|
||||||
|
|
||||||
# Собираем все фреймы в один буфер
|
if self._writer_error is not None:
|
||||||
audio_data = b"".join(self._frames)
|
raise RecorderError(f"Ошибка записи WAV на диск: {self._writer_error}")
|
||||||
self._frames = []
|
if self._data_size == 0:
|
||||||
|
|
||||||
if not audio_data:
|
|
||||||
raise RecorderError("Нет записанных данных")
|
raise RecorderError("Нет записанных данных")
|
||||||
|
|
||||||
duration_sec = len(audio_data) / (self._sample_rate * self._channels * 2)
|
duration_sec = self._data_size / (
|
||||||
|
self._sample_rate * self._channels * _SAMPLE_WIDTH_BYTES
|
||||||
# Конвертируем в 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)
|
|
||||||
|
|
||||||
file_size = output_path.stat().st_size
|
file_size = output_path.stat().st_size
|
||||||
|
|
||||||
if duration_sec < _MIN_DURATION_SEC:
|
if duration_sec < _MIN_DURATION_SEC:
|
||||||
output_path.unlink(missing_ok=True)
|
output_path.unlink(missing_ok=True)
|
||||||
raise RecorderError(
|
raise RecorderError(
|
||||||
f"Запись слишком короткая: {duration_sec:.2f}с"
|
f"Запись слишком короткая: {duration_sec:.2f}с (минимум {_MIN_DURATION_SEC}с)",
|
||||||
)
|
)
|
||||||
if file_size < _MIN_FILE_SIZE_BYTES:
|
if file_size < _MIN_FILE_SIZE_BYTES:
|
||||||
output_path.unlink(missing_ok=True)
|
output_path.unlink(missing_ok=True)
|
||||||
raise RecorderError(
|
raise RecorderError(
|
||||||
f"Файл слишком маленький: {file_size} байт"
|
f"Файл слишком маленький: {file_size} байт (минимум {_MIN_FILE_SIZE_BYTES})",
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.debug("Запись остановлена: %.2fс, %d байт", duration_sec, file_size)
|
logger.debug("Запись остановлена: %.2fс, %d байт", duration_sec, file_size)
|
||||||
return RecordingResult(path=output_path, duration_sec=duration_sec)
|
return RecordingResult(path=output_path, duration_sec=duration_sec)
|
||||||
|
|
||||||
def _write_wav(self, path: Path, data: bytes) -> None:
|
def _write_stream(
|
||||||
"""Записывает корректный WAV-файл."""
|
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
|
num_channels = self._channels
|
||||||
sample_width = 2 # 16-bit
|
sample_width = _SAMPLE_WIDTH_BYTES
|
||||||
byte_rate = self._sample_rate * num_channels * sample_width
|
byte_rate = self._sample_rate * num_channels * sample_width
|
||||||
block_align = num_channels * sample_width
|
block_align = num_channels * sample_width
|
||||||
data_size = len(data)
|
|
||||||
file_size = 36 + data_size
|
file_size = 36 + data_size
|
||||||
|
return b"".join(
|
||||||
with open(path, "wb") as f:
|
(
|
||||||
# RIFF header
|
b"RIFF",
|
||||||
f.write(b"RIFF")
|
struct.pack("<I", file_size),
|
||||||
f.write(struct.pack("<I", file_size))
|
b"WAVE",
|
||||||
f.write(b"WAVE")
|
b"fmt ",
|
||||||
# fmt chunk
|
struct.pack("<I", 16),
|
||||||
f.write(b"fmt ")
|
struct.pack("<H", 1),
|
||||||
f.write(struct.pack("<I", 16)) # chunk size
|
struct.pack("<H", num_channels),
|
||||||
f.write(struct.pack("<H", 1)) # PCM
|
struct.pack("<I", self._sample_rate),
|
||||||
f.write(struct.pack("<H", num_channels))
|
struct.pack("<I", byte_rate),
|
||||||
f.write(struct.pack("<I", self._sample_rate))
|
struct.pack("<H", block_align),
|
||||||
f.write(struct.pack("<I", byte_rate))
|
struct.pack("<H", sample_width * 8),
|
||||||
f.write(struct.pack("<H", block_align))
|
b"data",
|
||||||
f.write(struct.pack("<H", sample_width * 8))
|
struct.pack("<I", data_size),
|
||||||
# data chunk
|
)
|
||||||
f.write(b"data")
|
)
|
||||||
f.write(struct.pack("<I", data_size))
|
|
||||||
f.write(data)
|
|
||||||
|
|
||||||
def _write_ogg(self, data: bytes, path: Path) -> 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}")
|
|
||||||
|
|
||||||
def __del__(self) -> None:
|
def __del__(self) -> None:
|
||||||
|
"""Гарантированно останавливает stream при уничтожении объекта."""
|
||||||
if self._stream is not None:
|
if self._stream is not None:
|
||||||
try:
|
try:
|
||||||
self._stream.stop()
|
self._stream.stop()
|
||||||
self._stream.close()
|
self._stream.close()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
self._finish_writer()
|
||||||
|
|
|
||||||
193
src/voice_dictation/core/session_store.py
Normal file
193
src/voice_dictation/core/session_store.py
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
"""Долговечное хранилище аудиосессий и checkpoint-ов транскрипции."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
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) -> Path:
|
||||||
|
"""Создаёт сессию и возвращает путь для потоковой записи WAV."""
|
||||||
|
now = datetime.now(tz=UTC)
|
||||||
|
session_id = f"{now.strftime('%Y%m%dT%H%M%SZ')}_{uuid4().hex[:8]}"
|
||||||
|
session_dir = self._sessions_dir / session_id
|
||||||
|
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 pending(self) -> list[Path]:
|
||||||
|
"""Возвращает незавершённые сессии, для которых осталось аудио."""
|
||||||
|
pending: list[Path] = []
|
||||||
|
for session_dir in sorted(self._sessions_dir.iterdir()):
|
||||||
|
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._sessions_dir.iterdir():
|
||||||
|
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)
|
||||||
67
src/voice_dictation/core/text_stitcher.py
Normal file
67
src/voice_dictation/core/text_stitcher.py
Normal file
|
|
@ -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))
|
||||||
|
|
@ -17,9 +17,32 @@ from voice_dictation.infrastructure.errors import TranscriptionError, WhisperAPI
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_API_URL = "https://api.openai.com/v1/audio/transcriptions"
|
_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
|
_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:
|
class WhisperTranscriber:
|
||||||
"""Транскрипция WAV-файлов через OpenAI Whisper API.
|
"""Транскрипция WAV-файлов через OpenAI Whisper API.
|
||||||
|
|
@ -32,23 +55,25 @@ class WhisperTranscriber:
|
||||||
def __init__(self, api_key: str, model: str = "gpt-4o-mini-transcribe") -> None:
|
def __init__(self, api_key: str, model: str = "gpt-4o-mini-transcribe") -> None:
|
||||||
self._api_key = api_key
|
self._api_key = api_key
|
||||||
self._model = model
|
self._model = model
|
||||||
self._client = httpx.Client(
|
# Клиент без статического timeout — таймаут задаётся на каждый запрос по длине аудио.
|
||||||
headers={"Authorization": f"Bearer {api_key}"},
|
self._client = httpx.Client(headers={"Authorization": f"Bearer {api_key}"})
|
||||||
timeout=_TIMEOUT_SEC,
|
|
||||||
)
|
|
||||||
|
|
||||||
def transcribe(
|
def transcribe(
|
||||||
self,
|
self,
|
||||||
audio_path: Path,
|
audio_path: Path,
|
||||||
prompt: str = "",
|
prompt: str = "",
|
||||||
language: str | None = None,
|
language: str | None = None,
|
||||||
|
model: str | None = None,
|
||||||
|
duration_sec: float | None = None,
|
||||||
) -> TranscriptionResult:
|
) -> TranscriptionResult:
|
||||||
"""Отправляет WAV в Whisper API и возвращает результат.
|
"""Отправляет аудио в Whisper API и возвращает результат.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
audio_path: Путь к WAV-файлу.
|
audio_path: Путь к аудио-файлу (wav/ogg/mp3/m4a/flac/webm).
|
||||||
prompt: Подсказка со специальными словами.
|
prompt: Подсказка со специальными словами.
|
||||||
language: Код языка (None — автоопределение).
|
language: Код языка (None — автоопределение).
|
||||||
|
model: Переопределяет модель на этот один вызов (None — использует self._model).
|
||||||
|
duration_sec: Длительность аудио для расчёта таймаута.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
TranscriptionResult с текстом и метаданными.
|
TranscriptionResult с текстом и метаданными.
|
||||||
|
|
@ -58,11 +83,21 @@ class WhisperTranscriber:
|
||||||
WhisperAPIError: При HTTP-ошибке от API.
|
WhisperAPIError: При HTTP-ошибке от API.
|
||||||
"""
|
"""
|
||||||
requested_at = datetime.now(tz=UTC)
|
requested_at = datetime.now(tz=UTC)
|
||||||
|
effective_model = model or self._model
|
||||||
|
timeout = _compute_timeout(duration_sec)
|
||||||
|
|
||||||
last_exc: Exception | None = None
|
last_exc: Exception | None = None
|
||||||
for attempt in range(_MAX_RETRIES + 1):
|
for attempt in range(_MAX_RETRIES + 1):
|
||||||
try:
|
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
|
return result
|
||||||
except WhisperAPIError as exc:
|
except WhisperAPIError as exc:
|
||||||
# Не ретраим 4xx — это клиентские ошибки
|
# Не ретраим 4xx — это клиентские ошибки
|
||||||
|
|
@ -91,14 +126,19 @@ class WhisperTranscriber:
|
||||||
prompt: str,
|
prompt: str,
|
||||||
language: str | None,
|
language: str | None,
|
||||||
requested_at: datetime,
|
requested_at: datetime,
|
||||||
|
model: str,
|
||||||
|
timeout: float,
|
||||||
|
duration_hint: float | None,
|
||||||
) -> TranscriptionResult:
|
) -> TranscriptionResult:
|
||||||
"""Выполняет один HTTP-запрос к Whisper API.
|
"""Выполняет один HTTP-запрос к Whisper API.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
audio_path: Путь к WAV.
|
audio_path: Путь к аудио-файлу.
|
||||||
prompt: Подсказка.
|
prompt: Подсказка.
|
||||||
language: Код языка.
|
language: Код языка.
|
||||||
requested_at: Время запроса.
|
requested_at: Время запроса.
|
||||||
|
model: Модель для этого запроса.
|
||||||
|
timeout: Таймаут HTTP-запроса.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
TranscriptionResult.
|
TranscriptionResult.
|
||||||
|
|
@ -107,9 +147,9 @@ class WhisperTranscriber:
|
||||||
WhisperAPIError: При HTTP-ошибке.
|
WhisperAPIError: При HTTP-ошибке.
|
||||||
TranscriptionError: При сетевой ошибке или невалидном JSON.
|
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] = {
|
data: dict[str, str] = {
|
||||||
"model": self._model,
|
"model": model,
|
||||||
"response_format": response_format,
|
"response_format": response_format,
|
||||||
}
|
}
|
||||||
if language:
|
if language:
|
||||||
|
|
@ -117,12 +157,15 @@ class WhisperTranscriber:
|
||||||
if prompt:
|
if prompt:
|
||||||
data["prompt"] = prompt
|
data["prompt"] = prompt
|
||||||
|
|
||||||
|
content_type = _content_type_for(audio_path)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with audio_path.open("rb") as audio_file:
|
with audio_path.open("rb") as audio_file:
|
||||||
response = self._client.post(
|
response = self._client.post(
|
||||||
_API_URL,
|
_API_URL,
|
||||||
data=data,
|
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:
|
except httpx.TimeoutException as exc:
|
||||||
raise TranscriptionError(f"Timeout при запросе к Whisper API: {exc}") from exc
|
raise TranscriptionError(f"Timeout при запросе к Whisper API: {exc}") from exc
|
||||||
|
|
@ -141,19 +184,24 @@ class WhisperTranscriber:
|
||||||
raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc
|
raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc
|
||||||
|
|
||||||
text: str = body.get("text", "").strip()
|
text: str = body.get("text", "").strip()
|
||||||
duration_sec: float = float(body.get("duration", 0.0)) or _wav_duration(audio_path)
|
api_duration = float(body.get("duration", 0.0))
|
||||||
|
duration_sec: float = (
|
||||||
|
api_duration
|
||||||
|
or (duration_hint if duration_hint and duration_hint > 0 else 0.0)
|
||||||
|
or _wav_duration(audio_path)
|
||||||
|
)
|
||||||
detected_language: str | None = body.get("language") or language
|
detected_language: str | None = body.get("language") or language
|
||||||
|
|
||||||
cost = PriceCalculator.cost(self._model, duration_sec)
|
cost = PriceCalculator.cost(model, duration_sec)
|
||||||
|
|
||||||
return TranscriptionResult(
|
return TranscriptionResult(
|
||||||
text=text,
|
text=text,
|
||||||
duration_sec=duration_sec,
|
duration_sec=duration_sec,
|
||||||
model=self._model,
|
model=model,
|
||||||
language=detected_language,
|
language=detected_language,
|
||||||
prompt_used=prompt or None,
|
prompt_used=prompt or None,
|
||||||
requested_at=requested_at,
|
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:
|
def close(self) -> None:
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import threading
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from dataclasses import dataclass
|
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 decimal import Decimal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
@ -110,17 +110,18 @@ class UsageDB:
|
||||||
text_preview=preview,
|
text_preview=preview,
|
||||||
)
|
)
|
||||||
|
|
||||||
def today_total(self, tz: timezone = UTC) -> UsageStats:
|
def today_total(self, tz: tzinfo | None = None) -> UsageStats:
|
||||||
"""Статистика за сегодня в указанной TZ.
|
"""Статистика за сегодня в указанной TZ.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tz: Часовой пояс для определения "сегодня".
|
tz: Часовой пояс для определения "сегодня". None → UTC.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
UsageStats за текущий день.
|
UsageStats за текущий день.
|
||||||
"""
|
"""
|
||||||
now_local = datetime.now(tz)
|
effective_tz: tzinfo = tz if tz is not None else UTC
|
||||||
start_local = datetime.combine(now_local.date(), time.min, tzinfo=tz)
|
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)
|
end_local = start_local + timedelta(days=1)
|
||||||
return self.stats(start_local, end_local)
|
return self.stats(start_local, end_local)
|
||||||
|
|
||||||
|
|
@ -196,20 +197,21 @@ class UsageDB:
|
||||||
total_cost_usd=Decimal(str(total_cost)).quantize(Decimal("0.000001")),
|
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:
|
Args:
|
||||||
year: Год.
|
year: Год.
|
||||||
month: Месяц (1-12).
|
month: Месяц (1-12).
|
||||||
tz: Часовой пояс.
|
tz: Часовой пояс. None → UTC.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
UsageStats за указанный месяц.
|
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:
|
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:
|
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)
|
return self.stats(start, end)
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
@ -36,14 +37,17 @@ def load_env() -> EnvConfig:
|
||||||
Raises:
|
Raises:
|
||||||
ConfigError: Если OPENAI_API_KEY не задан или пустой.
|
ConfigError: Если OPENAI_API_KEY не задан или пустой.
|
||||||
"""
|
"""
|
||||||
# Ищем .env: рядом с exe → cwd → ~/.dictate/
|
# Ищем .env: рядом с exe (для PyInstaller-сборки) → cwd → ~/.dictate/
|
||||||
import sys
|
is_frozen = bool(getattr(sys, "frozen", False))
|
||||||
exe_dir = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path.cwd()
|
candidates = []
|
||||||
candidates = [
|
if is_frozen:
|
||||||
exe_dir / ".env",
|
candidates.append(Path(sys.executable).parent / ".env")
|
||||||
|
candidates.extend(
|
||||||
|
[
|
||||||
Path.cwd() / ".env",
|
Path.cwd() / ".env",
|
||||||
Path.home() / ".dictate" / ".env",
|
Path.home() / ".dictate" / ".env",
|
||||||
]
|
]
|
||||||
|
)
|
||||||
for candidate in candidates:
|
for candidate in candidates:
|
||||||
if candidate.exists():
|
if candidate.exists():
|
||||||
load_dotenv(candidate, override=False)
|
load_dotenv(candidate, override=False)
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,10 @@ class SoxNotFoundError(RecorderError):
|
||||||
"""sox не найден в системном PATH."""
|
"""sox не найден в системном PATH."""
|
||||||
|
|
||||||
|
|
||||||
|
class CompressionError(DictationError):
|
||||||
|
"""Ошибка сжатия аудио (ffmpeg недоступен/упал)."""
|
||||||
|
|
||||||
|
|
||||||
class TranscriptionError(DictationError):
|
class TranscriptionError(DictationError):
|
||||||
"""Ошибка транскрипции (сеть, парсинг)."""
|
"""Ошибка транскрипции (сеть, парсинг)."""
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -20,19 +20,66 @@ logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Карта имён клавиш в virtual key codes macOS
|
# Карта имён клавиш в virtual key codes macOS
|
||||||
_KEY_CODES: dict[str, int] = {
|
_KEY_CODES: dict[str, int] = {
|
||||||
"a": 0x00, "s": 0x01, "d": 0x02, "f": 0x03, "h": 0x04, "g": 0x05,
|
"a": 0x00,
|
||||||
"z": 0x06, "x": 0x07, "c": 0x08, "v": 0x09, "b": 0x0B, "q": 0x0C,
|
"s": 0x01,
|
||||||
"w": 0x0D, "e": 0x0E, "r": 0x0F, "y": 0x10, "t": 0x11,
|
"d": 0x02,
|
||||||
"1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17,
|
"f": 0x03,
|
||||||
"9": 0x19, "7": 0x1A, "8": 0x1C, "0": 0x1D,
|
"h": 0x04,
|
||||||
"o": 0x1F, "u": 0x20, "i": 0x22, "p": 0x23,
|
"g": 0x05,
|
||||||
"l": 0x25, "j": 0x26, "k": 0x28, "n": 0x2D, "m": 0x2E,
|
"z": 0x06,
|
||||||
"space": 0x31, "tab": 0x30, "enter": 0x24, "return": 0x24,
|
"x": 0x07,
|
||||||
"escape": 0x35, "esc": 0x35, "delete": 0x33, "backspace": 0x33,
|
"c": 0x08,
|
||||||
"f1": 0x7A, "f2": 0x78, "f3": 0x63, "f4": 0x76, "f5": 0x60,
|
"v": 0x09,
|
||||||
"f6": 0x61, "f7": 0x62, "f8": 0x64, "f9": 0x65, "f10": 0x6D,
|
"b": 0x0B,
|
||||||
"f11": 0x67, "f12": 0x6F,
|
"q": 0x0C,
|
||||||
"left": 0x7B, "right": 0x7C, "down": 0x7D, "up": 0x7E,
|
"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"}
|
_MODIFIER_TOKENS = {"cmd", "command", "ctrl", "control", "alt", "option", "shift", "super"}
|
||||||
|
|
@ -167,8 +214,10 @@ class MacHotkeyListener:
|
||||||
|
|
||||||
def _runner() -> None:
|
def _runner() -> None:
|
||||||
try:
|
try:
|
||||||
# Маленькая задержка, чтобы система успела вставить символ
|
# Задержка: дать (1) системе вставить символ в активное поле,
|
||||||
time.sleep(0.02)
|
# (2) пользователю отпустить Cmd. Иначе Backspace уйдёт с
|
||||||
|
# зажатым Cmd → Cmd+Backspace = удалить до начала строки.
|
||||||
|
time.sleep(0.12)
|
||||||
_send_backspace_via_quartz()
|
_send_backspace_via_quartz()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.debug("Не удалось послать Backspace: %s", exc)
|
logger.debug("Не удалось послать Backspace: %s", exc)
|
||||||
|
|
@ -180,27 +229,32 @@ class MacHotkeyListener:
|
||||||
return _wrapped
|
return _wrapped
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
"""Регистрирует NSEvent monitor и блокирует поток до stop().
|
"""Регистрирует NSEvent global monitor на main thread (non-blocking).
|
||||||
|
|
||||||
В этом методе крутится NSRunLoop текущего потока. Если callback нужен
|
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_ требует, чтобы
|
||||||
в главном потоке (например, для AppKit), вызывайте start() из главного.
|
callback приходил на main run loop. Если регистрировать в worker-потоке,
|
||||||
|
события не доставляются в наш handler (main runloop занят pystray).
|
||||||
|
Поэтому регистрация откладывается на main через AppHelper.callAfter —
|
||||||
|
как только pystray.run() запустит main runloop, регистрация выполнится
|
||||||
|
и callbacks пойдут в этот же runloop.
|
||||||
|
|
||||||
|
Метод non-blocking: возвращает управление сразу.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
PlatformError: Если нет хоткеев или AppKit недоступен.
|
PlatformError: Если нет хоткеев или AppKit/PyObjC недоступны.
|
||||||
"""
|
"""
|
||||||
if not self._hotkeys:
|
if not self._hotkeys:
|
||||||
raise PlatformError("Нет зарегистрированных хоткеев")
|
raise PlatformError("Нет зарегистрированных хоткеев")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from AppKit import NSEvent, NSEventMaskKeyDown
|
from AppKit import NSEvent, NSEventMaskKeyDown
|
||||||
from Foundation import NSDate, NSDefaultRunLoopMode, NSRunLoop
|
from PyObjCTools import AppHelper
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
raise PlatformError("AppKit/Foundation недоступны (PyObjC)") from exc
|
raise PlatformError("AppKit/PyObjC недоступны") from exc
|
||||||
|
|
||||||
all_mods = _all_modifier_flags()
|
all_mods = _all_modifier_flags()
|
||||||
|
|
||||||
registered = [(sorted(mods), main) for (mods, main, *_) in self._hotkeys]
|
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:
|
def _handler(event: Any) -> None:
|
||||||
try:
|
try:
|
||||||
|
|
@ -216,45 +270,63 @@ class MacHotkeyListener:
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("Ошибка в NSEvent handler: %s", exc)
|
logger.exception("Ошибка в NSEvent handler: %s", exc)
|
||||||
|
|
||||||
|
def _do_register() -> None:
|
||||||
self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
|
self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
|
||||||
NSEventMaskKeyDown, _handler
|
NSEventMaskKeyDown, _handler
|
||||||
)
|
)
|
||||||
|
|
||||||
if self._monitor is None:
|
if self._monitor is None:
|
||||||
raise PlatformError(
|
logger.error(
|
||||||
"Не удалось создать NSEvent global monitor — нужны права Accessibility"
|
"NSEvent global monitor не создался — нужны Accessibility + Input Monitoring",
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
logger.info("NSEvent global monitor зарегистрирован на main thread")
|
||||||
|
|
||||||
# Блокируем поток, пока не вызовут stop()
|
AppHelper.callAfter(_do_register)
|
||||||
run_loop = NSRunLoop.currentRunLoop()
|
|
||||||
while not self._stop_event.is_set():
|
|
||||||
run_loop.runMode_beforeDate_(
|
|
||||||
NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow_(0.5)
|
|
||||||
)
|
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
"""Останавливает слушатель."""
|
"""Снимает NSEvent monitor (на main thread)."""
|
||||||
self._stop_event.set()
|
self._stop_event.set()
|
||||||
if self._monitor is not None:
|
if self._monitor is None:
|
||||||
|
return
|
||||||
try:
|
try:
|
||||||
from AppKit import NSEvent
|
from AppKit import NSEvent
|
||||||
|
from PyObjCTools import AppHelper
|
||||||
|
|
||||||
NSEvent.removeMonitor_(self._monitor)
|
monitor = self._monitor
|
||||||
|
|
||||||
|
def _do_remove() -> None:
|
||||||
|
try:
|
||||||
|
NSEvent.removeMonitor_(monitor)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.debug("Ошибка снятия NSEvent monitor: %s", 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
|
self._monitor = None
|
||||||
|
|
||||||
|
|
||||||
def _send_backspace_via_quartz() -> None:
|
def _send_backspace_via_quartz() -> None:
|
||||||
"""Эмулирует нажатие Backspace через Quartz CGEvent (без pynput)."""
|
"""Эмулирует чистый Backspace через Quartz CGEvent.
|
||||||
|
|
||||||
|
Критично явно обнулить modifierFlags на событии: иначе CGEvent наследует
|
||||||
|
текущие физические модификаторы (если юзер ещё держит Cmd после хоткея)
|
||||||
|
→ получаем Cmd+Backspace = «удалить до начала строки», то есть стираем
|
||||||
|
весь набранный текст вместо одного символа-пробела.
|
||||||
|
"""
|
||||||
from Quartz import (
|
from Quartz import (
|
||||||
CGEventCreateKeyboardEvent,
|
CGEventCreateKeyboardEvent,
|
||||||
CGEventPost,
|
CGEventPost,
|
||||||
|
CGEventSetFlags,
|
||||||
kCGHIDEventTap,
|
kCGHIDEventTap,
|
||||||
)
|
)
|
||||||
|
|
||||||
keycode = 0x33 # Backspace virtual key code
|
keycode = 0x33 # Backspace virtual key code
|
||||||
down = CGEventCreateKeyboardEvent(None, keycode, True)
|
down = CGEventCreateKeyboardEvent(None, keycode, True)
|
||||||
up = CGEventCreateKeyboardEvent(None, keycode, False)
|
up = CGEventCreateKeyboardEvent(None, keycode, False)
|
||||||
|
# Обнуляем флаги модификаторов — стираем ОДИН символ, не до начала строки.
|
||||||
|
CGEventSetFlags(down, 0)
|
||||||
|
CGEventSetFlags(up, 0)
|
||||||
CGEventPost(kCGHIDEventTap, down)
|
CGEventPost(kCGHIDEventTap, down)
|
||||||
CGEventPost(kCGHIDEventTap, up)
|
CGEventPost(kCGHIDEventTap, up)
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
"""Автовставка на Windows через Win32 keybd_event (Ctrl+V)."""
|
"""Автовставка на Windows через pynput (Ctrl+V)."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ctypes
|
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
|
@ -10,13 +9,9 @@ from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
VK_CONTROL = 0x11
|
|
||||||
VK_V = 0x56
|
|
||||||
KEYEVENTF_KEYUP = 0x0002
|
|
||||||
|
|
||||||
|
|
||||||
class WinAutoPaste:
|
class WinAutoPaste:
|
||||||
"""Имитирует Ctrl+V через Win32 keybd_event.
|
"""Имитирует Ctrl+V в активном окне через pynput.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
||||||
|
|
@ -26,27 +21,25 @@ class WinAutoPaste:
|
||||||
self._paste_delay_ms = paste_delay_ms
|
self._paste_delay_ms = paste_delay_ms
|
||||||
|
|
||||||
def paste(self) -> None:
|
def paste(self) -> None:
|
||||||
"""Нажимает Ctrl+V в активном окне."""
|
"""Нажимает Ctrl+V в активном окне.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если pynput не может отправить событие.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from pynput.keyboard import Controller, Key
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("pynput не установлен") from exc
|
||||||
|
|
||||||
if self._paste_delay_ms > 0:
|
if self._paste_delay_ms > 0:
|
||||||
time.sleep(self._paste_delay_ms / 1000)
|
time.sleep(self._paste_delay_ms / 1000)
|
||||||
|
|
||||||
|
keyboard = Controller()
|
||||||
try:
|
try:
|
||||||
# Отпускаем все модификаторы которые могут быть зажаты
|
with keyboard.pressed(Key.ctrl):
|
||||||
ctypes.windll.user32.keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0)
|
keyboard.press("v")
|
||||||
ctypes.windll.user32.keybd_event(0x12, 0, KEYEVENTF_KEYUP, 0) # Alt
|
keyboard.release("v")
|
||||||
ctypes.windll.user32.keybd_event(0x10, 0, KEYEVENTF_KEYUP, 0) # Shift
|
|
||||||
ctypes.windll.user32.keybd_event(0x20, 0, KEYEVENTF_KEYUP, 0) # Space
|
|
||||||
time.sleep(0.5)
|
|
||||||
|
|
||||||
# Ctrl+V
|
|
||||||
ctypes.windll.user32.keybd_event(VK_CONTROL, 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)
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc
|
raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc
|
||||||
|
|
||||||
logger.debug("WinAutoPaste: Ctrl+V выполнен (keybd_event)")
|
logger.debug("WinAutoPaste: Ctrl+V выполнен")
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,9 @@ def _play_file(path: Path) -> None:
|
||||||
try:
|
try:
|
||||||
import winsound
|
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:
|
except Exception as exc:
|
||||||
logger.warning("winsound не удалось воспроизвести %s: %s", path, exc)
|
logger.warning("winsound не удалось воспроизвести %s: %s", path, exc)
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,9 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import sys
|
|
||||||
import threading
|
import threading
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
from dataclasses import replace
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tkinter import filedialog
|
from tkinter import filedialog
|
||||||
|
|
@ -22,11 +22,7 @@ if TYPE_CHECKING:
|
||||||
from voice_dictation.platform.protocols import HotkeyListener, SystemSoundsScanner
|
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"]
|
_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"]
|
_MODELS = ["gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1"]
|
||||||
_LANGUAGES = ["ru", "en", "auto"]
|
_LANGUAGES = ["ru", "en", "auto"]
|
||||||
|
|
||||||
|
|
@ -43,8 +39,9 @@ Transcription, MacWhisper) либо платные, либо неудобные,
|
||||||
═══ Что под капотом ═══
|
═══ Что под капотом ═══
|
||||||
|
|
||||||
• Хоткей — pynput GlobalHotKeys (macOS Cmd+Space по умолчанию)
|
• Хоткей — pynput GlobalHotKeys (macOS Cmd+Space по умолчанию)
|
||||||
• Запись — sox subprocess, 16 kHz mono WAV
|
• Запись — sounddevice, потоковый 16 kHz mono WAV
|
||||||
• Транскрипция — OpenAI Whisper API (gpt-4o-mini-transcribe, ~$0.003/мин)
|
• Надёжность — сессии на диске, чанки с overlap, resume после сбоя
|
||||||
|
• Транскрипция — OpenAI Audio API (gpt-4o-mini-transcribe, ~$0.003/мин)
|
||||||
• Словарь — ~/.dictate/dictionary.txt с подсказками для Whisper
|
• Словарь — ~/.dictate/dictionary.txt с подсказками для Whisper
|
||||||
• Автовставка — pbcopy + Cmd+V через pynput
|
• Автовставка — pbcopy + Cmd+V через pynput
|
||||||
• Звуки — afplay + системные звуки macOS (Tink/Pop/Basso)
|
• Звуки — afplay + системные звуки macOS (Tink/Pop/Basso)
|
||||||
|
|
@ -73,7 +70,7 @@ Transcription, MacWhisper) либо платные, либо неудобные,
|
||||||
• Этап 4 — tray icon с динамической иконкой
|
• Этап 4 — tray icon с динамической иконкой
|
||||||
• Этап 5 — окно настроек (5 табов на customtkinter)
|
• Этап 5 — окно настроек (5 табов на customtkinter)
|
||||||
• Этап 6 — баланс OpenAI через Admin API
|
• Этап 6 — баланс OpenAI через Admin API
|
||||||
• Этап 7 — линтер (ruff), 44 теста, README, autostart-скрипт
|
• Этап 7 — линтер (ruff), тесты, README, autostart-скрипт
|
||||||
|
|
||||||
4. Багфиксы по ходу:
|
4. Багфиксы по ходу:
|
||||||
• verbose_json не работает с gpt-4o-mini → переключение на json
|
• verbose_json не работает с gpt-4o-mini → переключение на json
|
||||||
|
|
@ -117,20 +114,6 @@ personal/voice-dictation/
|
||||||
https://flowmasters.ru/
|
https://flowmasters.ru/
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_CHANGELOG = """═══ Что нового ═══
|
|
||||||
|
|
||||||
v0.2.0
|
|
||||||
• Режимы обработки вместо одной галочки Summary: Чистая диктовка,
|
|
||||||
Чистовик (без паразитов), Summary, Переводчик RU→EN, Промпт для
|
|
||||||
LLM, Буллеты, Деловое письмо. Выбор в трее → «Режим обработки».
|
|
||||||
• Свои стили: таб «Стили» — пишешь название и промпт, режим
|
|
||||||
появляется в трее.
|
|
||||||
|
|
||||||
v0.1.0
|
|
||||||
• Первая версия под Windows: запись, Whisper, автовставка, трей,
|
|
||||||
звуки, статистика, баланс, установщик.
|
|
||||||
"""
|
|
||||||
|
|
||||||
_window_lock = threading.Lock()
|
_window_lock = threading.Lock()
|
||||||
_window_holder: dict[str, SettingsWindow] = {}
|
_window_holder: dict[str, SettingsWindow] = {}
|
||||||
|
|
||||||
|
|
@ -248,7 +231,9 @@ class SettingsWindow:
|
||||||
# с LSUIElement=true Tk-окно создаётся, но прячется за активным приложением.
|
# с LSUIElement=true Tk-окно создаётся, но прячется за активным приложением.
|
||||||
_activate_app()
|
_activate_app()
|
||||||
self._root.after(50, self._root.lift)
|
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(
|
self._root.after(
|
||||||
500, lambda: self._root.attributes("-topmost", False) if self._root else None
|
500, lambda: self._root.attributes("-topmost", False) if self._root else None
|
||||||
)
|
)
|
||||||
|
|
@ -258,7 +243,6 @@ class SettingsWindow:
|
||||||
tabs.pack(fill="both", expand=True, padx=12, pady=12)
|
tabs.pack(fill="both", expand=True, padx=12, pady=12)
|
||||||
|
|
||||||
general_tab = tabs.add("Общие")
|
general_tab = tabs.add("Общие")
|
||||||
styles_tab = tabs.add("Стили")
|
|
||||||
sound_tab = tabs.add("Звук")
|
sound_tab = tabs.add("Звук")
|
||||||
dictionary_tab = tabs.add("Словарь")
|
dictionary_tab = tabs.add("Словарь")
|
||||||
stats_tab = tabs.add("Статистика")
|
stats_tab = tabs.add("Статистика")
|
||||||
|
|
@ -266,7 +250,6 @@ class SettingsWindow:
|
||||||
about_tab = tabs.add("О проекте")
|
about_tab = tabs.add("О проекте")
|
||||||
|
|
||||||
self._build_general_tab(general_tab, config)
|
self._build_general_tab(general_tab, config)
|
||||||
self._build_styles_tab(styles_tab, config)
|
|
||||||
self._build_sound_tab(sound_tab, config)
|
self._build_sound_tab(sound_tab, config)
|
||||||
self._build_dictionary_tab(dictionary_tab)
|
self._build_dictionary_tab(dictionary_tab)
|
||||||
self._build_stats_tab(stats_tab)
|
self._build_stats_tab(stats_tab)
|
||||||
|
|
@ -340,12 +323,10 @@ class SettingsWindow:
|
||||||
row += 1
|
row += 1
|
||||||
|
|
||||||
def _save_general() -> None:
|
def _save_general() -> None:
|
||||||
import dataclasses
|
|
||||||
|
|
||||||
language_choice = language_var.get()
|
language_choice = language_var.get()
|
||||||
new_hotkey = hotkey_var.get().strip().lower()
|
new_hotkey = hotkey_var.get().strip().lower()
|
||||||
current = self._config_store.current()
|
current = self._config_store.current()
|
||||||
updated = dataclasses.replace(
|
updated = replace(
|
||||||
current,
|
current,
|
||||||
hotkey=new_hotkey,
|
hotkey=new_hotkey,
|
||||||
model=model_var.get(),
|
model=model_var.get(),
|
||||||
|
|
@ -365,122 +346,6 @@ class SettingsWindow:
|
||||||
row=row, column=0, columnspan=2, pady=14
|
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
|
|
||||||
|
|
||||||
assert isinstance(config, Config)
|
|
||||||
|
|
||||||
ctk.CTkLabel(
|
|
||||||
parent,
|
|
||||||
text=(
|
|
||||||
"Свои стили обработки. Название появится в меню «Режим обработки» в трее, "
|
|
||||||
"промпт — это инструкция для LLM (что сделать с надиктованным текстом)."
|
|
||||||
),
|
|
||||||
anchor="w",
|
|
||||||
wraplength=660,
|
|
||||||
justify="left",
|
|
||||||
).pack(fill="x", padx=8, pady=(8, 4))
|
|
||||||
|
|
||||||
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)
|
|
||||||
)
|
|
||||||
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))
|
|
||||||
|
|
||||||
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
|
|
||||||
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)
|
|
||||||
self._toast("Стили сохранены. Доступны в меню трея.")
|
|
||||||
|
|
||||||
ctk.CTkButton(parent, text="Сохранить", command=_save_styles).pack(pady=10)
|
|
||||||
|
|
||||||
def _build_sound_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
def _build_sound_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
||||||
from voice_dictation.core.config import Config
|
from voice_dictation.core.config import Config
|
||||||
|
|
||||||
|
|
@ -508,14 +373,6 @@ class SettingsWindow:
|
||||||
stop_var = ctk.StringVar(value=_name_of(config.stop_sound_path))
|
stop_var = ctk.StringVar(value=_name_of(config.stop_sound_path))
|
||||||
error_var = ctk.StringVar(value=_name_of(config.error_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(
|
for row, (label, var) in enumerate(
|
||||||
[("Старт записи:", start_var), ("Остановка:", stop_var), ("Ошибка:", error_var)],
|
[("Старт записи:", start_var), ("Остановка:", stop_var), ("Ошибка:", error_var)],
|
||||||
start=2,
|
start=2,
|
||||||
|
|
@ -524,18 +381,18 @@ class SettingsWindow:
|
||||||
ctk.CTkComboBox(parent, values=sound_options, variable=var, width=240).grid(
|
ctk.CTkComboBox(parent, values=sound_options, variable=var, width=240).grid(
|
||||||
row=row, column=1, sticky="w", padx=8, pady=8
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
)
|
)
|
||||||
ctk.CTkButton(
|
|
||||||
parent,
|
def _resolve(name: str) -> Path | None:
|
||||||
text="▶",
|
if name == sound_options[0]:
|
||||||
width=36,
|
return None
|
||||||
command=lambda v=var: self._preview_sound(_resolve(v.get())),
|
for s in self._system_sounds:
|
||||||
).grid(row=row, column=2, sticky="w", padx=4, pady=8)
|
if s.name == name:
|
||||||
|
return s.path
|
||||||
|
return None
|
||||||
|
|
||||||
def _save_sound() -> None:
|
def _save_sound() -> None:
|
||||||
import dataclasses
|
|
||||||
|
|
||||||
current = self._config_store.current()
|
current = self._config_store.current()
|
||||||
updated = dataclasses.replace(
|
updated = replace(
|
||||||
current,
|
current,
|
||||||
sounds_enabled=sounds_enabled_var.get(),
|
sounds_enabled=sounds_enabled_var.get(),
|
||||||
volume=float(volume_var.get()),
|
volume=float(volume_var.get()),
|
||||||
|
|
@ -698,18 +555,9 @@ class SettingsWindow:
|
||||||
ctk.CTkButton(parent, text="Получить баланс", command=_fetch).pack(padx=8, pady=8)
|
ctk.CTkButton(parent, text="Получить баланс", command=_fetch).pack(padx=8, pady=8)
|
||||||
|
|
||||||
def _build_about_tab(self, parent: ctk.CTkFrame) -> None:
|
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 = ctk.CTkTextbox(parent, wrap="word")
|
||||||
text_widget.pack(fill="both", expand=True, padx=8, pady=8)
|
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")
|
text_widget.configure(state="disabled")
|
||||||
|
|
||||||
controls = ctk.CTkFrame(parent, fg_color="transparent")
|
controls = ctk.CTkFrame(parent, fg_color="transparent")
|
||||||
|
|
@ -720,9 +568,7 @@ class SettingsWindow:
|
||||||
|
|
||||||
webbrowser.open("https://flowmasters.ru/")
|
webbrowser.open("https://flowmasters.ru/")
|
||||||
|
|
||||||
ctk.CTkButton(controls, text="flowmasters.ru", command=_open_site).pack(
|
ctk.CTkButton(controls, text="flowmasters.ru", command=_open_site).pack(side="left", padx=4)
|
||||||
side="left", padx=4
|
|
||||||
)
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------ helpers
|
# ------------------------------------------------------------------ helpers
|
||||||
|
|
||||||
|
|
@ -738,34 +584,6 @@ class SettingsWindow:
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("Не удалось перерегистрировать хоткей: %s", 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:
|
def _toast(self, message: str) -> None:
|
||||||
if self._root is None:
|
if self._root is None:
|
||||||
return
|
return
|
||||||
|
|
|
||||||
154
src/voice_dictation/ui/splash.py
Normal file
154
src/voice_dictation/ui/splash.py
Normal file
|
|
@ -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("<Button-1>", _close)
|
||||||
|
root.bind("<Escape>", _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]
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import functools
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
|
@ -24,6 +25,11 @@ class TrayApp:
|
||||||
on_stats: Колбэк при клике "Статистика".
|
on_stats: Колбэк при клике "Статистика".
|
||||||
on_quit: Колбэк при клике "Выход".
|
on_quit: Колбэк при клике "Выход".
|
||||||
title: Заголовок tray (tooltip).
|
title: Заголовок tray (tooltip).
|
||||||
|
on_preset_select: Колбэк выбора пресета по имени (опционально).
|
||||||
|
get_active_preset: Геттер имени активного пресета (опционально).
|
||||||
|
get_preset_names: Геттер списка имён всех пресетов (опционально).
|
||||||
|
on_splash_toggle: Колбэк toggle splash при старте (опционально).
|
||||||
|
get_splash_state: Геттер текущего состояния splash (опционально).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
|
|
@ -32,21 +38,26 @@ class TrayApp:
|
||||||
on_settings: Callable[[], None],
|
on_settings: Callable[[], None],
|
||||||
on_stats: Callable[[], None],
|
on_stats: Callable[[], None],
|
||||||
on_quit: 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",
|
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:
|
) -> None:
|
||||||
self._on_toggle = on_toggle
|
self._on_toggle = on_toggle
|
||||||
self._on_settings = on_settings
|
self._on_settings = on_settings
|
||||||
self._on_stats = on_stats
|
self._on_stats = on_stats
|
||||||
self._on_quit = on_quit
|
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._title = title
|
||||||
self._state = RecordingState.IDLE
|
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(
|
self._icon = pystray.Icon(
|
||||||
"voice_dictation",
|
"voice_dictation",
|
||||||
icon=make_icon(self._state),
|
icon=make_icon(self._state),
|
||||||
|
|
@ -55,47 +66,47 @@ class TrayApp:
|
||||||
)
|
)
|
||||||
|
|
||||||
def _build_menu(self) -> pystray.Menu:
|
def _build_menu(self) -> pystray.Menu:
|
||||||
items = [
|
items: list[MenuItem] = [
|
||||||
MenuItem(self._toggle_label, self._handle_toggle, default=True),
|
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()))
|
if self._on_preset_select is not None and self._get_preset_names is not None:
|
||||||
items.extend([
|
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_stats),
|
||||||
MenuItem("Настройки", self._handle_settings),
|
MenuItem("Настройки", self._handle_settings),
|
||||||
pystray.Menu.SEPARATOR,
|
pystray.Menu.SEPARATOR,
|
||||||
MenuItem("Выход", self._handle_quit),
|
MenuItem("Выход", self._handle_quit),
|
||||||
])
|
]
|
||||||
|
)
|
||||||
|
|
||||||
return pystray.Menu(*items)
|
return pystray.Menu(*items)
|
||||||
|
|
||||||
def _build_mode_submenu(self) -> pystray.Menu:
|
def _build_presets_submenu(self) -> pystray.Menu:
|
||||||
"""Строит подменю выбора режима с радио-галочками."""
|
"""Строит submenu с радио-кнопками по списку имён пресетов."""
|
||||||
sub_items = []
|
assert self._get_preset_names is not None
|
||||||
modes = self._modes_provider() if self._modes_provider is not None else []
|
names = self._get_preset_names()
|
||||||
for key, label in modes:
|
preset_items = [
|
||||||
sub_items.append(
|
|
||||||
MenuItem(
|
MenuItem(
|
||||||
label,
|
name,
|
||||||
self._make_mode_handler(key),
|
functools.partial(self._handle_preset_select, name),
|
||||||
checked=self._make_mode_checked(key),
|
checked=functools.partial(self._preset_checked, name),
|
||||||
radio=True,
|
radio=True,
|
||||||
)
|
)
|
||||||
)
|
for name in names
|
||||||
return pystray.Menu(*sub_items)
|
]
|
||||||
|
return pystray.Menu(*preset_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
|
|
||||||
|
|
||||||
def _toggle_label(self, _item: object) -> str:
|
def _toggle_label(self, _item: object) -> str:
|
||||||
if self._state == RecordingState.RECORDING:
|
if self._state == RecordingState.RECORDING:
|
||||||
|
|
@ -104,6 +115,16 @@ class TrayApp:
|
||||||
return "Обработка..."
|
return "Обработка..."
|
||||||
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:
|
def _handle_toggle(self, *_args: object) -> None:
|
||||||
self._on_toggle()
|
self._on_toggle()
|
||||||
|
|
||||||
|
|
@ -117,6 +138,24 @@ class TrayApp:
|
||||||
self._on_quit()
|
self._on_quit()
|
||||||
self._icon.stop()
|
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:
|
def update_state(self, state: RecordingState) -> None:
|
||||||
"""Обновляет иконку и меню в соответствии с состоянием.
|
"""Обновляет иконку и меню в соответствии с состоянием.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ def tmp_paths(tmp_path: pytest.TempPathFactory) -> AppPaths:
|
||||||
log_file=root / "app.log",
|
log_file=root / "app.log",
|
||||||
pid_file=root / "dictate.pid",
|
pid_file=root / "dictate.pid",
|
||||||
tmp_dir=root / "tmp",
|
tmp_dir=root / "tmp",
|
||||||
bin_dir=root / "bin",
|
|
||||||
)
|
)
|
||||||
paths.ensure_exists()
|
paths.ensure_exists()
|
||||||
return paths
|
return paths
|
||||||
|
|
|
||||||
|
|
@ -62,9 +62,17 @@ class FakeTranscriber:
|
||||||
fail: Если True — transcribe() бросит TranscriptionError.
|
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.text = text
|
||||||
self.fail = fail
|
self.fail = fail
|
||||||
|
self.texts = texts
|
||||||
|
self.fail_on_call = fail_on_call
|
||||||
self.calls: list[tuple[Path, str, str | None]] = []
|
self.calls: list[tuple[Path, str, str | None]] = []
|
||||||
|
|
||||||
def transcribe(
|
def transcribe(
|
||||||
|
|
@ -72,14 +80,19 @@ class FakeTranscriber:
|
||||||
audio_path: Path,
|
audio_path: Path,
|
||||||
prompt: str = "",
|
prompt: str = "",
|
||||||
language: str | None = None,
|
language: str | None = None,
|
||||||
|
model: str | None = None,
|
||||||
|
duration_sec: float | None = None,
|
||||||
) -> TranscriptionResult:
|
) -> TranscriptionResult:
|
||||||
self.calls.append((audio_path, prompt, language))
|
self.calls.append((audio_path, prompt, language))
|
||||||
if self.fail:
|
if self.fail or self.fail_on_call == len(self.calls):
|
||||||
raise TranscriptionError("FakeTranscriber: принудительная ошибка")
|
raise TranscriptionError("FakeTranscriber: принудительная ошибка")
|
||||||
|
text = self.text
|
||||||
|
if self.texts:
|
||||||
|
text = self.texts[min(len(self.calls) - 1, len(self.texts) - 1)]
|
||||||
return TranscriptionResult(
|
return TranscriptionResult(
|
||||||
text=self.text,
|
text=text,
|
||||||
duration_sec=2.0,
|
duration_sec=duration_sec or 2.0,
|
||||||
model="gpt-4o-mini-transcribe",
|
model=model or "gpt-4o-mini-transcribe",
|
||||||
language=language or "ru",
|
language=language or "ru",
|
||||||
prompt_used=prompt or None,
|
prompt_used=prompt or None,
|
||||||
requested_at=datetime.now(tz=UTC),
|
requested_at=datetime.now(tz=UTC),
|
||||||
|
|
|
||||||
104
tests/unit/test_compressor.py
Normal file
104
tests/unit/test_compressor.py
Normal file
|
|
@ -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
|
||||||
|
|
@ -14,19 +14,26 @@ from voice_dictation.core.paths import AppPaths
|
||||||
def test_default_config_values() -> None:
|
def test_default_config_values() -> None:
|
||||||
"""Дефолтный конфиг имеет правильные значения."""
|
"""Дефолтный конфиг имеет правильные значения."""
|
||||||
config = Config()
|
config = Config()
|
||||||
assert config.hotkey == "cmd+space"
|
assert config.hotkey == "cmd+alt+d"
|
||||||
assert config.model == "gpt-4o-mini-transcribe"
|
assert config.model == "gpt-4o-mini-transcribe"
|
||||||
assert config.language == "ru"
|
assert config.language == "ru"
|
||||||
assert config.auto_paste is True
|
assert config.auto_paste is True
|
||||||
assert config.paste_delay_ms == 80
|
assert config.paste_delay_ms == 80
|
||||||
assert config.volume == 0.6
|
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:
|
def test_load_missing_file_returns_defaults(tmp_paths: AppPaths) -> None:
|
||||||
"""Загрузка несуществующего файла возвращает дефолтный конфиг."""
|
"""Загрузка несуществующего файла возвращает дефолтный конфиг."""
|
||||||
store = ConfigStore(tmp_paths.config_file)
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
config = store.load()
|
config = store.load()
|
||||||
assert config.hotkey == "cmd+space"
|
assert config.hotkey == "cmd+alt+d"
|
||||||
assert config.model == "gpt-4o-mini-transcribe"
|
assert config.model == "gpt-4o-mini-transcribe"
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -38,6 +45,13 @@ def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None:
|
||||||
language="en",
|
language="en",
|
||||||
auto_paste=False,
|
auto_paste=False,
|
||||||
paste_delay_ms=150,
|
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 = ConfigStore(tmp_paths.config_file)
|
||||||
store.save(original)
|
store.save(original)
|
||||||
|
|
@ -50,6 +64,13 @@ def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None:
|
||||||
assert loaded.language == "en"
|
assert loaded.language == "en"
|
||||||
assert loaded.auto_paste is False
|
assert loaded.auto_paste is False
|
||||||
assert loaded.paste_delay_ms == 150
|
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:
|
def test_save_with_path_fields(tmp_paths: AppPaths) -> None:
|
||||||
|
|
@ -95,4 +116,4 @@ def test_load_corrupted_json_returns_defaults(tmp_paths: AppPaths) -> None:
|
||||||
tmp_paths.config_file.write_text("{ NOT VALID JSON }")
|
tmp_paths.config_file.write_text("{ NOT VALID JSON }")
|
||||||
store = ConfigStore(tmp_paths.config_file)
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
config = store.load()
|
config = store.load()
|
||||||
assert config.hotkey == "cmd+space"
|
assert config.hotkey == "cmd+alt+d"
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import time
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from tests.fakes.fake_components import (
|
from tests.fakes.fake_components import (
|
||||||
FakeAutoPaste,
|
FakeAutoPaste,
|
||||||
|
|
@ -12,6 +13,7 @@ from tests.fakes.fake_components import (
|
||||||
FakeSoundPlayer,
|
FakeSoundPlayer,
|
||||||
FakeTranscriber,
|
FakeTranscriber,
|
||||||
)
|
)
|
||||||
|
from voice_dictation.core.compressor import AudioChunk, ChunkingResult
|
||||||
from voice_dictation.core.config import Config
|
from voice_dictation.core.config import Config
|
||||||
from voice_dictation.core.dictionary import Dictionary
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
from voice_dictation.core.enums import RecordingState, SoundKind
|
from voice_dictation.core.enums import RecordingState, SoundKind
|
||||||
|
|
@ -28,6 +30,7 @@ def _make_orchestrator(
|
||||||
sound_player: FakeSoundPlayer | None = None,
|
sound_player: FakeSoundPlayer | None = None,
|
||||||
notifier: FakeNotifier | None = None,
|
notifier: FakeNotifier | None = None,
|
||||||
config: Config | None = None,
|
config: Config | None = None,
|
||||||
|
compressor=None,
|
||||||
) -> DictationOrchestrator:
|
) -> DictationOrchestrator:
|
||||||
"""Вспомогательная функция — создаёт оркестратор с фейками."""
|
"""Вспомогательная функция — создаёт оркестратор с фейками."""
|
||||||
cfg = config or Config()
|
cfg = config or Config()
|
||||||
|
|
@ -41,9 +44,46 @@ def _make_orchestrator(
|
||||||
notifier=notifier or FakeNotifier(),
|
notifier=notifier or FakeNotifier(),
|
||||||
config_provider=lambda: cfg,
|
config_provider=lambda: cfg,
|
||||||
paths=tmp_paths,
|
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:
|
def test_initial_state_is_idle(tmp_paths: AppPaths) -> None:
|
||||||
"""Начальное состояние — IDLE."""
|
"""Начальное состояние — IDLE."""
|
||||||
o = _make_orchestrator(tmp_paths)
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
|
@ -206,9 +246,13 @@ def test_cancel_stops_recording(tmp_paths: AppPaths) -> None:
|
||||||
assert o.state == RecordingState.IDLE
|
assert o.state == RecordingState.IDLE
|
||||||
|
|
||||||
|
|
||||||
def test_autopaste_skipped_for_long_text(tmp_paths: AppPaths) -> None:
|
def test_autopaste_skipped_for_very_long_text(tmp_paths: AppPaths) -> None:
|
||||||
"""Автовставка не выполняется если текст длиннее 10000 символов."""
|
"""Текст >10000 символов автоматически НЕ вставляется (только буфер).
|
||||||
long_text = "а" * 15000
|
|
||||||
|
После merge с веткой Жени: при превышении MAX_AUTOPASTE_CHARS показываем
|
||||||
|
notify «вставьте вручную ⌘V», autopaste не вызываем.
|
||||||
|
"""
|
||||||
|
long_text = "а" * 50_000
|
||||||
transcriber = FakeTranscriber(text=long_text)
|
transcriber = FakeTranscriber(text=long_text)
|
||||||
auto_paste = FakeAutoPaste()
|
auto_paste = FakeAutoPaste()
|
||||||
o = _make_orchestrator(tmp_paths, transcriber=transcriber, auto_paste=auto_paste)
|
o = _make_orchestrator(tmp_paths, transcriber=transcriber, auto_paste=auto_paste)
|
||||||
|
|
@ -220,3 +264,75 @@ def test_autopaste_skipped_for_long_text(tmp_paths: AppPaths) -> None:
|
||||||
time.sleep(0.05)
|
time.sleep(0.05)
|
||||||
|
|
||||||
assert auto_paste.paste_count == 0
|
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] == "раз два три четыре пять шесть семь"
|
||||||
|
|
|
||||||
49
tests/unit/test_session_store.py
Normal file
49
tests/unit/test_session_store.py
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
"""Тесты долговечных сессий и 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]
|
||||||
35
tests/unit/test_text_stitcher.py
Normal file
35
tests/unit/test_text_stitcher.py
Normal file
|
|
@ -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
|
||||||
Loading…
Reference in a new issue