voice-dictation/ARCHITECTURE.md
Claude Zhenya b96b49f1d5 v0.2.0: режимы обработки, кастомные стили, новая иконка, прослушка звуков
- Реестр режимов постобработки вместо бинарного summary_mode:
  Чистая диктовка, Чистовик (без паразитов), Summary, Переводчик RU→EN,
  Промпт для LLM, Буллеты, Деловое письмо
- Кастомные стили: свои промпты в настройках (таб «Стили»)
- Новая иконка приложения (микрофон + VД)
- Прослушка звуков в настройках (кнопки ▶)
- ffmpeg как опциональная докачка (кнопка в настройках), WAV-fallback без него
- Версия 0.2.0 + changelog в «О программе»
- Фикс: сохранение настроек через dataclasses.replace (не теряет поля)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 22:48:38 +03:00

460 lines
19 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Voice Dictation — архитектурный план
Desktop-приложение для голосовой диктовки в Claude Code CLI. Python, кроссплатформенное (macOS + Windows). Hotkey → запись через sox → Whisper API → автовставка.
---
## 1. Структура папок
```
personal/voice-dictation/
├── pyproject.toml # Poetry/PEP621, зависимости, ruff/mypy конфиг
├── requirements.txt # Заморозка pip
├── requirements-dev.txt # pytest, mypy, ruff, pre-commit
├── .env.example # OPENAI_API_KEY=, OPENAI_ADMIN_API_KEY=
├── .gitignore # .env, __pycache__, .venv, *.db, sounds/custom/
├── .pre-commit-config.yaml
├── README.md
├── Makefile # install / run / test / lint
│
├── assets/
│ ├── icons/ # tray_idle.png, tray_recording.png, tray_processing.png
│ └── sounds/ # default_start.wav, default_stop.wav, default_error.wav
│
├── src/voice_dictation/
│ ├── __init__.py
│ ├── __main__.py # entrypoint: `python -m voice_dictation`, DI-сборка
│ │
│ ├── core/ # Бизнес-логика, не знает про UI и ОС
│ │ ├── config.py # Config dataclass + ConfigStore
│ │ ├── paths.py # AppPaths dataclass
│ │ ├── enums.py # RecordingState, SoundKind, WhisperModel
│ │ ├── models.py # TranscriptionResult, UsageRecord, SoundTheme, BalanceInfo
│ │ ├── recorder.py # AudioRecorder Protocol + SoxRecorder
│ │ ├── transcriber.py # WhisperTranscriber через httpx
│ │ ├── dictionary.py # Dictionary: загрузка + build_prompt
│ │ ├── usage_db.py # UsageDB: SQLite CRUD
│ │ ├── pricing.py # PriceCalculator
│ │ ├── balance.py # BalanceClient: Admin API
│ │ └── orchestrator.py # DictationOrchestrator — главная state-machine
│ │
│ ├── platform/ # Platform abstraction
│ │ ├── protocols.py # Все Protocol-интерфейсы
│ │ ├── factory.py # build_platform() -> PlatformBundle
│ │ ├── system_sound.py # SystemSound dataclass
│ │ ├── macos/
│ │ │ ├── sound_player.py # afplay
│ │ │ ├── notifier.py # pync / osascript
│ │ │ ├── clipboard.py # pbcopy/pbpaste
│ │ │ ├── autopaste.py # pynput Cmd+V
│ │ │ ├── hotkey_listener.py # pynput GlobalHotKeys
│ │ │ └── system_sounds_scanner.py # /System/Library/Sounds/*.aiff
│ │ └── windows/
│ │ ├── sound_player.py # winsound
│ │ ├── notifier.py # winotify
│ │ ├── clipboard.py # pyperclip
│ │ ├── autopaste.py # pynput Ctrl+V
│ │ ├── hotkey_listener.py # pynput GlobalHotKeys
│ │ └── system_sounds_scanner.py # C:\Windows\Media\*.wav
│ │
│ ├── ui/ # pystray + customtkinter
│ │ ├── tray.py # TrayApp: pystray + меню
│ │ ├── settings_window.py # SettingsWindow с табами
│ │ ├── tabs/
│ │ │ ├── general_tab.py
│ │ │ ├── sound_tab.py
│ │ │ ├── dictionary_tab.py
│ │ │ ├── statistics_tab.py
│ │ │ └── balance_tab.py
│ │ └── widgets/
│ │ ├── sound_picker.py # dropdown + Browse + Play
│ │ └── hotkey_input.py # захват комбинации
│ │
│ ├── infrastructure/
│ │ ├── logging_setup.py # RotatingFileHandler в ~/.dictate/app.log
│ │ ├── single_instance.py # PID-файл lock
│ │ ├── env_loader.py # dotenv + валидация
│ │ └── errors.py # Иерархия исключений
│ │
│ └── cli/
│ └── headless.py # Этап 1 без tray
│
└── tests/
├── conftest.py
├── unit/ # test_config, test_dictionary, test_usage_db, test_pricing, test_orchestrator
├── integration/ # test_sox_recorder (skipIf), test_transcriber (httpx mock)
└── fakes/ # in-memory реализации Protocols
```
---
## 2. Модули
### Core
**`core/models.py`** — dataclasses, только stdlib:
```python
@dataclass(frozen=True, slots=True)
class TranscriptionResult:
text: str
duration_sec: float
model: str
language: str | None
prompt_used: str | None
requested_at: datetime
cost_usd: Decimal
@dataclass(frozen=True, slots=True)
class UsageRecord:
id: int | None
created_at: datetime
duration_sec: float
cost_usd: Decimal
model: str
text_preview: str
@dataclass(frozen=True, slots=True)
class SoundTheme:
start: Path | None
stop: Path | None
error: Path | None
volume: float
@dataclass(frozen=True, slots=True)
class BalanceInfo:
total_granted_usd: Decimal
total_used_usd: Decimal
total_available_usd: Decimal
fetched_at: datetime
```
**`core/config.py`**:
```python
@dataclass(slots=True)
class Config:
hotkey: str = "cmd+alt+d" # на win нормализуется к "ctrl+alt+d"
model: str = "gpt-4o-mini-transcribe"
language: str | None = "ru"
notifications_enabled: bool = True
show_cost_in_notification: bool = True
sounds_enabled: bool = True
volume: float = 0.6
start_sound_path: Path | None = None
stop_sound_path: Path | None = None
error_sound_path: Path | None = None
dictionary_path: Path | None = None
auto_paste: bool = True
paste_delay_ms: int = 80
class ConfigStore:
def __init__(self, path: Path) -> None: ...
def load(self) -> Config: ...
def save(self, config: Config) -> None: ...
def current(self) -> Config: ...
```
**`core/paths.py`**:
```python
@dataclass(frozen=True, slots=True)
class AppPaths:
root: Path # ~/.dictate
config_file: Path # ~/.dictate/config.json
usage_db: Path # ~/.dictate/usage.db
dictionary_file: Path # ~/.dictate/dictionary.txt
custom_sounds_dir: Path # ~/.dictate/sounds/
log_file: Path # ~/.dictate/app.log
pid_file: Path # ~/.dictate/dictate.pid
tmp_dir: Path # ~/.dictate/tmp/
@classmethod
def default(cls) -> "AppPaths": ...
def ensure_exists(self) -> None: ...
```
**`core/enums.py`**:
```python
class RecordingState(Enum):
IDLE = auto()
RECORDING = auto()
PROCESSING = auto()
ERROR = auto()
class SoundKind(Enum):
START = auto()
STOP = auto()
ERROR = auto()
class WhisperModel(StrEnum):
WHISPER_1 = "whisper-1"
GPT_4O_TRANSCRIBE = "gpt-4o-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/transcriber.py`** — `WhisperTranscriber` через `httpx.Client`. Multipart upload к `POST /v1/audio/transcriptions`. Параметры: `model`, `language`, `prompt`, `response_format=verbose_json` (для duration). Retries=2 на 5xx. Поднимает `TranscriptionError`.
**`core/dictionary.py`** — загрузка построчно, `#` комментарии, `build_prompt(max_chars=896)` режет хвост.
**`core/usage_db.py`** — SQLite. Миграция через `PRAGMA user_version`. Методы: `insert`, `today_total(tz)`, `stats(since, until)`, `recent(limit)`.
**`core/pricing.py`**:
```python
class PriceCalculator:
PRICES_PER_MINUTE: Final[Mapping[str, Decimal]] = MappingProxyType({
"gpt-4o-mini-transcribe": Decimal("0.003"),
"gpt-4o-transcribe": Decimal("0.006"),
"whisper-1": Decimal("0.006"),
})
@classmethod
def cost(cls, model: str, duration_sec: float) -> Decimal: ...
```
**`core/balance.py`** — `BalanceClient(admin_api_key)`. `fetch() -> BalanceInfo`. Endpoints `/v1/organization/costs` (GET с `start_time`, `end_time`).
**`core/orchestrator.py`** — **главный модуль, state-machine**:
```python
class DictationOrchestrator:
def __init__(
self,
recorder: AudioRecorder,
transcriber: WhisperTranscriber,
dictionary: Dictionary,
usage_db: UsageDB,
clipboard: Clipboard,
auto_paste: AutoPaste,
sound_player: SoundPlayer,
notifier: Notifier,
config_provider: Callable[[], Config],
paths: AppPaths,
state_listener: Callable[[RecordingState], None] | None = None,
) -> None: ...
def toggle(self) -> None: ...
def cancel(self) -> None: ...
@property
def state(self) -> RecordingState: ...
```
`threading.Lock` защищает переходы. Whisper-запрос — в `ThreadPoolExecutor(max_workers=1)` чтобы не блокировать UI.
### Platform
**`platform/protocols.py`** — все интерфейсы в одном файле: `AudioRecorder`, `SoundPlayer`, `Notifier`, `Clipboard`, `AutoPaste`, `HotkeyListener`, `SystemSoundsScanner`.
**`platform/factory.py`**:
```python
@dataclass(frozen=True, slots=True)
class PlatformBundle:
sound_player: SoundPlayer
notifier: Notifier
clipboard: Clipboard
auto_paste: AutoPaste
hotkey_listener: HotkeyListener
system_sounds_scanner: SystemSoundsScanner
def build_platform() -> PlatformBundle:
match sys.platform:
case "darwin": return _build_macos()
case "win32": return _build_windows()
case _: raise UnsupportedPlatformError(sys.platform)
```
### Infrastructure
**`infrastructure/errors.py`**:
```
DictationError
├── RecorderError
│ └── SoxNotFoundError
├── TranscriptionError
│ └── WhisperAPIError
├── ConfigError
├── PlatformError
│ └── UnsupportedPlatformError
└── BalanceError
```
**`infrastructure/single_instance.py`** — atomic PID-file через `os.open(O_CREAT | O_EXCL)`. `atexit` удаляет. На винде — `msvcrt.locking`.
**`infrastructure/logging_setup.py`** — RotatingFileHandler (5MB × 3) + stderr. Маскирует API-ключи.
---
## 3. Data flow
```
[User presses ⌘⌥D]
│
▼
HotkeyListener → orchestrator.toggle()
│
▼
state: IDLE → RECORDING
├── SoundPlayer.play(start_sound)
├── state_listener(RECORDING) → tray icon red
└── SoxRecorder.start(tmp.wav)
... user speaks ...
[User presses ⌘⌥D again]
│
▼
state: RECORDING → PROCESSING
├── SoundPlayer.play(stop_sound)
├── recording = SoxRecorder.stop()
│ (sanity: duration<0.3s OR size<4KB → skip, no API call)
│
└── ThreadPoolExecutor submit:
├── prompt = Dictionary.build_prompt()
├── result = Transcriber.transcribe(wav, prompt, language)
├── UsageDB.insert(UsageRecord(...))
├── Clipboard.copy(result.text)
├── AutoPaste.paste() (имитирует ⌘V/Ctrl+V)
├── Notifier.show("Transcribed", f"{sec}s · ${cost} · today ${total}")
└── state: PROCESSING → IDLE
```
**Потоки:**
- Main: pystray/Tk mainloop
- Hotkey: pynput внутренний
- Worker: ThreadPoolExecutor (Whisper API)
- Sox: отдельный subprocess
---
## 4. Конфиг и БД
### `~/.dictate/config.json` — сериализованный `Config`
### SQLite `usage.db`:
```sql
PRAGMA journal_mode = WAL;
PRAGMA user_version = 1;
CREATE TABLE transcriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL, -- ISO 8601 UTC
duration_sec REAL NOT NULL,
cost_usd TEXT NOT NULL, -- Decimal как строка
model TEXT NOT NULL,
language TEXT,
text_preview TEXT NOT NULL, -- 80 chars
char_count INTEGER NOT NULL,
prompt_hash TEXT
);
CREATE INDEX idx_tx_created ON transcriptions(created_at);
```
### Структура `~/.dictate/`:
```
~/.dictate/
├── config.json
├── usage.db
├── dictionary.txt # построчно, # — комментарии
├── app.log
├── dictate.pid
├── sounds/ # custom sounds
└── tmp/ # session_*.wav, чистится при старте >1ч
```
---
## 5. Этапы разработки
### Этап 1 — Ядро headless
**Файлы:** `core/{models,paths,enums,config,recorder,transcriber,dictionary,pricing,orchestrator}.py`, `platform/{protocols,factory,system_sound}.py`, `platform/macos/{clipboard,autopaste,hotkey_listener}.py`, `platform/windows/{clipboard,autopaste,hotkey_listener}.py`, `infrastructure/{logging_setup,env_loader,errors,single_instance}.py`, `cli/headless.py`, `pyproject.toml`, `.env.example`, `.gitignore`, `README.md`.
**Acceptance:** `python -m voice_dictation.cli.headless` → ⌘⌥D работает, запись/транскрипция/вставка.
### Этап 2 — SQLite + stats
**Файлы:** `core/usage_db.py`. CLI `stats` подкоманда.
**Acceptance:** в БД появляются записи; `headless stats` выводит сводку.
### Этап 3 — Звуки + уведомления
**Файлы:** `platform/{macos,windows}/{sound_player,notifier,system_sounds_scanner}.py`.
**Acceptance:** звуки на старт/стоп/ошибку; toast с длительностью/стоимостью/сегодня.
### Этап 4 — Tray icon
**Файлы:** `ui/tray.py`, иконки.
**Acceptance:** иконка в tray, ПКМ → меню, смена иконки по состоянию.
### Этап 5 — Settings window
**Файлы:** `ui/settings_window.py`, `ui/tabs/{general,sound,dictionary,statistics}_tab.py`, `ui/widgets/{sound_picker,hotkey_input}.py`.
**Acceptance:** все табы рабочие, изменения применяются на лету.
### Этап 6 — Баланс
**Файлы:** `core/balance.py`, `ui/tabs/balance_tab.py`.
**Acceptance:** с Admin-ключом показывает granted/used/available.
### Этап 7 — Полировка
Тесты, pre-commit, README, autostart, bundling (pyinstaller опционально).
---
## 6. Точки расширения
- **Локальный whisper.cpp** — `Transcriber(Protocol)` + `LocalWhisperTranscriber`
- **Streaming-транскрипция** — `StreamingSoxRecorder.chunks() -> AsyncIterator[bytes]`
- **Post-processing GPT** — `PostProcessor(Protocol)` между transcribe и copy
- **Workflows** — `Config.workflows: dict[str, WorkflowConfig]`, switch через tray
---
## 7. Риски
| Риск | Митигация |
|---|---|
| macOS микрофон permission | README скриншоты; ловим sox exit code |
| macOS accessibility для autopaste | probe на старте; диалог с ссылкой на Settings |
| Windows микрофон permission | README упоминание |
| UAC для `keyboard` lib | Используем `pynput` на обеих платформах |
| Race condition PID-файла | `os.open(O_CREAT\|O_EXCL)` + `psutil.pid_exists`; на win `msvcrt.locking` |
| Race condition в toggle | `threading.Lock`; повторный toggle в PROCESSING игнорируется |
| Admin API Key утечка | Только `.env`; маскирование в логах `sk-admin-***` |
| sox не установлен | `shutil.which("sox")` на старте; фатальный диалог |
| Тишина / короткая запись | `duration<0.3s` или `size<4KB` → skip, нет API-вызова |
| OpenAI rate-limit/сеть | `httpx` retries=2 на 5xx/timeout |
| Zombie sox-процесс | `__del__` + `atexit` шлют SIGTERM/kill |
| customtkinter + pystray main thread | pystray на main, Tk-действия через `root.after(0, ...)` |
| Длинный транскрипт в чат | `>10000 chars` → только copy, без autopaste, toast |
| Хоткей конфликт | `register` возвращает bool; fallback на `cmd+shift+d` |
| Словарь >224 токенов | `build_prompt` берёт хвост; UI счётчик `N/224` |
---
## 8. Стандарты кода (обязательные для всех модулей)
- **Python 3.11+**, `from __future__ import annotations` во всех файлах
- **Полная типизация** (mypy --strict clean), без `Any`
- **Google-style docstrings** на публичных классах/функциях: Args / Returns / Raises
- **Dataclasses** для структур данных (`@dataclass(frozen=True, slots=True)` где возможно)
- **Protocols** для кроссплатформенных абстракций
- **Pathlib** вместо `os.path`
- **logging** вместо `print`
- **Enum** для констант (`StrEnum`, `IntEnum` где уместно)
- **SRP** — каждый модуль одно дело
- **Минимум комментариев в коде** — только "почему", не "что"
- **Инструменты**: `ruff` + `mypy --strict` + `pre-commit`
---
## 9. DI-граф (entrypoint)
```
__main__.py
├── env_loader → EnvConfig
├── AppPaths.default().ensure_exists()
├── configure_logging(paths)
├── SingleInstanceLock(paths.pid_file).acquire()
├── ConfigStore → Config
├── build_platform() → PlatformBundle
├── SoxRecorder
├── WhisperTranscriber(api_key, config.model)
├── Dictionary(paths.dictionary_file)
├── UsageDB(paths.usage_db)
├── BalanceClient(admin_api_key) [optional]
├── DictationOrchestrator(...)
├── hotkey_listener.register(config.hotkey, orchestrator.toggle)
└── TrayApp(orchestrator, settings_opener, ...).run()
```