From 0d95cca4377b661e23fcef19146ea139dd76a009 Mon Sep 17 00:00:00 2001 From: Vickenty Zherebov Date: Mon, 19 Oct 2026 14:53:29 +0300 Subject: [PATCH] Add isolated beta preferences and recognition model controls --- src/voice_dictation/__main__.py | 5 + src/voice_dictation/cli/headless.py | 5 + src/voice_dictation/core/config.py | 8 +- src/voice_dictation/core/paths.py | 15 ++- src/voice_dictation/ui/recognition_tab.py | 112 ++++++++++++++++++++++ src/voice_dictation/ui/settings_window.py | 8 +- 6 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 src/voice_dictation/ui/recognition_tab.py diff --git a/src/voice_dictation/__main__.py b/src/voice_dictation/__main__.py index 268ecf2..67b72ec 100644 --- a/src/voice_dictation/__main__.py +++ b/src/voice_dictation/__main__.py @@ -66,6 +66,11 @@ def main() -> None: config_store = ConfigStore(paths.config_file) config = config_store.load() + if not paths.config_file.exists() and paths.root.name == ".dictate-beta": + config.transcription_backend = "local" + config.hotkey = "cmd+alt+shift+d" + config.splash_enabled = False + config_store.save(config) logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model) if config.splash_enabled: diff --git a/src/voice_dictation/cli/headless.py b/src/voice_dictation/cli/headless.py index 5265965..f79c5e6 100644 --- a/src/voice_dictation/cli/headless.py +++ b/src/voice_dictation/cli/headless.py @@ -51,6 +51,11 @@ def main() -> None: config_store = ConfigStore(paths.config_file) config = config_store.load() + if not paths.config_file.exists() and paths.root.name == ".dictate-beta": + config.transcription_backend = "local" + config.hotkey = "cmd+alt+shift+d" + config.splash_enabled = False + config_store.save(config) logger.info("Конфиг загружен: hotkey=%s, model=%s", config.hotkey, config.model) # 6. Платформенные компоненты diff --git a/src/voice_dictation/core/config.py b/src/voice_dictation/core/config.py index 5966651..9b052fc 100644 --- a/src/voice_dictation/core/config.py +++ b/src/voice_dictation/core/config.py @@ -96,6 +96,8 @@ class Config: hotkey: str = "cmd+alt+d" model: str = "gpt-4o-mini-transcribe" + transcription_backend: str = "openai" + local_model: str = "whisper-base" language: str | None = "ru" notifications_enabled: bool = True show_cost_in_notification: bool = True @@ -212,6 +214,8 @@ class ConfigStore: try: with self._path.open(encoding="utf-8") as fh: data = json.load(fh) + if not isinstance(data, dict): + raise TypeError("Конфигурация должна быть JSON-объектом") self._current = _config_from_dict(data) except (json.JSONDecodeError, TypeError) as exc: logger.warning("Не удалось загрузить конфиг, использую дефолтный: %s", exc) @@ -228,8 +232,10 @@ class ConfigStore: """ self._path.parent.mkdir(parents=True, exist_ok=True) data = _config_to_dict(config) - with self._path.open("w", encoding="utf-8") as fh: + temporary = self._path.with_suffix(".json.tmp") + with temporary.open("w", encoding="utf-8") as fh: json.dump(data, fh, indent=2, ensure_ascii=False) + temporary.replace(self._path) self._current = config logger.debug("Конфиг сохранён в %s", self._path) diff --git a/src/voice_dictation/core/paths.py b/src/voice_dictation/core/paths.py index f8d28f6..dc8147d 100644 --- a/src/voice_dictation/core/paths.py +++ b/src/voice_dictation/core/paths.py @@ -2,6 +2,8 @@ from __future__ import annotations +import os +import sys from dataclasses import dataclass from pathlib import Path @@ -37,7 +39,13 @@ class AppPaths: Returns: AppPaths с путями в ~/.dictate/. """ - root = Path.home() / ".dictate" + override = os.environ.get("VOICE_DICTATION_HOME") + beta = bool(getattr(sys, "frozen", False)) and any( + parent.name == "Voice Dictation Beta.app" for parent in Path(sys.executable).parents + ) + root = Path(override).expanduser() if override else Path.home() / ( + ".dictate-beta" if beta else ".dictate" + ) return cls( root=root, config_file=root / "config.json", @@ -74,3 +82,8 @@ class AppPaths: def bin_dir(self) -> Path: """Downloaded helper binaries, preserved across application updates.""" return self.root / "bin" + + @property + def models_dir(self) -> Path: + """Downloaded models are independent of the application bundle.""" + return self.root / "models" diff --git a/src/voice_dictation/ui/recognition_tab.py b/src/voice_dictation/ui/recognition_tab.py new file mode 100644 index 0000000..3b1d938 --- /dev/null +++ b/src/voice_dictation/ui/recognition_tab.py @@ -0,0 +1,112 @@ +"""Recognition preferences and asynchronous model downloads.""" + +from __future__ import annotations + +import queue +import threading +from collections.abc import Callable +from dataclasses import replace + +import customtkinter as ctk + +from voice_dictation.core.config import ConfigStore +from voice_dictation.core.model_manager import CATALOG, ModelManager +from voice_dictation.core.paths import AppPaths + + +def build_recognition_tab( + parent: ctk.CTkFrame, + store: ConfigStore, + paths: AppPaths, + toast: Callable[[str], None], +) -> None: + """Build controls; all widget updates stay on the Tk main thread.""" + config = store.load() + manager = ModelManager(paths.models_dir) + labels = {f"{m.name} — {m.size_bytes / 1048576:.0f} МБ": m.id for m in CATALOG} + initial_label = next((k for k, v in labels.items() if v == config.local_model), next(iter(labels))) + backend = ctk.StringVar(value="Локально" if config.transcription_backend == "local" else "OpenAI API") + selected = ctk.StringVar(value=initial_label) + ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4)) + ctk.CTkOptionMenu(parent, values=["Локально", "OpenAI API"], variable=backend).pack(anchor="w", padx=12) + ctk.CTkLabel( + parent, text="Локально: аудио и текст не отправляются в облако.\n" + "Облачные стили обработки отключены. Наш сервер — в следующем этапе.", + justify="left", wraplength=620, + ).pack(anchor="w", padx=12, pady=8) + ctk.CTkLabel(parent, text="Локальная модель (Whisper):").pack(anchor="w", padx=12) + ctk.CTkOptionMenu(parent, values=list(labels), variable=selected, width=460).pack(anchor="w", padx=12, pady=6) + status = ctk.CTkLabel(parent, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620) + status.pack(anchor="w", padx=12, pady=6) + bar = ctk.CTkProgressBar(parent, width=460) + bar.set(0) + bar.pack(anchor="w", padx=12, pady=6) + events: queue.Queue[tuple[str, float]] = queue.Queue() + cancel = threading.Event() + busy = False + buttons: list[ctk.CTkButton] = [] + + def worker(action: str, model_id: str) -> None: + try: + if action == "download": + manager.download(model_id, progress=lambda done, total: events.put( + ("progress", done / total if total else 0)), cancel=cancel) + events.put(("Модель скачана и проверена. Можно использовать.", 1)) + elif action == "delete": + manager.delete(model_id) + events.put(("Модель удалена.", 0)) + else: + installed = manager.is_installed(model_id) + events.put(("Модель установлена и проверена." if installed else "Модель ещё не скачана.", 1 if installed else 0)) + except Exception as exc: + events.put((str(exc), -1)) + + def start(action: str) -> None: + nonlocal busy + if busy: + return + busy = True + cancel.clear() + for button in buttons: + button.configure(state="disabled") + status.configure(text="Проверяю модель…" if action == "check" else "Выполняю…") + threading.Thread(target=worker, args=(action, labels[selected.get()]), daemon=True).start() + + def poll() -> None: + nonlocal busy + if not parent.winfo_exists(): + cancel.set() + return + try: + while True: + message, value = events.get_nowait() + if message == "progress": + bar.set(value) + status.configure(text=f"Скачивание: {value:.0%}. После загрузки — проверка файла.") + else: + status.configure(text=message) + bar.set(max(0, value)) + busy = False + for button in buttons: + button.configure(state="normal") + except queue.Empty: + pass + parent.after(100, poll) + + row = ctk.CTkFrame(parent, fg_color="transparent") + row.pack(anchor="w", padx=12, pady=6) + for title, action in [("Скачать", "download"), ("Проверить", "check"), ("Удалить", "delete")]: + button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a)) + button.pack(side="left", padx=(0, 6)) + buttons.append(button) + ctk.CTkButton(row, text="Отменить", width=100, command=cancel.set).pack(side="left") + + def save() -> None: + updated = replace(store.load(), transcription_backend="local" if backend.get() == "Локально" else "openai", local_model=labels[selected.get()]) + store.save(updated) + toast("Сохранено. Новый режим применяется к следующей записи.") + + ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save).pack(anchor="w", padx=12, pady=12) + ctk.CTkLabel(parent, text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}", justify="left", wraplength=620).pack(anchor="w", padx=12) + parent.bind("", lambda event: cancel.set() if event.widget == parent else None, add="+") + parent.after(100, poll) diff --git a/src/voice_dictation/ui/settings_window.py b/src/voice_dictation/ui/settings_window.py index 4c6404f..001520f 100644 --- a/src/voice_dictation/ui/settings_window.py +++ b/src/voice_dictation/ui/settings_window.py @@ -225,7 +225,7 @@ class SettingsWindow: self._root = ctk.CTk() self._root.title("Voice Dictation — настройки") - self._root.geometry("720x560") + self._root.geometry("820x680") # Принудительно вытаскиваем окно на передний план — иначе в bundle # с LSUIElement=true Tk-окно создаётся, но прячется за активным приложением. @@ -242,6 +242,7 @@ class SettingsWindow: tabs = ctk.CTkTabview(self._root) tabs.pack(fill="both", expand=True, padx=12, pady=12) + recognition_tab = tabs.add("Распознавание") general_tab = tabs.add("Общие") styles_tab = tabs.add("Стили") sound_tab = tabs.add("Звук") @@ -250,6 +251,9 @@ class SettingsWindow: balance_tab = tabs.add("Баланс") about_tab = tabs.add("О проекте") + from voice_dictation.ui.recognition_tab import build_recognition_tab + + build_recognition_tab(recognition_tab, self._config_store, self._paths, self._toast) self._build_general_tab(general_tab, config) self._build_styles_tab(styles_tab, config) self._build_sound_tab(sound_tab, config) @@ -282,7 +286,7 @@ class SettingsWindow: 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) + ctk.CTkLabel(parent, text="Модель OpenAI:").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