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>
This commit is contained in:
commit
b96b49f1d5
84 changed files with 7503 additions and 0 deletions
6
.env.example
Normal file
6
.env.example
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# Обязательный ключ для Whisper API транскрипции
|
||||||
|
OPENAI_API_KEY=
|
||||||
|
|
||||||
|
# Опциональный Admin API Key для просмотра баланса организации (этап 6)
|
||||||
|
# Получить: https://platform.openai.com/settings/organization/admin-keys
|
||||||
|
OPENAI_ADMIN_API_KEY=
|
||||||
44
.gitignore
vendored
Normal file
44
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
# Секреты
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.pyo
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
*.egg-info/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
.eggs/
|
||||||
|
|
||||||
|
# Данные приложения
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
*.db-wal
|
||||||
|
*.db-shm
|
||||||
|
|
||||||
|
# Логи
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Временные файлы записей
|
||||||
|
*.wav
|
||||||
|
tmp/
|
||||||
|
|
||||||
|
# Пользовательские звуки
|
||||||
|
assets/sounds/custom/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# Сборка инсталлятора (идёт в релиз, не в git)
|
||||||
|
installer_output/
|
||||||
|
*_log.txt
|
||||||
26
.pre-commit-config.yaml
Normal file
26
.pre-commit-config.yaml
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
repos:
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v4.6.0
|
||||||
|
hooks:
|
||||||
|
- id: end-of-file-fixer
|
||||||
|
- id: trailing-whitespace
|
||||||
|
- id: check-yaml
|
||||||
|
- id: check-toml
|
||||||
|
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
rev: v0.4.4
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args: ["--fix"]
|
||||||
|
- id: ruff-format
|
||||||
|
|
||||||
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
|
rev: v1.10.0
|
||||||
|
hooks:
|
||||||
|
- id: mypy
|
||||||
|
args: ["--strict"]
|
||||||
|
additional_dependencies:
|
||||||
|
- httpx
|
||||||
|
- types-psutil
|
||||||
|
pass_filenames: false
|
||||||
|
entry: mypy --strict src/
|
||||||
460
ARCHITECTURE.md
Normal file
460
ARCHITECTURE.md
Normal file
|
|
@ -0,0 +1,460 @@
|
||||||
|
# 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()
|
||||||
|
```
|
||||||
291
BUILD_WINDOWS.md
Normal file
291
BUILD_WINDOWS.md
Normal file
|
|
@ -0,0 +1,291 @@
|
||||||
|
# Voice Dictation — сборка под Windows (инструкция для Claude Code)
|
||||||
|
|
||||||
|
**Привет, Claude Code!** Эта инструкция адресована тебе. Выполняй шаги
|
||||||
|
последовательно. Комментируй прогресс, на каждом шаге проверяй результат.
|
||||||
|
|
||||||
|
Если что-то не работает — отчитайся пользователю по-русски, покажи лог
|
||||||
|
ошибки. Не придумывай лишних действий, строго следуй инструкции.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что это за проект
|
||||||
|
|
||||||
|
Десктоп-приложение для голосовой диктовки. Нажал хоткей → запись с микрофона
|
||||||
|
→ OpenAI Whisper API транскрибирует → текст вставляется в активное окно.
|
||||||
|
Живёт в системном трее (рядом с часами), без окна в панели задач.
|
||||||
|
|
||||||
|
Уже работает на macOS у автора (Викентий Жеребов, Flowmasters). Код
|
||||||
|
кроссплатформенный, Windows-реализации (clipboard, autopaste, hotkey,
|
||||||
|
sound player, notifier) уже написаны в `src/voice_dictation/platform/windows/`.
|
||||||
|
|
||||||
|
**Твоя задача:** собрать нативное Windows `.exe` приложение через PyInstaller.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Предварительные требования
|
||||||
|
|
||||||
|
Открой PowerShell (НЕ cmd.exe — PowerShell!) и проверь:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python --version
|
||||||
|
sox --version
|
||||||
|
```
|
||||||
|
|
||||||
|
Должно быть:
|
||||||
|
- Python **3.11+** (лучше 3.12 или 3.13)
|
||||||
|
- sox любой версии
|
||||||
|
|
||||||
|
### Если нет Python
|
||||||
|
|
||||||
|
Скачай и установи с https://www.python.org/downloads/windows/
|
||||||
|
**Обязательно поставь галку "Add Python to PATH"** при установке.
|
||||||
|
|
||||||
|
### Если нет sox
|
||||||
|
|
||||||
|
**Вариант A — через Chocolatey** (если установлен):
|
||||||
|
```powershell
|
||||||
|
choco install sox
|
||||||
|
```
|
||||||
|
|
||||||
|
**Вариант B — ручная установка:**
|
||||||
|
1. Скачай с https://sourceforge.net/projects/sox/files/sox/
|
||||||
|
2. Установи в `C:\Program Files (x86)\sox-14-4-2\` (или аналогично)
|
||||||
|
3. Добавь путь к `sox.exe` в PATH:
|
||||||
|
- "Изменение переменных среды для вашей учётной записи"
|
||||||
|
- `Path` → "Изменить" → "Создать" → путь к папке с sox.exe
|
||||||
|
4. Открой **новый** PowerShell и проверь: `where sox`
|
||||||
|
|
||||||
|
### Проверка Python/sox
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python --version
|
||||||
|
where python
|
||||||
|
where sox
|
||||||
|
sox --version
|
||||||
|
```
|
||||||
|
|
||||||
|
Всё должно выводиться без ошибок.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 1. Настройка виртуального окружения
|
||||||
|
|
||||||
|
В корне проекта:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd voice-dictation
|
||||||
|
|
||||||
|
python -m venv .venv
|
||||||
|
.\.venv\Scripts\Activate.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
Если PowerShell блокирует Activate.ps1 (execution policy):
|
||||||
|
```powershell
|
||||||
|
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
||||||
|
.\.venv\Scripts\Activate.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
После активации в приглашении PowerShell слева появится префикс `(.venv)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 2. Установка зависимостей
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m pip install --upgrade pip
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
pip install pyinstaller
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверь, что пакет установился и команды доступны:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -c "import voice_dictation; print(voice_dictation.__file__)"
|
||||||
|
pyinstaller --version
|
||||||
|
```
|
||||||
|
|
||||||
|
Должно напечатать путь внутри `src\voice_dictation\__init__.py` и версию PyInstaller (6.x).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 3. Настройка `.env`
|
||||||
|
|
||||||
|
В корне `voice-dictation\` создай файл `.env` на основе `.env.example`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Copy-Item .env.example .env
|
||||||
|
notepad .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Впиши свой ключ:
|
||||||
|
|
||||||
|
```
|
||||||
|
OPENAI_API_KEY=sk-...
|
||||||
|
```
|
||||||
|
|
||||||
|
Ключ выдаст сам автор. `OPENAI_ADMIN_API_KEY` можно оставить пустым — он нужен
|
||||||
|
только для просмотра баланса организации.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 4. Пробный запуск из исходников
|
||||||
|
|
||||||
|
Перед сборкой `.exe` убедись, что всё работает в dev-режиме:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m voice_dictation
|
||||||
|
```
|
||||||
|
|
||||||
|
Должно произойти:
|
||||||
|
|
||||||
|
1. В трее (правый нижний угол, рядом с часами) появится иконка микрофона.
|
||||||
|
2. Нажатие `Ctrl+Alt+D` запускает запись — услышишь системный звук старта.
|
||||||
|
3. Второе нажатие останавливает запись — через 1-3 секунды текст
|
||||||
|
автоматически вставится в активное окно.
|
||||||
|
|
||||||
|
Если ничего не происходит:
|
||||||
|
- проверь, что sox в PATH (`where sox`);
|
||||||
|
- разреши микрофон: **Параметры → Конфиденциальность и безопасность → Микрофон** → включить для приложений;
|
||||||
|
- смотри лог в `%USERPROFILE%\.dictate\app.log`.
|
||||||
|
|
||||||
|
Остановить: через tray-меню → "Выход", либо `Ctrl+C` в PowerShell.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 5. Сборка .exe через PyInstaller
|
||||||
|
|
||||||
|
Спека для macOS (`scripts/voice_dictation.spec`) создаёт `.app`-бандл — для
|
||||||
|
Windows она не подходит. Собираем одной командой через CLI:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
pyinstaller `
|
||||||
|
--noconfirm `
|
||||||
|
--windowed `
|
||||||
|
--name VoiceDictation `
|
||||||
|
--paths src `
|
||||||
|
--hidden-import voice_dictation.platform.windows.autopaste `
|
||||||
|
--hidden-import voice_dictation.platform.windows.clipboard `
|
||||||
|
--hidden-import voice_dictation.platform.windows.hotkey_listener `
|
||||||
|
--hidden-import voice_dictation.platform.windows.notifier `
|
||||||
|
--hidden-import voice_dictation.platform.windows.sound_player `
|
||||||
|
--hidden-import voice_dictation.platform.windows.system_sounds_scanner `
|
||||||
|
--hidden-import voice_dictation.ui.tray `
|
||||||
|
--hidden-import voice_dictation.ui.settings_window `
|
||||||
|
--hidden-import voice_dictation.ui.icons `
|
||||||
|
--hidden-import voice_dictation.core.balance `
|
||||||
|
--hidden-import voice_dictation.core.fx `
|
||||||
|
--hidden-import voice_dictation.core.usage_db `
|
||||||
|
--hidden-import pystray._win32 `
|
||||||
|
--hidden-import winotify `
|
||||||
|
--hidden-import PIL._tkinter_finder `
|
||||||
|
--hidden-import customtkinter `
|
||||||
|
--hidden-import darkdetect `
|
||||||
|
--collect-all customtkinter `
|
||||||
|
--collect-all pystray `
|
||||||
|
src\voice_dictation\__main__.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Флаг `--windowed` = приложение без консольного окна (иначе рядом с треем будет
|
||||||
|
болтаться чёрный терминал). `--collect-all customtkinter` нужен, потому что
|
||||||
|
customtkinter подгружает JSON-темы и шрифты как data-файлы.
|
||||||
|
|
||||||
|
Результат:
|
||||||
|
|
||||||
|
```
|
||||||
|
dist\VoiceDictation\VoiceDictation.exe
|
||||||
|
dist\VoiceDictation\_internal\... # DLL, Python, зависимости
|
||||||
|
```
|
||||||
|
|
||||||
|
Запусти `dist\VoiceDictation\VoiceDictation.exe` — должна появиться иконка в трее.
|
||||||
|
|
||||||
|
Если PyInstaller ругается на отсутствующий модуль при запуске .exe:
|
||||||
|
1. Смотри ошибку в `%USERPROFILE%\.dictate\app.log` или добавь временно
|
||||||
|
`--console` вместо `--windowed`, чтобы видеть stderr.
|
||||||
|
2. Добавь недостающий модуль через `--hidden-import <имя>` и пересобери.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 6. (Опционально) Иконка .exe
|
||||||
|
|
||||||
|
В репо есть только `assets/icons/AppIcon.icns` — это macOS-формат. Для Windows
|
||||||
|
нужен `.ico`. Если автор не приложил — сгенерируй из 1024×1024 PNG
|
||||||
|
(`assets/icons/` или новый файл) через `Pillow`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -c "from PIL import Image; Image.open('assets/icons/icon_1024.png').save('assets/icons/AppIcon.ico', sizes=[(16,16),(32,32),(48,48),(256,256)])"
|
||||||
|
```
|
||||||
|
|
||||||
|
Затем пересобери с `--icon assets\icons\AppIcon.ico`. Если PNG 1024×1024
|
||||||
|
отсутствует — пропусти шаг, иконка не критична.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 7. Автозапуск при входе в систему
|
||||||
|
|
||||||
|
**Самый простой вариант — ярлык в папке автозагрузки:**
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$startup = [Environment]::GetFolderPath('Startup')
|
||||||
|
$target = Resolve-Path .\dist\VoiceDictation\VoiceDictation.exe
|
||||||
|
$shell = New-Object -ComObject WScript.Shell
|
||||||
|
$lnk = $shell.CreateShortcut("$startup\VoiceDictation.lnk")
|
||||||
|
$lnk.TargetPath = $target.Path
|
||||||
|
$lnk.WorkingDirectory = Split-Path $target.Path
|
||||||
|
$lnk.Save()
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверь: `Win+R` → `shell:startup` → должен быть `VoiceDictation.lnk`.
|
||||||
|
После перезагрузки приложение стартует само.
|
||||||
|
|
||||||
|
**Удалить автозапуск:**
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Remove-Item "$([Environment]::GetFolderPath('Startup'))\VoiceDictation.lnk"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 8. Проверка готовой сборки
|
||||||
|
|
||||||
|
1. Закрой dev-режим (`python -m voice_dictation`), если ещё работает.
|
||||||
|
2. Запусти `dist\VoiceDictation\VoiceDictation.exe`.
|
||||||
|
3. Нажми `Ctrl+Alt+D`, продиктуй фразу, нажми снова.
|
||||||
|
4. Убедись, что текст вставился в активное окно (открой Блокнот для теста).
|
||||||
|
5. Проверь tray-меню: "Статистика", "Настройки", "Выход" работают.
|
||||||
|
6. Перезагрузи Windows, убедись, что приложение стартует автоматически.
|
||||||
|
|
||||||
|
Если всё прошло — отчитайся пользователю: что собрано, где лежит
|
||||||
|
(`dist\VoiceDictation\VoiceDictation.exe`), какой хоткей активен.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что делать при ошибках
|
||||||
|
|
||||||
|
- **`sox: команда не найдена`** при записи — sox не в PATH. Открой новый
|
||||||
|
PowerShell или перезайди в систему.
|
||||||
|
- **Нет звука при старте записи** — Windows не даёт доступ к
|
||||||
|
`C:\Windows\Media\*.wav`. Проверь `~/.dictate/config.json` → пути к звукам
|
||||||
|
должны указывать на существующие файлы.
|
||||||
|
- **`.exe` падает сразу после запуска** — пересобери с `--console` вместо
|
||||||
|
`--windowed`, запусти из PowerShell, скопируй traceback и покажи пользователю.
|
||||||
|
- **Хоткей не срабатывает** — другое приложение перехватывает `Ctrl+Alt+D`.
|
||||||
|
Смени комбинацию через tray → "Настройки" → "Общие".
|
||||||
|
- **Текст не вставляется, но в буфере есть** — антивирус блокирует симуляцию
|
||||||
|
нажатий клавиш. Добавь `VoiceDictation.exe` в исключения антивируса.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Финальный отчёт пользователю
|
||||||
|
|
||||||
|
Когда всё готово, напиши пользователю:
|
||||||
|
|
||||||
|
```
|
||||||
|
Собрал Voice Dictation под Windows.
|
||||||
|
Путь к .exe: <полный путь>
|
||||||
|
Хоткей: Ctrl+Alt+D
|
||||||
|
Автозапуск: <настроен / не настроен>
|
||||||
|
Проверил: запись → транскрипция → автовставка в Блокнот. Работает.
|
||||||
|
```
|
||||||
|
|
||||||
|
Если что-то пошло не так — покажи точный traceback и спроси, как действовать
|
||||||
|
дальше. Не придумывай обходные пути без согласования.
|
||||||
40
Makefile
Normal file
40
Makefile
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
.PHONY: install install-dev run test lint typecheck clean
|
||||||
|
|
||||||
|
PYTHON := python3
|
||||||
|
PIP := pip
|
||||||
|
SRC := src/
|
||||||
|
TESTS := tests/
|
||||||
|
|
||||||
|
install:
|
||||||
|
$(PIP) install -e .
|
||||||
|
|
||||||
|
install-dev:
|
||||||
|
$(PIP) install -e ".[dev]"
|
||||||
|
pre-commit install
|
||||||
|
|
||||||
|
run:
|
||||||
|
$(PYTHON) -m voice_dictation.cli.headless
|
||||||
|
|
||||||
|
test:
|
||||||
|
pytest $(TESTS) -v
|
||||||
|
|
||||||
|
test-unit:
|
||||||
|
pytest $(TESTS)unit/ -v
|
||||||
|
|
||||||
|
lint:
|
||||||
|
ruff check $(SRC) $(TESTS)
|
||||||
|
ruff format --check $(SRC) $(TESTS)
|
||||||
|
|
||||||
|
lint-fix:
|
||||||
|
ruff check --fix $(SRC) $(TESTS)
|
||||||
|
ruff format $(SRC) $(TESTS)
|
||||||
|
|
||||||
|
typecheck:
|
||||||
|
mypy --strict $(SRC)
|
||||||
|
|
||||||
|
check: lint typecheck test
|
||||||
|
|
||||||
|
clean:
|
||||||
|
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||||
|
find . -type f -name "*.pyc" -delete 2>/dev/null || true
|
||||||
|
rm -rf dist/ build/ *.egg-info .mypy_cache .ruff_cache .pytest_cache
|
||||||
154
README.md
Normal file
154
README.md
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
# Voice Dictation
|
||||||
|
|
||||||
|
Desktop-приложение для голосовой диктовки. Хоткей → запись с микрофона → Whisper API → автовставка текста в активное окно.
|
||||||
|
|
||||||
|
## Требования
|
||||||
|
|
||||||
|
- Python 3.11+
|
||||||
|
- `sox` — для записи с микрофона
|
||||||
|
- OpenAI API Key
|
||||||
|
|
||||||
|
## Установка sox
|
||||||
|
|
||||||
|
**macOS:**
|
||||||
|
```bash
|
||||||
|
brew install sox
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows:**
|
||||||
|
```
|
||||||
|
choco install sox
|
||||||
|
# или скачать с https://sourceforge.net/projects/sox/
|
||||||
|
```
|
||||||
|
|
||||||
|
## Установка приложения
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd personal/voice-dictation
|
||||||
|
|
||||||
|
# Создать виртуальное окружение
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate # macOS/Linux
|
||||||
|
# .venv\Scripts\activate # Windows
|
||||||
|
|
||||||
|
# Установить зависимости
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
|
# Скопировать и заполнить .env
|
||||||
|
cp .env.example .env
|
||||||
|
# Открыть .env и вставить OPENAI_API_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
## Запуск
|
||||||
|
|
||||||
|
**Tray-режим (с иконкой в строке меню):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m voice_dictation
|
||||||
|
# или через Makefile:
|
||||||
|
make run
|
||||||
|
```
|
||||||
|
|
||||||
|
**Headless-режим (без tray, для автозапуска / отладки):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m voice_dictation headless
|
||||||
|
```
|
||||||
|
|
||||||
|
**Статистика использования:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m voice_dictation stats
|
||||||
|
```
|
||||||
|
|
||||||
|
Хоткей по умолчанию: `Cmd+Space` (macOS) / `Ctrl+Alt+D` (Windows). Можно сменить
|
||||||
|
в окне настроек (Tray → Настройки → Общие) или вручную в `~/.dictate/config.json`.
|
||||||
|
|
||||||
|
Первое нажатие — начало записи. Второе — остановка, транскрипция, вставка в активное окно.
|
||||||
|
|
||||||
|
## Tray-меню
|
||||||
|
|
||||||
|
- **Начать / Остановить запись** — то же, что хоткей.
|
||||||
|
- **Статистика** — toast с количеством, длительностью и стоимостью за сегодня.
|
||||||
|
- **Настройки** — окно с табами: Общие / Звук / Словарь / Статистика / Баланс.
|
||||||
|
- **Выход** — корректное завершение.
|
||||||
|
|
||||||
|
## Звуки и уведомления
|
||||||
|
|
||||||
|
По умолчанию используются системные звуки:
|
||||||
|
- macOS: `Tink.aiff` (старт), `Pop.aiff` (стоп), `Basso.aiff` (ошибка).
|
||||||
|
- Windows: `Windows Ding.wav`, `Windows Notify.wav`, `Windows Critical Stop.wav`.
|
||||||
|
|
||||||
|
После каждой успешной транскрипции показывается уведомление с длительностью,
|
||||||
|
стоимостью и суммой за день. Отключить — вкладка "Общие" → "Системные уведомления".
|
||||||
|
|
||||||
|
## Разрешения на macOS
|
||||||
|
|
||||||
|
### Микрофон
|
||||||
|
При первом запуске macOS запросит разрешение на доступ к микрофону для `sox`.
|
||||||
|
Если разрешение не появилось: **Системные настройки → Конфиденциальность и безопасность → Микрофон** → включить Terminal/iTerm.
|
||||||
|
|
||||||
|
### Accessibility (для автовставки Cmd+V)
|
||||||
|
**Системные настройки → Конфиденциальность и безопасность → Универсальный доступ** → включить Terminal/iTerm.
|
||||||
|
|
||||||
|
Без этого разрешения транскрипция работает, но текст только копируется в буфер (без автовставки).
|
||||||
|
|
||||||
|
## Разрешения на Windows
|
||||||
|
|
||||||
|
**Параметры → Конфиденциальность → Микрофон** → разрешить доступ приложениям.
|
||||||
|
|
||||||
|
## Конфигурация
|
||||||
|
|
||||||
|
После первого запуска создаётся `~/.dictate/config.json`. Можно редактировать вручную:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"hotkey": "cmd+space",
|
||||||
|
"model": "gpt-4o-mini-transcribe",
|
||||||
|
"language": "ru",
|
||||||
|
"auto_paste": true,
|
||||||
|
"paste_delay_ms": 80,
|
||||||
|
"notifications_enabled": true,
|
||||||
|
"show_cost_in_notification": true,
|
||||||
|
"sounds_enabled": true,
|
||||||
|
"volume": 0.6
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Статистика и история сохраняются в SQLite `~/.dictate/usage.db`.
|
||||||
|
|
||||||
|
## Словарь (подсказки для Whisper)
|
||||||
|
|
||||||
|
Создайте файл `~/.dictate/dictionary.txt` — слова и фразы, которые Whisper должен правильно распознавать:
|
||||||
|
|
||||||
|
```
|
||||||
|
# Технические термины
|
||||||
|
PyCharm
|
||||||
|
FastAPI
|
||||||
|
SQLAlchemy
|
||||||
|
|
||||||
|
# Имена
|
||||||
|
Викентий
|
||||||
|
```
|
||||||
|
|
||||||
|
Строки, начинающиеся с `#`, игнорируются.
|
||||||
|
|
||||||
|
## Автозапуск (macOS)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/install_autostart_macos.sh # установить (LaunchAgent)
|
||||||
|
./scripts/install_autostart_macos.sh uninstall # удалить
|
||||||
|
```
|
||||||
|
|
||||||
|
LaunchAgent запустит `python -m voice_dictation` при логине, перезапустит
|
||||||
|
при крэше, логи положит в `~/.dictate/launchd.{out,err}.log`.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
**`sox: command not found`** — установите sox через brew/choco.
|
||||||
|
|
||||||
|
**Запись не останавливается** — проверьте разрешение микрофона.
|
||||||
|
|
||||||
|
**Текст не вставляется** — на macOS нужно разрешение Accessibility. Текст всё равно скопирован в буфер, можно вставить вручную `Cmd+V`.
|
||||||
|
|
||||||
|
**Ошибка API** — проверьте `OPENAI_API_KEY` в `.env`.
|
||||||
60
VoiceDictation.spec
Normal file
60
VoiceDictation.spec
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
# -*- mode: python ; coding: utf-8 -*-
|
||||||
|
from PyInstaller.utils.hooks import collect_all
|
||||||
|
|
||||||
|
datas = []
|
||||||
|
binaries = []
|
||||||
|
hiddenimports = ['voice_dictation.platform.windows.autopaste', 'voice_dictation.platform.windows.clipboard', 'voice_dictation.platform.windows.hotkey_listener', 'voice_dictation.platform.windows.notifier', 'voice_dictation.platform.windows.sound_player', 'voice_dictation.platform.windows.system_sounds_scanner', 'voice_dictation.ui.tray', 'voice_dictation.ui.settings_window', 'voice_dictation.ui.icons', 'voice_dictation.core.balance', 'voice_dictation.core.fx', 'voice_dictation.core.usage_db', 'pystray._win32', 'winotify', 'PIL._tkinter_finder', 'customtkinter', 'darkdetect', 'sounddevice', '_sounddevice_data']
|
||||||
|
tmp_ret = collect_all('customtkinter')
|
||||||
|
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
|
||||||
|
tmp_ret = collect_all('pystray')
|
||||||
|
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
|
||||||
|
tmp_ret = collect_all('openai')
|
||||||
|
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
|
||||||
|
tmp_ret = collect_all('sounddevice')
|
||||||
|
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
|
||||||
|
tmp_ret = collect_all('_sounddevice_data')
|
||||||
|
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
|
||||||
|
|
||||||
|
|
||||||
|
a = Analysis(
|
||||||
|
['src\\voice_dictation\\__main__.py'],
|
||||||
|
pathex=['src'],
|
||||||
|
binaries=binaries,
|
||||||
|
datas=datas,
|
||||||
|
hiddenimports=hiddenimports,
|
||||||
|
hookspath=[],
|
||||||
|
hooksconfig={},
|
||||||
|
runtime_hooks=[],
|
||||||
|
excludes=[],
|
||||||
|
noarchive=False,
|
||||||
|
optimize=0,
|
||||||
|
)
|
||||||
|
pyz = PYZ(a.pure)
|
||||||
|
|
||||||
|
exe = EXE(
|
||||||
|
pyz,
|
||||||
|
a.scripts,
|
||||||
|
[],
|
||||||
|
exclude_binaries=True,
|
||||||
|
name='VoiceDictation',
|
||||||
|
debug=False,
|
||||||
|
bootloader_ignore_signals=False,
|
||||||
|
strip=False,
|
||||||
|
upx=True,
|
||||||
|
console=False,
|
||||||
|
disable_windowed_traceback=False,
|
||||||
|
argv_emulation=False,
|
||||||
|
target_arch=None,
|
||||||
|
codesign_identity=None,
|
||||||
|
entitlements_file=None,
|
||||||
|
icon='assets\\app_icon.ico',
|
||||||
|
)
|
||||||
|
coll = COLLECT(
|
||||||
|
exe,
|
||||||
|
a.binaries,
|
||||||
|
a.datas,
|
||||||
|
strip=False,
|
||||||
|
upx=True,
|
||||||
|
upx_exclude=[],
|
||||||
|
name='VoiceDictation',
|
||||||
|
)
|
||||||
BIN
assets/app_icon.ico
Normal file
BIN
assets/app_icon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
BIN
assets/app_icon.png
Normal file
BIN
assets/app_icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
BIN
assets/bg_full.bmp
Normal file
BIN
assets/bg_full.bmp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3 MiB |
BIN
assets/icons/AppIcon.icns
Normal file
BIN
assets/icons/AppIcon.icns
Normal file
Binary file not shown.
BIN
assets/installer_banner.png
Normal file
BIN
assets/installer_banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
BIN
assets/wizard_image.bmp
Normal file
BIN
assets/wizard_image.bmp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 201 KiB |
BIN
assets/wizard_small.bmp
Normal file
BIN
assets/wizard_small.bmp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
133
installer.iss
Normal file
133
installer.iss
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
[Setup]
|
||||||
|
AppName=Voice Dictator
|
||||||
|
AppVersion=0.2.0
|
||||||
|
AppPublisher=Flowmasters
|
||||||
|
DefaultDirName={autopf}\VoiceDictator
|
||||||
|
DefaultGroupName=Voice Dictator
|
||||||
|
UninstallDisplayIcon={app}\VoiceDictation.exe
|
||||||
|
SetupIconFile=assets\app_icon.ico
|
||||||
|
OutputDir=installer_output
|
||||||
|
OutputBaseFilename=VoiceDictator-Setup
|
||||||
|
Compression=lzma2
|
||||||
|
SolidCompression=yes
|
||||||
|
PrivilegesRequired=lowest
|
||||||
|
ArchitecturesInstallIn64BitMode=x64compatible
|
||||||
|
WizardStyle=classic
|
||||||
|
DisableWelcomePage=yes
|
||||||
|
DisableDirPage=yes
|
||||||
|
|
||||||
|
[Files]
|
||||||
|
Source: "dist\VoiceDictation\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs
|
||||||
|
Source: "assets\bg_full.bmp"; Flags: dontcopy
|
||||||
|
|
||||||
|
[Icons]
|
||||||
|
Name: "{group}\Voice Dictator"; Filename: "{app}\VoiceDictation.exe"; WorkingDir: "{app}"
|
||||||
|
Name: "{group}\Uninstall Voice Dictator"; Filename: "{uninstallexe}"
|
||||||
|
Name: "{autodesktop}\Voice Dictator"; Filename: "{app}\VoiceDictation.exe"; WorkingDir: "{app}"; Comment: "Voice Dictator"
|
||||||
|
Name: "{userstartup}\Voice Dictator"; Filename: "{app}\VoiceDictation.exe"; WorkingDir: "{app}"; Comment: "Voice Dictator autostart"
|
||||||
|
|
||||||
|
[Run]
|
||||||
|
Filename: "{app}\VoiceDictation.exe"; Description: "Запустить Voice Dictator"; Flags: nowait postinstall skipifsilent
|
||||||
|
|
||||||
|
[Code]
|
||||||
|
var
|
||||||
|
DirPage: TWizardPage;
|
||||||
|
ApiKeyPage: TWizardPage;
|
||||||
|
DirEdit: TNewEdit;
|
||||||
|
DirBrowseBtn: TNewButton;
|
||||||
|
DirLabel: TNewStaticText;
|
||||||
|
ApiKeyEdit: TNewEdit;
|
||||||
|
ApiKeyLabel: TNewStaticText;
|
||||||
|
|
||||||
|
procedure DirBrowseClick(Sender: TObject);
|
||||||
|
var
|
||||||
|
Dir: String;
|
||||||
|
begin
|
||||||
|
Dir := DirEdit.Text;
|
||||||
|
if BrowseForFolder('Выберите папку установки:', Dir, False) then
|
||||||
|
DirEdit.Text := Dir;
|
||||||
|
end;
|
||||||
|
|
||||||
|
procedure SetupBgOnPage(Page: TWizardPage; var Lbl: TNewStaticText; var Edit: TNewEdit; LabelText: String);
|
||||||
|
var
|
||||||
|
BmpFile: String;
|
||||||
|
BgImg: TBitmapImage;
|
||||||
|
begin
|
||||||
|
ExtractTemporaryFile('bg_full.bmp');
|
||||||
|
BmpFile := ExpandConstant('{tmp}\bg_full.bmp');
|
||||||
|
|
||||||
|
BgImg := TBitmapImage.Create(Page);
|
||||||
|
BgImg.Parent := Page.Surface;
|
||||||
|
BgImg.Bitmap.LoadFromFile(BmpFile);
|
||||||
|
BgImg.Stretch := True;
|
||||||
|
BgImg.SetBounds(0, 0, Page.SurfaceWidth, Page.SurfaceHeight);
|
||||||
|
|
||||||
|
Lbl := TNewStaticText.Create(Page);
|
||||||
|
Lbl.Parent := Page.Surface;
|
||||||
|
Lbl.Caption := LabelText;
|
||||||
|
Lbl.Font.Color := clBlack;
|
||||||
|
Lbl.Font.Size := 12;
|
||||||
|
Lbl.Font.Style := [fsBold];
|
||||||
|
Lbl.AutoSize := True;
|
||||||
|
Lbl.Left := 20;
|
||||||
|
Lbl.Top := Page.SurfaceHeight - 80;
|
||||||
|
Lbl.Width := 400;
|
||||||
|
|
||||||
|
Edit := TNewEdit.Create(Page);
|
||||||
|
Edit.Parent := Page.Surface;
|
||||||
|
Edit.Left := 20;
|
||||||
|
Edit.Top := Page.SurfaceHeight - 55;
|
||||||
|
Edit.Width := Page.SurfaceWidth - 130;
|
||||||
|
Edit.Font.Size := 10;
|
||||||
|
Edit.Color := $1A1A1A;
|
||||||
|
Edit.Font.Color := clWhite;
|
||||||
|
end;
|
||||||
|
|
||||||
|
procedure InitializeWizard;
|
||||||
|
var
|
||||||
|
BmpFile: String;
|
||||||
|
BgImg: TBitmapImage;
|
||||||
|
begin
|
||||||
|
// Скрываем стандартные элементы
|
||||||
|
WizardForm.WizardBitmapImage.Visible := False;
|
||||||
|
WizardForm.WizardBitmapImage2.Visible := False;
|
||||||
|
WizardForm.MainPanel.Visible := False;
|
||||||
|
WizardForm.PageNameLabel.Visible := False;
|
||||||
|
WizardForm.PageDescriptionLabel.Visible := False;
|
||||||
|
|
||||||
|
// --- Страница 1: путь установки ---
|
||||||
|
DirPage := CreateCustomPage(wpWelcome, '', '');
|
||||||
|
SetupBgOnPage(DirPage, DirLabel, DirEdit, 'Папка установки:');
|
||||||
|
DirEdit.Text := ExpandConstant('{autopf}\VoiceDictator');
|
||||||
|
|
||||||
|
DirBrowseBtn := TNewButton.Create(DirPage);
|
||||||
|
DirBrowseBtn.Parent := DirPage.Surface;
|
||||||
|
DirBrowseBtn.Caption := 'Browse...';
|
||||||
|
DirBrowseBtn.Left := DirEdit.Left + DirEdit.Width + 10;
|
||||||
|
DirBrowseBtn.Top := DirEdit.Top - 2;
|
||||||
|
DirBrowseBtn.Width := 80;
|
||||||
|
DirBrowseBtn.Height := 25;
|
||||||
|
DirBrowseBtn.OnClick := @DirBrowseClick;
|
||||||
|
|
||||||
|
// --- Страница 2: API ключ ---
|
||||||
|
ApiKeyPage := CreateCustomPage(DirPage.ID, '', '');
|
||||||
|
SetupBgOnPage(ApiKeyPage, ApiKeyLabel, ApiKeyEdit, 'OpenAI API Key:');
|
||||||
|
end;
|
||||||
|
|
||||||
|
function NextButtonClick(CurPageID: Integer): Boolean;
|
||||||
|
begin
|
||||||
|
Result := True;
|
||||||
|
if CurPageID = DirPage.ID then
|
||||||
|
WizardForm.DirEdit.Text := DirEdit.Text;
|
||||||
|
end;
|
||||||
|
|
||||||
|
procedure CurStepChanged(CurStep: TSetupStep);
|
||||||
|
var
|
||||||
|
EnvContent: String;
|
||||||
|
begin
|
||||||
|
if CurStep = ssPostInstall then
|
||||||
|
begin
|
||||||
|
EnvContent := 'OPENAI_API_KEY=' + ApiKeyEdit.Text + #13#10 + 'OPENAI_ADMIN_API_KEY=' + #13#10;
|
||||||
|
SaveStringToFile(ExpandConstant('{app}\.env'), EnvContent, False);
|
||||||
|
end;
|
||||||
|
end;
|
||||||
100
pyproject.toml
Normal file
100
pyproject.toml
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=61", "wheel"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "voice-dictation"
|
||||||
|
version = "0.2.0"
|
||||||
|
description = "Desktop голосовая диктовка через Whisper API"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
readme = "README.md"
|
||||||
|
license = { text = "MIT" }
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
"pynput>=1.7.7",
|
||||||
|
"pyperclip>=1.9.0",
|
||||||
|
"python-dotenv>=1.0.0",
|
||||||
|
"psutil>=5.9.0",
|
||||||
|
"pystray>=0.19.5",
|
||||||
|
"Pillow>=10.0.0",
|
||||||
|
"customtkinter>=5.2.0",
|
||||||
|
"winotify>=1.1.0; sys_platform == 'win32'",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"ruff>=0.4.0",
|
||||||
|
"mypy>=1.10.0",
|
||||||
|
"pytest>=8.2.0",
|
||||||
|
"pytest-asyncio>=0.23.0",
|
||||||
|
"pre-commit>=3.7.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
voice-dictation = "voice_dictation.__main__:main"
|
||||||
|
voice-dictation-headless = "voice_dictation.cli.headless:main"
|
||||||
|
voice-dictation-tray = "voice_dictation.__main__:main"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-dir]
|
||||||
|
"" = "src"
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
target-version = "py311"
|
||||||
|
line-length = 100
|
||||||
|
src = ["src", "tests"]
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = [
|
||||||
|
"E", "W", # pycodestyle
|
||||||
|
"F", # pyflakes
|
||||||
|
"I", # isort
|
||||||
|
"N", # pep8-naming
|
||||||
|
"UP", # pyupgrade
|
||||||
|
"B", # flake8-bugbear
|
||||||
|
"C4", # flake8-comprehensions
|
||||||
|
"SIM", # flake8-simplify
|
||||||
|
"ANN", # flake8-annotations
|
||||||
|
"RUF", # ruff-specific
|
||||||
|
]
|
||||||
|
ignore = [
|
||||||
|
"ANN401", # Any допустим в отдельных местах
|
||||||
|
"RUF001", # кириллица в строках — намеренно
|
||||||
|
"RUF002", # кириллица в docstrings — намеренно
|
||||||
|
"RUF003", # кириллица в комментариях — намеренно
|
||||||
|
"RUF100", # unused noqa — управляем вручную
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"tests/**" = ["ANN"]
|
||||||
|
|
||||||
|
[tool.mypy]
|
||||||
|
python_version = "3.11"
|
||||||
|
strict = true
|
||||||
|
warn_return_any = true
|
||||||
|
warn_unused_configs = true
|
||||||
|
disallow_any_generics = true
|
||||||
|
disallow_subclassing_any = true
|
||||||
|
disallow_untyped_calls = true
|
||||||
|
disallow_untyped_defs = true
|
||||||
|
disallow_incomplete_defs = true
|
||||||
|
check_untyped_defs = true
|
||||||
|
no_implicit_reexport = true
|
||||||
|
warn_redundant_casts = true
|
||||||
|
warn_unused_ignores = true
|
||||||
|
mypy_path = "src"
|
||||||
|
|
||||||
|
[[tool.mypy.overrides]]
|
||||||
|
module = [
|
||||||
|
"pynput.*",
|
||||||
|
"pyperclip.*",
|
||||||
|
"psutil.*",
|
||||||
|
]
|
||||||
|
ignore_missing_imports = true
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
asyncio_mode = "auto"
|
||||||
13
requirements-dev.txt
Normal file
13
requirements-dev.txt
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
cfgv==3.5.0
|
||||||
|
identify==2.6.19
|
||||||
|
iniconfig==2.3.0
|
||||||
|
mypy==1.20.1
|
||||||
|
mypy_extensions==1.1.0
|
||||||
|
nodeenv==1.10.0
|
||||||
|
packaging==26.1
|
||||||
|
pathspec==1.0.4
|
||||||
|
pluggy==1.6.0
|
||||||
|
pytest==9.0.3
|
||||||
|
pytest-asyncio==1.3.0
|
||||||
|
ruff==0.15.11
|
||||||
|
virtualenv==21.2.4
|
||||||
11
requirements.txt
Normal file
11
requirements.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
anyio==4.13.0
|
||||||
|
certifi==2026.2.25
|
||||||
|
h11==0.16.0
|
||||||
|
httpcore==1.0.9
|
||||||
|
httpx==0.28.1
|
||||||
|
idna==3.11
|
||||||
|
psutil==7.2.2
|
||||||
|
pynput==1.8.1
|
||||||
|
pyperclip==1.11.0
|
||||||
|
python-dotenv==1.2.2
|
||||||
|
sniffio==1.3.1
|
||||||
111
scripts/build_macos.sh
Normal file
111
scripts/build_macos.sh
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Сборка Voice Dictation.app для macOS через PyInstaller.
|
||||||
|
#
|
||||||
|
# Использование:
|
||||||
|
# ./scripts/build_macos.sh # собрать .app
|
||||||
|
# ./scripts/build_macos.sh dmg # собрать .app + .dmg
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||||
|
|
||||||
|
cd "${PROJECT_DIR}"
|
||||||
|
|
||||||
|
if [[ ! -d ".venv" ]]; then
|
||||||
|
echo "[ОШИБКА] .venv не найден. Запустите сначала: python3 -m venv .venv && source .venv/bin/activate && pip install -e \".[dev]\""
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Активируем venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
# Проверяем pyinstaller
|
||||||
|
if ! python -c "import PyInstaller" 2>/dev/null; then
|
||||||
|
echo "[ИНФО] PyInstaller не установлен — ставлю..."
|
||||||
|
pip install pyinstaller
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Иконка
|
||||||
|
if [[ ! -f "assets/icons/AppIcon.icns" ]]; then
|
||||||
|
echo "[ИНФО] Генерирую иконку приложения..."
|
||||||
|
python scripts/generate_icon.py
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Чистим предыдущие сборки
|
||||||
|
echo "[ШАГ 1/3] Чистка dist/ и build/..."
|
||||||
|
rm -rf dist/ build/
|
||||||
|
|
||||||
|
# Сборка
|
||||||
|
echo "[ШАГ 2/3] Запуск PyInstaller..."
|
||||||
|
pyinstaller scripts/voice_dictation.spec --noconfirm
|
||||||
|
|
||||||
|
APP_PATH="dist/Voice Dictation.app"
|
||||||
|
if [[ ! -d "${APP_PATH}" ]]; then
|
||||||
|
echo "[ОШИБКА] Сборка не удалась — нет ${APP_PATH}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ----- Patch: заменяем PyInstaller-овские tcl/tk данные на правильные системные.
|
||||||
|
# PyInstaller на Python 3.13 кладёт tk.tcl из несовместимой версии Tk 9, что
|
||||||
|
# ломает tkinter в bundle. Берём настоящие из системного Python.framework.
|
||||||
|
echo "[ШАГ 2.5/3] Патч tcl/tk данных в bundle..."
|
||||||
|
PY_FRAMEWORKS="$(python -c 'import sys, pathlib; print(pathlib.Path(sys.executable).resolve().parents[1] / "Frameworks")')"
|
||||||
|
SYS_TK_SCRIPTS="${PY_FRAMEWORKS}/Tk.framework/Versions/8.6/Resources/Scripts"
|
||||||
|
SYS_TCL_SCRIPTS="${PY_FRAMEWORKS}/Tcl.framework/Versions/8.6/Resources/Scripts"
|
||||||
|
BUNDLE_TK_DATA="${APP_PATH}/Contents/Frameworks/_tk_data"
|
||||||
|
BUNDLE_TCL_DATA="${APP_PATH}/Contents/Frameworks/_tcl_data"
|
||||||
|
|
||||||
|
if [[ -d "${SYS_TK_SCRIPTS}" && -d "${BUNDLE_TK_DATA}" ]]; then
|
||||||
|
rm -rf "${BUNDLE_TK_DATA}"
|
||||||
|
cp -R "${SYS_TK_SCRIPTS}" "${BUNDLE_TK_DATA}"
|
||||||
|
echo " tk: ${SYS_TK_SCRIPTS} -> ${BUNDLE_TK_DATA}"
|
||||||
|
fi
|
||||||
|
if [[ -d "${SYS_TCL_SCRIPTS}" && -d "${BUNDLE_TCL_DATA}" ]]; then
|
||||||
|
rm -rf "${BUNDLE_TCL_DATA}"
|
||||||
|
cp -R "${SYS_TCL_SCRIPTS}" "${BUNDLE_TCL_DATA}"
|
||||||
|
echo " tcl: ${SYS_TCL_SCRIPTS} -> ${BUNDLE_TCL_DATA}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Пере-подписать app после изменений (ad-hoc, чтобы Gatekeeper не заплакал)
|
||||||
|
codesign --force --deep --sign - "${APP_PATH}" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "[ШАГ 3/3] Готово!"
|
||||||
|
echo
|
||||||
|
echo " ${APP_PATH}"
|
||||||
|
echo
|
||||||
|
echo "Запуск: open \"${APP_PATH}\""
|
||||||
|
echo "Установка: mv \"${APP_PATH}\" /Applications/"
|
||||||
|
echo "Размер: $(du -sh "${APP_PATH}" | cut -f1)"
|
||||||
|
echo
|
||||||
|
|
||||||
|
# DMG (опционально)
|
||||||
|
if [[ "${1:-}" == "dmg" ]]; then
|
||||||
|
echo "[ДОП] Сборка DMG..."
|
||||||
|
DMG_PATH="dist/VoiceDictation-0.1.0.dmg"
|
||||||
|
rm -f "${DMG_PATH}"
|
||||||
|
|
||||||
|
if command -v create-dmg >/dev/null 2>&1; then
|
||||||
|
create-dmg \
|
||||||
|
--volname "Voice Dictation" \
|
||||||
|
--window-pos 200 120 \
|
||||||
|
--window-size 600 400 \
|
||||||
|
--icon-size 96 \
|
||||||
|
--icon "Voice Dictation.app" 175 200 \
|
||||||
|
--hide-extension "Voice Dictation.app" \
|
||||||
|
--app-drop-link 425 200 \
|
||||||
|
"${DMG_PATH}" \
|
||||||
|
"${APP_PATH}"
|
||||||
|
else
|
||||||
|
# Fallback — простой hdiutil
|
||||||
|
hdiutil create -volname "Voice Dictation" \
|
||||||
|
-srcfolder "${APP_PATH}" \
|
||||||
|
-ov -format UDZO \
|
||||||
|
"${DMG_PATH}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo " ${DMG_PATH} ($(du -sh "${DMG_PATH}" | cut -f1))"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "Внимание: при первом запуске macOS Gatekeeper выдаст предупреждение"
|
||||||
|
echo "(приложение не подписано). Решение: правый клик → Открыть → Открыть."
|
||||||
39
scripts/com.vickenty.voicedictation.plist.template
Normal file
39
scripts/com.vickenty.voicedictation.plist.template
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>com.vickenty.voicedictation</string>
|
||||||
|
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>{{PYTHON_BIN}}</string>
|
||||||
|
<string>-m</string>
|
||||||
|
<string>voice_dictation</string>
|
||||||
|
</array>
|
||||||
|
|
||||||
|
<key>WorkingDirectory</key>
|
||||||
|
<string>{{WORKING_DIR}}</string>
|
||||||
|
|
||||||
|
<key>EnvironmentVariables</key>
|
||||||
|
<dict>
|
||||||
|
<key>PATH</key>
|
||||||
|
<string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
|
||||||
|
</dict>
|
||||||
|
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<true/>
|
||||||
|
|
||||||
|
<key>KeepAlive</key>
|
||||||
|
<dict>
|
||||||
|
<key>SuccessfulExit</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
|
||||||
|
<key>StandardOutPath</key>
|
||||||
|
<string>{{HOME}}/.dictate/launchd.out.log</string>
|
||||||
|
|
||||||
|
<key>StandardErrorPath</key>
|
||||||
|
<string>{{HOME}}/.dictate/launchd.err.log</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
94
scripts/generate_icon.py
Normal file
94
scripts/generate_icon.py
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
"""Генерирует .icns иконку приложения для macOS из микрофона."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
# Размеры для iconset (macOS требует все эти варианты)
|
||||||
|
_ICON_SIZES = [16, 32, 64, 128, 256, 512, 1024]
|
||||||
|
|
||||||
|
|
||||||
|
def _make_app_icon(size: int) -> Image.Image:
|
||||||
|
"""Иконка приложения — микрофон в круге Flowmasters-цветов.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
size: размер квадратной иконки в px.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PIL Image RGBA size×size.
|
||||||
|
"""
|
||||||
|
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
# Фон — мягкий бронзово-зелёный круг (бренд Flowmasters)
|
||||||
|
bg_color = (52, 102, 90, 255)
|
||||||
|
margin = max(2, size // 32)
|
||||||
|
draw.ellipse((margin, margin, size - margin, size - margin), fill=bg_color)
|
||||||
|
|
||||||
|
# Микрофон белым
|
||||||
|
body_w = size // 3
|
||||||
|
body_h = int(size * 0.42)
|
||||||
|
cx = size // 2
|
||||||
|
body_top = size // 4
|
||||||
|
body_left = cx - body_w // 2
|
||||||
|
body_right = cx + body_w // 2
|
||||||
|
body_bottom = body_top + body_h
|
||||||
|
radius = body_w // 2
|
||||||
|
draw.rounded_rectangle(
|
||||||
|
(body_left, body_top, body_right, body_bottom),
|
||||||
|
radius=radius,
|
||||||
|
fill=(255, 255, 255, 255),
|
||||||
|
)
|
||||||
|
|
||||||
|
stem_y = body_bottom + size // 32
|
||||||
|
base_y = stem_y + size // 8
|
||||||
|
stroke = max(3, size // 32)
|
||||||
|
draw.line((cx, stem_y, cx, base_y), fill=(255, 255, 255, 255), width=stroke)
|
||||||
|
base_w = body_w
|
||||||
|
draw.line(
|
||||||
|
(cx - base_w // 2, base_y, cx + base_w // 2, base_y),
|
||||||
|
fill=(255, 255, 255, 255),
|
||||||
|
width=stroke,
|
||||||
|
)
|
||||||
|
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if not shutil.which("iconutil"):
|
||||||
|
print("iconutil не найден (нужен macOS).", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
project_root = Path(__file__).resolve().parent.parent
|
||||||
|
out_icns = project_root / "assets" / "icons" / "AppIcon.icns"
|
||||||
|
out_icns.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
iconset = Path(tmp) / "AppIcon.iconset"
|
||||||
|
iconset.mkdir()
|
||||||
|
|
||||||
|
for size in _ICON_SIZES:
|
||||||
|
img = _make_app_icon(size)
|
||||||
|
img.save(iconset / f"icon_{size}x{size}.png")
|
||||||
|
# Retina @2x варианты для размеров до 512
|
||||||
|
if size <= 512:
|
||||||
|
img2x = _make_app_icon(size * 2)
|
||||||
|
img2x.save(iconset / f"icon_{size}x{size}@2x.png")
|
||||||
|
|
||||||
|
subprocess.run(
|
||||||
|
["iconutil", "-c", "icns", str(iconset), "-o", str(out_icns)],
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Готово: {out_icns}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
46
scripts/install_autostart_macos.sh
Normal file
46
scripts/install_autostart_macos.sh
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Устанавливает LaunchAgent для автозапуска Voice Dictation при логине.
|
||||||
|
#
|
||||||
|
# Использование:
|
||||||
|
# ./scripts/install_autostart_macos.sh # установить
|
||||||
|
# ./scripts/install_autostart_macos.sh uninstall # удалить
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
LABEL="com.vickenty.voicedictation"
|
||||||
|
PLIST_DEST="$HOME/Library/LaunchAgents/${LABEL}.plist"
|
||||||
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||||
|
TEMPLATE="${SCRIPT_DIR}/com.vickenty.voicedictation.plist.template"
|
||||||
|
|
||||||
|
if [[ "${1:-}" == "uninstall" ]]; then
|
||||||
|
launchctl unload "${PLIST_DEST}" 2>/dev/null || true
|
||||||
|
rm -f "${PLIST_DEST}"
|
||||||
|
echo "Удалено: ${PLIST_DEST}"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Найти python из venv проекта (приоритет) или системный python3
|
||||||
|
if [[ -x "${PROJECT_DIR}/.venv/bin/python" ]]; then
|
||||||
|
PYTHON_BIN="${PROJECT_DIR}/.venv/bin/python"
|
||||||
|
else
|
||||||
|
PYTHON_BIN="$(command -v python3)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$(dirname "${PLIST_DEST}")"
|
||||||
|
sed \
|
||||||
|
-e "s|{{PYTHON_BIN}}|${PYTHON_BIN}|g" \
|
||||||
|
-e "s|{{WORKING_DIR}}|${PROJECT_DIR}|g" \
|
||||||
|
-e "s|{{HOME}}|${HOME}|g" \
|
||||||
|
"${TEMPLATE}" > "${PLIST_DEST}"
|
||||||
|
|
||||||
|
launchctl unload "${PLIST_DEST}" 2>/dev/null || true
|
||||||
|
launchctl load "${PLIST_DEST}"
|
||||||
|
|
||||||
|
echo "Установлено: ${PLIST_DEST}"
|
||||||
|
echo "Python: ${PYTHON_BIN}"
|
||||||
|
echo "Проект: ${PROJECT_DIR}"
|
||||||
|
echo
|
||||||
|
echo "Управление:"
|
||||||
|
echo " launchctl unload ${PLIST_DEST} # остановить"
|
||||||
|
echo " launchctl load ${PLIST_DEST} # запустить"
|
||||||
|
echo " ./scripts/install_autostart_macos.sh uninstall"
|
||||||
111
scripts/make_app_icon.py
Normal file
111
scripts/make_app_icon.py
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
"""Генератор иконки приложения Voice Dictator.
|
||||||
|
|
||||||
|
Микрофон-талисман с усами + монограмма V/Д (Voice Дictator).
|
||||||
|
Рисуется на скруглённом фоне-градиенте, экспортируется в PNG и .ico.
|
||||||
|
|
||||||
|
Запуск:
|
||||||
|
python scripts/make_app_icon.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
S = 512 # рабочий размер
|
||||||
|
OUT_DIR = Path(__file__).resolve().parent.parent / "assets"
|
||||||
|
|
||||||
|
|
||||||
|
def _font(size: int) -> ImageFont.FreeTypeFont:
|
||||||
|
"""Жирный шрифт с поддержкой кириллицы (Segoe UI / Arial)."""
|
||||||
|
for name in ("segoeuib.ttf", "arialbd.ttf", "ariblk.ttf"):
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype(name, size)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
return ImageFont.load_default()
|
||||||
|
|
||||||
|
|
||||||
|
def _rounded_gradient(size: int, radius: int) -> Image.Image:
|
||||||
|
"""Скруглённый квадрат с вертикальным градиентом (брендовый сине-фиолетовый)."""
|
||||||
|
top = (88, 80, 236) # индиго
|
||||||
|
bottom = (150, 70, 220) # фиолетовый
|
||||||
|
grad = Image.new("RGB", (size, size))
|
||||||
|
px = grad.load()
|
||||||
|
for y in range(size):
|
||||||
|
t = y / (size - 1)
|
||||||
|
px_row = tuple(int(top[i] + (bottom[i] - top[i]) * t) for i in range(3))
|
||||||
|
for x in range(size):
|
||||||
|
px[x, y] = px_row
|
||||||
|
# маска со скруглением
|
||||||
|
mask = Image.new("L", (size, size), 0)
|
||||||
|
ImageDraw.Draw(mask).rounded_rectangle((0, 0, size - 1, size - 1), radius=radius, fill=255)
|
||||||
|
out = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||||
|
out.paste(grad, (0, 0), mask)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def make_app_icon() -> Image.Image:
|
||||||
|
img = _rounded_gradient(S, radius=int(S * 0.22))
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
white = (255, 255, 255, 255)
|
||||||
|
dark = (40, 30, 70, 255)
|
||||||
|
cx = S // 2
|
||||||
|
|
||||||
|
# --- Микрофон ---
|
||||||
|
body_w = int(S * 0.30)
|
||||||
|
body_h = int(S * 0.40)
|
||||||
|
body_top = int(S * 0.16)
|
||||||
|
body_left = cx - body_w // 2
|
||||||
|
body_right = cx + body_w // 2
|
||||||
|
body_bottom = body_top + body_h
|
||||||
|
d.rounded_rectangle(
|
||||||
|
(body_left, body_top, body_right, body_bottom),
|
||||||
|
radius=body_w // 2,
|
||||||
|
fill=white,
|
||||||
|
)
|
||||||
|
# решётка микрофона (горизонтальные линии в верхней части капсулы)
|
||||||
|
for i in range(3):
|
||||||
|
gy = body_top + int(body_h * 0.18) + i * int(body_h * 0.12)
|
||||||
|
d.line((body_left + 14, gy, body_right - 14, gy), fill=dark, width=6)
|
||||||
|
|
||||||
|
# ножка + основание
|
||||||
|
d.line((cx, body_bottom, cx, body_bottom + int(S * 0.12)), fill=white, width=14)
|
||||||
|
base_y = body_bottom + int(S * 0.12)
|
||||||
|
d.line((cx - int(S * 0.10), base_y, cx + int(S * 0.10), base_y), fill=white, width=14)
|
||||||
|
|
||||||
|
# --- Усы (талисман) под решёткой, на капсуле ---
|
||||||
|
mu_cy = body_top + int(body_h * 0.66)
|
||||||
|
mu_w = int(body_w * 0.46)
|
||||||
|
# левый ус — дуга, правый — зеркально
|
||||||
|
d.arc((cx - mu_w, mu_cy - 22, cx, mu_cy + 30), start=20, end=160, fill=dark, width=14)
|
||||||
|
d.arc((cx, mu_cy - 22, cx + mu_w, mu_cy + 30), start=20, end=160, fill=dark, width=14)
|
||||||
|
# закрученные кончики усов
|
||||||
|
d.ellipse((cx - mu_w - 6, mu_cy - 6, cx - mu_w + 16, mu_cy + 16), fill=dark)
|
||||||
|
d.ellipse((cx + mu_w - 16, mu_cy - 6, cx + mu_w + 6, mu_cy + 16), fill=dark)
|
||||||
|
|
||||||
|
# --- Монограмма V / Д в нижних углах ---
|
||||||
|
f = _font(int(S * 0.20))
|
||||||
|
d.text((int(S * 0.10), int(S * 0.70)), "V", font=f, fill=white)
|
||||||
|
dw = d.textlength("Д", font=f)
|
||||||
|
d.text((S - int(S * 0.10) - dw, int(S * 0.70)), "Д", font=f, fill=white)
|
||||||
|
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
icon = make_app_icon()
|
||||||
|
png_path = OUT_DIR / "app_icon.png"
|
||||||
|
icon.save(png_path)
|
||||||
|
# .ico с набором размеров для Windows
|
||||||
|
ico_path = OUT_DIR / "app_icon.ico"
|
||||||
|
icon.save(ico_path, sizes=[(256, 256), (128, 128), (64, 64), (48, 48), (32, 32), (16, 16)])
|
||||||
|
print(f"saved: {png_path}")
|
||||||
|
print(f"saved: {ico_path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
17
scripts/pyi_rth_tk.py
Normal file
17
scripts/pyi_rth_tk.py
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
"""Runtime hook для PyInstaller: указывает Tcl/Tk на упакованные библиотеки.
|
||||||
|
|
||||||
|
PyInstaller на Python 3.13 + Tk 8.6 на macOS неправильно прописывает
|
||||||
|
TCL_LIBRARY/TK_LIBRARY — приходится делать руками.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if hasattr(sys, "_MEIPASS"):
|
||||||
|
base = sys._MEIPASS
|
||||||
|
tcl_dir = os.path.join(base, "tcl")
|
||||||
|
tk_dir = os.path.join(base, "tk")
|
||||||
|
if os.path.isdir(tcl_dir):
|
||||||
|
os.environ["TCL_LIBRARY"] = tcl_dir
|
||||||
|
if os.path.isdir(tk_dir):
|
||||||
|
os.environ["TK_LIBRARY"] = tk_dir
|
||||||
134
scripts/voice_dictation.spec
Normal file
134
scripts/voice_dictation.spec
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
# -*- mode: python ; coding: utf-8 -*-
|
||||||
|
"""PyInstaller spec для упаковки Voice Dictation в .app (macOS).
|
||||||
|
|
||||||
|
Сборка:
|
||||||
|
cd personal/voice-dictation
|
||||||
|
source .venv/bin/activate
|
||||||
|
pyinstaller scripts/voice_dictation.spec --noconfirm
|
||||||
|
|
||||||
|
Результат:
|
||||||
|
dist/Voice Dictation.app
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_ROOT = Path(SPECPATH).parent
|
||||||
|
SRC = PROJECT_ROOT / "src"
|
||||||
|
ICON = PROJECT_ROOT / "assets" / "icons" / "AppIcon.icns"
|
||||||
|
RT_HOOK_TK = PROJECT_ROOT / "scripts" / "pyi_rth_tk.py"
|
||||||
|
|
||||||
|
block_cipher = None
|
||||||
|
|
||||||
|
|
||||||
|
a = Analysis(
|
||||||
|
[str(SRC / "voice_dictation" / "__main__.py")],
|
||||||
|
pathex=[str(SRC)],
|
||||||
|
binaries=[],
|
||||||
|
datas=[],
|
||||||
|
hiddenimports=[
|
||||||
|
"voice_dictation",
|
||||||
|
"voice_dictation.cli.headless",
|
||||||
|
"voice_dictation.ui.settings_cli",
|
||||||
|
"voice_dictation.ui.settings_window",
|
||||||
|
"voice_dictation.ui.tray",
|
||||||
|
"voice_dictation.ui.icons",
|
||||||
|
"voice_dictation.platform.macos.autopaste",
|
||||||
|
"voice_dictation.platform.macos.clipboard",
|
||||||
|
"voice_dictation.platform.macos.hotkey_listener",
|
||||||
|
"voice_dictation.platform.macos.notifier",
|
||||||
|
"voice_dictation.platform.macos.sound_player",
|
||||||
|
"voice_dictation.platform.macos.system_sounds_scanner",
|
||||||
|
"voice_dictation.platform.windows.autopaste",
|
||||||
|
"voice_dictation.platform.windows.clipboard",
|
||||||
|
"voice_dictation.platform.windows.hotkey_listener",
|
||||||
|
"voice_dictation.platform.windows.notifier",
|
||||||
|
"voice_dictation.platform.windows.sound_player",
|
||||||
|
"voice_dictation.platform.windows.system_sounds_scanner",
|
||||||
|
"voice_dictation.core.balance",
|
||||||
|
"voice_dictation.core.fx",
|
||||||
|
"voice_dictation.core.usage_db",
|
||||||
|
"pkg_resources",
|
||||||
|
"pkg_resources.extern",
|
||||||
|
"customtkinter",
|
||||||
|
"darkdetect",
|
||||||
|
"pystray._darwin",
|
||||||
|
"PIL._tkinter_finder",
|
||||||
|
],
|
||||||
|
hookspath=[],
|
||||||
|
hooksconfig={},
|
||||||
|
runtime_hooks=[str(RT_HOOK_TK)],
|
||||||
|
excludes=[
|
||||||
|
"tkinter.test",
|
||||||
|
"test",
|
||||||
|
"unittest",
|
||||||
|
"pydoc",
|
||||||
|
],
|
||||||
|
win_no_prefer_redirects=False,
|
||||||
|
win_private_assemblies=False,
|
||||||
|
cipher=block_cipher,
|
||||||
|
noarchive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||||
|
|
||||||
|
exe = EXE(
|
||||||
|
pyz,
|
||||||
|
a.scripts,
|
||||||
|
[],
|
||||||
|
exclude_binaries=True,
|
||||||
|
name="VoiceDictation",
|
||||||
|
debug=False,
|
||||||
|
bootloader_ignore_signals=False,
|
||||||
|
strip=False,
|
||||||
|
upx=False,
|
||||||
|
console=False,
|
||||||
|
disable_windowed_traceback=False,
|
||||||
|
argv_emulation=False,
|
||||||
|
target_arch=None,
|
||||||
|
codesign_identity=None,
|
||||||
|
entitlements_file=None,
|
||||||
|
icon=str(ICON),
|
||||||
|
)
|
||||||
|
|
||||||
|
coll = COLLECT(
|
||||||
|
exe,
|
||||||
|
a.binaries,
|
||||||
|
a.zipfiles,
|
||||||
|
a.datas,
|
||||||
|
strip=False,
|
||||||
|
upx=False,
|
||||||
|
upx_exclude=[],
|
||||||
|
name="VoiceDictation",
|
||||||
|
)
|
||||||
|
|
||||||
|
app = BUNDLE(
|
||||||
|
coll,
|
||||||
|
name="Voice Dictation.app",
|
||||||
|
icon=str(ICON),
|
||||||
|
bundle_identifier="ru.flowmasters.voicedictation",
|
||||||
|
version="0.1.0",
|
||||||
|
info_plist={
|
||||||
|
"CFBundleName": "Voice Dictation",
|
||||||
|
"CFBundleDisplayName": "Voice Dictation",
|
||||||
|
"CFBundleShortVersionString": "0.1.0",
|
||||||
|
"CFBundleVersion": "0.1.0",
|
||||||
|
"CFBundleIdentifier": "ru.flowmasters.voicedictation",
|
||||||
|
"CFBundleExecutable": "VoiceDictation",
|
||||||
|
# LSUIElement=true — приложение живёт только в трее, без иконки в Dock
|
||||||
|
"LSUIElement": True,
|
||||||
|
"NSHighResolutionCapable": True,
|
||||||
|
# Минимальная версия macOS (universal2 рантайм)
|
||||||
|
"LSMinimumSystemVersion": "11.0",
|
||||||
|
# Permissions — пояснения для пользователя
|
||||||
|
"NSMicrophoneUsageDescription": (
|
||||||
|
"Voice Dictation использует микрофон для записи речи и её "
|
||||||
|
"транскрипции через OpenAI Whisper API."
|
||||||
|
),
|
||||||
|
"NSAppleEventsUsageDescription": (
|
||||||
|
"Voice Dictation использует AppleScript для показа уведомлений "
|
||||||
|
"и автоматической вставки текста."
|
||||||
|
),
|
||||||
|
# Локализация
|
||||||
|
"CFBundleDevelopmentRegion": "ru_RU",
|
||||||
|
},
|
||||||
|
)
|
||||||
5
src/voice_dictation/__init__.py
Normal file
5
src/voice_dictation/__init__.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""Voice Dictation — голосовая диктовка через Whisper API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
__version__ = "0.2.0"
|
||||||
265
src/voice_dictation/__main__.py
Normal file
265
src/voice_dictation/__main__.py
Normal file
|
|
@ -0,0 +1,265 @@
|
||||||
|
"""Точка входа: запускает tray-приложение с фоновым оркестратором."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _format_hotkey(hotkey: str) -> str:
|
||||||
|
"""Человекочитаемое отображение хоткея под текущую ОС.
|
||||||
|
|
||||||
|
На macOS — символы клавиш (⌘⌥⌃⇧), на Windows/Linux — словами (Ctrl + Shift + Space).
|
||||||
|
"""
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
return (
|
||||||
|
hotkey.replace("cmd", "⌘")
|
||||||
|
.replace("alt", "⌥")
|
||||||
|
.replace("ctrl", "⌃")
|
||||||
|
.replace("shift", "⇧")
|
||||||
|
)
|
||||||
|
return " + ".join(part.capitalize() for part in hotkey.split("+"))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Tray-режим: иконка в строке меню + хоткей.
|
||||||
|
|
||||||
|
Если в argv передана подкоманда `headless` или `stats` — делегирует CLI.
|
||||||
|
"""
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "settings":
|
||||||
|
from voice_dictation.ui.settings_cli import main as settings_main
|
||||||
|
|
||||||
|
settings_main()
|
||||||
|
return
|
||||||
|
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] in {"headless", "stats"}:
|
||||||
|
from voice_dictation.cli.headless import main as cli_main
|
||||||
|
|
||||||
|
# Уберём первый аргумент так, чтобы headless/stats обрабатывались правильно
|
||||||
|
if sys.argv[1] == "headless":
|
||||||
|
del sys.argv[1]
|
||||||
|
cli_main()
|
||||||
|
return
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
|
||||||
|
try:
|
||||||
|
env = load_env()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
paths = AppPaths.default().ensure_exists()
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.logging_setup import configure_logging
|
||||||
|
|
||||||
|
verbose = "--verbose" in sys.argv or "-v" in sys.argv
|
||||||
|
configure_logging(paths, verbose=verbose)
|
||||||
|
logger.info("Voice Dictation запускается (tray)")
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.single_instance import SingleInstanceLock
|
||||||
|
|
||||||
|
lock = SingleInstanceLock(paths.pid_file)
|
||||||
|
lock.acquire()
|
||||||
|
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
|
||||||
|
config_store = ConfigStore(paths.config_file)
|
||||||
|
config = config_store.load()
|
||||||
|
logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model)
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import (
|
||||||
|
SoxNotFoundError,
|
||||||
|
UnsupportedPlatformError,
|
||||||
|
)
|
||||||
|
from voice_dictation.platform.factory import build_platform
|
||||||
|
|
||||||
|
try:
|
||||||
|
platform_bundle = build_platform()
|
||||||
|
except UnsupportedPlatformError as exc:
|
||||||
|
logger.error("%s", exc)
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
from voice_dictation.core.recorder import SoxRecorder
|
||||||
|
|
||||||
|
try:
|
||||||
|
recorder = SoxRecorder(sample_rate=16000, bin_dir=paths.bin_dir)
|
||||||
|
except SoxNotFoundError as exc:
|
||||||
|
logger.error("%s", exc)
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
|
|
||||||
|
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||||
|
|
||||||
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
|
||||||
|
dictionary = Dictionary(paths.dictionary_file)
|
||||||
|
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
|
||||||
|
usage_db = UsageDB(paths.usage_db)
|
||||||
|
|
||||||
|
from voice_dictation.core.enums import RecordingState
|
||||||
|
from voice_dictation.core.orchestrator import DictationOrchestrator
|
||||||
|
from voice_dictation.ui.tray import TrayApp
|
||||||
|
|
||||||
|
tray_holder: dict[str, TrayApp] = {}
|
||||||
|
|
||||||
|
def _state_changed(state: RecordingState) -> None:
|
||||||
|
logger.debug("Состояние: %s", state)
|
||||||
|
tray = tray_holder.get("tray")
|
||||||
|
if tray is not None:
|
||||||
|
tray.update_state(state)
|
||||||
|
|
||||||
|
orchestrator = DictationOrchestrator(
|
||||||
|
recorder=recorder,
|
||||||
|
transcriber=transcriber,
|
||||||
|
dictionary=dictionary,
|
||||||
|
clipboard=platform_bundle.clipboard,
|
||||||
|
auto_paste=platform_bundle.auto_paste,
|
||||||
|
sound_player=platform_bundle.sound_player,
|
||||||
|
notifier=platform_bundle.notifier,
|
||||||
|
config_provider=config_store.current,
|
||||||
|
paths=paths,
|
||||||
|
state_listener=_state_changed,
|
||||||
|
usage_db=usage_db,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Проверяем Accessibility — без неё NSEvent global monitor не получает событий
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
try:
|
||||||
|
from ApplicationServices import AXIsProcessTrusted
|
||||||
|
|
||||||
|
trusted = bool(AXIsProcessTrusted())
|
||||||
|
logger.info("Accessibility trusted: %s", trusted)
|
||||||
|
if not trusted:
|
||||||
|
platform_bundle.notifier.show(
|
||||||
|
"Voice Dictation",
|
||||||
|
"Нет прав Accessibility — хоткей не работает. "
|
||||||
|
"Системные настройки → Конфиденциальность → Универсальный доступ.",
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось проверить Accessibility: %s", exc)
|
||||||
|
|
||||||
|
registered = platform_bundle.hotkey_listener.register(config.hotkey, orchestrator.toggle)
|
||||||
|
if not registered:
|
||||||
|
fallback = "cmd+shift+d" if sys.platform == "darwin" else "ctrl+shift+d"
|
||||||
|
logger.warning("Не удалось зарегистрировать %s, fallback %s", config.hotkey, fallback)
|
||||||
|
platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle)
|
||||||
|
|
||||||
|
def _show_stats() -> None:
|
||||||
|
tz = datetime.now().astimezone().tzinfo
|
||||||
|
today = usage_db.today_total(tz=tz)
|
||||||
|
platform_bundle.notifier.show(
|
||||||
|
"Voice Dictation — сегодня",
|
||||||
|
f"{today.count} транскрипций · "
|
||||||
|
f"{today.total_duration_sec / 60:.1f} мин · ${today.total_cost_usd:.4f}",
|
||||||
|
)
|
||||||
|
|
||||||
|
def _show_settings() -> None:
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
is_frozen = getattr(sys, "frozen", False)
|
||||||
|
if is_frozen:
|
||||||
|
# В bundle ищем сам .app и запускаем второй экземпляр через `open -n`,
|
||||||
|
# чтобы macOS дал процессу полноценный GUI scope.
|
||||||
|
executable = Path(sys.executable)
|
||||||
|
app_path: Path | None = None
|
||||||
|
for parent in executable.parents:
|
||||||
|
if parent.suffix == ".app":
|
||||||
|
app_path = parent
|
||||||
|
break
|
||||||
|
if app_path is not None:
|
||||||
|
cmd: list[str] = ["/usr/bin/open", "-n", "-a", str(app_path), "--args", "settings"]
|
||||||
|
else:
|
||||||
|
cmd = [sys.executable, "settings"]
|
||||||
|
else:
|
||||||
|
cmd = [sys.executable, "-m", "voice_dictation", "settings"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
subprocess.Popen(cmd, start_new_session=True)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Settings window error: %s", exc)
|
||||||
|
platform_bundle.notifier.show("Настройки", f"Ошибка открытия: {exc}")
|
||||||
|
|
||||||
|
shutdown_event = threading.Event()
|
||||||
|
|
||||||
|
def _quit() -> None:
|
||||||
|
shutdown_event.set()
|
||||||
|
|
||||||
|
from voice_dictation.core.modes import all_specs, get_mode
|
||||||
|
|
||||||
|
def _list_modes() -> list[tuple[str, str]]:
|
||||||
|
cfg = config_store.current()
|
||||||
|
return [(m.key, m.label) for m in all_specs(cfg.custom_modes)]
|
||||||
|
|
||||||
|
def _select_mode(key: str) -> None:
|
||||||
|
cfg = config_store.current()
|
||||||
|
cfg.mode = key
|
||||||
|
config_store.save(cfg)
|
||||||
|
spec = get_mode(key, cfg.custom_modes)
|
||||||
|
platform_bundle.notifier.show("Voice Dictator", f"Режим: {spec.label}")
|
||||||
|
logger.info("Режим переключён: mode=%s", key)
|
||||||
|
|
||||||
|
def _get_mode() -> str:
|
||||||
|
return config_store.current().mode
|
||||||
|
|
||||||
|
tray = TrayApp(
|
||||||
|
on_toggle=orchestrator.toggle,
|
||||||
|
on_settings=_show_settings,
|
||||||
|
on_stats=_show_stats,
|
||||||
|
on_quit=_quit,
|
||||||
|
modes_provider=_list_modes,
|
||||||
|
on_mode_select=_select_mode,
|
||||||
|
current_mode=_get_mode,
|
||||||
|
)
|
||||||
|
tray_holder["tray"] = tray
|
||||||
|
|
||||||
|
# Hotkey listener — в фоновом потоке (tray должен быть в главном для macOS)
|
||||||
|
listener_thread = threading.Thread(
|
||||||
|
target=platform_bundle.hotkey_listener.start,
|
||||||
|
name="hotkey-listener",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
listener_thread.start()
|
||||||
|
|
||||||
|
def _signal_shutdown(signum: int, _frame: object) -> None:
|
||||||
|
logger.info("Получен сигнал %d, завершение...", signum)
|
||||||
|
shutdown_event.set()
|
||||||
|
tray.stop()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, _signal_shutdown)
|
||||||
|
signal.signal(signal.SIGINT, _signal_shutdown)
|
||||||
|
|
||||||
|
def _watchdog() -> None:
|
||||||
|
shutdown_event.wait()
|
||||||
|
tray.stop()
|
||||||
|
|
||||||
|
threading.Thread(target=_watchdog, name="shutdown-watchdog", daemon=True).start()
|
||||||
|
|
||||||
|
hotkey_display = _format_hotkey(config.hotkey)
|
||||||
|
print(f"Voice Dictation запущен в трее. Хоткей: {hotkey_display}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
tray.run()
|
||||||
|
finally:
|
||||||
|
shutdown_event.set()
|
||||||
|
orchestrator.shutdown()
|
||||||
|
platform_bundle.hotkey_listener.stop()
|
||||||
|
lock.release()
|
||||||
|
logger.info("Voice Dictation остановлен")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
3
src/voice_dictation/cli/__init__.py
Normal file
3
src/voice_dictation/cli/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""CLI-модуль приложения."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
201
src/voice_dictation/cli/headless.py
Normal file
201
src/voice_dictation/cli/headless.py
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
"""Headless-режим — этап 1. Без tray, только хоткей + запись + транскрипция."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Точка входа headless-режима.
|
||||||
|
|
||||||
|
DI-сборка всех компонентов и запуск слушателя хоткеев.
|
||||||
|
"""
|
||||||
|
# Подкоманды до запуска основного цикла
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "stats":
|
||||||
|
_stats_command()
|
||||||
|
return
|
||||||
|
|
||||||
|
# 1. Загрузка env (сначала, до логирования, чтобы поймать ошибку конфига)
|
||||||
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
|
||||||
|
try:
|
||||||
|
env = load_env()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 2. Пути и директории
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
paths = AppPaths.default().ensure_exists()
|
||||||
|
|
||||||
|
# 3. Логирование
|
||||||
|
from voice_dictation.infrastructure.logging_setup import configure_logging
|
||||||
|
|
||||||
|
verbose = "--verbose" in sys.argv or "-v" in sys.argv
|
||||||
|
configure_logging(paths, verbose=verbose)
|
||||||
|
logger.info("Voice Dictation запускается (headless)")
|
||||||
|
|
||||||
|
# 4. Single-instance lock
|
||||||
|
from voice_dictation.infrastructure.single_instance import SingleInstanceLock
|
||||||
|
|
||||||
|
lock = SingleInstanceLock(paths.pid_file)
|
||||||
|
lock.acquire()
|
||||||
|
|
||||||
|
# 5. Конфигурация
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
|
||||||
|
config_store = ConfigStore(paths.config_file)
|
||||||
|
config = config_store.load()
|
||||||
|
logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model)
|
||||||
|
|
||||||
|
# 6. Платформенные компоненты
|
||||||
|
from voice_dictation.infrastructure.errors import UnsupportedPlatformError
|
||||||
|
from voice_dictation.platform.factory import build_platform
|
||||||
|
|
||||||
|
try:
|
||||||
|
platform_bundle = build_platform()
|
||||||
|
except UnsupportedPlatformError as exc:
|
||||||
|
logger.error("%s", exc)
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 7. Recorder
|
||||||
|
from voice_dictation.core.recorder import SoxRecorder
|
||||||
|
from voice_dictation.infrastructure.errors import SoxNotFoundError
|
||||||
|
|
||||||
|
try:
|
||||||
|
recorder = SoxRecorder(sample_rate=16000)
|
||||||
|
except SoxNotFoundError as exc:
|
||||||
|
logger.error("%s", exc)
|
||||||
|
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 8. Transcriber
|
||||||
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
|
|
||||||
|
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||||
|
|
||||||
|
# 9. Dictionary
|
||||||
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
|
||||||
|
dictionary = Dictionary(paths.dictionary_file)
|
||||||
|
|
||||||
|
# 9.1. UsageDB
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
|
||||||
|
usage_db = UsageDB(paths.usage_db)
|
||||||
|
|
||||||
|
# 10. Orchestrator
|
||||||
|
from voice_dictation.core.orchestrator import DictationOrchestrator
|
||||||
|
|
||||||
|
def _state_changed(state: object) -> None:
|
||||||
|
logger.info("Состояние: %s", state)
|
||||||
|
|
||||||
|
orchestrator = DictationOrchestrator(
|
||||||
|
recorder=recorder,
|
||||||
|
transcriber=transcriber,
|
||||||
|
dictionary=dictionary,
|
||||||
|
clipboard=platform_bundle.clipboard,
|
||||||
|
auto_paste=platform_bundle.auto_paste,
|
||||||
|
sound_player=platform_bundle.sound_player,
|
||||||
|
notifier=platform_bundle.notifier,
|
||||||
|
config_provider=config_store.current,
|
||||||
|
paths=paths,
|
||||||
|
state_listener=_state_changed,
|
||||||
|
usage_db=usage_db,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 11. Регистрация хоткея
|
||||||
|
registered = platform_bundle.hotkey_listener.register(config.hotkey, orchestrator.toggle)
|
||||||
|
if not registered:
|
||||||
|
logger.warning("Не удалось зарегистрировать хоткей %s, пробую fallback", config.hotkey)
|
||||||
|
fallback = "cmd+shift+d" if sys.platform == "darwin" else "ctrl+shift+d"
|
||||||
|
platform_bundle.hotkey_listener.register(fallback, orchestrator.toggle)
|
||||||
|
|
||||||
|
# 12. Обработчик сигналов для graceful shutdown
|
||||||
|
def _shutdown(signum: int, frame: object) -> None:
|
||||||
|
logger.info("Получен сигнал %d, завершение...", signum)
|
||||||
|
orchestrator.shutdown()
|
||||||
|
platform_bundle.hotkey_listener.stop()
|
||||||
|
lock.release()
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, _shutdown)
|
||||||
|
signal.signal(signal.SIGINT, _shutdown)
|
||||||
|
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
hotkey_display = (
|
||||||
|
config.hotkey.replace("cmd", "⌘")
|
||||||
|
.replace("alt", "⌥")
|
||||||
|
.replace("ctrl", "⌃")
|
||||||
|
.replace("shift", "⇧")
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
hotkey_display = " + ".join(part.capitalize() for part in config.hotkey.split("+"))
|
||||||
|
print(
|
||||||
|
f"Voice Dictation запущен. Хоткей: {hotkey_display}\n"
|
||||||
|
"Нажмите хоткей для начала записи, ещё раз — для остановки и транскрипции.\n"
|
||||||
|
"Ctrl+C для выхода."
|
||||||
|
)
|
||||||
|
|
||||||
|
# 13. Блокирующий запуск слушателя
|
||||||
|
try:
|
||||||
|
platform_bundle.hotkey_listener.start()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
logger.info("Прерывание по Ctrl+C")
|
||||||
|
finally:
|
||||||
|
orchestrator.shutdown()
|
||||||
|
lock.release()
|
||||||
|
logger.info("Voice Dictation остановлен")
|
||||||
|
|
||||||
|
|
||||||
|
def _stats_command() -> None:
|
||||||
|
"""Выводит сводку статистики использования."""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
|
||||||
|
paths = AppPaths.default().ensure_exists()
|
||||||
|
db = UsageDB(paths.usage_db)
|
||||||
|
|
||||||
|
tz = datetime.now().astimezone().tzinfo
|
||||||
|
today = db.today_total(tz=tz)
|
||||||
|
now = datetime.now(tz=tz)
|
||||||
|
month = db.month_stats(now.year, now.month, tz=tz)
|
||||||
|
total = db.all_time()
|
||||||
|
|
||||||
|
def _fmt(stats: "object") -> str: # noqa: UP037 — forward ref в строке для mypy совместимости
|
||||||
|
from voice_dictation.core.usage_db import UsageStats
|
||||||
|
|
||||||
|
assert isinstance(stats, UsageStats)
|
||||||
|
mins = stats.total_duration_sec / 60
|
||||||
|
return (
|
||||||
|
f" транскрипций: {stats.count}\n"
|
||||||
|
f" длительность: {mins:.1f} мин ({stats.total_duration_sec:.0f} сек)\n"
|
||||||
|
f" стоимость: ${stats.total_cost_usd:.4f}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("Voice Dictation — статистика\n")
|
||||||
|
print(f"Сегодня ({now.strftime('%Y-%m-%d')}):")
|
||||||
|
print(_fmt(today))
|
||||||
|
print(f"\nМесяц ({now.strftime('%Y-%m')}):")
|
||||||
|
print(_fmt(month))
|
||||||
|
print("\nЗа всё время:")
|
||||||
|
print(_fmt(total))
|
||||||
|
|
||||||
|
recent = db.recent(limit=10)
|
||||||
|
if recent:
|
||||||
|
print("\nПоследние 10 записей:")
|
||||||
|
for r in recent:
|
||||||
|
ts = r.created_at.astimezone(tz).strftime("%m-%d %H:%M")
|
||||||
|
print(f" {ts} {r.duration_sec:5.1f}с ${r.cost_usd:7.4f} {r.text_preview}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
3
src/voice_dictation/core/__init__.py
Normal file
3
src/voice_dictation/core/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""Core бизнес-логика — не зависит от UI и ОС."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
118
src/voice_dictation/core/balance.py
Normal file
118
src/voice_dictation/core/balance.py
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
"""Получение баланса OpenAI через Admin API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from voice_dictation.core.models import BalanceInfo
|
||||||
|
from voice_dictation.infrastructure.errors import BalanceError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_BASE_URL = "https://api.openai.com/v1"
|
||||||
|
_TIMEOUT = 15.0
|
||||||
|
|
||||||
|
|
||||||
|
class BalanceClient:
|
||||||
|
"""Клиент Admin API для получения баланса организации.
|
||||||
|
|
||||||
|
Для работы нужен Admin API key (sk-admin-...) с правом на /organization/costs.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
api_key: Admin API ключ.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, api_key: str) -> None:
|
||||||
|
self._client = httpx.Client(
|
||||||
|
base_url=_BASE_URL,
|
||||||
|
headers={"Authorization": f"Bearer {api_key}"},
|
||||||
|
timeout=_TIMEOUT,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fetch(self) -> BalanceInfo:
|
||||||
|
"""Получает баланс организации (выдано / потрачено / остаток).
|
||||||
|
|
||||||
|
OpenAI публичный Admin API не отдаёт «остаток кредитов» напрямую — мы
|
||||||
|
берём суммарные траты за последние 90 дней и сравниваем с лимитом
|
||||||
|
биллинга. Если эндпоинт лимита недоступен — возвращаем только used и 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
BalanceInfo.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
BalanceError: Если запрос не удался или ответ невалиден.
|
||||||
|
"""
|
||||||
|
used = self._fetch_used_last_90d()
|
||||||
|
granted, available = self._fetch_credit_grants()
|
||||||
|
return BalanceInfo(
|
||||||
|
total_granted_usd=granted,
|
||||||
|
total_used_usd=used,
|
||||||
|
total_available_usd=available,
|
||||||
|
fetched_at=datetime.now(UTC),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _fetch_used_last_90d(self) -> Decimal:
|
||||||
|
"""Сумма трат за последние 90 дней через /organization/costs."""
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
end = datetime.now(UTC)
|
||||||
|
start = end - timedelta(days=90)
|
||||||
|
try:
|
||||||
|
response = self._client.get(
|
||||||
|
"/organization/costs",
|
||||||
|
params={
|
||||||
|
"start_time": int(start.timestamp()),
|
||||||
|
"end_time": int(end.timestamp()),
|
||||||
|
"bucket_width": "1d",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
except httpx.RequestError as exc:
|
||||||
|
raise BalanceError(f"Сетевая ошибка: {exc}") from exc
|
||||||
|
|
||||||
|
if not response.is_success:
|
||||||
|
raise BalanceError(f"Admin API вернул {response.status_code}: {response.text[:200]}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
body = response.json()
|
||||||
|
except ValueError as exc:
|
||||||
|
raise BalanceError(f"Невалидный JSON: {exc}") from exc
|
||||||
|
|
||||||
|
total = Decimal("0")
|
||||||
|
for bucket in body.get("data", []):
|
||||||
|
for result in bucket.get("results", []):
|
||||||
|
amount = result.get("amount", {})
|
||||||
|
value = amount.get("value")
|
||||||
|
if value is not None:
|
||||||
|
total += Decimal(str(value))
|
||||||
|
return total.quantize(Decimal("0.0001"))
|
||||||
|
|
||||||
|
def _fetch_credit_grants(self) -> tuple[Decimal, Decimal]:
|
||||||
|
"""Возвращает (granted, available). Если эндпоинт недоступен — (0, 0).
|
||||||
|
|
||||||
|
OpenAI несколько раз менял схему биллинга. Старый dashboard
|
||||||
|
/dashboard/billing/credit_grants больше не работает. Здесь —
|
||||||
|
best-effort попытка через subscription, иначе нули.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
response = self._client.get("/dashboard/billing/credit_grants")
|
||||||
|
except httpx.RequestError:
|
||||||
|
return Decimal("0"), Decimal("0")
|
||||||
|
|
||||||
|
if not response.is_success:
|
||||||
|
return Decimal("0"), Decimal("0")
|
||||||
|
|
||||||
|
try:
|
||||||
|
body = response.json()
|
||||||
|
except ValueError:
|
||||||
|
return Decimal("0"), Decimal("0")
|
||||||
|
|
||||||
|
granted = Decimal(str(body.get("total_granted", "0") or "0"))
|
||||||
|
available = Decimal(str(body.get("total_available", "0") or "0"))
|
||||||
|
return granted.quantize(Decimal("0.0001")), available.quantize(Decimal("0.0001"))
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._client.close()
|
||||||
142
src/voice_dictation/core/config.py
Normal file
142
src/voice_dictation/core/config.py
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
"""Конфигурация приложения с персистентностью в JSON."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from dataclasses import asdict, dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class Config:
|
||||||
|
"""Конфигурация приложения.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Комбинация клавиш для начала/остановки записи.
|
||||||
|
model: Модель Whisper API.
|
||||||
|
language: Код языка (None — автоопределение).
|
||||||
|
notifications_enabled: Показывать уведомления.
|
||||||
|
show_cost_in_notification: Показывать стоимость в уведомлении.
|
||||||
|
sounds_enabled: Воспроизводить звуки.
|
||||||
|
volume: Громкость звуков (0.0–1.0).
|
||||||
|
start_sound_path: Путь к звуку начала записи.
|
||||||
|
stop_sound_path: Путь к звуку окончания записи.
|
||||||
|
error_sound_path: Путь к звуку ошибки.
|
||||||
|
dictionary_path: Путь к словарю (None — стандартный).
|
||||||
|
auto_paste: Автоматически вставлять текст после транскрипции.
|
||||||
|
paste_delay_ms: Задержка перед вставкой в миллисекундах.
|
||||||
|
"""
|
||||||
|
|
||||||
|
hotkey: str = "ctrl+space"
|
||||||
|
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
|
||||||
|
mode: str = "raw" # ключ режима постобработки из core.modes
|
||||||
|
proc_model: str = "gpt-4o-mini" # модель LLM для режимов постобработки
|
||||||
|
custom_modes: dict[str, str] = field(default_factory=dict) # {название: промпт}
|
||||||
|
|
||||||
|
# Не включать в JSON-сериализацию
|
||||||
|
_path: Path | None = field(default=None, repr=False, compare=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _config_to_dict(config: Config) -> dict[str, object]:
|
||||||
|
"""Сериализует Config в dict для JSON, конвертируя Path в строки."""
|
||||||
|
d = asdict(config)
|
||||||
|
# Убираем приватное поле
|
||||||
|
d.pop("_path", None)
|
||||||
|
for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"):
|
||||||
|
if d[key] is not None:
|
||||||
|
d[key] = str(d[key])
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def _config_from_dict(data: dict[str, object]) -> Config:
|
||||||
|
"""Десериализует Config из dict, конвертируя строки в Path."""
|
||||||
|
kwargs: dict[str, object] = dict(data)
|
||||||
|
kwargs.pop("_path", None)
|
||||||
|
|
||||||
|
# Миграция со старой схемы (summary_mode/summary_model) на mode/proc_model.
|
||||||
|
# Делается ДО фильтрации неизвестных ключей, иначе старые поля потеряются.
|
||||||
|
if "mode" not in kwargs and kwargs.get("summary_mode") is True:
|
||||||
|
kwargs["mode"] = "summary"
|
||||||
|
if "proc_model" not in kwargs and isinstance(kwargs.get("summary_model"), str):
|
||||||
|
kwargs["proc_model"] = kwargs["summary_model"]
|
||||||
|
|
||||||
|
for key in ("start_sound_path", "stop_sound_path", "error_sound_path", "dictionary_path"):
|
||||||
|
val = kwargs.get(key)
|
||||||
|
if val is not None and isinstance(val, str):
|
||||||
|
kwargs[key] = Path(val)
|
||||||
|
# Игнорируем неизвестные ключи из будущих версий конфига
|
||||||
|
import dataclasses
|
||||||
|
|
||||||
|
known = {f.name for f in dataclasses.fields(Config)}
|
||||||
|
filtered = {k: v for k, v in kwargs.items() if k in known}
|
||||||
|
return Config(**filtered) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigStore:
|
||||||
|
"""Хранилище конфигурации с загрузкой и сохранением в JSON.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Путь к JSON-файлу конфигурации.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, path: Path) -> None:
|
||||||
|
self._path = path
|
||||||
|
self._current: Config | None = None
|
||||||
|
|
||||||
|
def load(self) -> Config:
|
||||||
|
"""Загружает конфиг из файла. Если файла нет — возвращает дефолтный.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Загруженный или дефолтный Config.
|
||||||
|
"""
|
||||||
|
if self._path.exists():
|
||||||
|
try:
|
||||||
|
with self._path.open(encoding="utf-8") as fh:
|
||||||
|
data = json.load(fh)
|
||||||
|
self._current = _config_from_dict(data)
|
||||||
|
except (json.JSONDecodeError, TypeError) as exc:
|
||||||
|
logger.warning("Не удалось загрузить конфиг, использую дефолтный: %s", exc)
|
||||||
|
self._current = Config()
|
||||||
|
else:
|
||||||
|
self._current = Config()
|
||||||
|
return self._current
|
||||||
|
|
||||||
|
def save(self, config: Config) -> None:
|
||||||
|
"""Сохраняет конфиг в JSON-файл.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config: Конфигурация для сохранения.
|
||||||
|
"""
|
||||||
|
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
data = _config_to_dict(config)
|
||||||
|
with self._path.open("w", encoding="utf-8") as fh:
|
||||||
|
json.dump(data, fh, indent=2, ensure_ascii=False)
|
||||||
|
self._current = config
|
||||||
|
logger.debug("Конфиг сохранён в %s", self._path)
|
||||||
|
|
||||||
|
def current(self) -> Config:
|
||||||
|
"""Возвращает текущий загруженный конфиг.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Текущий Config.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: Если load() не был вызван.
|
||||||
|
"""
|
||||||
|
if self._current is None:
|
||||||
|
raise RuntimeError("Вызовите load() перед current()")
|
||||||
|
return self._current
|
||||||
67
src/voice_dictation/core/dictionary.py
Normal file
67
src/voice_dictation/core/dictionary.py
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
"""Словарь подсказок для Whisper API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Dictionary:
|
||||||
|
"""Загружает и обслуживает словарь специальных слов для Whisper prompt.
|
||||||
|
|
||||||
|
Формат файла: одно слово/фраза на строку. Строки с # — комментарии.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Путь к файлу словаря.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, path: Path) -> None:
|
||||||
|
self._path = path
|
||||||
|
|
||||||
|
def load(self) -> list[str]:
|
||||||
|
"""Загружает словарь из файла.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список слов/фраз. Пустой список если файл не существует.
|
||||||
|
"""
|
||||||
|
if not self._path.exists():
|
||||||
|
return []
|
||||||
|
lines: list[str] = []
|
||||||
|
try:
|
||||||
|
with self._path.open(encoding="utf-8") as fh:
|
||||||
|
for line in fh:
|
||||||
|
stripped = line.strip()
|
||||||
|
if stripped and not stripped.startswith("#"):
|
||||||
|
lines.append(stripped)
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning("Не удалось загрузить словарь %s: %s", self._path, exc)
|
||||||
|
return lines
|
||||||
|
|
||||||
|
def build_prompt(self, max_chars: int = 896) -> str:
|
||||||
|
"""Собирает строку подсказки для Whisper из словаря.
|
||||||
|
|
||||||
|
Берёт слова с конца списка (более специфичные), чтобы не превысить лимит токенов.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
max_chars: Максимальная длина результирующей строки (по умолчанию 896 ~224 токена).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Строка со словами через запятую, не длиннее max_chars.
|
||||||
|
"""
|
||||||
|
words = self.load()
|
||||||
|
if not words:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# Берём с конца, пока влезает в лимит
|
||||||
|
selected: list[str] = []
|
||||||
|
total = 0
|
||||||
|
for word in reversed(words):
|
||||||
|
needed = len(word) + (2 if selected else 0) # +2 для ", "
|
||||||
|
if total + needed > max_chars:
|
||||||
|
break
|
||||||
|
selected.insert(0, word)
|
||||||
|
total += needed
|
||||||
|
|
||||||
|
return ", ".join(selected)
|
||||||
30
src/voice_dictation/core/enums.py
Normal file
30
src/voice_dictation/core/enums.py
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
"""Перечисления для всего приложения."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from enum import Enum, StrEnum, auto
|
||||||
|
|
||||||
|
|
||||||
|
class RecordingState(Enum):
|
||||||
|
"""Состояния state-machine оркестратора."""
|
||||||
|
|
||||||
|
IDLE = auto()
|
||||||
|
RECORDING = auto()
|
||||||
|
PROCESSING = auto()
|
||||||
|
ERROR = auto()
|
||||||
|
|
||||||
|
|
||||||
|
class SoundKind(Enum):
|
||||||
|
"""Тип звукового события."""
|
||||||
|
|
||||||
|
START = auto()
|
||||||
|
STOP = auto()
|
||||||
|
ERROR = auto()
|
||||||
|
|
||||||
|
|
||||||
|
class WhisperModel(StrEnum):
|
||||||
|
"""Доступные модели транскрипции Whisper API."""
|
||||||
|
|
||||||
|
WHISPER_1 = "whisper-1"
|
||||||
|
GPT_4O_TRANSCRIBE = "gpt-4o-transcribe"
|
||||||
|
GPT_4O_MINI_TRANSCRIBE = "gpt-4o-mini-transcribe"
|
||||||
112
src/voice_dictation/core/ffmpeg_setup.py
Normal file
112
src/voice_dictation/core/ffmpeg_setup.py
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
"""Поиск и опциональная докачка ffmpeg.
|
||||||
|
|
||||||
|
ffmpeg НЕ входит в установщик (он весит ~80 МБ). Без него запись работает
|
||||||
|
через WAV. ffmpeg нужен только для сжатия в OGG/Opus (~10× меньше файл →
|
||||||
|
быстрее отправка в Whisper). Пользователь может докачать его одной кнопкой
|
||||||
|
в настройках — сюда складывается логика поиска и загрузки.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import zipfile
|
||||||
|
from collections.abc import Callable
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Стабильный URL «последней» essentials-сборки (включает libopus).
|
||||||
|
# Отдаёт 303-редирект на конкретную версию — urllib следует за ним сам.
|
||||||
|
_FFMPEG_URL = "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip"
|
||||||
|
|
||||||
|
_EXE_NAME = "ffmpeg.exe" if os.name == "nt" else "ffmpeg"
|
||||||
|
|
||||||
|
|
||||||
|
def find_ffmpeg(bin_dir: Path | None = None) -> str | None:
|
||||||
|
"""Ищет ffmpeg: сначала в нашем bin_dir, затем рядом с exe, затем в PATH.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
bin_dir: Каталог докачанных бинарников (~/.dictate/bin).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Путь к ffmpeg или None, если не найден.
|
||||||
|
"""
|
||||||
|
candidates: list[Path] = []
|
||||||
|
if bin_dir is not None:
|
||||||
|
candidates.append(bin_dir / _EXE_NAME)
|
||||||
|
# рядом с собранным приложением (PyInstaller)
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
exe_dir = Path(sys.executable).parent
|
||||||
|
candidates.append(exe_dir / _EXE_NAME)
|
||||||
|
meipass = getattr(sys, "_MEIPASS", None)
|
||||||
|
if meipass:
|
||||||
|
candidates.append(Path(meipass) / _EXE_NAME)
|
||||||
|
for c in candidates:
|
||||||
|
if c.exists():
|
||||||
|
return str(c)
|
||||||
|
found = shutil.which("ffmpeg")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def download_ffmpeg(
|
||||||
|
bin_dir: Path,
|
||||||
|
progress: Callable[[str], None] | None = None,
|
||||||
|
) -> Path:
|
||||||
|
"""Скачивает ffmpeg и распаковывает только ffmpeg.exe в bin_dir.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
bin_dir: Куда положить ffmpeg (создаётся при необходимости).
|
||||||
|
progress: Колбэк для текстовых сообщений о прогрессе (опционально).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Путь к установленному ffmpeg.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: Если в архиве не найден исполняемый файл ffmpeg.
|
||||||
|
"""
|
||||||
|
import tempfile
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
def _say(msg: str) -> None:
|
||||||
|
logger.info("ffmpeg setup: %s", msg)
|
||||||
|
if progress is not None:
|
||||||
|
progress(msg)
|
||||||
|
|
||||||
|
bin_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
target = bin_dir / _EXE_NAME
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
zip_path = Path(tmp) / "ffmpeg.zip"
|
||||||
|
_say("Скачиваю ffmpeg (~100 МБ)…")
|
||||||
|
req = urllib.request.Request(_FFMPEG_URL, headers={"User-Agent": "VoiceDictator"})
|
||||||
|
with urllib.request.urlopen(req, timeout=120) as resp, zip_path.open("wb") as fh:
|
||||||
|
total = int(resp.headers.get("Content-Length", 0))
|
||||||
|
read = 0
|
||||||
|
chunk = 1024 * 256
|
||||||
|
while True:
|
||||||
|
buf = resp.read(chunk)
|
||||||
|
if not buf:
|
||||||
|
break
|
||||||
|
fh.write(buf)
|
||||||
|
read += len(buf)
|
||||||
|
if total:
|
||||||
|
_say(f"Скачивание: {read * 100 // total}%")
|
||||||
|
|
||||||
|
_say("Распаковываю…")
|
||||||
|
with zipfile.ZipFile(zip_path) as zf:
|
||||||
|
exe_member = next(
|
||||||
|
(n for n in zf.namelist() if n.replace("\\", "/").endswith(f"bin/{_EXE_NAME}")),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if exe_member is None:
|
||||||
|
raise RuntimeError("ffmpeg не найден в архиве")
|
||||||
|
with zf.open(exe_member) as src, target.open("wb") as dst:
|
||||||
|
shutil.copyfileobj(src, dst)
|
||||||
|
|
||||||
|
if os.name != "nt":
|
||||||
|
target.chmod(0o755)
|
||||||
|
_say("ffmpeg установлен.")
|
||||||
|
return target
|
||||||
78
src/voice_dictation/core/fx.py
Normal file
78
src/voice_dictation/core/fx.py
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
"""Курс USD→RUB через ЦБ РФ (бесплатно, без ключа)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_CBR_URL = "https://www.cbr-xml-daily.ru/daily_json.js"
|
||||||
|
_TIMEOUT = 10.0
|
||||||
|
_CACHE_TTL_SEC = 60 * 60 # 1 час
|
||||||
|
|
||||||
|
|
||||||
|
class UsdRubRate:
|
||||||
|
"""Кэшируемый курс USD→RUB.
|
||||||
|
|
||||||
|
Берёт официальный курс ЦБ РФ с https://www.cbr-xml-daily.ru/daily_json.js.
|
||||||
|
Кэширует в памяти на 1 час.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._rate: Decimal | None = None
|
||||||
|
self._fetched_at: float = 0.0
|
||||||
|
|
||||||
|
def get(self) -> Decimal | None:
|
||||||
|
"""Возвращает курс USD/RUB или None если получить не удалось.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Decimal с курсом (например, 80.5) или None.
|
||||||
|
"""
|
||||||
|
now = time.time()
|
||||||
|
with self._lock:
|
||||||
|
if self._rate is not None and now - self._fetched_at < _CACHE_TTL_SEC:
|
||||||
|
return self._rate
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = httpx.get(_CBR_URL, timeout=_TIMEOUT)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
usd = data["Valute"]["USD"]["Value"]
|
||||||
|
rate = Decimal(str(usd))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось получить курс ЦБ: %s", exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
self._rate = rate
|
||||||
|
self._fetched_at = now
|
||||||
|
return rate
|
||||||
|
|
||||||
|
|
||||||
|
def usd_to_rub(amount_usd: Decimal, rate: Decimal | None) -> Decimal | None:
|
||||||
|
"""Конвертирует доллары в рубли по заданному курсу.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
amount_usd: Сумма в USD.
|
||||||
|
rate: Курс USD/RUB (None — вернёт None).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Сумма в рублях, округлённая до копеек, или None.
|
||||||
|
"""
|
||||||
|
if rate is None:
|
||||||
|
return None
|
||||||
|
return (amount_usd * rate).quantize(Decimal("0.01"))
|
||||||
|
|
||||||
|
|
||||||
|
_singleton = UsdRubRate()
|
||||||
|
|
||||||
|
|
||||||
|
def get_rate() -> Decimal | None:
|
||||||
|
"""Глобальный кэшируемый курс USD/RUB (singleton)."""
|
||||||
|
return _singleton.get()
|
||||||
99
src/voice_dictation/core/models.py
Normal file
99
src/voice_dictation/core/models.py
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
"""Доменные модели данных приложения."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TranscriptionResult:
|
||||||
|
"""Результат транскрипции от Whisper API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Распознанный текст.
|
||||||
|
duration_sec: Длительность аудио в секундах.
|
||||||
|
model: Название модели.
|
||||||
|
language: Код языка (None если не определён).
|
||||||
|
prompt_used: Подсказка, переданная в API.
|
||||||
|
requested_at: Время запроса.
|
||||||
|
cost_usd: Стоимость запроса в USD.
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 RecordingResult:
|
||||||
|
"""Результат записи с микрофона.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Путь к WAV-файлу.
|
||||||
|
duration_sec: Длительность записи в секундах.
|
||||||
|
"""
|
||||||
|
|
||||||
|
path: Path
|
||||||
|
duration_sec: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class UsageRecord:
|
||||||
|
"""Запись об использовании для сохранения в БД.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
id: ID записи (None до сохранения).
|
||||||
|
created_at: Время создания.
|
||||||
|
duration_sec: Длительность аудио.
|
||||||
|
cost_usd: Стоимость запроса.
|
||||||
|
model: Модель транскрипции.
|
||||||
|
text_preview: Первые 80 символов текста.
|
||||||
|
"""
|
||||||
|
|
||||||
|
id: int | None
|
||||||
|
created_at: datetime
|
||||||
|
duration_sec: float
|
||||||
|
cost_usd: Decimal
|
||||||
|
model: str
|
||||||
|
text_preview: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SoundTheme:
|
||||||
|
"""Набор звуков для событий.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
start: Путь к звуку начала записи.
|
||||||
|
stop: Путь к звуку окончания записи.
|
||||||
|
error: Путь к звуку ошибки.
|
||||||
|
volume: Громкость от 0.0 до 1.0.
|
||||||
|
"""
|
||||||
|
|
||||||
|
start: Path | None
|
||||||
|
stop: Path | None
|
||||||
|
error: Path | None
|
||||||
|
volume: float
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BalanceInfo:
|
||||||
|
"""Информация о балансе OpenAI организации.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
total_granted_usd: Всего выдано кредитов.
|
||||||
|
total_used_usd: Всего потрачено.
|
||||||
|
total_available_usd: Доступный остаток.
|
||||||
|
fetched_at: Время получения данных.
|
||||||
|
"""
|
||||||
|
|
||||||
|
total_granted_usd: Decimal
|
||||||
|
total_used_usd: Decimal
|
||||||
|
total_available_usd: Decimal
|
||||||
|
fetched_at: datetime
|
||||||
150
src/voice_dictation/core/modes.py
Normal file
150
src/voice_dictation/core/modes.py
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
"""Реестр режимов постобработки транскрипции.
|
||||||
|
|
||||||
|
Каждый режим — это пара «ключ → спецификация»: что показывать в меню и каким
|
||||||
|
промптом гонять текст через LLM. Режим RAW — без LLM, текст вставляется как есть.
|
||||||
|
|
||||||
|
Добавить новый режим = добавить одну запись в DEFAULT_MODES.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ProcessModeSpec:
|
||||||
|
"""Спецификация режима постобработки.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: Машинный ключ режима (хранится в конфиге как ``mode``).
|
||||||
|
label: Человекочитаемое название для меню трея.
|
||||||
|
prompt: Системная инструкция для LLM. Пустая строка — режим без LLM (RAW).
|
||||||
|
"""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
label: str
|
||||||
|
prompt: str
|
||||||
|
|
||||||
|
@property
|
||||||
|
def uses_llm(self) -> bool:
|
||||||
|
"""True, если режим требует обращения к LLM."""
|
||||||
|
return bool(self.prompt)
|
||||||
|
|
||||||
|
|
||||||
|
_DECLUTTER_PROMPT = (
|
||||||
|
"Ты — редактор устной речи. Убери из расшифровки слова-паразиты "
|
||||||
|
"(ну, вот, как бы, типа, это самое, короче, блин), заминки, мычание, "
|
||||||
|
"повторы и оборванные фразы. СОХРАНИ авторский стиль, порядок мыслей и "
|
||||||
|
"ВСЕ факты, имена, числа, решения дословно — это причёсанная стенограмма, "
|
||||||
|
"а не пересказ. Ничего не сокращай и не перефразируй без необходимости. "
|
||||||
|
"Важно: если «да», «нет», «вот», «давай» несут смысл (ответ, команда, "
|
||||||
|
"указание) — оставь их. Верни только очищенный текст на русском, без "
|
||||||
|
"комментариев."
|
||||||
|
)
|
||||||
|
|
||||||
|
_TRANSLATE_EN_PROMPT = (
|
||||||
|
"Translate the following Russian speech transcript into natural, fluent "
|
||||||
|
"English. Clean up filler words, false starts and repetitions along the "
|
||||||
|
"way. Preserve all facts, names, numbers and the speaker's intent. Return "
|
||||||
|
"only the English translation, no comments."
|
||||||
|
)
|
||||||
|
|
||||||
|
_PROMPT_MODE_PROMPT = (
|
||||||
|
"Преврати следующую надиктованную мысль вслух в чёткий структурированный "
|
||||||
|
"промпт для LLM: ясно сформулируй задачу, контекст и желаемый результат. "
|
||||||
|
"Убери воду и паразиты, сохрани все требования и детали. Верни только "
|
||||||
|
"готовый промпт, без пояснений."
|
||||||
|
)
|
||||||
|
|
||||||
|
_BULLETS_PROMPT = (
|
||||||
|
"Преобразуй надиктовку в аккуратный маркированный список: каждая отдельная "
|
||||||
|
"мысль/задача — отдельный пункт. Убери паразиты и повторы, сохрани все "
|
||||||
|
"пункты и детали. Верни только список на русском."
|
||||||
|
)
|
||||||
|
|
||||||
|
_EMAIL_PROMPT = (
|
||||||
|
"Оформи следующую надиктовку как деловое письмо на русском языке: связный "
|
||||||
|
"текст, корректные падежи и согласования, вежливый деловой тон. Сохрани "
|
||||||
|
"все факты, имена, числа и суть. Убери паразиты и повторы. Используй только "
|
||||||
|
"ту информацию, которую продиктовали: НЕ добавляй шапку, реквизиты, дату, "
|
||||||
|
"адреса и поля-заполнители вроде «[Ваша компания]» — если их не было в "
|
||||||
|
"тексте. Верни только текст письма, без пояснений."
|
||||||
|
)
|
||||||
|
|
||||||
|
_SUMMARY_PROMPT = (
|
||||||
|
"Структурируй и очисти от мусора следующую расшифровку речи. Сохрани ВСЕ "
|
||||||
|
"факты, имена, решения, числа, даты и технические детали. Убери только "
|
||||||
|
"слова-паразиты, повторы и незаконченные фразы. Результат на русском:"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Порядок здесь = порядок в меню трея.
|
||||||
|
DEFAULT_MODES: tuple[ProcessModeSpec, ...] = (
|
||||||
|
ProcessModeSpec("raw", "Чистая диктовка", ""),
|
||||||
|
ProcessModeSpec("declutter", "Чистовик (без паразитов)", _DECLUTTER_PROMPT),
|
||||||
|
ProcessModeSpec("summary", "Summary (структурировать)", _SUMMARY_PROMPT),
|
||||||
|
ProcessModeSpec("translate_en", "Переводчик RU→EN", _TRANSLATE_EN_PROMPT),
|
||||||
|
ProcessModeSpec("prompt", "Промпт для LLM", _PROMPT_MODE_PROMPT),
|
||||||
|
ProcessModeSpec("bullets", "Буллеты (список)", _BULLETS_PROMPT),
|
||||||
|
ProcessModeSpec("email", "Деловое письмо", _EMAIL_PROMPT),
|
||||||
|
)
|
||||||
|
|
||||||
|
_MODES_BY_KEY: dict[str, ProcessModeSpec] = {m.key: m for m in DEFAULT_MODES}
|
||||||
|
|
||||||
|
DEFAULT_MODE_KEY = "raw"
|
||||||
|
|
||||||
|
CUSTOM_PREFIX = "custom:"
|
||||||
|
|
||||||
|
|
||||||
|
def custom_specs(custom_modes: dict[str, str] | None) -> list[ProcessModeSpec]:
|
||||||
|
"""Превращает пользовательские стили из конфига в спецификации режимов.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
custom_modes: Словарь {название: промпт} из Config.custom_modes.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список спецификаций с ключами вида ``custom:<название>``.
|
||||||
|
Стили с пустым названием или промптом пропускаются.
|
||||||
|
"""
|
||||||
|
if not custom_modes:
|
||||||
|
return []
|
||||||
|
specs: list[ProcessModeSpec] = []
|
||||||
|
for name, prompt in custom_modes.items():
|
||||||
|
name = name.strip()
|
||||||
|
if name and prompt.strip():
|
||||||
|
specs.append(ProcessModeSpec(f"{CUSTOM_PREFIX}{name}", name, prompt))
|
||||||
|
return specs
|
||||||
|
|
||||||
|
|
||||||
|
def all_specs(custom_modes: dict[str, str] | None = None) -> list[ProcessModeSpec]:
|
||||||
|
"""Полный список режимов: встроенные + пользовательские.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
custom_modes: Словарь пользовательских стилей из конфига.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Встроенные режимы, затем пользовательские.
|
||||||
|
"""
|
||||||
|
return list(DEFAULT_MODES) + custom_specs(custom_modes)
|
||||||
|
|
||||||
|
|
||||||
|
def get_mode(key: str, custom_modes: dict[str, str] | None = None) -> ProcessModeSpec:
|
||||||
|
"""Возвращает спецификацию режима по ключу.
|
||||||
|
|
||||||
|
Ищет среди встроенных и пользовательских режимов. Неизвестный ключ
|
||||||
|
(например, удалённый кастомный стиль или конфиг будущей версии) безопасно
|
||||||
|
откатывается на RAW.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: Ключ режима.
|
||||||
|
custom_modes: Словарь пользовательских стилей из конфига.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Спецификация режима; RAW, если ключ неизвестен.
|
||||||
|
"""
|
||||||
|
if key in _MODES_BY_KEY:
|
||||||
|
return _MODES_BY_KEY[key]
|
||||||
|
for spec in custom_specs(custom_modes):
|
||||||
|
if spec.key == key:
|
||||||
|
return spec
|
||||||
|
return _MODES_BY_KEY[DEFAULT_MODE_KEY]
|
||||||
324
src/voice_dictation/core/orchestrator.py
Normal file
324
src/voice_dictation/core/orchestrator.py
Normal file
|
|
@ -0,0 +1,324 @@
|
||||||
|
"""Главный оркестратор — state-machine диктовки."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections.abc import Callable
|
||||||
|
from concurrent.futures import Future, ThreadPoolExecutor
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
from voice_dictation.core.enums import RecordingState, SoundKind
|
||||||
|
from voice_dictation.core.models import RecordingResult, TranscriptionResult, UsageRecord
|
||||||
|
from voice_dictation.core.modes import get_mode
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
from voice_dictation.infrastructure.errors import RecorderError, TranscriptionError
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from voice_dictation.platform.protocols import (
|
||||||
|
AudioRecorder,
|
||||||
|
AutoPaste,
|
||||||
|
Clipboard,
|
||||||
|
Notifier,
|
||||||
|
SoundPlayer,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_MAX_AUTOPASTE_CHARS = 10_000
|
||||||
|
|
||||||
|
|
||||||
|
class DictationOrchestrator:
|
||||||
|
"""Управляет полным циклом диктовки: хоткей → запись → транскрипция → вставка.
|
||||||
|
|
||||||
|
Реализует state-machine с состояниями IDLE → RECORDING → PROCESSING → IDLE.
|
||||||
|
Все переходы защищены threading.Lock.
|
||||||
|
Запрос к API выполняется в отдельном потоке (ThreadPoolExecutor).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
recorder: Реализация записи аудио.
|
||||||
|
transcriber: Реализация транскрипции.
|
||||||
|
dictionary: Словарь подсказок.
|
||||||
|
clipboard: Реализация буфера обмена.
|
||||||
|
auto_paste: Реализация автовставки.
|
||||||
|
sound_player: Реализация воспроизведения звуков.
|
||||||
|
notifier: Реализация уведомлений.
|
||||||
|
config_provider: Функция-провайдер текущей конфигурации.
|
||||||
|
paths: Пути приложения.
|
||||||
|
state_listener: Колбэк при смене состояния (опционально).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
recorder: AudioRecorder,
|
||||||
|
transcriber: WhisperTranscriber,
|
||||||
|
dictionary: Dictionary,
|
||||||
|
clipboard: Clipboard,
|
||||||
|
auto_paste: AutoPaste,
|
||||||
|
sound_player: SoundPlayer,
|
||||||
|
notifier: Notifier,
|
||||||
|
config_provider: Callable[[], Config],
|
||||||
|
paths: AppPaths,
|
||||||
|
state_listener: Callable[[RecordingState], None] | None = None,
|
||||||
|
usage_db: UsageDB | None = None,
|
||||||
|
) -> None:
|
||||||
|
self._recorder = recorder
|
||||||
|
self._transcriber = transcriber
|
||||||
|
self._dictionary = dictionary
|
||||||
|
self._clipboard = clipboard
|
||||||
|
self._auto_paste = auto_paste
|
||||||
|
self._sound_player = sound_player
|
||||||
|
self._notifier = notifier
|
||||||
|
self._config_provider = config_provider
|
||||||
|
self._paths = paths
|
||||||
|
self._state_listener = state_listener
|
||||||
|
self._usage_db = usage_db
|
||||||
|
|
||||||
|
self._state = RecordingState.IDLE
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="whisper")
|
||||||
|
self._current_future: Future[None] | None = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def state(self) -> RecordingState:
|
||||||
|
"""Текущее состояние оркестратора."""
|
||||||
|
return self._state
|
||||||
|
|
||||||
|
def toggle(self) -> None:
|
||||||
|
"""Переключает запись: IDLE→RECORDING или RECORDING→PROCESSING.
|
||||||
|
|
||||||
|
Вызов в состоянии PROCESSING игнорируется (запрос уже выполняется).
|
||||||
|
"""
|
||||||
|
with self._lock:
|
||||||
|
current = self._state
|
||||||
|
if current == RecordingState.IDLE:
|
||||||
|
self._start_recording()
|
||||||
|
elif current == RecordingState.RECORDING:
|
||||||
|
self._stop_recording()
|
||||||
|
else:
|
||||||
|
logger.debug("toggle() проигнорирован в состоянии %s", current)
|
||||||
|
|
||||||
|
def cancel(self) -> None:
|
||||||
|
"""Отменяет текущую запись без транскрипции."""
|
||||||
|
with self._lock:
|
||||||
|
if self._state != RecordingState.RECORDING:
|
||||||
|
return
|
||||||
|
with contextlib.suppress(RecorderError):
|
||||||
|
self._recorder.stop()
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
logger.info("Запись отменена")
|
||||||
|
|
||||||
|
def _start_recording(self) -> None:
|
||||||
|
"""Запускает запись (вызывается внутри lock)."""
|
||||||
|
config = self._config_provider()
|
||||||
|
output_path = self._paths.tmp_dir / f"session_{int(time.time() * 1000)}.wav"
|
||||||
|
try:
|
||||||
|
self._recorder.start(output_path)
|
||||||
|
except RecorderError as exc:
|
||||||
|
logger.error("Не удалось начать запись: %s", exc)
|
||||||
|
self._set_state(RecordingState.ERROR)
|
||||||
|
self._sound_player.play(SoundKind.ERROR, config=config)
|
||||||
|
self._notifier.show("Ошибка записи", str(exc))
|
||||||
|
# Сразу возвращаемся в IDLE после ошибки
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
return
|
||||||
|
|
||||||
|
self._set_state(RecordingState.RECORDING)
|
||||||
|
self._sound_player.play(SoundKind.START, config=config)
|
||||||
|
logger.info("Запись начата: %s", output_path)
|
||||||
|
|
||||||
|
def _stop_recording(self) -> None:
|
||||||
|
"""Останавливает запись и запускает транскрипцию (вызывается внутри lock)."""
|
||||||
|
config = self._config_provider()
|
||||||
|
try:
|
||||||
|
recording = self._recorder.stop()
|
||||||
|
except RecorderError as exc:
|
||||||
|
logger.error("Ошибка остановки записи: %s", exc)
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
self._sound_player.play(SoundKind.ERROR, config=config)
|
||||||
|
self._notifier.show("Ошибка записи", str(exc))
|
||||||
|
return
|
||||||
|
|
||||||
|
self._set_state(RecordingState.PROCESSING)
|
||||||
|
self._sound_player.play(SoundKind.STOP, config=config)
|
||||||
|
|
||||||
|
# Запрос к API — в отдельном потоке, не блокируем hotkey
|
||||||
|
self._current_future = self._executor.submit(self._process_recording, recording, config)
|
||||||
|
|
||||||
|
def _process_recording(self, recording: RecordingResult, config: Config) -> None:
|
||||||
|
"""Транскрибирует запись и вставляет текст (выполняется в worker-потоке).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
recording: Результат записи.
|
||||||
|
config: Текущая конфигурация.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
prompt = self._dictionary.build_prompt()
|
||||||
|
result = self._transcriber.transcribe(
|
||||||
|
recording.path,
|
||||||
|
prompt=prompt,
|
||||||
|
language=config.language,
|
||||||
|
)
|
||||||
|
self._on_transcription_success(result, config)
|
||||||
|
except TranscriptionError as exc:
|
||||||
|
logger.error("Ошибка транскрипции: %s", exc)
|
||||||
|
self._on_transcription_error(str(exc), config)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Неожиданная ошибка при транскрипции: %s", exc)
|
||||||
|
self._on_transcription_error(f"Неожиданная ошибка: {exc}", config)
|
||||||
|
finally:
|
||||||
|
recording.path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def _on_transcription_success(self, result: TranscriptionResult, config: Config) -> None:
|
||||||
|
"""Обрабатывает успешную транскрипцию.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
result: Результат транскрипции.
|
||||||
|
config: Конфигурация.
|
||||||
|
"""
|
||||||
|
if not result.text:
|
||||||
|
logger.info("Транскрипция вернула пустой текст")
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Транскрибировано: %.1fс, $%.6f, %d символов",
|
||||||
|
result.duration_sec,
|
||||||
|
result.cost_usd,
|
||||||
|
len(result.text),
|
||||||
|
)
|
||||||
|
|
||||||
|
today_cost = None
|
||||||
|
if self._usage_db is not None:
|
||||||
|
try:
|
||||||
|
self._usage_db.insert(
|
||||||
|
UsageRecord(
|
||||||
|
id=None,
|
||||||
|
created_at=result.requested_at,
|
||||||
|
duration_sec=result.duration_sec,
|
||||||
|
cost_usd=result.cost_usd,
|
||||||
|
model=result.model,
|
||||||
|
text_preview=result.text[:80],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
tz = datetime.now().astimezone().tzinfo
|
||||||
|
today_cost = self._usage_db.today_total(tz=tz).total_cost_usd
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось записать UsageRecord: %s", exc)
|
||||||
|
|
||||||
|
# Постобработка: гоним текст через LLM по выбранному режиму
|
||||||
|
final_text = result.text
|
||||||
|
mode = get_mode(config.mode, config.custom_modes)
|
||||||
|
if mode.uses_llm:
|
||||||
|
try:
|
||||||
|
final_text = self._post_process(result.text, mode.prompt, config)
|
||||||
|
logger.info(
|
||||||
|
"Режим '%s' готов: %d → %d символов",
|
||||||
|
mode.key,
|
||||||
|
len(result.text),
|
||||||
|
len(final_text),
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error("Ошибка постобработки (%s): %s, вставляю оригинал", mode.key, exc)
|
||||||
|
|
||||||
|
self._clipboard.copy(final_text)
|
||||||
|
|
||||||
|
if config.notifications_enabled:
|
||||||
|
from voice_dictation.core.fx import get_rate, usd_to_rub
|
||||||
|
|
||||||
|
chars = len(result.text)
|
||||||
|
summary_parts = [f"{result.duration_sec:.1f}с · {chars} симв."]
|
||||||
|
if config.show_cost_in_notification:
|
||||||
|
rate = get_rate()
|
||||||
|
cost_rub = usd_to_rub(result.cost_usd, rate)
|
||||||
|
cost_part = f"${result.cost_usd:.4f}"
|
||||||
|
if cost_rub is not None:
|
||||||
|
cost_part += f" ({cost_rub:.2f}₽)"
|
||||||
|
summary_parts.append(cost_part)
|
||||||
|
if today_cost is not None:
|
||||||
|
today_rub = usd_to_rub(today_cost, rate)
|
||||||
|
today_part = f"сегодня ${today_cost:.4f}"
|
||||||
|
if today_rub is not None:
|
||||||
|
today_part += f" ({today_rub:.2f}₽)"
|
||||||
|
summary_parts.append(today_part)
|
||||||
|
self._notifier.show("Диктовка готова", " · ".join(summary_parts))
|
||||||
|
|
||||||
|
if config.auto_paste and len(result.text) <= _MAX_AUTOPASTE_CHARS:
|
||||||
|
if config.paste_delay_ms > 0:
|
||||||
|
time.sleep(config.paste_delay_ms / 1000)
|
||||||
|
self._auto_paste.paste()
|
||||||
|
elif len(result.text) > _MAX_AUTOPASTE_CHARS:
|
||||||
|
# Слишком длинный текст — только буфер, без вставки
|
||||||
|
chars = len(result.text)
|
||||||
|
self._notifier.show(
|
||||||
|
"Текст скопирован",
|
||||||
|
f"Слишком длинный для автовставки ({chars} символов). Вставьте вручную Cmd+V.",
|
||||||
|
)
|
||||||
|
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _post_process(text: str, prompt: str, config: Config) -> str:
|
||||||
|
"""Прогоняет текст через LLM с заданным промптом режима.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Исходная транскрипция.
|
||||||
|
prompt: Системная инструкция режима.
|
||||||
|
config: Конфигурация (модель в proc_model).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Обработанный текст; исходный, если LLM вернул пусто.
|
||||||
|
"""
|
||||||
|
from openai import OpenAI
|
||||||
|
|
||||||
|
client = OpenAI()
|
||||||
|
resp = client.chat.completions.create(
|
||||||
|
model=config.proc_model,
|
||||||
|
messages=[
|
||||||
|
{"role": "user", "content": f"{prompt}\n\n{text}"}
|
||||||
|
],
|
||||||
|
max_tokens=2000,
|
||||||
|
)
|
||||||
|
return resp.choices[0].message.content or text
|
||||||
|
|
||||||
|
def _on_transcription_error(self, message: str, config: Config) -> None:
|
||||||
|
"""Обрабатывает ошибку транскрипции.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: Сообщение об ошибке.
|
||||||
|
config: Конфигурация.
|
||||||
|
"""
|
||||||
|
self._sound_player.play(SoundKind.ERROR, config=config)
|
||||||
|
self._notifier.show("Ошибка транскрипции", message)
|
||||||
|
self._set_state(RecordingState.IDLE)
|
||||||
|
|
||||||
|
def _set_state(self, new_state: RecordingState) -> None:
|
||||||
|
"""Устанавливает новое состояние и уведомляет слушателя.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
new_state: Новое состояние.
|
||||||
|
"""
|
||||||
|
old_state = self._state
|
||||||
|
self._state = new_state
|
||||||
|
if old_state != new_state:
|
||||||
|
logger.debug("Состояние: %s → %s", old_state.name, new_state.name)
|
||||||
|
if self._state_listener is not None:
|
||||||
|
try:
|
||||||
|
self._state_listener(new_state)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Ошибка в state_listener: %s", exc)
|
||||||
|
|
||||||
|
def shutdown(self) -> None:
|
||||||
|
"""Корректно завершает работу оркестратора."""
|
||||||
|
self._executor.shutdown(wait=False, cancel_futures=True)
|
||||||
|
if self._state == RecordingState.RECORDING:
|
||||||
|
with contextlib.suppress(RecorderError):
|
||||||
|
self._recorder.stop()
|
||||||
|
logger.info("Оркестратор остановлен")
|
||||||
62
src/voice_dictation/core/paths.py
Normal file
62
src/voice_dictation/core/paths.py
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""Пути файловой системы приложения."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class AppPaths:
|
||||||
|
"""Все пути приложения в одном месте.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
root: Корневая директория (~/.dictate).
|
||||||
|
config_file: Файл конфигурации.
|
||||||
|
usage_db: База данных статистики.
|
||||||
|
dictionary_file: Словарь подсказок для Whisper.
|
||||||
|
custom_sounds_dir: Директория пользовательских звуков.
|
||||||
|
log_file: Файл лога.
|
||||||
|
pid_file: PID-файл для single-instance lock.
|
||||||
|
tmp_dir: Временные WAV-файлы записей.
|
||||||
|
"""
|
||||||
|
|
||||||
|
root: Path
|
||||||
|
config_file: Path
|
||||||
|
usage_db: Path
|
||||||
|
dictionary_file: Path
|
||||||
|
custom_sounds_dir: Path
|
||||||
|
log_file: Path
|
||||||
|
pid_file: Path
|
||||||
|
tmp_dir: Path
|
||||||
|
bin_dir: Path
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def default(cls) -> AppPaths:
|
||||||
|
"""Создаёт AppPaths со стандартными путями в домашней директории.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AppPaths с путями в ~/.dictate/.
|
||||||
|
"""
|
||||||
|
root = Path.home() / ".dictate"
|
||||||
|
return cls(
|
||||||
|
root=root,
|
||||||
|
config_file=root / "config.json",
|
||||||
|
usage_db=root / "usage.db",
|
||||||
|
dictionary_file=root / "dictionary.txt",
|
||||||
|
custom_sounds_dir=root / "sounds",
|
||||||
|
log_file=root / "app.log",
|
||||||
|
pid_file=root / "dictate.pid",
|
||||||
|
tmp_dir=root / "tmp",
|
||||||
|
bin_dir=root / "bin",
|
||||||
|
)
|
||||||
|
|
||||||
|
def ensure_exists(self) -> AppPaths:
|
||||||
|
"""Создаёт все необходимые директории.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
self для удобства цепочки вызовов.
|
||||||
|
"""
|
||||||
|
for directory in (self.root, self.custom_sounds_dir, self.tmp_dir, self.bin_dir):
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
return self
|
||||||
44
src/voice_dictation/core/pricing.py
Normal file
44
src/voice_dictation/core/pricing.py
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
"""Расчёт стоимости транскрипции Whisper API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from decimal import Decimal
|
||||||
|
from types import MappingProxyType
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
|
||||||
|
class PriceCalculator:
|
||||||
|
"""Вычисляет стоимость транскрипции по модели и длительности.
|
||||||
|
|
||||||
|
Цены — за минуту аудио, округление вверх до целой минуты (как у OpenAI).
|
||||||
|
"""
|
||||||
|
|
||||||
|
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:
|
||||||
|
"""Рассчитывает стоимость транскрипции.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: Идентификатор модели.
|
||||||
|
duration_sec: Длительность аудио в секундах.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Стоимость в USD с точностью до 6 знаков.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
KeyError: Если модель не найдена в прайсе.
|
||||||
|
"""
|
||||||
|
price_per_minute = cls.PRICES_PER_MINUTE[model]
|
||||||
|
# OpenAI округляет вверх до целой секунды, минимум 1 сек
|
||||||
|
duration_sec_ceil = max(1.0, math.ceil(duration_sec))
|
||||||
|
minutes = Decimal(str(duration_sec_ceil)) / Decimal("60")
|
||||||
|
return (price_per_minute * minutes).quantize(Decimal("0.000001"))
|
||||||
198
src/voice_dictation/core/recorder.py
Normal file
198
src/voice_dictation/core/recorder.py
Normal file
|
|
@ -0,0 +1,198 @@
|
||||||
|
"""Запись аудио с микрофона через sounddevice (кроссплатформенно)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import struct
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.core.models import RecordingResult
|
||||||
|
from voice_dictation.infrastructure.errors import RecorderError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_MIN_DURATION_SEC = 0.3
|
||||||
|
_MIN_FILE_SIZE_BYTES = 4 * 1024 # 4 KB
|
||||||
|
|
||||||
|
|
||||||
|
class SoxRecorder:
|
||||||
|
"""Запись WAV с микрофона через sounddevice.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sample_rate: Частота дискретизации (по умолчанию 16000 Гц).
|
||||||
|
channels: Количество каналов (по умолчанию 1 — моно).
|
||||||
|
bin_dir: Каталог докачанных бинарников (для поиска ffmpeg).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, sample_rate: int = 16000, channels: int = 1, bin_dir: Path | None = None
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
import sounddevice # noqa: F401
|
||||||
|
except ImportError:
|
||||||
|
raise RecorderError(
|
||||||
|
"sounddevice не установлен. pip install sounddevice"
|
||||||
|
)
|
||||||
|
self._sample_rate = sample_rate
|
||||||
|
self._channels = channels
|
||||||
|
self._bin_dir = bin_dir
|
||||||
|
self._frames: list[bytes] = []
|
||||||
|
self._stream = None
|
||||||
|
self._output_path: Path | None = None
|
||||||
|
self._start_time: float | None = None
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def start(self, output_path: Path) -> None:
|
||||||
|
"""Начинает запись в указанный файл."""
|
||||||
|
import sounddevice as sd
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
if self._stream is not None:
|
||||||
|
raise RecorderError("Запись уже запущена")
|
||||||
|
|
||||||
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._frames = []
|
||||||
|
self._output_path = output_path
|
||||||
|
|
||||||
|
def callback(indata, frames, time_info, status):
|
||||||
|
if status:
|
||||||
|
logger.warning("sounddevice status: %s", status)
|
||||||
|
self._frames.append(bytes(indata))
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._stream = sd.RawInputStream(
|
||||||
|
samplerate=self._sample_rate,
|
||||||
|
channels=self._channels,
|
||||||
|
dtype="int16",
|
||||||
|
callback=callback,
|
||||||
|
blocksize=1024,
|
||||||
|
)
|
||||||
|
self._stream.start()
|
||||||
|
except Exception as exc:
|
||||||
|
self._stream = None
|
||||||
|
raise RecorderError(f"Не удалось начать запись: {exc}") from exc
|
||||||
|
|
||||||
|
self._start_time = time.monotonic()
|
||||||
|
logger.debug("Запись начата: %s", output_path)
|
||||||
|
|
||||||
|
def stop(self) -> RecordingResult:
|
||||||
|
"""Останавливает запись и возвращает результат."""
|
||||||
|
with self._lock:
|
||||||
|
if self._stream is None or self._output_path is None:
|
||||||
|
raise RecorderError("Запись не запущена")
|
||||||
|
|
||||||
|
stream = self._stream
|
||||||
|
output_path = self._output_path
|
||||||
|
|
||||||
|
try:
|
||||||
|
stream.stop()
|
||||||
|
stream.close()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Ошибка остановки stream: %s", exc)
|
||||||
|
|
||||||
|
self._stream = None
|
||||||
|
self._output_path = None
|
||||||
|
elapsed = time.monotonic() - (self._start_time or 0)
|
||||||
|
self._start_time = None
|
||||||
|
|
||||||
|
# Собираем все фреймы в один буфер
|
||||||
|
audio_data = b"".join(self._frames)
|
||||||
|
self._frames = []
|
||||||
|
|
||||||
|
if not audio_data:
|
||||||
|
raise RecorderError("Нет записанных данных")
|
||||||
|
|
||||||
|
duration_sec = len(audio_data) / (self._sample_rate * self._channels * 2)
|
||||||
|
|
||||||
|
# Конвертируем в OGG/Opus — ~10x сжатие
|
||||||
|
ogg_path = output_path.with_suffix(".ogg")
|
||||||
|
try:
|
||||||
|
self._write_ogg(audio_data, ogg_path)
|
||||||
|
output_path = ogg_path
|
||||||
|
logger.debug("Конвертировано в OGG: %d байт", ogg_path.stat().st_size)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("OGG конвертация не удалась, пишем WAV: %s", exc)
|
||||||
|
self._write_wav(output_path, audio_data)
|
||||||
|
|
||||||
|
file_size = output_path.stat().st_size
|
||||||
|
|
||||||
|
if duration_sec < _MIN_DURATION_SEC:
|
||||||
|
output_path.unlink(missing_ok=True)
|
||||||
|
raise RecorderError(
|
||||||
|
f"Запись слишком короткая: {duration_sec:.2f}с"
|
||||||
|
)
|
||||||
|
if file_size < _MIN_FILE_SIZE_BYTES:
|
||||||
|
output_path.unlink(missing_ok=True)
|
||||||
|
raise RecorderError(
|
||||||
|
f"Файл слишком маленький: {file_size} байт"
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.debug("Запись остановлена: %.2fс, %d байт", duration_sec, file_size)
|
||||||
|
return RecordingResult(path=output_path, duration_sec=duration_sec)
|
||||||
|
|
||||||
|
def _write_wav(self, path: Path, data: bytes) -> None:
|
||||||
|
"""Записывает корректный WAV-файл."""
|
||||||
|
num_channels = self._channels
|
||||||
|
sample_width = 2 # 16-bit
|
||||||
|
byte_rate = self._sample_rate * num_channels * sample_width
|
||||||
|
block_align = num_channels * sample_width
|
||||||
|
data_size = len(data)
|
||||||
|
file_size = 36 + data_size
|
||||||
|
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
# RIFF header
|
||||||
|
f.write(b"RIFF")
|
||||||
|
f.write(struct.pack("<I", file_size))
|
||||||
|
f.write(b"WAVE")
|
||||||
|
# fmt chunk
|
||||||
|
f.write(b"fmt ")
|
||||||
|
f.write(struct.pack("<I", 16)) # chunk size
|
||||||
|
f.write(struct.pack("<H", 1)) # PCM
|
||||||
|
f.write(struct.pack("<H", num_channels))
|
||||||
|
f.write(struct.pack("<I", self._sample_rate))
|
||||||
|
f.write(struct.pack("<I", byte_rate))
|
||||||
|
f.write(struct.pack("<H", block_align))
|
||||||
|
f.write(struct.pack("<H", sample_width * 8))
|
||||||
|
# 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:
|
||||||
|
if self._stream is not None:
|
||||||
|
try:
|
||||||
|
self._stream.stop()
|
||||||
|
self._stream.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
177
src/voice_dictation/core/transcriber.py
Normal file
177
src/voice_dictation/core/transcriber.py
Normal file
|
|
@ -0,0 +1,177 @@
|
||||||
|
"""Транскрипция аудио через OpenAI Whisper API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import wave
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from voice_dictation.core.models import TranscriptionResult
|
||||||
|
from voice_dictation.core.pricing import PriceCalculator
|
||||||
|
from voice_dictation.infrastructure.errors import TranscriptionError, WhisperAPIError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_API_URL = "https://api.openai.com/v1/audio/transcriptions"
|
||||||
|
_TIMEOUT_SEC = 60.0
|
||||||
|
_MAX_RETRIES = 2
|
||||||
|
|
||||||
|
|
||||||
|
class WhisperTranscriber:
|
||||||
|
"""Транскрипция WAV-файлов через OpenAI Whisper API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
api_key: OpenAI API ключ.
|
||||||
|
model: Модель транскрипции.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, api_key: str, model: str = "gpt-4o-mini-transcribe") -> None:
|
||||||
|
self._api_key = api_key
|
||||||
|
self._model = model
|
||||||
|
self._client = httpx.Client(
|
||||||
|
headers={"Authorization": f"Bearer {api_key}"},
|
||||||
|
timeout=_TIMEOUT_SEC,
|
||||||
|
)
|
||||||
|
|
||||||
|
def transcribe(
|
||||||
|
self,
|
||||||
|
audio_path: Path,
|
||||||
|
prompt: str = "",
|
||||||
|
language: str | None = None,
|
||||||
|
) -> TranscriptionResult:
|
||||||
|
"""Отправляет WAV в Whisper API и возвращает результат.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_path: Путь к WAV-файлу.
|
||||||
|
prompt: Подсказка со специальными словами.
|
||||||
|
language: Код языка (None — автоопределение).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
TranscriptionResult с текстом и метаданными.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
TranscriptionError: При ошибке сети или невалидном ответе.
|
||||||
|
WhisperAPIError: При HTTP-ошибке от API.
|
||||||
|
"""
|
||||||
|
requested_at = datetime.now(tz=UTC)
|
||||||
|
|
||||||
|
last_exc: Exception | None = None
|
||||||
|
for attempt in range(_MAX_RETRIES + 1):
|
||||||
|
try:
|
||||||
|
result = self._do_request(audio_path, prompt, language, requested_at)
|
||||||
|
return result
|
||||||
|
except WhisperAPIError as exc:
|
||||||
|
# Не ретраим 4xx — это клиентские ошибки
|
||||||
|
if exc.status_code is not None and 400 <= exc.status_code < 500:
|
||||||
|
raise
|
||||||
|
last_exc = exc
|
||||||
|
if attempt < _MAX_RETRIES:
|
||||||
|
logger.warning(
|
||||||
|
"Попытка %d/%d не удалась: %s, повторяю...",
|
||||||
|
attempt + 1,
|
||||||
|
_MAX_RETRIES + 1,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
except TranscriptionError as exc:
|
||||||
|
last_exc = exc
|
||||||
|
if attempt < _MAX_RETRIES:
|
||||||
|
logger.warning(
|
||||||
|
"Попытка %d/%d: %s, повторяю...", attempt + 1, _MAX_RETRIES + 1, exc
|
||||||
|
)
|
||||||
|
|
||||||
|
raise last_exc or TranscriptionError("Все попытки транскрипции исчерпаны")
|
||||||
|
|
||||||
|
def _do_request(
|
||||||
|
self,
|
||||||
|
audio_path: Path,
|
||||||
|
prompt: str,
|
||||||
|
language: str | None,
|
||||||
|
requested_at: datetime,
|
||||||
|
) -> TranscriptionResult:
|
||||||
|
"""Выполняет один HTTP-запрос к Whisper API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
audio_path: Путь к WAV.
|
||||||
|
prompt: Подсказка.
|
||||||
|
language: Код языка.
|
||||||
|
requested_at: Время запроса.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
TranscriptionResult.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
WhisperAPIError: При HTTP-ошибке.
|
||||||
|
TranscriptionError: При сетевой ошибке или невалидном JSON.
|
||||||
|
"""
|
||||||
|
response_format = "verbose_json" if self._model == "whisper-1" else "json"
|
||||||
|
data: dict[str, str] = {
|
||||||
|
"model": self._model,
|
||||||
|
"response_format": response_format,
|
||||||
|
}
|
||||||
|
if language:
|
||||||
|
data["language"] = language
|
||||||
|
if prompt:
|
||||||
|
data["prompt"] = prompt
|
||||||
|
|
||||||
|
try:
|
||||||
|
with audio_path.open("rb") as audio_file:
|
||||||
|
response = self._client.post(
|
||||||
|
_API_URL,
|
||||||
|
data=data,
|
||||||
|
files={"file": (audio_path.name, audio_file, "audio/ogg" if audio_path.suffix == ".ogg" else "audio/wav")},
|
||||||
|
)
|
||||||
|
except httpx.TimeoutException as exc:
|
||||||
|
raise TranscriptionError(f"Timeout при запросе к Whisper API: {exc}") from exc
|
||||||
|
except httpx.RequestError as exc:
|
||||||
|
raise TranscriptionError(f"Сетевая ошибка: {exc}") from exc
|
||||||
|
|
||||||
|
if not response.is_success:
|
||||||
|
raise WhisperAPIError(
|
||||||
|
f"Whisper API вернул {response.status_code}: {response.text[:200]}",
|
||||||
|
status_code=response.status_code,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
body = response.json()
|
||||||
|
except Exception as exc:
|
||||||
|
raise TranscriptionError(f"Невалидный JSON от API: {exc}") from exc
|
||||||
|
|
||||||
|
text: str = body.get("text", "").strip()
|
||||||
|
duration_sec: float = float(body.get("duration", 0.0)) or _wav_duration(audio_path)
|
||||||
|
detected_language: str | None = body.get("language") or language
|
||||||
|
|
||||||
|
cost = PriceCalculator.cost(self._model, duration_sec)
|
||||||
|
|
||||||
|
return TranscriptionResult(
|
||||||
|
text=text,
|
||||||
|
duration_sec=duration_sec,
|
||||||
|
model=self._model,
|
||||||
|
language=detected_language,
|
||||||
|
prompt_used=prompt or None,
|
||||||
|
requested_at=requested_at,
|
||||||
|
cost_usd=cost if cost != Decimal("0") else PriceCalculator.cost(self._model, 1.0),
|
||||||
|
)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Закрывает HTTP-клиент."""
|
||||||
|
self._client.close()
|
||||||
|
|
||||||
|
def __del__(self) -> None:
|
||||||
|
import contextlib
|
||||||
|
|
||||||
|
with contextlib.suppress(Exception):
|
||||||
|
self._client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _wav_duration(path: Path) -> float:
|
||||||
|
try:
|
||||||
|
with wave.open(str(path), "rb") as wf:
|
||||||
|
frames = wf.getnframes()
|
||||||
|
rate = wf.getframerate()
|
||||||
|
return frames / float(rate) if rate else 0.0
|
||||||
|
except (wave.Error, EOFError, OSError):
|
||||||
|
return 0.0
|
||||||
215
src/voice_dictation/core/usage_db.py
Normal file
215
src/voice_dictation/core/usage_db.py
Normal file
|
|
@ -0,0 +1,215 @@
|
||||||
|
"""Хранение статистики использования в SQLite."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, date, datetime, time, timedelta, timezone
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.core.models import UsageRecord
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_SCHEMA_VERSION = 1
|
||||||
|
|
||||||
|
_SCHEMA_V1 = """
|
||||||
|
CREATE TABLE IF NOT EXISTS usage (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
duration_sec REAL NOT NULL,
|
||||||
|
cost_usd TEXT NOT NULL,
|
||||||
|
model TEXT NOT NULL,
|
||||||
|
text_preview TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usage_created_at ON usage(created_at);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class UsageStats:
|
||||||
|
"""Агрегированная статистика за период.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
count: Количество транскрипций.
|
||||||
|
total_duration_sec: Суммарная длительность.
|
||||||
|
total_cost_usd: Суммарная стоимость.
|
||||||
|
"""
|
||||||
|
|
||||||
|
count: int
|
||||||
|
total_duration_sec: float
|
||||||
|
total_cost_usd: Decimal
|
||||||
|
|
||||||
|
|
||||||
|
class UsageDB:
|
||||||
|
"""SQLite-хранилище записей об использовании.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Путь к файлу БД.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, path: Path) -> None:
|
||||||
|
self._path = path
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._ensure_schema()
|
||||||
|
|
||||||
|
def _ensure_schema(self) -> None:
|
||||||
|
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with self._connect() as conn:
|
||||||
|
current = conn.execute("PRAGMA user_version").fetchone()[0]
|
||||||
|
if current < 1:
|
||||||
|
conn.executescript(_SCHEMA_V1)
|
||||||
|
conn.execute(f"PRAGMA user_version = {_SCHEMA_VERSION}")
|
||||||
|
conn.commit()
|
||||||
|
logger.debug("usage.db: схема инициализирована (v%d)", _SCHEMA_VERSION)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _connect(self) -> Iterator[sqlite3.Connection]:
|
||||||
|
conn = sqlite3.connect(self._path)
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def insert(self, record: UsageRecord) -> UsageRecord:
|
||||||
|
"""Сохраняет запись. Возвращает копию с проставленным id.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
record: Запись для сохранения.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
UsageRecord с заполненным id.
|
||||||
|
"""
|
||||||
|
preview = record.text_preview[:80]
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
cursor = conn.execute(
|
||||||
|
"INSERT INTO usage(created_at, duration_sec, cost_usd, model, text_preview) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?)",
|
||||||
|
(
|
||||||
|
record.created_at.astimezone(UTC).isoformat(),
|
||||||
|
record.duration_sec,
|
||||||
|
str(record.cost_usd),
|
||||||
|
record.model,
|
||||||
|
preview,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
new_id = cursor.lastrowid
|
||||||
|
return UsageRecord(
|
||||||
|
id=new_id,
|
||||||
|
created_at=record.created_at,
|
||||||
|
duration_sec=record.duration_sec,
|
||||||
|
cost_usd=record.cost_usd,
|
||||||
|
model=record.model,
|
||||||
|
text_preview=preview,
|
||||||
|
)
|
||||||
|
|
||||||
|
def today_total(self, tz: timezone = UTC) -> UsageStats:
|
||||||
|
"""Статистика за сегодня в указанной TZ.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
tz: Часовой пояс для определения "сегодня".
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
UsageStats за текущий день.
|
||||||
|
"""
|
||||||
|
now_local = datetime.now(tz)
|
||||||
|
start_local = datetime.combine(now_local.date(), time.min, tzinfo=tz)
|
||||||
|
end_local = start_local + timedelta(days=1)
|
||||||
|
return self.stats(start_local, end_local)
|
||||||
|
|
||||||
|
def stats(self, since: datetime, until: datetime) -> UsageStats:
|
||||||
|
"""Агрегированная статистика за период [since, until).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
since: Начало периода (включительно).
|
||||||
|
until: Конец периода (не включая).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
UsageStats за период.
|
||||||
|
"""
|
||||||
|
since_utc = since.astimezone(UTC).isoformat()
|
||||||
|
until_utc = until.astimezone(UTC).isoformat()
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COUNT(*), COALESCE(SUM(duration_sec), 0), "
|
||||||
|
"COALESCE(SUM(CAST(cost_usd AS REAL)), 0) "
|
||||||
|
"FROM usage WHERE created_at >= ? AND created_at < ?",
|
||||||
|
(since_utc, until_utc),
|
||||||
|
).fetchone()
|
||||||
|
count, total_duration, total_cost = row
|
||||||
|
return UsageStats(
|
||||||
|
count=int(count),
|
||||||
|
total_duration_sec=float(total_duration),
|
||||||
|
total_cost_usd=Decimal(str(total_cost)).quantize(Decimal("0.000001")),
|
||||||
|
)
|
||||||
|
|
||||||
|
def recent(self, limit: int = 20) -> list[UsageRecord]:
|
||||||
|
"""Последние N записей.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
limit: Сколько записей вернуть.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список UsageRecord (самые новые первыми).
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, created_at, duration_sec, cost_usd, model, text_preview "
|
||||||
|
"FROM usage ORDER BY id DESC LIMIT ?",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
return [
|
||||||
|
UsageRecord(
|
||||||
|
id=r[0],
|
||||||
|
created_at=datetime.fromisoformat(r[1]),
|
||||||
|
duration_sec=float(r[2]),
|
||||||
|
cost_usd=Decimal(r[3]),
|
||||||
|
model=r[4],
|
||||||
|
text_preview=r[5],
|
||||||
|
)
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
def all_time(self) -> UsageStats:
|
||||||
|
"""Суммарная статистика за всё время.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
UsageStats без фильтра по дате.
|
||||||
|
"""
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COUNT(*), COALESCE(SUM(duration_sec), 0), "
|
||||||
|
"COALESCE(SUM(CAST(cost_usd AS REAL)), 0) "
|
||||||
|
"FROM usage"
|
||||||
|
).fetchone()
|
||||||
|
count, total_duration, total_cost = row
|
||||||
|
return UsageStats(
|
||||||
|
count=int(count),
|
||||||
|
total_duration_sec=float(total_duration),
|
||||||
|
total_cost_usd=Decimal(str(total_cost)).quantize(Decimal("0.000001")),
|
||||||
|
)
|
||||||
|
|
||||||
|
def month_stats(self, year: int, month: int, tz: timezone = UTC) -> UsageStats:
|
||||||
|
"""Статистика за месяц.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
year: Год.
|
||||||
|
month: Месяц (1-12).
|
||||||
|
tz: Часовой пояс.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
UsageStats за указанный месяц.
|
||||||
|
"""
|
||||||
|
start = datetime.combine(date(year, month, 1), time.min, tzinfo=tz)
|
||||||
|
if month == 12:
|
||||||
|
end = datetime.combine(date(year + 1, 1, 1), time.min, tzinfo=tz)
|
||||||
|
else:
|
||||||
|
end = datetime.combine(date(year, month + 1, 1), time.min, tzinfo=tz)
|
||||||
|
return self.stats(start, end)
|
||||||
3
src/voice_dictation/infrastructure/__init__.py
Normal file
3
src/voice_dictation/infrastructure/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""Infrastructure — логирование, окружение, single-instance, ошибки."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
64
src/voice_dictation/infrastructure/env_loader.py
Normal file
64
src/voice_dictation/infrastructure/env_loader.py
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
"""Загрузка переменных окружения из .env файлов."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import ConfigError
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class EnvConfig:
|
||||||
|
"""Конфигурация из переменных окружения.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
api_key: OpenAI API ключ (обязательный).
|
||||||
|
admin_api_key: OpenAI Admin API ключ (опциональный, для баланса).
|
||||||
|
"""
|
||||||
|
|
||||||
|
api_key: str
|
||||||
|
admin_api_key: str | None
|
||||||
|
|
||||||
|
|
||||||
|
def load_env() -> EnvConfig:
|
||||||
|
"""Загружает .env файлы и возвращает конфигурацию.
|
||||||
|
|
||||||
|
Ищет .env в текущей рабочей директории, затем в ~/.dictate/.
|
||||||
|
Если файл .env не найден — продолжает с переменными окружения.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
EnvConfig с ключами API.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConfigError: Если OPENAI_API_KEY не задан или пустой.
|
||||||
|
"""
|
||||||
|
# Ищем .env: рядом с exe → cwd → ~/.dictate/
|
||||||
|
import sys
|
||||||
|
exe_dir = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path.cwd()
|
||||||
|
candidates = [
|
||||||
|
exe_dir / ".env",
|
||||||
|
Path.cwd() / ".env",
|
||||||
|
Path.home() / ".dictate" / ".env",
|
||||||
|
]
|
||||||
|
for candidate in candidates:
|
||||||
|
if candidate.exists():
|
||||||
|
load_dotenv(candidate, override=False)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
# .env не найден — используем существующие переменные окружения
|
||||||
|
pass
|
||||||
|
|
||||||
|
api_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
||||||
|
if not api_key:
|
||||||
|
raise ConfigError(
|
||||||
|
"OPENAI_API_KEY не задан. Создайте файл .env на основе .env.example "
|
||||||
|
"и укажите ключ: OPENAI_API_KEY=sk-..."
|
||||||
|
)
|
||||||
|
|
||||||
|
admin_key = os.environ.get("OPENAI_ADMIN_API_KEY", "").strip() or None
|
||||||
|
|
||||||
|
return EnvConfig(api_key=api_key, admin_api_key=admin_key)
|
||||||
56
src/voice_dictation/infrastructure/errors.py
Normal file
56
src/voice_dictation/infrastructure/errors.py
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
"""Иерархия исключений приложения."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
class DictationError(Exception):
|
||||||
|
"""Базовое исключение приложения."""
|
||||||
|
|
||||||
|
|
||||||
|
class RecorderError(DictationError):
|
||||||
|
"""Ошибка записи аудио."""
|
||||||
|
|
||||||
|
|
||||||
|
class SoxNotFoundError(RecorderError):
|
||||||
|
"""sox не найден в системном PATH."""
|
||||||
|
|
||||||
|
|
||||||
|
class TranscriptionError(DictationError):
|
||||||
|
"""Ошибка транскрипции (сеть, парсинг)."""
|
||||||
|
|
||||||
|
|
||||||
|
class WhisperAPIError(TranscriptionError):
|
||||||
|
"""HTTP-ошибка от Whisper API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: Описание ошибки.
|
||||||
|
status_code: HTTP-статус ответа.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, status_code: int | None = None) -> None:
|
||||||
|
super().__init__(message)
|
||||||
|
self.status_code = status_code
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigError(DictationError):
|
||||||
|
"""Ошибка конфигурации."""
|
||||||
|
|
||||||
|
|
||||||
|
class PlatformError(DictationError):
|
||||||
|
"""Ошибка платформы (clipboard, autopaste, hotkeys)."""
|
||||||
|
|
||||||
|
|
||||||
|
class UnsupportedPlatformError(PlatformError):
|
||||||
|
"""Платформа не поддерживается.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
platform: Идентификатор платформы (sys.platform).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, platform: str) -> None:
|
||||||
|
super().__init__(f"Платформа не поддерживается: {platform!r}")
|
||||||
|
self.platform = platform
|
||||||
|
|
||||||
|
|
||||||
|
class BalanceError(DictationError):
|
||||||
|
"""Ошибка при получении баланса OpenAI."""
|
||||||
86
src/voice_dictation/infrastructure/logging_setup.py
Normal file
86
src/voice_dictation/infrastructure/logging_setup.py
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
"""Настройка логирования с ротацией файлов и маскированием ключей."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import logging.handlers
|
||||||
|
import re
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
_LogArgs = tuple[object, ...] | Mapping[str, object] | None
|
||||||
|
|
||||||
|
_LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
|
||||||
|
_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
|
||||||
|
_MAX_BYTES = 5 * 1024 * 1024 # 5 MB
|
||||||
|
_BACKUP_COUNT = 3
|
||||||
|
|
||||||
|
# Маскируем API-ключи в логах
|
||||||
|
_API_KEY_PATTERN = re.compile(r"(sk-(?:admin-)?[A-Za-z0-9]{8})[A-Za-z0-9-]+")
|
||||||
|
_API_KEY_REPLACEMENT = r"\1***"
|
||||||
|
|
||||||
|
|
||||||
|
class _ApiKeyMaskingFilter(logging.Filter):
|
||||||
|
"""Фильтр, маскирующий OpenAI API-ключи в лог-сообщениях."""
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
record.msg = _mask_keys(str(record.msg))
|
||||||
|
record.args = _mask_args(record.args)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _mask_keys(text: str) -> str:
|
||||||
|
"""Маскирует sk-... ключи в строке."""
|
||||||
|
return _API_KEY_PATTERN.sub(_API_KEY_REPLACEMENT, text)
|
||||||
|
|
||||||
|
|
||||||
|
def _mask_args(args: _LogArgs) -> _LogArgs:
|
||||||
|
"""Рекурсивно маскирует ключи в аргументах форматирования."""
|
||||||
|
if args is None:
|
||||||
|
return None
|
||||||
|
if isinstance(args, tuple):
|
||||||
|
return tuple(_mask_keys(str(a)) if isinstance(a, str) else a for a in args)
|
||||||
|
if isinstance(args, Mapping):
|
||||||
|
return {k: (_mask_keys(str(v)) if isinstance(v, str) else v) for k, v in args.items()}
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logging(paths: AppPaths, verbose: bool = False) -> None:
|
||||||
|
"""Настраивает логирование: файл с ротацией + stderr.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
paths: Пути приложения (для log_file).
|
||||||
|
verbose: Если True — уровень DEBUG, иначе INFO.
|
||||||
|
"""
|
||||||
|
level = logging.DEBUG if verbose else logging.INFO
|
||||||
|
|
||||||
|
root_logger = logging.getLogger()
|
||||||
|
root_logger.setLevel(level)
|
||||||
|
|
||||||
|
# Удаляем существующие обработчики чтобы не дублировать
|
||||||
|
root_logger.handlers.clear()
|
||||||
|
|
||||||
|
masking_filter = _ApiKeyMaskingFilter()
|
||||||
|
|
||||||
|
# Файловый обработчик с ротацией
|
||||||
|
file_handler = logging.handlers.RotatingFileHandler(
|
||||||
|
paths.log_file,
|
||||||
|
maxBytes=_MAX_BYTES,
|
||||||
|
backupCount=_BACKUP_COUNT,
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
file_handler.setLevel(level)
|
||||||
|
file_handler.setFormatter(logging.Formatter(_LOG_FORMAT, _DATE_FORMAT))
|
||||||
|
file_handler.addFilter(masking_filter)
|
||||||
|
root_logger.addHandler(file_handler)
|
||||||
|
|
||||||
|
# Консольный обработчик — только WARNING и выше в обычном режиме
|
||||||
|
console_handler = logging.StreamHandler()
|
||||||
|
console_handler.setLevel(logging.DEBUG if verbose else logging.WARNING)
|
||||||
|
console_handler.setFormatter(logging.Formatter(_LOG_FORMAT, _DATE_FORMAT))
|
||||||
|
console_handler.addFilter(masking_filter)
|
||||||
|
root_logger.addHandler(console_handler)
|
||||||
|
|
||||||
|
level_name = logging.getLevelName(level)
|
||||||
|
logging.getLogger(__name__).debug("Логирование настроено, level=%s", level_name)
|
||||||
156
src/voice_dictation/infrastructure/single_instance.py
Normal file
156
src/voice_dictation/infrastructure/single_instance.py
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
"""Single-instance lock через PID-файл."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import atexit
|
||||||
|
import contextlib
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from types import TracebackType
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class SingleInstanceLock:
|
||||||
|
"""Контекст-менеджер для обеспечения единственного экземпляра приложения.
|
||||||
|
|
||||||
|
Использует atomic PID-файл (os.O_CREAT | os.O_EXCL) на Unix
|
||||||
|
и msvcrt.locking на Windows.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
pid_file: Путь к PID-файлу.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, pid_file: Path) -> None:
|
||||||
|
self._pid_file = pid_file
|
||||||
|
self._fd: int | None = None
|
||||||
|
|
||||||
|
def acquire(self) -> SingleInstanceLock:
|
||||||
|
"""Захватывает блокировку.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
self для использования как контекст-менеджер.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SystemExit: Если другой экземпляр уже запущен.
|
||||||
|
"""
|
||||||
|
if sys.platform == "win32":
|
||||||
|
self._acquire_windows()
|
||||||
|
else:
|
||||||
|
self._acquire_unix()
|
||||||
|
atexit.register(self._cleanup)
|
||||||
|
return self
|
||||||
|
|
||||||
|
def _acquire_unix(self) -> None:
|
||||||
|
"""Atomic PID-файл на Unix через O_CREAT | O_EXCL."""
|
||||||
|
stale = self._is_stale_lock()
|
||||||
|
if stale and self._pid_file.exists():
|
||||||
|
self._pid_file.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
fd = os.open(
|
||||||
|
str(self._pid_file),
|
||||||
|
os.O_CREAT | os.O_EXCL | os.O_WRONLY,
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
except FileExistsError:
|
||||||
|
existing_pid = self._read_pid()
|
||||||
|
logger.error(
|
||||||
|
"Приложение уже запущено (PID %s). Завершение.",
|
||||||
|
existing_pid or "неизвестен",
|
||||||
|
)
|
||||||
|
self._notify_already_running(existing_pid)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
with os.fdopen(fd, "w") as fh:
|
||||||
|
fh.write(str(os.getpid()))
|
||||||
|
self._fd = None # файловый дескриптор закрыт через fdopen
|
||||||
|
|
||||||
|
def _acquire_windows(self) -> None:
|
||||||
|
"""PID-файл на Windows через обычное создание файла."""
|
||||||
|
stale = self._is_stale_lock()
|
||||||
|
if stale and self._pid_file.exists():
|
||||||
|
self._pid_file.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
if self._pid_file.exists():
|
||||||
|
existing_pid = self._read_pid()
|
||||||
|
logger.error(
|
||||||
|
"Приложение уже запущено (PID %s). Завершение.",
|
||||||
|
existing_pid or "неизвестен",
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
self._pid_file.write_text(str(os.getpid()), encoding="utf-8")
|
||||||
|
|
||||||
|
def _is_stale_lock(self) -> bool:
|
||||||
|
"""Проверяет, является ли существующий PID-файл устаревшим.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True если PID-файл существует, но процесс уже не работает.
|
||||||
|
"""
|
||||||
|
if not self._pid_file.exists():
|
||||||
|
return False
|
||||||
|
pid = self._read_pid()
|
||||||
|
if pid is None:
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
import psutil
|
||||||
|
|
||||||
|
return not psutil.pid_exists(pid)
|
||||||
|
except ImportError:
|
||||||
|
# psutil недоступен — не можем проверить, не удаляем
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _read_pid(self) -> int | None:
|
||||||
|
"""Читает PID из файла.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PID как int или None если файл нечитаем.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
text = self._pid_file.read_text(encoding="utf-8").strip()
|
||||||
|
return int(text) if text.isdigit() else None
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _notify_already_running(self, existing_pid: int | None) -> None:
|
||||||
|
"""Показывает системное уведомление macOS о том, что приложение уже запущено."""
|
||||||
|
if sys.platform != "darwin":
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
osascript = shutil.which("osascript") or "/usr/bin/osascript"
|
||||||
|
pid_str = f" (PID {existing_pid})" if existing_pid else ""
|
||||||
|
msg = f"Voice Dictation уже запущен{pid_str}. Иконка в строке меню."
|
||||||
|
subprocess.Popen(
|
||||||
|
[osascript, "-e", f'display notification "{msg}" with title "Voice Dictation"'],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
start_new_session=True,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _cleanup(self) -> None:
|
||||||
|
"""Удаляет PID-файл при завершении."""
|
||||||
|
with contextlib.suppress(OSError):
|
||||||
|
self._pid_file.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
def release(self) -> None:
|
||||||
|
"""Явно освобождает блокировку."""
|
||||||
|
self._cleanup()
|
||||||
|
|
||||||
|
def __enter__(self) -> SingleInstanceLock:
|
||||||
|
return self.acquire()
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc_val: BaseException | None,
|
||||||
|
exc_tb: TracebackType | None,
|
||||||
|
) -> None:
|
||||||
|
self.release()
|
||||||
3
src/voice_dictation/platform/__init__.py
Normal file
3
src/voice_dictation/platform/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""Platform abstraction layer — кроссплатформенные реализации."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
101
src/voice_dictation/platform/factory.py
Normal file
101
src/voice_dictation/platform/factory.py
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
"""Фабрика платформенных компонентов."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import UnsupportedPlatformError
|
||||||
|
from voice_dictation.platform.protocols import (
|
||||||
|
AutoPaste,
|
||||||
|
Clipboard,
|
||||||
|
HotkeyListener,
|
||||||
|
Notifier,
|
||||||
|
SoundPlayer,
|
||||||
|
SystemSoundsScanner,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PlatformBundle:
|
||||||
|
"""Набор платформенных компонентов.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sound_player: Воспроизведение звуков.
|
||||||
|
notifier: Системные уведомления.
|
||||||
|
clipboard: Буфер обмена.
|
||||||
|
auto_paste: Автовставка.
|
||||||
|
hotkey_listener: Слушатель хоткеев.
|
||||||
|
system_sounds_scanner: Сканер системных звуков.
|
||||||
|
"""
|
||||||
|
|
||||||
|
sound_player: SoundPlayer
|
||||||
|
notifier: Notifier
|
||||||
|
clipboard: Clipboard
|
||||||
|
auto_paste: AutoPaste
|
||||||
|
hotkey_listener: HotkeyListener
|
||||||
|
system_sounds_scanner: SystemSoundsScanner
|
||||||
|
|
||||||
|
|
||||||
|
def build_platform() -> PlatformBundle:
|
||||||
|
"""Создаёт PlatformBundle для текущей операционной системы.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PlatformBundle с реализациями для текущей платформы.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
UnsupportedPlatformError: Если платформа не поддерживается.
|
||||||
|
"""
|
||||||
|
match sys.platform:
|
||||||
|
case "darwin":
|
||||||
|
return _build_macos()
|
||||||
|
case "win32":
|
||||||
|
return _build_windows()
|
||||||
|
case _:
|
||||||
|
raise UnsupportedPlatformError(sys.platform)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_macos() -> PlatformBundle:
|
||||||
|
"""Собирает PlatformBundle для macOS.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PlatformBundle с macOS-реализациями.
|
||||||
|
"""
|
||||||
|
from voice_dictation.platform.macos.autopaste import MacAutoPaste
|
||||||
|
from voice_dictation.platform.macos.clipboard import MacClipboard
|
||||||
|
from voice_dictation.platform.macos.hotkey_listener import MacHotkeyListener
|
||||||
|
from voice_dictation.platform.macos.notifier import MacNotifier
|
||||||
|
from voice_dictation.platform.macos.sound_player import MacSoundPlayer
|
||||||
|
from voice_dictation.platform.macos.system_sounds_scanner import MacSystemSoundsScanner
|
||||||
|
|
||||||
|
return PlatformBundle(
|
||||||
|
sound_player=MacSoundPlayer(),
|
||||||
|
notifier=MacNotifier(),
|
||||||
|
clipboard=MacClipboard(),
|
||||||
|
auto_paste=MacAutoPaste(),
|
||||||
|
hotkey_listener=MacHotkeyListener(),
|
||||||
|
system_sounds_scanner=MacSystemSoundsScanner(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_windows() -> PlatformBundle:
|
||||||
|
"""Собирает PlatformBundle для Windows.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PlatformBundle с Windows-реализациями.
|
||||||
|
"""
|
||||||
|
from voice_dictation.platform.windows.autopaste import WinAutoPaste
|
||||||
|
from voice_dictation.platform.windows.clipboard import WinClipboard
|
||||||
|
from voice_dictation.platform.windows.hotkey_listener import WinHotkeyListener
|
||||||
|
from voice_dictation.platform.windows.notifier import WinNotifier
|
||||||
|
from voice_dictation.platform.windows.sound_player import WinSoundPlayer
|
||||||
|
from voice_dictation.platform.windows.system_sounds_scanner import WinSystemSoundsScanner
|
||||||
|
|
||||||
|
return PlatformBundle(
|
||||||
|
sound_player=WinSoundPlayer(),
|
||||||
|
notifier=WinNotifier(),
|
||||||
|
clipboard=WinClipboard(),
|
||||||
|
auto_paste=WinAutoPaste(),
|
||||||
|
hotkey_listener=WinHotkeyListener(),
|
||||||
|
system_sounds_scanner=WinSystemSoundsScanner(),
|
||||||
|
)
|
||||||
3
src/voice_dictation/platform/macos/__init__.py
Normal file
3
src/voice_dictation/platform/macos/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""macOS-реализации платформенных протоколов."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
63
src/voice_dictation/platform/macos/autopaste.py
Normal file
63
src/voice_dictation/platform/macos/autopaste.py
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
"""Автовставка на macOS через Quartz CGEvent (Cmd+V)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_KEY_V = 0x09
|
||||||
|
_KEY_CMD = 0x37 # Left Command
|
||||||
|
|
||||||
|
|
||||||
|
class MacAutoPaste:
|
||||||
|
"""Имитирует Cmd+V в активном окне через Quartz CGEvent.
|
||||||
|
|
||||||
|
Раньше использовался pynput, но в bundle он крашится при вызове Carbon TSM
|
||||||
|
в фоновом потоке (dispatch_assert_queue trap на macOS 26+). Quartz CGEvent
|
||||||
|
работает из любого потока.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, paste_delay_ms: int = 0) -> None:
|
||||||
|
self._paste_delay_ms = paste_delay_ms
|
||||||
|
|
||||||
|
def paste(self) -> None:
|
||||||
|
"""Нажимает Cmd+V в активном окне.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если Quartz недоступен (нет PyObjC).
|
||||||
|
"""
|
||||||
|
if self._paste_delay_ms > 0:
|
||||||
|
time.sleep(self._paste_delay_ms / 1000)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from Quartz import (
|
||||||
|
CGEventCreateKeyboardEvent,
|
||||||
|
CGEventPost,
|
||||||
|
CGEventSetFlags,
|
||||||
|
kCGEventFlagMaskCommand,
|
||||||
|
kCGHIDEventTap,
|
||||||
|
)
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("Quartz недоступен (нет PyObjC)") from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
v_down = CGEventCreateKeyboardEvent(None, _KEY_V, True)
|
||||||
|
v_up = CGEventCreateKeyboardEvent(None, _KEY_V, False)
|
||||||
|
CGEventSetFlags(v_down, kCGEventFlagMaskCommand)
|
||||||
|
CGEventSetFlags(v_up, kCGEventFlagMaskCommand)
|
||||||
|
CGEventPost(kCGHIDEventTap, v_down)
|
||||||
|
CGEventPost(kCGHIDEventTap, v_up)
|
||||||
|
except Exception as exc:
|
||||||
|
raise PlatformError(
|
||||||
|
f"Не удалось выполнить Cmd+V: {exc}. "
|
||||||
|
"Проверьте разрешение Accessibility в Системных настройках."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
logger.debug("MacAutoPaste: Cmd+V выполнен")
|
||||||
54
src/voice_dictation/platform/macos/clipboard.py
Normal file
54
src/voice_dictation/platform/macos/clipboard.py
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
"""Буфер обмена macOS через нативный NSPasteboard.
|
||||||
|
|
||||||
|
Раньше использовался subprocess pbcopy/pbpaste, но в bundle без локали
|
||||||
|
pbcopy интерпретирует входные байты как MacRoman и корёжит кириллицу.
|
||||||
|
NSPasteboard работает с NSString напрямую — никаких кодировок.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class MacClipboard:
|
||||||
|
"""Буфер обмена macOS через NSPasteboard."""
|
||||||
|
|
||||||
|
def copy(self, text: str) -> None:
|
||||||
|
"""Копирует текст в общий буфер обмена.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Текст для копирования.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если AppKit недоступен.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from AppKit import NSPasteboard, NSPasteboardTypeString
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("AppKit недоступен (нет PyObjC)") from exc
|
||||||
|
|
||||||
|
pb = NSPasteboard.generalPasteboard()
|
||||||
|
pb.clearContents()
|
||||||
|
pb.setString_forType_(text, NSPasteboardTypeString)
|
||||||
|
|
||||||
|
def paste(self) -> str:
|
||||||
|
"""Возвращает содержимое буфера обмена.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Текст из буфера (пустая строка если в буфере не текст).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если AppKit недоступен.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from AppKit import NSPasteboard, NSPasteboardTypeString
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("AppKit недоступен (нет PyObjC)") from exc
|
||||||
|
|
||||||
|
pb = NSPasteboard.generalPasteboard()
|
||||||
|
value = pb.stringForType_(NSPasteboardTypeString)
|
||||||
|
return str(value) if value is not None else ""
|
||||||
260
src/voice_dictation/platform/macos/hotkey_listener.py
Normal file
260
src/voice_dictation/platform/macos/hotkey_listener.py
Normal file
|
|
@ -0,0 +1,260 @@
|
||||||
|
"""Глобальный слушатель хоткеев на macOS через NSEvent global monitor.
|
||||||
|
|
||||||
|
В bundle pynput-based listener крашится при вызове Carbon TSM из фонового
|
||||||
|
потока (dispatch_assert_queue trap на macOS 26+). NSEvent работает корректно,
|
||||||
|
требует только Accessibility права.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Карта имён клавиш в virtual key codes macOS
|
||||||
|
_KEY_CODES: dict[str, int] = {
|
||||||
|
"a": 0x00, "s": 0x01, "d": 0x02, "f": 0x03, "h": 0x04, "g": 0x05,
|
||||||
|
"z": 0x06, "x": 0x07, "c": 0x08, "v": 0x09, "b": 0x0B, "q": 0x0C,
|
||||||
|
"w": 0x0D, "e": 0x0E, "r": 0x0F, "y": 0x10, "t": 0x11,
|
||||||
|
"1": 0x12, "2": 0x13, "3": 0x14, "4": 0x15, "6": 0x16, "5": 0x17,
|
||||||
|
"9": 0x19, "7": 0x1A, "8": 0x1C, "0": 0x1D,
|
||||||
|
"o": 0x1F, "u": 0x20, "i": 0x22, "p": 0x23,
|
||||||
|
"l": 0x25, "j": 0x26, "k": 0x28, "n": 0x2D, "m": 0x2E,
|
||||||
|
"space": 0x31, "tab": 0x30, "enter": 0x24, "return": 0x24,
|
||||||
|
"escape": 0x35, "esc": 0x35, "delete": 0x33, "backspace": 0x33,
|
||||||
|
"f1": 0x7A, "f2": 0x78, "f3": 0x63, "f4": 0x76, "f5": 0x60,
|
||||||
|
"f6": 0x61, "f7": 0x62, "f8": 0x64, "f9": 0x65, "f10": 0x6D,
|
||||||
|
"f11": 0x67, "f12": 0x6F,
|
||||||
|
"left": 0x7B, "right": 0x7C, "down": 0x7D, "up": 0x7E,
|
||||||
|
}
|
||||||
|
|
||||||
|
_MODIFIER_TOKENS = {"cmd", "command", "ctrl", "control", "alt", "option", "shift", "super"}
|
||||||
|
|
||||||
|
# Печатные клавиши, после которых надо стереть символ из активного поля
|
||||||
|
_PRINTABLE_MAIN_KEYS = {"space", "tab", "enter", "return"}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_hotkey(hotkey: str) -> tuple[set[str], str]:
|
||||||
|
"""Разбирает строку хоткея в (модификаторы, главная клавиша).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: "cmd+space", "cmd+alt+d".
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(set модификаторов в каноническом виде, имя главной клавиши).
|
||||||
|
"""
|
||||||
|
tokens = [t.strip() for t in re.split(r"[+\-]", hotkey.lower().strip()) if t.strip()]
|
||||||
|
mods: set[str] = set()
|
||||||
|
main: str | None = None
|
||||||
|
for token in tokens:
|
||||||
|
if token in {"cmd", "command", "super"}:
|
||||||
|
mods.add("cmd")
|
||||||
|
elif token in {"ctrl", "control"}:
|
||||||
|
mods.add("ctrl")
|
||||||
|
elif token in {"alt", "option"}:
|
||||||
|
mods.add("alt")
|
||||||
|
elif token == "shift":
|
||||||
|
mods.add("shift")
|
||||||
|
else:
|
||||||
|
main = token
|
||||||
|
if main is None:
|
||||||
|
raise PlatformError(f"В хоткее '{hotkey}' нет основной клавиши")
|
||||||
|
return mods, main
|
||||||
|
|
||||||
|
|
||||||
|
def _modifier_mask(mods: set[str]) -> int:
|
||||||
|
"""Конвертирует набор модификаторов в NSEventModifierFlags маску."""
|
||||||
|
from AppKit import (
|
||||||
|
NSEventModifierFlagCommand,
|
||||||
|
NSEventModifierFlagControl,
|
||||||
|
NSEventModifierFlagOption,
|
||||||
|
NSEventModifierFlagShift,
|
||||||
|
)
|
||||||
|
|
||||||
|
mask = 0
|
||||||
|
if "cmd" in mods:
|
||||||
|
mask |= int(NSEventModifierFlagCommand)
|
||||||
|
if "ctrl" in mods:
|
||||||
|
mask |= int(NSEventModifierFlagControl)
|
||||||
|
if "alt" in mods:
|
||||||
|
mask |= int(NSEventModifierFlagOption)
|
||||||
|
if "shift" in mods:
|
||||||
|
mask |= int(NSEventModifierFlagShift)
|
||||||
|
return mask
|
||||||
|
|
||||||
|
|
||||||
|
def _all_modifier_flags() -> int:
|
||||||
|
"""Маска всех 4 модификаторов — для отбрасывания caps lock и прочего."""
|
||||||
|
from AppKit import (
|
||||||
|
NSEventModifierFlagCommand,
|
||||||
|
NSEventModifierFlagControl,
|
||||||
|
NSEventModifierFlagOption,
|
||||||
|
NSEventModifierFlagShift,
|
||||||
|
)
|
||||||
|
|
||||||
|
return int(
|
||||||
|
NSEventModifierFlagCommand
|
||||||
|
| NSEventModifierFlagControl
|
||||||
|
| NSEventModifierFlagOption
|
||||||
|
| NSEventModifierFlagShift
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MacHotkeyListener:
|
||||||
|
"""Глобальный слушатель хоткеев через NSEvent.
|
||||||
|
|
||||||
|
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_ ловит события из
|
||||||
|
других приложений. Требует Accessibility права. Регистрируется в любом
|
||||||
|
потоке, callback приходит в том же потоке, где работает NSRunLoop.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._hotkeys: list[tuple[set[str], str, int, int, Callable[[], None]]] = []
|
||||||
|
self._monitor: Any = None
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
|
||||||
|
def register(self, hotkey: str, callback: Callable[[], None]) -> bool:
|
||||||
|
"""Регистрирует хоткей.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Строка хоткея, например "cmd+space".
|
||||||
|
callback: Функция, вызываемая при нажатии.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True если хоткей разобран успешно.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
mods, main = _parse_hotkey(hotkey)
|
||||||
|
except PlatformError as exc:
|
||||||
|
logger.warning("Не удалось разобрать '%s': %s", hotkey, exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
if main not in _KEY_CODES:
|
||||||
|
logger.warning("Неизвестная клавиша '%s' в хоткее '%s'", main, hotkey)
|
||||||
|
return False
|
||||||
|
|
||||||
|
wrapped = self._wrap_with_backspace(callback, main)
|
||||||
|
mods_mask = _modifier_mask(mods)
|
||||||
|
keycode = _KEY_CODES[main]
|
||||||
|
|
||||||
|
for i, (m, k, *_) in enumerate(self._hotkeys):
|
||||||
|
if m == mods and k == main:
|
||||||
|
self._hotkeys[i] = (mods, main, mods_mask, keycode, wrapped)
|
||||||
|
return True
|
||||||
|
|
||||||
|
self._hotkeys.append((mods, main, mods_mask, keycode, wrapped))
|
||||||
|
logger.debug("Хоткей зарегистрирован: %s -> mods=%s, key=%s", hotkey, sorted(mods), main)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _wrap_with_backspace(
|
||||||
|
self, callback: Callable[[], None], main_key: str
|
||||||
|
) -> Callable[[], None]:
|
||||||
|
"""Если хоткей с печатной клавишей — после нажатия шлём Backspace.
|
||||||
|
|
||||||
|
macOS успевает вставить пробел/таб в активное поле до перехвата хоткея
|
||||||
|
через NSEvent global monitor (он не блокирует событие, только наблюдает).
|
||||||
|
Стираем лишний символ, чтобы поле осталось чистым.
|
||||||
|
"""
|
||||||
|
if main_key not in _PRINTABLE_MAIN_KEYS:
|
||||||
|
return callback
|
||||||
|
|
||||||
|
def _runner() -> None:
|
||||||
|
try:
|
||||||
|
# Маленькая задержка, чтобы система успела вставить символ
|
||||||
|
time.sleep(0.02)
|
||||||
|
_send_backspace_via_quartz()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Не удалось послать Backspace: %s", exc)
|
||||||
|
|
||||||
|
def _wrapped() -> None:
|
||||||
|
threading.Thread(target=_runner, name="bs-eraser", daemon=True).start()
|
||||||
|
callback()
|
||||||
|
|
||||||
|
return _wrapped
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Регистрирует NSEvent monitor и блокирует поток до stop().
|
||||||
|
|
||||||
|
В этом методе крутится NSRunLoop текущего потока. Если callback нужен
|
||||||
|
в главном потоке (например, для AppKit), вызывайте start() из главного.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если нет хоткеев или AppKit недоступен.
|
||||||
|
"""
|
||||||
|
if not self._hotkeys:
|
||||||
|
raise PlatformError("Нет зарегистрированных хоткеев")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from AppKit import NSEvent, NSEventMaskKeyDown
|
||||||
|
from Foundation import NSDate, NSDefaultRunLoopMode, NSRunLoop
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("AppKit/Foundation недоступны (PyObjC)") from exc
|
||||||
|
|
||||||
|
all_mods = _all_modifier_flags()
|
||||||
|
|
||||||
|
registered = [(sorted(mods), main) for (mods, main, *_) in self._hotkeys]
|
||||||
|
logger.info("Запуск слушателя хоткеев: %s", registered)
|
||||||
|
|
||||||
|
def _handler(event: Any) -> None:
|
||||||
|
try:
|
||||||
|
event_keycode = int(event.keyCode())
|
||||||
|
event_mods = int(event.modifierFlags()) & all_mods
|
||||||
|
for _mods_set, _main, target_mods, target_key, callback in self._hotkeys:
|
||||||
|
if event_keycode == target_key and event_mods == target_mods:
|
||||||
|
try:
|
||||||
|
callback()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Ошибка в callback хоткея: %s", exc)
|
||||||
|
break
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Ошибка в NSEvent handler: %s", exc)
|
||||||
|
|
||||||
|
self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
|
||||||
|
NSEventMaskKeyDown, _handler
|
||||||
|
)
|
||||||
|
|
||||||
|
if self._monitor is None:
|
||||||
|
raise PlatformError(
|
||||||
|
"Не удалось создать NSEvent global monitor — нужны права Accessibility"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Блокируем поток, пока не вызовут stop()
|
||||||
|
run_loop = NSRunLoop.currentRunLoop()
|
||||||
|
while not self._stop_event.is_set():
|
||||||
|
run_loop.runMode_beforeDate_(
|
||||||
|
NSDefaultRunLoopMode, NSDate.dateWithTimeIntervalSinceNow_(0.5)
|
||||||
|
)
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Останавливает слушатель."""
|
||||||
|
self._stop_event.set()
|
||||||
|
if self._monitor is not None:
|
||||||
|
try:
|
||||||
|
from AppKit import NSEvent
|
||||||
|
|
||||||
|
NSEvent.removeMonitor_(self._monitor)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Ошибка снятия NSEvent monitor: %s", exc)
|
||||||
|
self._monitor = None
|
||||||
|
|
||||||
|
|
||||||
|
def _send_backspace_via_quartz() -> None:
|
||||||
|
"""Эмулирует нажатие Backspace через Quartz CGEvent (без pynput)."""
|
||||||
|
from Quartz import (
|
||||||
|
CGEventCreateKeyboardEvent,
|
||||||
|
CGEventPost,
|
||||||
|
kCGHIDEventTap,
|
||||||
|
)
|
||||||
|
|
||||||
|
keycode = 0x33 # Backspace virtual key code
|
||||||
|
down = CGEventCreateKeyboardEvent(None, keycode, True)
|
||||||
|
up = CGEventCreateKeyboardEvent(None, keycode, False)
|
||||||
|
CGEventPost(kCGHIDEventTap, down)
|
||||||
|
CGEventPost(kCGHIDEventTap, up)
|
||||||
52
src/voice_dictation/platform/macos/notifier.py
Normal file
52
src/voice_dictation/platform/macos/notifier.py
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
"""Нативные уведомления macOS через osascript."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class MacNotifier:
|
||||||
|
"""Показывает системные уведомления через `osascript display notification`.
|
||||||
|
|
||||||
|
На macOS при первом показе ОС попросит пользователя разрешить уведомления
|
||||||
|
для Terminal / процесса-родителя.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._osascript = shutil.which("osascript") or "/usr/bin/osascript"
|
||||||
|
|
||||||
|
def show(self, title: str, message: str) -> None:
|
||||||
|
"""Показывает уведомление.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
title: Заголовок.
|
||||||
|
message: Текст.
|
||||||
|
"""
|
||||||
|
safe_title = _escape(title)
|
||||||
|
safe_message = _escape(message)
|
||||||
|
script = f'display notification "{safe_message}" with title "{safe_title}"'
|
||||||
|
try:
|
||||||
|
subprocess.Popen(
|
||||||
|
[self._osascript, "-e", script],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
start_new_session=True,
|
||||||
|
)
|
||||||
|
except (FileNotFoundError, OSError) as exc:
|
||||||
|
logger.warning("osascript не удалось запустить: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def _escape(value: str) -> str:
|
||||||
|
"""Экранирует строку для AppleScript.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value: Исходная строка.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Строка, безопасная для вставки в двойные кавычки AppleScript.
|
||||||
|
"""
|
||||||
|
return value.replace("\\", "\\\\").replace('"', '\\"')
|
||||||
78
src/voice_dictation/platform/macos/sound_player.py
Normal file
78
src/voice_dictation/platform/macos/sound_player.py
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
"""Воспроизведение звуков на macOS через afplay."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.enums import SoundKind
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_DEFAULT_SYSTEM_SOUNDS_DIR = Path("/System/Library/Sounds")
|
||||||
|
_DEFAULT_SOUNDS: dict[SoundKind, str] = {
|
||||||
|
SoundKind.START: "Tink.aiff",
|
||||||
|
SoundKind.STOP: "Pop.aiff",
|
||||||
|
SoundKind.ERROR: "Basso.aiff",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class MacSoundPlayer:
|
||||||
|
"""Проигрывает звуки через macOS `afplay`.
|
||||||
|
|
||||||
|
Выбор файла: пользовательский путь из Config → дефолтный системный звук.
|
||||||
|
Если `sounds_enabled=False` — ничего не проигрывает.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._afplay = shutil.which("afplay") or "/usr/bin/afplay"
|
||||||
|
|
||||||
|
def play(self, kind: SoundKind, config: Config) -> None:
|
||||||
|
"""Воспроизводит звук для события.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kind: Тип события (START/STOP/ERROR).
|
||||||
|
config: Конфигурация.
|
||||||
|
"""
|
||||||
|
if not config.sounds_enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
path = self._resolve_path(kind, config)
|
||||||
|
if path is None or not path.exists():
|
||||||
|
logger.debug("MacSoundPlayer: звук %s не найден, пропуск", kind)
|
||||||
|
return
|
||||||
|
|
||||||
|
volume = max(0.0, min(1.0, config.volume))
|
||||||
|
try:
|
||||||
|
subprocess.Popen(
|
||||||
|
[self._afplay, "-v", f"{volume:.2f}", str(path)],
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
start_new_session=True,
|
||||||
|
)
|
||||||
|
except (FileNotFoundError, OSError) as exc:
|
||||||
|
logger.warning("afplay не удалось запустить: %s", exc)
|
||||||
|
|
||||||
|
def _resolve_path(self, kind: SoundKind, config: Config) -> Path | None:
|
||||||
|
"""Выбирает файл звука для события.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kind: Тип события.
|
||||||
|
config: Конфигурация.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Путь к файлу или None.
|
||||||
|
"""
|
||||||
|
custom_attr = {
|
||||||
|
SoundKind.START: config.start_sound_path,
|
||||||
|
SoundKind.STOP: config.stop_sound_path,
|
||||||
|
SoundKind.ERROR: config.error_sound_path,
|
||||||
|
}[kind]
|
||||||
|
|
||||||
|
if custom_attr is not None:
|
||||||
|
return custom_attr
|
||||||
|
|
||||||
|
return _DEFAULT_SYSTEM_SOUNDS_DIR / _DEFAULT_SOUNDS[kind]
|
||||||
32
src/voice_dictation/platform/macos/system_sounds_scanner.py
Normal file
32
src/voice_dictation/platform/macos/system_sounds_scanner.py
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
"""Сканирование системных звуков macOS."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.platform.system_sound import SystemSound
|
||||||
|
|
||||||
|
_SYSTEM_SOUNDS_DIRS = (
|
||||||
|
Path("/System/Library/Sounds"),
|
||||||
|
Path("/Library/Sounds"),
|
||||||
|
Path.home() / "Library/Sounds",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MacSystemSoundsScanner:
|
||||||
|
"""Ищет .aiff файлы в стандартных каталогах macOS."""
|
||||||
|
|
||||||
|
def scan(self) -> list[SystemSound]:
|
||||||
|
"""Возвращает системные звуки macOS.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список SystemSound, отсортированный по имени.
|
||||||
|
"""
|
||||||
|
sounds: dict[str, Path] = {}
|
||||||
|
for directory in _SYSTEM_SOUNDS_DIRS:
|
||||||
|
if not directory.exists():
|
||||||
|
continue
|
||||||
|
for path in sorted(directory.glob("*.aiff")):
|
||||||
|
name = path.stem
|
||||||
|
sounds.setdefault(name, path)
|
||||||
|
return [SystemSound(name=name, path=path) for name, path in sorted(sounds.items())]
|
||||||
83
src/voice_dictation/platform/noop.py
Normal file
83
src/voice_dictation/platform/noop.py
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
"""No-op реализации платформенных протоколов для этапа 1."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.enums import SoundKind
|
||||||
|
from voice_dictation.platform.system_sound import SystemSound
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class NoopSoundPlayer:
|
||||||
|
"""Заглушка звукового плеера — ничего не воспроизводит."""
|
||||||
|
|
||||||
|
def play(self, kind: SoundKind, config: Config) -> None:
|
||||||
|
"""Ничего не делает.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kind: Тип события.
|
||||||
|
config: Конфигурация.
|
||||||
|
"""
|
||||||
|
logger.debug("NoopSoundPlayer.play(%s)", kind)
|
||||||
|
|
||||||
|
|
||||||
|
class NoopNotifier:
|
||||||
|
"""Заглушка уведомлений — пишет в лог."""
|
||||||
|
|
||||||
|
def show(self, title: str, message: str) -> None:
|
||||||
|
"""Логирует уведомление вместо показа.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
title: Заголовок уведомления.
|
||||||
|
message: Текст уведомления.
|
||||||
|
"""
|
||||||
|
logger.info("Уведомление: %s — %s", title, message)
|
||||||
|
|
||||||
|
|
||||||
|
class NoopSystemSoundsScanner:
|
||||||
|
"""Заглушка сканера системных звуков."""
|
||||||
|
|
||||||
|
def scan(self) -> list[SystemSound]:
|
||||||
|
"""Возвращает пустой список.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Пустой список системных звуков.
|
||||||
|
"""
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
class NoopHotkeyListener:
|
||||||
|
"""Заглушка слушателя хоткеев (только для тестов)."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._callback: Callable[[], None] | None = None
|
||||||
|
self._hotkey: str = ""
|
||||||
|
|
||||||
|
def register(self, hotkey: str, callback: Callable[[], None]) -> bool:
|
||||||
|
"""Регистрирует хоткей.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Строка хоткея.
|
||||||
|
callback: Колбэк.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True.
|
||||||
|
"""
|
||||||
|
self._hotkey = hotkey
|
||||||
|
self._callback = callback
|
||||||
|
return True
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Ничего не делает."""
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Ничего не делает."""
|
||||||
|
|
||||||
|
def trigger(self) -> None:
|
||||||
|
"""Вызывает зарегистрированный колбэк (для тестов)."""
|
||||||
|
if self._callback is not None:
|
||||||
|
self._callback()
|
||||||
129
src/voice_dictation/platform/protocols.py
Normal file
129
src/voice_dictation/platform/protocols.py
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
"""Protocol-интерфейсы для кроссплатформенных компонентов."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Protocol, runtime_checkable
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.enums import SoundKind
|
||||||
|
from voice_dictation.core.models import RecordingResult
|
||||||
|
from voice_dictation.platform.system_sound import SystemSound
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class AudioRecorder(Protocol):
|
||||||
|
"""Запись аудио с микрофона."""
|
||||||
|
|
||||||
|
def start(self, output_path: Path) -> None:
|
||||||
|
"""Начинает запись в указанный файл.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
output_path: Путь для сохранения WAV.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def stop(self) -> RecordingResult:
|
||||||
|
"""Останавливает запись.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
RecordingResult с путём и длительностью.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class SoundPlayer(Protocol):
|
||||||
|
"""Воспроизведение звуковых событий."""
|
||||||
|
|
||||||
|
def play(self, kind: SoundKind, config: Config) -> None:
|
||||||
|
"""Воспроизводит звук для события.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kind: Тип события.
|
||||||
|
config: Конфигурация со звуками и громкостью.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class Notifier(Protocol):
|
||||||
|
"""Системные уведомления."""
|
||||||
|
|
||||||
|
def show(self, title: str, message: str) -> None:
|
||||||
|
"""Показывает уведомление.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
title: Заголовок.
|
||||||
|
message: Текст уведомления.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class Clipboard(Protocol):
|
||||||
|
"""Буфер обмена."""
|
||||||
|
|
||||||
|
def copy(self, text: str) -> None:
|
||||||
|
"""Копирует текст в буфер обмена.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Текст для копирования.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def paste(self) -> str:
|
||||||
|
"""Возвращает текущее содержимое буфера обмена.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Текст из буфера.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class AutoPaste(Protocol):
|
||||||
|
"""Автоматическая вставка из буфера обмена."""
|
||||||
|
|
||||||
|
def paste(self) -> None:
|
||||||
|
"""Имитирует нажатие Cmd+V / Ctrl+V в активном окне."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class HotkeyListener(Protocol):
|
||||||
|
"""Слушатель глобальных горячих клавиш."""
|
||||||
|
|
||||||
|
def register(self, hotkey: str, callback: Callable[[], None]) -> bool:
|
||||||
|
"""Регистрирует хоткей с колбэком.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Строка хоткея, например "cmd+alt+d".
|
||||||
|
callback: Функция, вызываемая при нажатии.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True если хоткей зарегистрирован успешно.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Запускает прослушивание (блокирующий вызов)."""
|
||||||
|
...
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Останавливает прослушивание."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class SystemSoundsScanner(Protocol):
|
||||||
|
"""Сканирование системных звуков ОС."""
|
||||||
|
|
||||||
|
def scan(self) -> list[SystemSound]:
|
||||||
|
"""Возвращает список доступных системных звуков.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список SystemSound.
|
||||||
|
"""
|
||||||
|
...
|
||||||
19
src/voice_dictation/platform/system_sound.py
Normal file
19
src/voice_dictation/platform/system_sound.py
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
"""Системный звук — путь и отображаемое имя."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SystemSound:
|
||||||
|
"""Системный звуковой файл.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: Отображаемое имя.
|
||||||
|
path: Путь к файлу.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
path: Path
|
||||||
3
src/voice_dictation/platform/windows/__init__.py
Normal file
3
src/voice_dictation/platform/windows/__init__.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""Windows-реализации платформенных протоколов."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
52
src/voice_dictation/platform/windows/autopaste.py
Normal file
52
src/voice_dictation/platform/windows/autopaste.py
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
"""Автовставка на Windows через Win32 keybd_event (Ctrl+V)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
VK_CONTROL = 0x11
|
||||||
|
VK_V = 0x56
|
||||||
|
KEYEVENTF_KEYUP = 0x0002
|
||||||
|
|
||||||
|
|
||||||
|
class WinAutoPaste:
|
||||||
|
"""Имитирует Ctrl+V через Win32 keybd_event.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
paste_delay_ms: Дополнительная задержка перед вставкой (мс).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, paste_delay_ms: int = 0) -> None:
|
||||||
|
self._paste_delay_ms = paste_delay_ms
|
||||||
|
|
||||||
|
def paste(self) -> None:
|
||||||
|
"""Нажимает Ctrl+V в активном окне."""
|
||||||
|
if self._paste_delay_ms > 0:
|
||||||
|
time.sleep(self._paste_delay_ms / 1000)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Отпускаем все модификаторы которые могут быть зажаты
|
||||||
|
ctypes.windll.user32.keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0)
|
||||||
|
ctypes.windll.user32.keybd_event(0x12, 0, KEYEVENTF_KEYUP, 0) # Alt
|
||||||
|
ctypes.windll.user32.keybd_event(0x10, 0, KEYEVENTF_KEYUP, 0) # Shift
|
||||||
|
ctypes.windll.user32.keybd_event(0x20, 0, KEYEVENTF_KEYUP, 0) # Space
|
||||||
|
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:
|
||||||
|
raise PlatformError(f"Не удалось выполнить Ctrl+V: {exc}") from exc
|
||||||
|
|
||||||
|
logger.debug("WinAutoPaste: Ctrl+V выполнен (keybd_event)")
|
||||||
45
src/voice_dictation/platform/windows/clipboard.py
Normal file
45
src/voice_dictation/platform/windows/clipboard.py
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
"""Буфер обмена Windows через pyperclip."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
|
||||||
|
class WinClipboard:
|
||||||
|
"""Буфер обмена Windows через pyperclip."""
|
||||||
|
|
||||||
|
def copy(self, text: str) -> None:
|
||||||
|
"""Копирует текст в буфер обмена.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Текст для копирования.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: При ошибке pyperclip.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import pyperclip
|
||||||
|
|
||||||
|
pyperclip.copy(text)
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("pyperclip не установлен") from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise PlatformError(f"Ошибка копирования в буфер: {exc}") from exc
|
||||||
|
|
||||||
|
def paste(self) -> str:
|
||||||
|
"""Возвращает содержимое буфера обмена.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Текст из буфера.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: При ошибке pyperclip.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import pyperclip
|
||||||
|
|
||||||
|
return str(pyperclip.paste())
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("pyperclip не установлен") from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise PlatformError(f"Ошибка чтения буфера: {exc}") from exc
|
||||||
100
src/voice_dictation/platform/windows/hotkey_listener.py
Normal file
100
src/voice_dictation/platform/windows/hotkey_listener.py
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
"""Глобальный слушатель хоткеев на Windows через pynput."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from collections.abc import Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from voice_dictation.infrastructure.errors import PlatformError
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_TOKEN_MAP: dict[str, str] = {
|
||||||
|
"ctrl": "<ctrl>",
|
||||||
|
"control": "<ctrl>",
|
||||||
|
"alt": "<alt>",
|
||||||
|
"shift": "<shift>",
|
||||||
|
"win": "<cmd>",
|
||||||
|
"windows": "<cmd>",
|
||||||
|
"super": "<cmd>",
|
||||||
|
"cmd": "<ctrl>", # На Windows cmd маппируется на ctrl
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_hotkey(hotkey: str) -> str:
|
||||||
|
"""Конвертирует "ctrl+alt+d" в "<ctrl>+<alt>+d" для pynput.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Строка хоткея в свободном формате.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Строка хоткея в формате pynput GlobalHotKeys.
|
||||||
|
"""
|
||||||
|
tokens = re.split(r"[+\-]", hotkey.lower().strip())
|
||||||
|
normalized: list[str] = []
|
||||||
|
for token in tokens:
|
||||||
|
token = token.strip()
|
||||||
|
if not token:
|
||||||
|
continue
|
||||||
|
mapped = _TOKEN_MAP.get(token)
|
||||||
|
if mapped:
|
||||||
|
normalized.append(mapped)
|
||||||
|
elif len(token) == 1:
|
||||||
|
normalized.append(token)
|
||||||
|
else:
|
||||||
|
normalized.append(f"<{token}>")
|
||||||
|
return "+".join(normalized)
|
||||||
|
|
||||||
|
|
||||||
|
class WinHotkeyListener:
|
||||||
|
"""Глобальный слушатель горячих клавиш через pynput GlobalHotKeys."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._hotkeys: dict[str, Callable[[], None]] = {}
|
||||||
|
self._listener: Any = None
|
||||||
|
|
||||||
|
def register(self, hotkey: str, callback: Callable[[], None]) -> bool:
|
||||||
|
"""Регистрирует хоткей.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
hotkey: Строка хоткея, например "ctrl+alt+d".
|
||||||
|
callback: Функция, вызываемая при нажатии.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True если регистрация прошла успешно.
|
||||||
|
"""
|
||||||
|
normalized = _normalize_hotkey(hotkey)
|
||||||
|
self._hotkeys[normalized] = callback
|
||||||
|
logger.debug("Хоткей зарегистрирован: %s -> %s", hotkey, normalized)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
"""Запускает прослушивание (блокирующий вызов).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
PlatformError: Если pynput не установлен или нет хоткеев.
|
||||||
|
"""
|
||||||
|
if not self._hotkeys:
|
||||||
|
raise PlatformError("Нет зарегистрированных хоткеев")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from pynput import keyboard as kb
|
||||||
|
except ImportError as exc:
|
||||||
|
raise PlatformError("pynput не установлен") from exc
|
||||||
|
|
||||||
|
logger.info("Запуск слушателя хоткеев: %s", list(self._hotkeys.keys()))
|
||||||
|
|
||||||
|
listener = kb.GlobalHotKeys(self._hotkeys)
|
||||||
|
self._listener = listener
|
||||||
|
listener.run()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Останавливает прослушивание."""
|
||||||
|
if self._listener is not None:
|
||||||
|
try:
|
||||||
|
self._listener.stop()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Ошибка при остановке HotkeyListener: %s", exc)
|
||||||
|
self._listener = None
|
||||||
35
src/voice_dictation/platform/windows/notifier.py
Normal file
35
src/voice_dictation/platform/windows/notifier.py
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
"""Нативные уведомления Windows через winotify."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class WinNotifier:
|
||||||
|
"""Показывает toast-уведомления Windows через `winotify`."""
|
||||||
|
|
||||||
|
def __init__(self, app_id: str = "Voice Dictation") -> None:
|
||||||
|
self._app_id = app_id
|
||||||
|
|
||||||
|
def show(self, title: str, message: str) -> None:
|
||||||
|
"""Показывает уведомление.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
title: Заголовок.
|
||||||
|
message: Текст.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
from winotify import Notification # type: ignore[import-not-found]
|
||||||
|
except ImportError:
|
||||||
|
logger.warning(
|
||||||
|
"winotify не установлен — уведомление пропущено: %s — %s", title, message
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
toast = Notification(app_id=self._app_id, title=title, msg=message)
|
||||||
|
toast.show()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("winotify не смог показать уведомление: %s", exc)
|
||||||
61
src/voice_dictation/platform/windows/sound_player.py
Normal file
61
src/voice_dictation/platform/windows/sound_player.py
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
"""Воспроизведение звуков на Windows через winsound."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.enums import SoundKind
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_DEFAULT_SYSTEM_SOUNDS_DIR = Path(r"C:\Windows\Media")
|
||||||
|
_DEFAULT_SOUNDS: dict[SoundKind, str] = {
|
||||||
|
SoundKind.START: "Windows Ding.wav",
|
||||||
|
SoundKind.STOP: "Windows Notify.wav",
|
||||||
|
SoundKind.ERROR: "Windows Critical Stop.wav",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class WinSoundPlayer:
|
||||||
|
"""Проигрывает звуки через `winsound.PlaySound` в отдельном потоке."""
|
||||||
|
|
||||||
|
def play(self, kind: SoundKind, config: Config) -> None:
|
||||||
|
"""Воспроизводит звук для события.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
kind: Тип события.
|
||||||
|
config: Конфигурация.
|
||||||
|
"""
|
||||||
|
if not config.sounds_enabled:
|
||||||
|
return
|
||||||
|
|
||||||
|
path = self._resolve_path(kind, config)
|
||||||
|
if path is None or not path.exists():
|
||||||
|
logger.debug("WinSoundPlayer: звук %s не найден, пропуск", kind)
|
||||||
|
return
|
||||||
|
|
||||||
|
threading.Thread(target=_play_file, args=(path,), daemon=True).start()
|
||||||
|
|
||||||
|
def _resolve_path(self, kind: SoundKind, config: Config) -> Path | None:
|
||||||
|
custom_attr = {
|
||||||
|
SoundKind.START: config.start_sound_path,
|
||||||
|
SoundKind.STOP: config.stop_sound_path,
|
||||||
|
SoundKind.ERROR: config.error_sound_path,
|
||||||
|
}[kind]
|
||||||
|
|
||||||
|
if custom_attr is not None:
|
||||||
|
return custom_attr
|
||||||
|
|
||||||
|
return _DEFAULT_SYSTEM_SOUNDS_DIR / _DEFAULT_SOUNDS[kind]
|
||||||
|
|
||||||
|
|
||||||
|
def _play_file(path: Path) -> None:
|
||||||
|
try:
|
||||||
|
import winsound
|
||||||
|
|
||||||
|
winsound.PlaySound(str(path), winsound.SND_FILENAME | winsound.SND_ASYNC)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("winsound не удалось воспроизвести %s: %s", path, exc)
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
"""Сканирование системных звуков Windows."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.platform.system_sound import SystemSound
|
||||||
|
|
||||||
|
_SYSTEM_SOUNDS_DIR = Path(r"C:\Windows\Media")
|
||||||
|
|
||||||
|
|
||||||
|
class WinSystemSoundsScanner:
|
||||||
|
"""Ищет .wav файлы в C:\\Windows\\Media."""
|
||||||
|
|
||||||
|
def scan(self) -> list[SystemSound]:
|
||||||
|
"""Возвращает системные звуки Windows.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Список SystemSound, отсортированный по имени.
|
||||||
|
"""
|
||||||
|
if not _SYSTEM_SOUNDS_DIR.exists():
|
||||||
|
return []
|
||||||
|
sounds = [
|
||||||
|
SystemSound(name=path.stem, path=path)
|
||||||
|
for path in sorted(_SYSTEM_SOUNDS_DIR.glob("*.wav"))
|
||||||
|
]
|
||||||
|
return sounds
|
||||||
0
src/voice_dictation/ui/__init__.py
Normal file
0
src/voice_dictation/ui/__init__.py
Normal file
50
src/voice_dictation/ui/icons.py
Normal file
50
src/voice_dictation/ui/icons.py
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
"""Генерация иконок tray на лету через Pillow."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
from voice_dictation.core.enums import RecordingState
|
||||||
|
|
||||||
|
_SIZE = 64
|
||||||
|
|
||||||
|
_COLORS: dict[RecordingState, tuple[int, int, int]] = {
|
||||||
|
RecordingState.IDLE: (120, 120, 120),
|
||||||
|
RecordingState.RECORDING: (220, 50, 50),
|
||||||
|
RecordingState.PROCESSING: (60, 130, 220),
|
||||||
|
RecordingState.ERROR: (220, 140, 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_icon(state: RecordingState) -> Image.Image:
|
||||||
|
"""Возвращает PNG-иконку для tray в зависимости от состояния.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
state: Текущее состояние оркестратора.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
PIL Image 64×64 RGBA.
|
||||||
|
"""
|
||||||
|
img = Image.new("RGBA", (_SIZE, _SIZE), (0, 0, 0, 0))
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
color = _COLORS.get(state, _COLORS[RecordingState.IDLE])
|
||||||
|
|
||||||
|
# Микрофон: капсула + ножка + основание
|
||||||
|
body_w, body_h = 22, 32
|
||||||
|
cx = _SIZE // 2
|
||||||
|
body_top = 10
|
||||||
|
body_left = cx - body_w // 2
|
||||||
|
body_right = cx + body_w // 2
|
||||||
|
body_bottom = body_top + body_h
|
||||||
|
draw.rounded_rectangle(
|
||||||
|
(body_left, body_top, body_right, body_bottom),
|
||||||
|
radius=body_w // 2,
|
||||||
|
fill=color,
|
||||||
|
)
|
||||||
|
# Ножка
|
||||||
|
draw.line((cx, body_bottom + 2, cx, body_bottom + 12), fill=color, width=4)
|
||||||
|
# Основание
|
||||||
|
draw.line((cx - 12, body_bottom + 14, cx + 12, body_bottom + 14), fill=color, width=4)
|
||||||
|
|
||||||
|
return img
|
||||||
58
src/voice_dictation/ui/settings_cli.py
Normal file
58
src/voice_dictation/ui/settings_cli.py
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
"""Запуск окна настроек как отдельного процесса.
|
||||||
|
|
||||||
|
На macOS Tk должен крутить mainloop в главном потоке. Tray pystray уже
|
||||||
|
занимает главный поток, поэтому из меню tray открыть Tk-окно нельзя.
|
||||||
|
Решение: tray запускает отдельный процесс `python -m voice_dictation.ui.settings_cli`,
|
||||||
|
который сам становится «главным потоком» для своего Tk.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Точка входа подпроцесса для окна настроек."""
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
from voice_dictation.infrastructure.logging_setup import configure_logging
|
||||||
|
from voice_dictation.platform.factory import build_platform
|
||||||
|
from voice_dictation.ui.settings_window import SettingsWindow
|
||||||
|
|
||||||
|
paths = AppPaths.default().ensure_exists()
|
||||||
|
configure_logging(paths, verbose=False)
|
||||||
|
logger.info("Окно настроек запускается")
|
||||||
|
|
||||||
|
try:
|
||||||
|
load_env()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("env не загружен: %s", exc)
|
||||||
|
|
||||||
|
config_store = ConfigStore(paths.config_file)
|
||||||
|
config_store.load()
|
||||||
|
|
||||||
|
platform_bundle = build_platform()
|
||||||
|
usage_db = UsageDB(paths.usage_db)
|
||||||
|
|
||||||
|
def _noop() -> None:
|
||||||
|
"""В подпроцессе настроек нет оркестратора — toggle через файловый сигнал не нужен."""
|
||||||
|
|
||||||
|
window = SettingsWindow(
|
||||||
|
config_store=config_store,
|
||||||
|
paths=paths,
|
||||||
|
hotkey_listener=platform_bundle.hotkey_listener,
|
||||||
|
orchestrator_toggle=_noop,
|
||||||
|
usage_db=usage_db,
|
||||||
|
system_sounds_scanner=platform_bundle.system_sounds_scanner,
|
||||||
|
)
|
||||||
|
window.run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
sys.exit(0)
|
||||||
774
src/voice_dictation/ui/settings_window.py
Normal file
774
src/voice_dictation/ui/settings_window.py
Normal file
|
|
@ -0,0 +1,774 @@
|
||||||
|
"""Окно настроек на customtkinter."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from collections.abc import Callable
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from tkinter import filedialog
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import customtkinter as ctk
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from voice_dictation.core.config import ConfigStore
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
from voice_dictation.platform.protocols import HotkeyListener, SystemSoundsScanner
|
||||||
|
|
||||||
|
|
||||||
|
# Пресеты зависят от ОС: на macOS — Cmd-сочетания, на Windows/Linux — Ctrl.
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
_HOTKEY_PRESETS = ["cmd+space", "cmd+shift+space", "cmd+alt+d", "cmd+shift+d", "ctrl+alt+d"]
|
||||||
|
else:
|
||||||
|
_HOTKEY_PRESETS = ["ctrl+shift+space", "ctrl+alt+d", "ctrl+shift+d", "ctrl+alt+space"]
|
||||||
|
_MODELS = ["gpt-4o-mini-transcribe", "gpt-4o-transcribe", "whisper-1"]
|
||||||
|
_LANGUAGES = ["ru", "en", "auto"]
|
||||||
|
|
||||||
|
_ABOUT_TEXT = """Voice Dictation — голосовая диктовка под macOS / Windows.
|
||||||
|
Сделано в рамках Flowmasters (https://flowmasters.ru/).
|
||||||
|
|
||||||
|
═══ Идея ═══
|
||||||
|
|
||||||
|
Хотелось диктовать текст голосом в любое поле ввода (Telegram, Slack,
|
||||||
|
браузер, IDE) одним хоткеем. Доступные решения (Voice Control, Whisper
|
||||||
|
Transcription, MacWhisper) либо платные, либо неудобные, либо без
|
||||||
|
учёта стоимости / истории.
|
||||||
|
|
||||||
|
═══ Что под капотом ═══
|
||||||
|
|
||||||
|
• Хоткей — pynput GlobalHotKeys (macOS Cmd+Space по умолчанию)
|
||||||
|
• Запись — sox subprocess, 16 kHz mono WAV
|
||||||
|
• Транскрипция — OpenAI Whisper API (gpt-4o-mini-transcribe, ~$0.003/мин)
|
||||||
|
• Словарь — ~/.dictate/dictionary.txt с подсказками для Whisper
|
||||||
|
• Автовставка — pbcopy + Cmd+V через pynput
|
||||||
|
• Звуки — afplay + системные звуки macOS (Tink/Pop/Basso)
|
||||||
|
• Уведомления — osascript display notification
|
||||||
|
• Tray — pystray + Pillow (иконка генерируется на лету)
|
||||||
|
• Настройки — customtkinter (отдельный процесс из-за Tk threading)
|
||||||
|
• Статистика — SQLite ~/.dictate/usage.db (PRAGMA user_version)
|
||||||
|
• Баланс — OpenAI Admin API + курс ЦБ РФ (cbr-xml-daily.ru)
|
||||||
|
• Архитектура — DI, Protocol-интерфейсы, кроссплатформенная фабрика
|
||||||
|
|
||||||
|
═══ Процесс разработки ═══
|
||||||
|
|
||||||
|
Проект сделан за один вечер совместно с Claude Code (Opus 4.7) — CLI
|
||||||
|
от Anthropic для разработки в терминале с прямым доступом к файловой
|
||||||
|
системе и shell. Подход:
|
||||||
|
|
||||||
|
1. Архитектурный план (ARCHITECTURE.md, ~440 строк): структура папок,
|
||||||
|
модули, протоколы, состояния, этапы 1-7. Утверждён до кода.
|
||||||
|
|
||||||
|
2. Этап 1 — ядро headless: запись + транскрипция + автовставка.
|
||||||
|
Реализован сразу целиком, протестирован вручную.
|
||||||
|
|
||||||
|
3. Этапы 2-7 (этот разговор):
|
||||||
|
• Этап 2 — SQLite usage_db, CLI stats команда
|
||||||
|
• Этап 3 — звуки и нативные уведомления macOS/Windows
|
||||||
|
• Этап 4 — tray icon с динамической иконкой
|
||||||
|
• Этап 5 — окно настроек (5 табов на customtkinter)
|
||||||
|
• Этап 6 — баланс OpenAI через Admin API
|
||||||
|
• Этап 7 — линтер (ruff), 44 теста, README, autostart-скрипт
|
||||||
|
|
||||||
|
4. Багфиксы по ходу:
|
||||||
|
• verbose_json не работает с gpt-4o-mini → переключение на json
|
||||||
|
• Cmd+Space вставлял пробел в активное поле → Backspace-stub
|
||||||
|
• Tk не запускается из worker-потока → запуск как subprocess
|
||||||
|
• pynput 1.7.7 → 1.8.1 для совместимости с macOS Tahoe
|
||||||
|
|
||||||
|
═══ Стандарты кода ═══
|
||||||
|
|
||||||
|
• Python 3.11+, full type hints, mypy strict
|
||||||
|
• Ruff (E/W/F/I/N/UP/B/C4/SIM/ANN/RUF), pre-commit
|
||||||
|
• Protocol-интерфейсы вместо ABC, dataclass(slots=True)
|
||||||
|
• Не использует ничего лишнего — только httpx, pynput, pyperclip,
|
||||||
|
python-dotenv, psutil, pystray, Pillow, customtkinter
|
||||||
|
• Тесты: pytest, фейковые реализации Protocol для unit-тестов
|
||||||
|
|
||||||
|
═══ Файловая структура ═══
|
||||||
|
|
||||||
|
personal/voice-dictation/
|
||||||
|
├── src/voice_dictation/
|
||||||
|
│ ├── core/ — бизнес-логика (без знаний о ОС/UI)
|
||||||
|
│ ├── platform/ — macOS/Windows реализации Protocol
|
||||||
|
│ ├── ui/ — tray, окно настроек, иконки
|
||||||
|
│ ├── infrastructure/ — env, логи, single-instance lock
|
||||||
|
│ └── cli/ — headless mode + stats команда
|
||||||
|
├── tests/ — pytest, 44 теста
|
||||||
|
├── scripts/ — install_autostart_macos.sh
|
||||||
|
└── ARCHITECTURE.md — детальный план
|
||||||
|
|
||||||
|
═══ Запуск ═══
|
||||||
|
|
||||||
|
cd personal/voice-dictation
|
||||||
|
python3 -m venv .venv && source .venv/bin/activate
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
cp .env.example .env # вставить OPENAI_API_KEY
|
||||||
|
python -m voice_dictation
|
||||||
|
|
||||||
|
═══ Контакт ═══
|
||||||
|
|
||||||
|
Викентий Жеребов · Flowmasters
|
||||||
|
https://flowmasters.ru/
|
||||||
|
"""
|
||||||
|
|
||||||
|
_CHANGELOG = """═══ Что нового ═══
|
||||||
|
|
||||||
|
v0.2.0
|
||||||
|
• Режимы обработки вместо одной галочки Summary: Чистая диктовка,
|
||||||
|
Чистовик (без паразитов), Summary, Переводчик RU→EN, Промпт для
|
||||||
|
LLM, Буллеты, Деловое письмо. Выбор в трее → «Режим обработки».
|
||||||
|
• Свои стили: таб «Стили» — пишешь название и промпт, режим
|
||||||
|
появляется в трее.
|
||||||
|
|
||||||
|
v0.1.0
|
||||||
|
• Первая версия под Windows: запись, Whisper, автовставка, трей,
|
||||||
|
звуки, статистика, баланс, установщик.
|
||||||
|
"""
|
||||||
|
|
||||||
|
_window_lock = threading.Lock()
|
||||||
|
_window_holder: dict[str, SettingsWindow] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _activate_app() -> None:
|
||||||
|
"""Активирует приложение и поднимает его в Dock-front (macOS).
|
||||||
|
|
||||||
|
Для bundle с LSUIElement=true (без иконки в Dock) окно Tk не получает
|
||||||
|
фокус автоматически — нужен прямой вызов AppKit с временным повышением
|
||||||
|
activation policy до Regular (на время жизни процесса настроек).
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if sys.platform != "darwin":
|
||||||
|
return
|
||||||
|
from AppKit import NSApplication, NSApplicationActivationPolicyRegular
|
||||||
|
|
||||||
|
app = NSApplication.sharedApplication()
|
||||||
|
app.setActivationPolicy_(NSApplicationActivationPolicyRegular)
|
||||||
|
app.activateIgnoringOtherApps_(True)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Не удалось активировать приложение: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
def open_settings_window(
|
||||||
|
*,
|
||||||
|
config_store: ConfigStore,
|
||||||
|
paths: AppPaths,
|
||||||
|
hotkey_listener: HotkeyListener,
|
||||||
|
orchestrator_toggle: Callable[[], None],
|
||||||
|
usage_db: UsageDB,
|
||||||
|
system_sounds_scanner: SystemSoundsScanner,
|
||||||
|
) -> None:
|
||||||
|
"""Открывает (или поднимает) окно настроек.
|
||||||
|
|
||||||
|
Tkinter не любит запуск из не-главного потока на macOS, но pystray-меню
|
||||||
|
выполняется в фоновом потоке. Чтобы не падать, поднимаем окно через
|
||||||
|
`after(0, ...)` если уже есть инстанс, иначе создаём новый Tk через
|
||||||
|
`ctk.CTk()` — он создаст собственный mainloop в этом потоке.
|
||||||
|
"""
|
||||||
|
with _window_lock:
|
||||||
|
existing = _window_holder.get("window")
|
||||||
|
if existing is not None and existing.is_alive():
|
||||||
|
existing.bring_to_front()
|
||||||
|
return
|
||||||
|
|
||||||
|
window = SettingsWindow(
|
||||||
|
config_store=config_store,
|
||||||
|
paths=paths,
|
||||||
|
hotkey_listener=hotkey_listener,
|
||||||
|
orchestrator_toggle=orchestrator_toggle,
|
||||||
|
usage_db=usage_db,
|
||||||
|
system_sounds_scanner=system_sounds_scanner,
|
||||||
|
)
|
||||||
|
_window_holder["window"] = window
|
||||||
|
|
||||||
|
window.run()
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsWindow:
|
||||||
|
"""Окно настроек с табами.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config_store: Хранилище конфига.
|
||||||
|
paths: Пути приложения.
|
||||||
|
hotkey_listener: Слушатель хоткеев — для перерегистрации.
|
||||||
|
orchestrator_toggle: Колбэк toggle.
|
||||||
|
usage_db: БД статистики.
|
||||||
|
system_sounds_scanner: Сканер системных звуков.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
config_store: ConfigStore,
|
||||||
|
paths: AppPaths,
|
||||||
|
hotkey_listener: HotkeyListener,
|
||||||
|
orchestrator_toggle: Callable[[], None],
|
||||||
|
usage_db: UsageDB,
|
||||||
|
system_sounds_scanner: SystemSoundsScanner,
|
||||||
|
) -> None:
|
||||||
|
self._config_store = config_store
|
||||||
|
self._paths = paths
|
||||||
|
self._hotkey_listener = hotkey_listener
|
||||||
|
self._orchestrator_toggle = orchestrator_toggle
|
||||||
|
self._usage_db = usage_db
|
||||||
|
self._system_sounds = system_sounds_scanner.scan()
|
||||||
|
|
||||||
|
self._root: ctk.CTk | None = None
|
||||||
|
|
||||||
|
def is_alive(self) -> bool:
|
||||||
|
return self._root is not None and self._root.winfo_exists()
|
||||||
|
|
||||||
|
def bring_to_front(self) -> None:
|
||||||
|
if self._root is None:
|
||||||
|
return
|
||||||
|
self._root.after(0, self._root.lift)
|
||||||
|
self._root.after(0, lambda: self._root.attributes("-topmost", True) if self._root else None)
|
||||||
|
self._root.after(
|
||||||
|
100, lambda: self._root.attributes("-topmost", False) if self._root else None
|
||||||
|
)
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
config = self._config_store.current()
|
||||||
|
|
||||||
|
ctk.set_appearance_mode("system")
|
||||||
|
ctk.set_default_color_theme("blue")
|
||||||
|
|
||||||
|
self._root = ctk.CTk()
|
||||||
|
self._root.title("Voice Dictation — настройки")
|
||||||
|
self._root.geometry("720x560")
|
||||||
|
|
||||||
|
# Принудительно вытаскиваем окно на передний план — иначе в bundle
|
||||||
|
# с LSUIElement=true Tk-окно создаётся, но прячется за активным приложением.
|
||||||
|
_activate_app()
|
||||||
|
self._root.after(50, self._root.lift)
|
||||||
|
self._root.after(50, lambda: self._root.attributes("-topmost", True) if self._root else None)
|
||||||
|
self._root.after(
|
||||||
|
500, lambda: self._root.attributes("-topmost", False) if self._root else None
|
||||||
|
)
|
||||||
|
self._root.after(50, self._root.focus_force)
|
||||||
|
|
||||||
|
tabs = ctk.CTkTabview(self._root)
|
||||||
|
tabs.pack(fill="both", expand=True, padx=12, pady=12)
|
||||||
|
|
||||||
|
general_tab = tabs.add("Общие")
|
||||||
|
styles_tab = tabs.add("Стили")
|
||||||
|
sound_tab = tabs.add("Звук")
|
||||||
|
dictionary_tab = tabs.add("Словарь")
|
||||||
|
stats_tab = tabs.add("Статистика")
|
||||||
|
balance_tab = tabs.add("Баланс")
|
||||||
|
about_tab = tabs.add("О проекте")
|
||||||
|
|
||||||
|
self._build_general_tab(general_tab, config)
|
||||||
|
self._build_styles_tab(styles_tab, config)
|
||||||
|
self._build_sound_tab(sound_tab, config)
|
||||||
|
self._build_dictionary_tab(dictionary_tab)
|
||||||
|
self._build_stats_tab(stats_tab)
|
||||||
|
self._build_balance_tab(balance_tab)
|
||||||
|
self._build_about_tab(about_tab)
|
||||||
|
|
||||||
|
self._root.protocol("WM_DELETE_WINDOW", self._on_close)
|
||||||
|
self._root.mainloop()
|
||||||
|
|
||||||
|
def _on_close(self) -> None:
|
||||||
|
if self._root is not None:
|
||||||
|
self._root.destroy()
|
||||||
|
self._root = None
|
||||||
|
with _window_lock:
|
||||||
|
_window_holder.pop("window", None)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ tabs
|
||||||
|
|
||||||
|
def _build_general_tab(self, parent: ctk.CTkFrame, config: object) -> None:
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
|
||||||
|
assert isinstance(config, Config)
|
||||||
|
|
||||||
|
row = 0
|
||||||
|
ctk.CTkLabel(parent, text="Хоткей:").grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
||||||
|
hotkey_var = ctk.StringVar(value=config.hotkey)
|
||||||
|
hotkey_box = ctk.CTkComboBox(parent, values=_HOTKEY_PRESETS, variable=hotkey_var, width=240)
|
||||||
|
hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
ctk.CTkLabel(parent, text="Модель:").grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
||||||
|
model_var = ctk.StringVar(value=config.model)
|
||||||
|
ctk.CTkComboBox(parent, values=_MODELS, variable=model_var, width=240).grid(
|
||||||
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
ctk.CTkLabel(parent, text="Язык:").grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
||||||
|
language_var = ctk.StringVar(value=config.language or "auto")
|
||||||
|
ctk.CTkComboBox(parent, values=_LANGUAGES, variable=language_var, width=240).grid(
|
||||||
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
auto_paste_var = ctk.BooleanVar(value=config.auto_paste)
|
||||||
|
ctk.CTkCheckBox(
|
||||||
|
parent, text="Автовставка после транскрипции", variable=auto_paste_var
|
||||||
|
).grid(row=row, column=0, columnspan=2, sticky="w", padx=8, pady=8)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
notif_var = ctk.BooleanVar(value=config.notifications_enabled)
|
||||||
|
ctk.CTkCheckBox(parent, text="Системные уведомления", variable=notif_var).grid(
|
||||||
|
row=row, column=0, columnspan=2, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
cost_var = ctk.BooleanVar(value=config.show_cost_in_notification)
|
||||||
|
ctk.CTkCheckBox(parent, text="Показывать стоимость в уведомлении", variable=cost_var).grid(
|
||||||
|
row=row, column=0, columnspan=2, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
ctk.CTkLabel(parent, text="Задержка перед вставкой (мс):").grid(
|
||||||
|
row=row, column=0, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
delay_var = ctk.IntVar(value=config.paste_delay_ms)
|
||||||
|
ctk.CTkEntry(parent, textvariable=delay_var, width=80).grid(
|
||||||
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
def _save_general() -> None:
|
||||||
|
import dataclasses
|
||||||
|
|
||||||
|
language_choice = language_var.get()
|
||||||
|
new_hotkey = hotkey_var.get().strip().lower()
|
||||||
|
current = self._config_store.current()
|
||||||
|
updated = dataclasses.replace(
|
||||||
|
current,
|
||||||
|
hotkey=new_hotkey,
|
||||||
|
model=model_var.get(),
|
||||||
|
language=None if language_choice == "auto" else language_choice,
|
||||||
|
notifications_enabled=notif_var.get(),
|
||||||
|
show_cost_in_notification=cost_var.get(),
|
||||||
|
auto_paste=auto_paste_var.get(),
|
||||||
|
paste_delay_ms=int(delay_var.get()),
|
||||||
|
)
|
||||||
|
self._config_store.save(updated)
|
||||||
|
if new_hotkey != current.hotkey:
|
||||||
|
self._toast("Сохранено. Перезапустите приложение для нового хоткея.")
|
||||||
|
else:
|
||||||
|
self._toast("Настройки сохранены")
|
||||||
|
|
||||||
|
ctk.CTkButton(parent, text="Сохранить", command=_save_general).grid(
|
||||||
|
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 = 3
|
||||||
|
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:
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
|
||||||
|
assert isinstance(config, Config)
|
||||||
|
|
||||||
|
sound_options = ["(системный по умолчанию)"] + [s.name for s in self._system_sounds]
|
||||||
|
|
||||||
|
sounds_enabled_var = ctk.BooleanVar(value=config.sounds_enabled)
|
||||||
|
ctk.CTkCheckBox(parent, text="Звуки включены", variable=sounds_enabled_var).grid(
|
||||||
|
row=0, column=0, columnspan=3, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
ctk.CTkLabel(parent, text="Громкость:").grid(row=1, column=0, sticky="w", padx=8, pady=8)
|
||||||
|
volume_var = ctk.DoubleVar(value=config.volume)
|
||||||
|
ctk.CTkSlider(parent, from_=0.0, to=1.0, variable=volume_var, width=240).grid(
|
||||||
|
row=1, column=1, padx=8, pady=8
|
||||||
|
)
|
||||||
|
|
||||||
|
def _name_of(path: Path | None) -> str:
|
||||||
|
if path is None:
|
||||||
|
return sound_options[0]
|
||||||
|
return path.stem
|
||||||
|
|
||||||
|
start_var = ctk.StringVar(value=_name_of(config.start_sound_path))
|
||||||
|
stop_var = ctk.StringVar(value=_name_of(config.stop_sound_path))
|
||||||
|
error_var = ctk.StringVar(value=_name_of(config.error_sound_path))
|
||||||
|
|
||||||
|
def _resolve(name: str) -> Path | None:
|
||||||
|
if name == sound_options[0]:
|
||||||
|
return None
|
||||||
|
for s in self._system_sounds:
|
||||||
|
if s.name == name:
|
||||||
|
return s.path
|
||||||
|
return None
|
||||||
|
|
||||||
|
for row, (label, var) in enumerate(
|
||||||
|
[("Старт записи:", start_var), ("Остановка:", stop_var), ("Ошибка:", error_var)],
|
||||||
|
start=2,
|
||||||
|
):
|
||||||
|
ctk.CTkLabel(parent, text=label).grid(row=row, column=0, sticky="w", padx=8, pady=8)
|
||||||
|
ctk.CTkComboBox(parent, values=sound_options, variable=var, width=240).grid(
|
||||||
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
|
)
|
||||||
|
ctk.CTkButton(
|
||||||
|
parent,
|
||||||
|
text="▶",
|
||||||
|
width=36,
|
||||||
|
command=lambda v=var: self._preview_sound(_resolve(v.get())),
|
||||||
|
).grid(row=row, column=2, sticky="w", padx=4, pady=8)
|
||||||
|
|
||||||
|
def _save_sound() -> None:
|
||||||
|
import dataclasses
|
||||||
|
|
||||||
|
current = self._config_store.current()
|
||||||
|
updated = dataclasses.replace(
|
||||||
|
current,
|
||||||
|
sounds_enabled=sounds_enabled_var.get(),
|
||||||
|
volume=float(volume_var.get()),
|
||||||
|
start_sound_path=_resolve(start_var.get()),
|
||||||
|
stop_sound_path=_resolve(stop_var.get()),
|
||||||
|
error_sound_path=_resolve(error_var.get()),
|
||||||
|
)
|
||||||
|
self._config_store.save(updated)
|
||||||
|
self._toast("Звуки сохранены")
|
||||||
|
|
||||||
|
ctk.CTkButton(parent, text="Сохранить", command=_save_sound).grid(
|
||||||
|
row=5, column=0, columnspan=2, pady=14
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_dictionary_tab(self, parent: ctk.CTkFrame) -> None:
|
||||||
|
ctk.CTkLabel(
|
||||||
|
parent,
|
||||||
|
text="Слова и фразы (по одной на строку, # — комментарий):",
|
||||||
|
anchor="w",
|
||||||
|
).pack(fill="x", padx=8, pady=(8, 4))
|
||||||
|
|
||||||
|
textbox = ctk.CTkTextbox(parent, wrap="word")
|
||||||
|
textbox.pack(fill="both", expand=True, padx=8, pady=4)
|
||||||
|
|
||||||
|
if self._paths.dictionary_file.exists():
|
||||||
|
try:
|
||||||
|
textbox.insert("1.0", self._paths.dictionary_file.read_text(encoding="utf-8"))
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning("Не удалось прочитать словарь: %s", exc)
|
||||||
|
|
||||||
|
def _save_dict() -> None:
|
||||||
|
text = textbox.get("1.0", "end").rstrip() + "\n"
|
||||||
|
self._paths.dictionary_file.write_text(text, encoding="utf-8")
|
||||||
|
self._toast("Словарь сохранён")
|
||||||
|
|
||||||
|
def _open_file() -> None:
|
||||||
|
path = filedialog.askopenfilename(
|
||||||
|
title="Открыть словарь",
|
||||||
|
filetypes=[("Текстовые файлы", "*.txt"), ("Все файлы", "*.*")],
|
||||||
|
)
|
||||||
|
if path:
|
||||||
|
content = Path(path).read_text(encoding="utf-8")
|
||||||
|
textbox.delete("1.0", "end")
|
||||||
|
textbox.insert("1.0", content)
|
||||||
|
|
||||||
|
controls = ctk.CTkFrame(parent, fg_color="transparent")
|
||||||
|
controls.pack(fill="x", padx=8, pady=8)
|
||||||
|
ctk.CTkButton(controls, text="Сохранить", command=_save_dict).pack(side="left", padx=4)
|
||||||
|
ctk.CTkButton(controls, text="Импорт...", command=_open_file).pack(side="left", padx=4)
|
||||||
|
|
||||||
|
def _build_stats_tab(self, parent: ctk.CTkFrame) -> None:
|
||||||
|
text_widget = ctk.CTkTextbox(parent, wrap="none")
|
||||||
|
text_widget.pack(fill="both", expand=True, padx=8, pady=8)
|
||||||
|
|
||||||
|
def _refresh() -> None:
|
||||||
|
text_widget.configure(state="normal")
|
||||||
|
text_widget.delete("1.0", "end")
|
||||||
|
tz = datetime.now().astimezone().tzinfo
|
||||||
|
today = self._usage_db.today_total(tz=tz)
|
||||||
|
now = datetime.now(tz=tz)
|
||||||
|
month = self._usage_db.month_stats(now.year, now.month, tz=tz)
|
||||||
|
total = self._usage_db.all_time()
|
||||||
|
recent = self._usage_db.recent(limit=20)
|
||||||
|
|
||||||
|
from voice_dictation.core.fx import get_rate, usd_to_rub
|
||||||
|
|
||||||
|
rate = get_rate()
|
||||||
|
|
||||||
|
def _row(label: str, stats: object) -> str:
|
||||||
|
from voice_dictation.core.usage_db import UsageStats
|
||||||
|
|
||||||
|
assert isinstance(stats, UsageStats)
|
||||||
|
mins = stats.total_duration_sec / 60
|
||||||
|
rub = usd_to_rub(stats.total_cost_usd, rate)
|
||||||
|
rub_part = f" ({rub:.2f} ₽)" if rub is not None else ""
|
||||||
|
return (
|
||||||
|
f"{label:<12}{stats.count:>4} · {mins:6.1f} мин · "
|
||||||
|
f"${stats.total_cost_usd:.4f}{rub_part}"
|
||||||
|
)
|
||||||
|
|
||||||
|
lines: list[str] = [
|
||||||
|
_row("Сегодня:", today),
|
||||||
|
_row("Месяц:", month),
|
||||||
|
_row("Всего:", total),
|
||||||
|
"",
|
||||||
|
"Последние:",
|
||||||
|
]
|
||||||
|
for r in recent:
|
||||||
|
ts = r.created_at.astimezone(tz).strftime("%m-%d %H:%M")
|
||||||
|
lines.append(
|
||||||
|
f" {ts} {r.duration_sec:5.1f}с ${r.cost_usd:7.4f} {r.text_preview}"
|
||||||
|
)
|
||||||
|
|
||||||
|
text_widget.insert("1.0", "\n".join(lines))
|
||||||
|
text_widget.configure(state="disabled")
|
||||||
|
|
||||||
|
controls = ctk.CTkFrame(parent, fg_color="transparent")
|
||||||
|
controls.pack(fill="x", padx=8, pady=(0, 8))
|
||||||
|
ctk.CTkButton(controls, text="Обновить", command=_refresh).pack(side="left", padx=4)
|
||||||
|
_refresh()
|
||||||
|
|
||||||
|
def _build_balance_tab(self, parent: ctk.CTkFrame) -> None:
|
||||||
|
info = ctk.CTkLabel(
|
||||||
|
parent,
|
||||||
|
text="Баланс OpenAI (требуется Admin API ключ).",
|
||||||
|
anchor="w",
|
||||||
|
)
|
||||||
|
info.pack(fill="x", padx=8, pady=8)
|
||||||
|
|
||||||
|
result_box = ctk.CTkTextbox(parent, height=120, wrap="word")
|
||||||
|
result_box.pack(fill="x", padx=8, pady=8)
|
||||||
|
result_box.insert("1.0", "Нажмите «Получить баланс».")
|
||||||
|
result_box.configure(state="disabled")
|
||||||
|
|
||||||
|
def _set_text(text: str) -> None:
|
||||||
|
result_box.configure(state="normal")
|
||||||
|
result_box.delete("1.0", "end")
|
||||||
|
result_box.insert("1.0", text)
|
||||||
|
result_box.configure(state="disabled")
|
||||||
|
|
||||||
|
def _fetch() -> None:
|
||||||
|
try:
|
||||||
|
from voice_dictation.core.balance import BalanceClient
|
||||||
|
from voice_dictation.infrastructure.env_loader import load_env
|
||||||
|
|
||||||
|
env = load_env()
|
||||||
|
if not env.admin_api_key:
|
||||||
|
_set_text(
|
||||||
|
"OPENAI_ADMIN_API_KEY не задан в .env.\n"
|
||||||
|
"Создайте Admin-ключ: https://platform.openai.com/settings/organization/admin-keys"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
from voice_dictation.core.fx import get_rate, usd_to_rub
|
||||||
|
|
||||||
|
client = BalanceClient(api_key=env.admin_api_key)
|
||||||
|
info_data = client.fetch()
|
||||||
|
rate = get_rate()
|
||||||
|
|
||||||
|
def _line(label: str, usd: object) -> str:
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
assert isinstance(usd, Decimal)
|
||||||
|
rub = usd_to_rub(usd, rate)
|
||||||
|
rub_part = f" ≈ {rub:.2f} ₽" if rub is not None else ""
|
||||||
|
return f"{label}${usd:.2f}{rub_part}"
|
||||||
|
|
||||||
|
rate_line = (
|
||||||
|
f"Курс ЦБ: 1$ = {rate:.2f} ₽" if rate is not None else "Курс ЦБ: недоступен"
|
||||||
|
)
|
||||||
|
_set_text(
|
||||||
|
f"{_line('Выдано: ', info_data.total_granted_usd)}\n"
|
||||||
|
f"{_line('Потрачено: ', info_data.total_used_usd)}\n"
|
||||||
|
f"{_line('Доступно: ', info_data.total_available_usd)}\n"
|
||||||
|
f"{rate_line}\n"
|
||||||
|
f"Обновлено: {info_data.fetched_at:%Y-%m-%d %H:%M}"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
_set_text(f"Ошибка: {exc}")
|
||||||
|
|
||||||
|
ctk.CTkButton(parent, text="Получить баланс", command=_fetch).pack(padx=8, pady=8)
|
||||||
|
|
||||||
|
def _build_about_tab(self, parent: ctk.CTkFrame) -> None:
|
||||||
|
from voice_dictation import __version__
|
||||||
|
|
||||||
|
ctk.CTkLabel(
|
||||||
|
parent,
|
||||||
|
text=f"Voice Dictation v{__version__}",
|
||||||
|
anchor="w",
|
||||||
|
font=("", 14, "bold"),
|
||||||
|
).pack(fill="x", padx=8, pady=(8, 0))
|
||||||
|
|
||||||
|
text_widget = ctk.CTkTextbox(parent, wrap="word")
|
||||||
|
text_widget.pack(fill="both", expand=True, padx=8, pady=8)
|
||||||
|
text_widget.insert("1.0", _CHANGELOG + "\n" + _ABOUT_TEXT)
|
||||||
|
text_widget.configure(state="disabled")
|
||||||
|
|
||||||
|
controls = ctk.CTkFrame(parent, fg_color="transparent")
|
||||||
|
controls.pack(fill="x", padx=8, pady=(0, 8))
|
||||||
|
|
||||||
|
def _open_site() -> None:
|
||||||
|
import webbrowser
|
||||||
|
|
||||||
|
webbrowser.open("https://flowmasters.ru/")
|
||||||
|
|
||||||
|
ctk.CTkButton(controls, text="flowmasters.ru", command=_open_site).pack(
|
||||||
|
side="left", padx=4
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ helpers
|
||||||
|
|
||||||
|
def _reregister_hotkey(self, hotkey: str) -> None:
|
||||||
|
try:
|
||||||
|
self._hotkey_listener.stop()
|
||||||
|
self._hotkey_listener.register(hotkey, self._orchestrator_toggle)
|
||||||
|
threading.Thread(
|
||||||
|
target=self._hotkey_listener.start,
|
||||||
|
name="hotkey-listener-restart",
|
||||||
|
daemon=True,
|
||||||
|
).start()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось перерегистрировать хоткей: %s", exc)
|
||||||
|
|
||||||
|
def _preview_sound(self, path: Path | None) -> None:
|
||||||
|
"""Проигрывает звук для предпрослушки (кроссплатформенно, в фоне).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Путь к звуку; None — системный звук по умолчанию.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _run() -> None:
|
||||||
|
try:
|
||||||
|
if sys.platform == "darwin":
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
target = str(path) if path else "/System/Library/Sounds/Ping.aiff"
|
||||||
|
subprocess.run(["afplay", target], timeout=10, check=False)
|
||||||
|
else:
|
||||||
|
import winsound
|
||||||
|
|
||||||
|
if path is not None and path.exists():
|
||||||
|
winsound.PlaySound(
|
||||||
|
str(path), winsound.SND_FILENAME | winsound.SND_ASYNC
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
winsound.MessageBeep()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось проиграть звук %s: %s", path, exc)
|
||||||
|
|
||||||
|
threading.Thread(target=_run, name="sound-preview", daemon=True).start()
|
||||||
|
|
||||||
|
def _toast(self, message: str) -> None:
|
||||||
|
if self._root is None:
|
||||||
|
return
|
||||||
|
toast = ctk.CTkLabel(self._root, text=message, text_color="green")
|
||||||
|
toast.pack(side="bottom", pady=4)
|
||||||
|
self._root.after(2000, toast.destroy)
|
||||||
153
src/voice_dictation/ui/tray.py
Normal file
153
src/voice_dictation/ui/tray.py
Normal file
|
|
@ -0,0 +1,153 @@
|
||||||
|
"""Tray-приложение с иконкой в строке меню (pystray)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
import pystray
|
||||||
|
from pystray import MenuItem
|
||||||
|
|
||||||
|
from voice_dictation.core.enums import RecordingState
|
||||||
|
from voice_dictation.ui.icons import make_icon
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class TrayApp:
|
||||||
|
"""Иконка в трее с меню. Обновляет иконку по состоянию оркестратора.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
on_toggle: Колбэк при клике "Запись/Стоп".
|
||||||
|
on_settings: Колбэк при клике "Настройки".
|
||||||
|
on_stats: Колбэк при клике "Статистика".
|
||||||
|
on_quit: Колбэк при клике "Выход".
|
||||||
|
title: Заголовок tray (tooltip).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
on_toggle: Callable[[], None],
|
||||||
|
on_settings: Callable[[], None],
|
||||||
|
on_stats: Callable[[], None],
|
||||||
|
on_quit: Callable[[], None],
|
||||||
|
modes_provider: Callable[[], list[tuple[str, str]]] | None = None,
|
||||||
|
on_mode_select: Callable[[str], None] | None = None,
|
||||||
|
current_mode: Callable[[], str] | None = None,
|
||||||
|
title: str = "Voice Dictation",
|
||||||
|
) -> None:
|
||||||
|
self._on_toggle = on_toggle
|
||||||
|
self._on_settings = on_settings
|
||||||
|
self._on_stats = on_stats
|
||||||
|
self._on_quit = on_quit
|
||||||
|
self._modes_provider = modes_provider
|
||||||
|
self._on_mode_select = on_mode_select
|
||||||
|
self._current_mode = current_mode
|
||||||
|
self._title = title
|
||||||
|
self._state = RecordingState.IDLE
|
||||||
|
|
||||||
|
self._icon = pystray.Icon(
|
||||||
|
"voice_dictation",
|
||||||
|
icon=make_icon(self._state),
|
||||||
|
title=self._title,
|
||||||
|
menu=self._build_menu(),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _build_menu(self) -> pystray.Menu:
|
||||||
|
items = [
|
||||||
|
MenuItem(self._toggle_label, self._handle_toggle, default=True),
|
||||||
|
]
|
||||||
|
if self._modes_provider is not None and self._on_mode_select is not None:
|
||||||
|
items.append(MenuItem("Режим обработки", self._build_mode_submenu()))
|
||||||
|
items.extend([
|
||||||
|
MenuItem("Статистика", self._handle_stats),
|
||||||
|
MenuItem("Настройки", self._handle_settings),
|
||||||
|
pystray.Menu.SEPARATOR,
|
||||||
|
MenuItem("Выход", self._handle_quit),
|
||||||
|
])
|
||||||
|
return pystray.Menu(*items)
|
||||||
|
|
||||||
|
def _build_mode_submenu(self) -> pystray.Menu:
|
||||||
|
"""Строит подменю выбора режима с радио-галочками."""
|
||||||
|
sub_items = []
|
||||||
|
modes = self._modes_provider() if self._modes_provider is not None else []
|
||||||
|
for key, label in modes:
|
||||||
|
sub_items.append(
|
||||||
|
MenuItem(
|
||||||
|
label,
|
||||||
|
self._make_mode_handler(key),
|
||||||
|
checked=self._make_mode_checked(key),
|
||||||
|
radio=True,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return pystray.Menu(*sub_items)
|
||||||
|
|
||||||
|
def _make_mode_handler(self, key: str) -> Callable[..., None]:
|
||||||
|
def handler(*_args: object) -> None:
|
||||||
|
if self._on_mode_select is not None:
|
||||||
|
self._on_mode_select(key)
|
||||||
|
self.update_state(self._state) # перерисовать галочки
|
||||||
|
return handler
|
||||||
|
|
||||||
|
def _make_mode_checked(self, key: str) -> Callable[[object], bool]:
|
||||||
|
def checked(_item: object) -> bool:
|
||||||
|
if self._current_mode is not None:
|
||||||
|
return self._current_mode() == key
|
||||||
|
return False
|
||||||
|
return checked
|
||||||
|
|
||||||
|
def _toggle_label(self, _item: object) -> str:
|
||||||
|
if self._state == RecordingState.RECORDING:
|
||||||
|
return "Остановить запись"
|
||||||
|
if self._state == RecordingState.PROCESSING:
|
||||||
|
return "Обработка..."
|
||||||
|
return "Начать запись"
|
||||||
|
|
||||||
|
def _handle_toggle(self, *_args: object) -> None:
|
||||||
|
self._on_toggle()
|
||||||
|
|
||||||
|
def _handle_settings(self, *_args: object) -> None:
|
||||||
|
self._on_settings()
|
||||||
|
|
||||||
|
def _handle_stats(self, *_args: object) -> None:
|
||||||
|
self._on_stats()
|
||||||
|
|
||||||
|
def _handle_quit(self, *_args: object) -> None:
|
||||||
|
self._on_quit()
|
||||||
|
self._icon.stop()
|
||||||
|
|
||||||
|
def update_state(self, state: RecordingState) -> None:
|
||||||
|
"""Обновляет иконку и меню в соответствии с состоянием.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
state: Новое состояние оркестратора.
|
||||||
|
"""
|
||||||
|
self._state = state
|
||||||
|
try:
|
||||||
|
self._icon.icon = make_icon(state)
|
||||||
|
self._icon.menu = self._build_menu()
|
||||||
|
self._icon.update_menu()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Не удалось обновить tray: %s", exc)
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
"""Блокирующий запуск tray-цикла."""
|
||||||
|
self._icon.run()
|
||||||
|
|
||||||
|
def run_detached(self) -> threading.Thread:
|
||||||
|
"""Запускает tray в фоновом потоке.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Поток с tray-циклом.
|
||||||
|
"""
|
||||||
|
thread = threading.Thread(target=self._icon.run, name="tray", daemon=True)
|
||||||
|
thread.start()
|
||||||
|
return thread
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""Останавливает tray."""
|
||||||
|
try:
|
||||||
|
self._icon.stop()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug("Tray уже остановлен: %s", exc)
|
||||||
1
tests/__init__.py
Normal file
1
tests/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Тесты voice_dictation."""
|
||||||
33
tests/conftest.py
Normal file
33
tests/conftest.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
"""Общие фикстуры pytest."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def tmp_paths(tmp_path: pytest.TempPathFactory) -> AppPaths:
|
||||||
|
"""AppPaths с временными директориями в pytest tmp_path.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
tmp_path: Встроенная фикстура pytest.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
AppPaths с путями в tmp_path.
|
||||||
|
"""
|
||||||
|
root = tmp_path # type: ignore[arg-type]
|
||||||
|
paths = AppPaths(
|
||||||
|
root=root,
|
||||||
|
config_file=root / "config.json",
|
||||||
|
usage_db=root / "usage.db",
|
||||||
|
dictionary_file=root / "dictionary.txt",
|
||||||
|
custom_sounds_dir=root / "sounds",
|
||||||
|
log_file=root / "app.log",
|
||||||
|
pid_file=root / "dictate.pid",
|
||||||
|
tmp_dir=root / "tmp",
|
||||||
|
bin_dir=root / "bin",
|
||||||
|
)
|
||||||
|
paths.ensure_exists()
|
||||||
|
return paths
|
||||||
1
tests/fakes/__init__.py
Normal file
1
tests/fakes/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""In-memory реализации протоколов для тестирования."""
|
||||||
157
tests/fakes/fake_components.py
Normal file
157
tests/fakes/fake_components.py
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
"""Фейковые реализации протоколов для тестирования."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.enums import SoundKind
|
||||||
|
from voice_dictation.core.models import RecordingResult, TranscriptionResult
|
||||||
|
from voice_dictation.infrastructure.errors import RecorderError, TranscriptionError
|
||||||
|
|
||||||
|
|
||||||
|
class FakeRecorder:
|
||||||
|
"""Фейковый рекордер — имитирует запись без sox.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
duration_sec: Длительность, которую вернёт stop().
|
||||||
|
fail_start: Если True — start() бросит RecorderError.
|
||||||
|
fail_stop: Если True — stop() бросит RecorderError.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
duration_sec: float = 2.0,
|
||||||
|
fail_start: bool = False,
|
||||||
|
fail_stop: bool = False,
|
||||||
|
) -> None:
|
||||||
|
self.duration_sec = duration_sec
|
||||||
|
self.fail_start = fail_start
|
||||||
|
self.fail_stop = fail_stop
|
||||||
|
self.started = False
|
||||||
|
self.stopped = False
|
||||||
|
self._output_path: Path | None = None
|
||||||
|
|
||||||
|
def start(self, output_path: Path) -> None:
|
||||||
|
if self.fail_start:
|
||||||
|
raise RecorderError("FakeRecorder: принудительная ошибка start")
|
||||||
|
self.started = True
|
||||||
|
self._output_path = output_path
|
||||||
|
# Создаём минимальный файл чтобы stop() не упал
|
||||||
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output_path.write_bytes(b"\x00" * 8000)
|
||||||
|
|
||||||
|
def stop(self) -> RecordingResult:
|
||||||
|
if not self.started:
|
||||||
|
raise RecorderError("FakeRecorder: запись не запущена")
|
||||||
|
if self.fail_stop:
|
||||||
|
raise RecorderError("FakeRecorder: принудительная ошибка stop")
|
||||||
|
self.stopped = True
|
||||||
|
path = self._output_path or Path("/tmp/fake_recording.wav")
|
||||||
|
return RecordingResult(path=path, duration_sec=self.duration_sec)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeTranscriber:
|
||||||
|
"""Фейковый транскрайбер — возвращает заданный текст без API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text: Текст, который будет возвращён.
|
||||||
|
fail: Если True — transcribe() бросит TranscriptionError.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, text: str = "Тестовый текст", fail: bool = False) -> None:
|
||||||
|
self.text = text
|
||||||
|
self.fail = fail
|
||||||
|
self.calls: list[tuple[Path, str, str | None]] = []
|
||||||
|
|
||||||
|
def transcribe(
|
||||||
|
self,
|
||||||
|
audio_path: Path,
|
||||||
|
prompt: str = "",
|
||||||
|
language: str | None = None,
|
||||||
|
) -> TranscriptionResult:
|
||||||
|
self.calls.append((audio_path, prompt, language))
|
||||||
|
if self.fail:
|
||||||
|
raise TranscriptionError("FakeTranscriber: принудительная ошибка")
|
||||||
|
return TranscriptionResult(
|
||||||
|
text=self.text,
|
||||||
|
duration_sec=2.0,
|
||||||
|
model="gpt-4o-mini-transcribe",
|
||||||
|
language=language or "ru",
|
||||||
|
prompt_used=prompt or None,
|
||||||
|
requested_at=datetime.now(tz=UTC),
|
||||||
|
cost_usd=Decimal("0.000100"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClipboard:
|
||||||
|
"""Фейковый буфер обмена — хранит в памяти."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._text: str = ""
|
||||||
|
self.copy_calls: list[str] = []
|
||||||
|
|
||||||
|
def copy(self, text: str) -> None:
|
||||||
|
self._text = text
|
||||||
|
self.copy_calls.append(text)
|
||||||
|
|
||||||
|
def paste(self) -> str:
|
||||||
|
return self._text
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAutoPaste:
|
||||||
|
"""Фейковая автовставка — считает вызовы."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.paste_count = 0
|
||||||
|
|
||||||
|
def paste(self) -> None:
|
||||||
|
self.paste_count += 1
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSoundPlayer:
|
||||||
|
"""Фейковый звуковой плеер — записывает вызовы."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.plays: list[SoundKind] = []
|
||||||
|
|
||||||
|
def play(self, kind: SoundKind, config: Config) -> None:
|
||||||
|
self.plays.append(kind)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeNotifier:
|
||||||
|
"""Фейковый нотифаер — записывает уведомления."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.notifications: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
def show(self, title: str, message: str) -> None:
|
||||||
|
self.notifications.append((title, message))
|
||||||
|
|
||||||
|
|
||||||
|
class FakeHotkeyListener:
|
||||||
|
"""Фейковый слушатель хоткеев."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._callback: Callable[[], None] | None = None
|
||||||
|
self._hotkey: str = ""
|
||||||
|
self.started = False
|
||||||
|
|
||||||
|
def register(self, hotkey: str, callback: Callable[[], None]) -> bool:
|
||||||
|
self._hotkey = hotkey
|
||||||
|
self._callback = callback
|
||||||
|
return True
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self.started = True
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self.started = False
|
||||||
|
|
||||||
|
def trigger(self) -> None:
|
||||||
|
"""Вызывает зарегистрированный колбэк."""
|
||||||
|
if self._callback is not None:
|
||||||
|
self._callback()
|
||||||
1
tests/unit/__init__.py
Normal file
1
tests/unit/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
"""Unit-тесты."""
|
||||||
98
tests/unit/test_config.py
Normal file
98
tests/unit/test_config.py
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
"""Тесты конфигурации."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from voice_dictation.core.config import Config, ConfigStore
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_config_values() -> None:
|
||||||
|
"""Дефолтный конфиг имеет правильные значения."""
|
||||||
|
config = Config()
|
||||||
|
assert config.hotkey == "cmd+space"
|
||||||
|
assert config.model == "gpt-4o-mini-transcribe"
|
||||||
|
assert config.language == "ru"
|
||||||
|
assert config.auto_paste is True
|
||||||
|
assert config.paste_delay_ms == 80
|
||||||
|
assert config.volume == 0.6
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_missing_file_returns_defaults(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Загрузка несуществующего файла возвращает дефолтный конфиг."""
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
config = store.load()
|
||||||
|
assert config.hotkey == "cmd+space"
|
||||||
|
assert config.model == "gpt-4o-mini-transcribe"
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_and_load_roundtrip(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Сохранение и загрузка конфига — round-trip."""
|
||||||
|
original = Config(
|
||||||
|
hotkey="ctrl+shift+r",
|
||||||
|
model="whisper-1",
|
||||||
|
language="en",
|
||||||
|
auto_paste=False,
|
||||||
|
paste_delay_ms=150,
|
||||||
|
)
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
store.save(original)
|
||||||
|
|
||||||
|
store2 = ConfigStore(tmp_paths.config_file)
|
||||||
|
loaded = store2.load()
|
||||||
|
|
||||||
|
assert loaded.hotkey == "ctrl+shift+r"
|
||||||
|
assert loaded.model == "whisper-1"
|
||||||
|
assert loaded.language == "en"
|
||||||
|
assert loaded.auto_paste is False
|
||||||
|
assert loaded.paste_delay_ms == 150
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_with_path_fields(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Path-поля корректно сериализуются в JSON и обратно."""
|
||||||
|
sound_path = Path("/some/path/start.wav")
|
||||||
|
original = Config(start_sound_path=sound_path)
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
store.save(original)
|
||||||
|
|
||||||
|
# Проверяем что в JSON путь сохранён как строка
|
||||||
|
data = json.loads(tmp_paths.config_file.read_text())
|
||||||
|
assert data["start_sound_path"] == str(sound_path)
|
||||||
|
|
||||||
|
loaded = store.load()
|
||||||
|
assert loaded.start_sound_path == sound_path
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_raises_before_load(tmp_paths: AppPaths) -> None:
|
||||||
|
"""current() поднимает RuntimeError если load() не вызывался."""
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
with pytest.raises(RuntimeError, match="load"):
|
||||||
|
store.current()
|
||||||
|
|
||||||
|
|
||||||
|
def test_current_returns_after_load(tmp_paths: AppPaths) -> None:
|
||||||
|
"""current() возвращает конфиг после load()."""
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
config = store.load()
|
||||||
|
assert store.current() is config
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_ignores_unknown_keys(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Неизвестные ключи из будущих версий конфига игнорируются."""
|
||||||
|
data = {"hotkey": "cmd+alt+x", "future_unknown_key": "value"}
|
||||||
|
tmp_paths.config_file.write_text(json.dumps(data))
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
config = store.load()
|
||||||
|
assert config.hotkey == "cmd+alt+x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_corrupted_json_returns_defaults(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Повреждённый JSON файл → дефолтный конфиг (не падает)."""
|
||||||
|
tmp_paths.config_file.write_text("{ NOT VALID JSON }")
|
||||||
|
store = ConfigStore(tmp_paths.config_file)
|
||||||
|
config = store.load()
|
||||||
|
assert config.hotkey == "cmd+space"
|
||||||
69
tests/unit/test_dictionary.py
Normal file
69
tests/unit/test_dictionary.py
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
"""Тесты словаря подсказок."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_empty_if_file_missing(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Загрузка несуществующего файла возвращает пустой список."""
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
assert d.load() == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_words(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Загрузка слов из файла."""
|
||||||
|
tmp_paths.dictionary_file.write_text("FastAPI\nSQLAlchemy\n")
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
assert d.load() == ["FastAPI", "SQLAlchemy"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_ignores_comments(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Строки с # игнорируются."""
|
||||||
|
tmp_paths.dictionary_file.write_text("# Комментарий\nFastAPI\n# Ещё один\nPydantic\n")
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
assert d.load() == ["FastAPI", "Pydantic"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_ignores_empty_lines(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Пустые строки игнорируются."""
|
||||||
|
tmp_paths.dictionary_file.write_text("FastAPI\n\n\nPydantic\n")
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
assert d.load() == ["FastAPI", "Pydantic"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_prompt_empty_dict(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Пустой словарь → пустая строка prompt."""
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
assert d.build_prompt() == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_prompt_basic(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Базовая сборка prompt из слов."""
|
||||||
|
tmp_paths.dictionary_file.write_text("FastAPI\nPydantic\n")
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
prompt = d.build_prompt()
|
||||||
|
assert "FastAPI" in prompt
|
||||||
|
assert "Pydantic" in prompt
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_prompt_respects_limit(tmp_paths: AppPaths) -> None:
|
||||||
|
"""build_prompt не превышает max_chars."""
|
||||||
|
# Создаём словарь с многими длинными словами
|
||||||
|
words = [f"LongTechnicalTermNumber{i:03d}" for i in range(100)]
|
||||||
|
tmp_paths.dictionary_file.write_text("\n".join(words))
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
prompt = d.build_prompt(max_chars=100)
|
||||||
|
assert len(prompt) <= 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_prompt_takes_from_end(tmp_paths: AppPaths) -> None:
|
||||||
|
"""При переполнении берутся слова с конца (более специфичные)."""
|
||||||
|
# Создаём файл где последнее слово точно влезет
|
||||||
|
tmp_paths.dictionary_file.write_text(
|
||||||
|
"a" * 90 + "\nLastWord\n" # первое слово не влезет в 50 символов
|
||||||
|
)
|
||||||
|
d = Dictionary(tmp_paths.dictionary_file)
|
||||||
|
prompt = d.build_prompt(max_chars=50)
|
||||||
|
assert "LastWord" in prompt
|
||||||
222
tests/unit/test_orchestrator.py
Normal file
222
tests/unit/test_orchestrator.py
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
"""Тесты оркестратора — state-machine и DI."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
from tests.fakes.fake_components import (
|
||||||
|
FakeAutoPaste,
|
||||||
|
FakeClipboard,
|
||||||
|
FakeNotifier,
|
||||||
|
FakeRecorder,
|
||||||
|
FakeSoundPlayer,
|
||||||
|
FakeTranscriber,
|
||||||
|
)
|
||||||
|
from voice_dictation.core.config import Config
|
||||||
|
from voice_dictation.core.dictionary import Dictionary
|
||||||
|
from voice_dictation.core.enums import RecordingState, SoundKind
|
||||||
|
from voice_dictation.core.orchestrator import DictationOrchestrator
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
|
||||||
|
|
||||||
|
def _make_orchestrator(
|
||||||
|
tmp_paths: AppPaths,
|
||||||
|
recorder: FakeRecorder | None = None,
|
||||||
|
transcriber: FakeTranscriber | None = None,
|
||||||
|
clipboard: FakeClipboard | None = None,
|
||||||
|
auto_paste: FakeAutoPaste | None = None,
|
||||||
|
sound_player: FakeSoundPlayer | None = None,
|
||||||
|
notifier: FakeNotifier | None = None,
|
||||||
|
config: Config | None = None,
|
||||||
|
) -> DictationOrchestrator:
|
||||||
|
"""Вспомогательная функция — создаёт оркестратор с фейками."""
|
||||||
|
cfg = config or Config()
|
||||||
|
return DictationOrchestrator(
|
||||||
|
recorder=recorder or FakeRecorder(),
|
||||||
|
transcriber=transcriber or FakeTranscriber(),
|
||||||
|
dictionary=Dictionary(tmp_paths.dictionary_file),
|
||||||
|
clipboard=clipboard or FakeClipboard(),
|
||||||
|
auto_paste=auto_paste or FakeAutoPaste(),
|
||||||
|
sound_player=sound_player or FakeSoundPlayer(),
|
||||||
|
notifier=notifier or FakeNotifier(),
|
||||||
|
config_provider=lambda: cfg,
|
||||||
|
paths=tmp_paths,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_initial_state_is_idle(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Начальное состояние — IDLE."""
|
||||||
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
assert o.state == RecordingState.IDLE
|
||||||
|
|
||||||
|
|
||||||
|
def test_toggle_idle_to_recording(tmp_paths: AppPaths) -> None:
|
||||||
|
"""toggle() в IDLE переводит в RECORDING."""
|
||||||
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
o.toggle()
|
||||||
|
assert o.state == RecordingState.RECORDING
|
||||||
|
|
||||||
|
|
||||||
|
def test_toggle_recording_to_processing(tmp_paths: AppPaths) -> None:
|
||||||
|
"""toggle() в RECORDING переводит в PROCESSING."""
|
||||||
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
o.toggle() # → RECORDING
|
||||||
|
o.toggle() # → PROCESSING
|
||||||
|
assert o.state == RecordingState.PROCESSING
|
||||||
|
|
||||||
|
|
||||||
|
def test_toggle_processing_ignored(tmp_paths: AppPaths) -> None:
|
||||||
|
"""toggle() в PROCESSING игнорируется."""
|
||||||
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
o.toggle() # → RECORDING
|
||||||
|
o.toggle() # → PROCESSING
|
||||||
|
o.toggle() # должен быть проигнорирован
|
||||||
|
assert o.state == RecordingState.PROCESSING
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_cycle_idle_after_transcription(tmp_paths: AppPaths) -> None:
|
||||||
|
"""После успешной транскрипции возвращается в IDLE."""
|
||||||
|
clipboard = FakeClipboard()
|
||||||
|
o = _make_orchestrator(tmp_paths, clipboard=clipboard)
|
||||||
|
o.toggle() # → RECORDING
|
||||||
|
o.toggle() # → PROCESSING (запускает worker)
|
||||||
|
|
||||||
|
# Даём worker-потоку завершиться
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while o.state != RecordingState.IDLE and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert o.state == RecordingState.IDLE
|
||||||
|
assert len(clipboard.copy_calls) == 1
|
||||||
|
assert clipboard.copy_calls[0] == "Тестовый текст"
|
||||||
|
|
||||||
|
|
||||||
|
def test_autopaste_called_after_transcription(tmp_paths: AppPaths) -> None:
|
||||||
|
"""AutoPaste.paste() вызывается после успешной транскрипции."""
|
||||||
|
auto_paste = FakeAutoPaste()
|
||||||
|
o = _make_orchestrator(tmp_paths, auto_paste=auto_paste, config=Config(paste_delay_ms=0))
|
||||||
|
o.toggle()
|
||||||
|
o.toggle()
|
||||||
|
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while o.state != RecordingState.IDLE and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert auto_paste.paste_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_start_sound_played_on_record(tmp_paths: AppPaths) -> None:
|
||||||
|
"""START-звук воспроизводится при начале записи."""
|
||||||
|
sound_player = FakeSoundPlayer()
|
||||||
|
o = _make_orchestrator(tmp_paths, sound_player=sound_player)
|
||||||
|
o.toggle()
|
||||||
|
assert SoundKind.START in sound_player.plays
|
||||||
|
|
||||||
|
|
||||||
|
def test_stop_sound_played_on_stop(tmp_paths: AppPaths) -> None:
|
||||||
|
"""STOP-звук воспроизводится при остановке записи."""
|
||||||
|
sound_player = FakeSoundPlayer()
|
||||||
|
o = _make_orchestrator(tmp_paths, sound_player=sound_player)
|
||||||
|
o.toggle()
|
||||||
|
o.toggle()
|
||||||
|
assert SoundKind.STOP in sound_player.plays
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_on_recorder_start_failure(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Ошибка recorder.start() → остаёмся в IDLE."""
|
||||||
|
recorder = FakeRecorder(fail_start=True)
|
||||||
|
o = _make_orchestrator(tmp_paths, recorder=recorder)
|
||||||
|
o.toggle()
|
||||||
|
assert o.state == RecordingState.IDLE
|
||||||
|
|
||||||
|
|
||||||
|
def test_error_sound_on_recorder_start_failure(tmp_paths: AppPaths) -> None:
|
||||||
|
"""При ошибке recorder.start() воспроизводится ERROR-звук."""
|
||||||
|
recorder = FakeRecorder(fail_start=True)
|
||||||
|
sound_player = FakeSoundPlayer()
|
||||||
|
o = _make_orchestrator(tmp_paths, recorder=recorder, sound_player=sound_player)
|
||||||
|
o.toggle()
|
||||||
|
assert SoundKind.ERROR in sound_player.plays
|
||||||
|
|
||||||
|
|
||||||
|
def test_transcription_error_returns_to_idle(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Ошибка транскрипции → возврат в IDLE."""
|
||||||
|
transcriber = FakeTranscriber(fail=True)
|
||||||
|
o = _make_orchestrator(tmp_paths, transcriber=transcriber)
|
||||||
|
o.toggle()
|
||||||
|
o.toggle()
|
||||||
|
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while o.state != RecordingState.IDLE and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert o.state == RecordingState.IDLE
|
||||||
|
|
||||||
|
|
||||||
|
def test_transcription_error_shows_notification(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Ошибка транскрипции → показывается уведомление."""
|
||||||
|
transcriber = FakeTranscriber(fail=True)
|
||||||
|
notifier = FakeNotifier()
|
||||||
|
o = _make_orchestrator(tmp_paths, transcriber=transcriber, notifier=notifier)
|
||||||
|
o.toggle()
|
||||||
|
o.toggle()
|
||||||
|
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while o.state != RecordingState.IDLE and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert len(notifier.notifications) > 0
|
||||||
|
titles = [n[0] for n in notifier.notifications]
|
||||||
|
assert any("ошибк" in t.lower() for t in titles)
|
||||||
|
|
||||||
|
|
||||||
|
def test_state_listener_called_on_transitions(tmp_paths: AppPaths) -> None:
|
||||||
|
"""state_listener вызывается при каждой смене состояния."""
|
||||||
|
states: list[RecordingState] = []
|
||||||
|
o = DictationOrchestrator(
|
||||||
|
recorder=FakeRecorder(),
|
||||||
|
transcriber=FakeTranscriber(),
|
||||||
|
dictionary=Dictionary(tmp_paths.dictionary_file),
|
||||||
|
clipboard=FakeClipboard(),
|
||||||
|
auto_paste=FakeAutoPaste(),
|
||||||
|
sound_player=FakeSoundPlayer(),
|
||||||
|
notifier=FakeNotifier(),
|
||||||
|
config_provider=lambda: Config(paste_delay_ms=0),
|
||||||
|
paths=tmp_paths,
|
||||||
|
state_listener=states.append,
|
||||||
|
)
|
||||||
|
o.toggle() # IDLE → RECORDING
|
||||||
|
o.toggle() # RECORDING → PROCESSING
|
||||||
|
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while RecordingState.IDLE not in states[2:] and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert RecordingState.RECORDING in states
|
||||||
|
assert RecordingState.PROCESSING in states
|
||||||
|
assert RecordingState.IDLE in states
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_stops_recording(tmp_paths: AppPaths) -> None:
|
||||||
|
"""cancel() в RECORDING переводит в IDLE."""
|
||||||
|
o = _make_orchestrator(tmp_paths)
|
||||||
|
o.toggle()
|
||||||
|
assert o.state == RecordingState.RECORDING
|
||||||
|
o.cancel()
|
||||||
|
assert o.state == RecordingState.IDLE
|
||||||
|
|
||||||
|
|
||||||
|
def test_autopaste_skipped_for_long_text(tmp_paths: AppPaths) -> None:
|
||||||
|
"""Автовставка не выполняется если текст длиннее 10000 символов."""
|
||||||
|
long_text = "а" * 15000
|
||||||
|
transcriber = FakeTranscriber(text=long_text)
|
||||||
|
auto_paste = FakeAutoPaste()
|
||||||
|
o = _make_orchestrator(tmp_paths, transcriber=transcriber, auto_paste=auto_paste)
|
||||||
|
o.toggle()
|
||||||
|
o.toggle()
|
||||||
|
|
||||||
|
deadline = time.time() + 5
|
||||||
|
while o.state != RecordingState.IDLE and time.time() < deadline:
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert auto_paste.paste_count == 0
|
||||||
62
tests/unit/test_pricing.py
Normal file
62
tests/unit/test_pricing.py
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""Тесты расчёта стоимости транскрипции."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from voice_dictation.core.pricing import PriceCalculator
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_gpt4o_mini_one_minute() -> None:
|
||||||
|
"""Стоимость gpt-4o-mini-transcribe за 60 секунд."""
|
||||||
|
cost = PriceCalculator.cost("gpt-4o-mini-transcribe", 60.0)
|
||||||
|
assert cost == Decimal("0.003000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_gpt4o_transcribe_one_minute() -> None:
|
||||||
|
"""Стоимость gpt-4o-transcribe за 60 секунд."""
|
||||||
|
cost = PriceCalculator.cost("gpt-4o-transcribe", 60.0)
|
||||||
|
assert cost == Decimal("0.006000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_whisper1_one_minute() -> None:
|
||||||
|
"""Стоимость whisper-1 за 60 секунд."""
|
||||||
|
cost = PriceCalculator.cost("whisper-1", 60.0)
|
||||||
|
assert cost == Decimal("0.006000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_rounds_up_to_full_second() -> None:
|
||||||
|
"""Дробные секунды округляются вверх до целой секунды."""
|
||||||
|
# 1.5 сек → 2 сек
|
||||||
|
cost_fractional = PriceCalculator.cost("gpt-4o-mini-transcribe", 1.5)
|
||||||
|
cost_full = PriceCalculator.cost("gpt-4o-mini-transcribe", 2.0)
|
||||||
|
assert cost_fractional == cost_full
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_minimum_one_second() -> None:
|
||||||
|
"""Минимальная длительность — 1 секунда."""
|
||||||
|
cost_zero = PriceCalculator.cost("gpt-4o-mini-transcribe", 0.0)
|
||||||
|
cost_one = PriceCalculator.cost("gpt-4o-mini-transcribe", 1.0)
|
||||||
|
assert cost_zero == cost_one
|
||||||
|
assert cost_zero > Decimal("0")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_thirty_seconds() -> None:
|
||||||
|
"""30 секунд = половина минуты."""
|
||||||
|
cost = PriceCalculator.cost("gpt-4o-mini-transcribe", 30.0)
|
||||||
|
expected = Decimal("0.003000") * Decimal("30") / Decimal("60")
|
||||||
|
assert cost == expected.quantize(Decimal("0.000001"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_cost_unknown_model_raises() -> None:
|
||||||
|
"""Неизвестная модель поднимает KeyError."""
|
||||||
|
with pytest.raises(KeyError):
|
||||||
|
PriceCalculator.cost("unknown-model", 10.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_prices_immutable() -> None:
|
||||||
|
"""PRICES_PER_MINUTE нельзя изменить (MappingProxyType)."""
|
||||||
|
with pytest.raises(TypeError):
|
||||||
|
PriceCalculator.PRICES_PER_MINUTE["new-model"] = Decimal("1.0") # type: ignore[index]
|
||||||
76
tests/unit/test_usage_db.py
Normal file
76
tests/unit/test_usage_db.py
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
"""Тесты для UsageDB."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from voice_dictation.core.models import UsageRecord
|
||||||
|
from voice_dictation.core.paths import AppPaths
|
||||||
|
from voice_dictation.core.usage_db import UsageDB
|
||||||
|
|
||||||
|
|
||||||
|
def _record(when: datetime, duration: float = 5.0, cost: str = "0.001") -> UsageRecord:
|
||||||
|
return UsageRecord(
|
||||||
|
id=None,
|
||||||
|
created_at=when,
|
||||||
|
duration_sec=duration,
|
||||||
|
cost_usd=Decimal(cost),
|
||||||
|
model="gpt-4o-mini-transcribe",
|
||||||
|
text_preview="hello",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_insert_assigns_id(tmp_paths: AppPaths) -> None:
|
||||||
|
db = UsageDB(tmp_paths.usage_db)
|
||||||
|
record = db.insert(_record(datetime.now(UTC)))
|
||||||
|
assert record.id is not None
|
||||||
|
assert record.id >= 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_today_total_aggregates(tmp_paths: AppPaths) -> None:
|
||||||
|
db = UsageDB(tmp_paths.usage_db)
|
||||||
|
now = datetime.now(UTC)
|
||||||
|
db.insert(_record(now, duration=10.0, cost="0.001"))
|
||||||
|
db.insert(_record(now, duration=20.0, cost="0.002"))
|
||||||
|
db.insert(_record(now - timedelta(days=2), duration=999.0, cost="0.5"))
|
||||||
|
|
||||||
|
today = db.today_total(tz=UTC)
|
||||||
|
assert today.count == 2
|
||||||
|
assert today.total_duration_sec == 30.0
|
||||||
|
assert today.total_cost_usd == Decimal("0.003000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_recent_returns_newest_first(tmp_paths: AppPaths) -> None:
|
||||||
|
db = UsageDB(tmp_paths.usage_db)
|
||||||
|
base = datetime.now(UTC)
|
||||||
|
for i in range(5):
|
||||||
|
db.insert(_record(base + timedelta(seconds=i)))
|
||||||
|
|
||||||
|
recent = db.recent(limit=3)
|
||||||
|
assert len(recent) == 3
|
||||||
|
assert recent[0].id is not None
|
||||||
|
assert recent[0].id > recent[1].id > recent[2].id
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_time_includes_old_records(tmp_paths: AppPaths) -> None:
|
||||||
|
db = UsageDB(tmp_paths.usage_db)
|
||||||
|
db.insert(_record(datetime.now(UTC) - timedelta(days=400), duration=60.0, cost="0.01"))
|
||||||
|
db.insert(_record(datetime.now(UTC), duration=30.0, cost="0.005"))
|
||||||
|
|
||||||
|
total = db.all_time()
|
||||||
|
assert total.count == 2
|
||||||
|
assert total.total_duration_sec == 90.0
|
||||||
|
assert total.total_cost_usd == Decimal("0.015000")
|
||||||
|
|
||||||
|
|
||||||
|
def test_month_stats_filters_correctly(tmp_paths: AppPaths) -> None:
|
||||||
|
db = UsageDB(tmp_paths.usage_db)
|
||||||
|
in_month = datetime(2026, 4, 15, 12, 0, tzinfo=UTC)
|
||||||
|
other_month = datetime(2026, 3, 15, 12, 0, tzinfo=UTC)
|
||||||
|
db.insert(_record(in_month, duration=10.0))
|
||||||
|
db.insert(_record(other_month, duration=999.0))
|
||||||
|
|
||||||
|
stats = db.month_stats(2026, 4, tz=UTC)
|
||||||
|
assert stats.count == 1
|
||||||
|
assert stats.total_duration_sec == 10.0
|
||||||
Loading…
Reference in a new issue