From 9c28557b743464771f905bcb4640733cd2a50766 Mon Sep 17 00:00:00 2001 From: Vickenty Zherebov Date: Mon, 19 Oct 2026 14:54:43 +0300 Subject: [PATCH] Connect model leases and offline file diagnostics --- src/voice_dictation/__main__.py | 6 ++ src/voice_dictation/cli/transcribe_file.py | 30 ++++++++ src/voice_dictation/core/local_transcriber.py | 7 +- src/voice_dictation/core/orchestrator.py | 22 ++++-- src/voice_dictation/core/paths.py | 6 +- src/voice_dictation/core/transcription.py | 21 ++++-- .../infrastructure/env_loader.py | 1 - src/voice_dictation/ui/recognition_tab.py | 69 +++++++++++++++---- src/voice_dictation/ui/settings_window.py | 4 +- 9 files changed, 137 insertions(+), 29 deletions(-) create mode 100644 src/voice_dictation/cli/transcribe_file.py diff --git a/src/voice_dictation/__main__.py b/src/voice_dictation/__main__.py index 67b72ec..32601e5 100644 --- a/src/voice_dictation/__main__.py +++ b/src/voice_dictation/__main__.py @@ -20,6 +20,12 @@ def main() -> None: Если в argv передана подкоманда `headless` или `stats` — делегирует CLI. """ + if len(sys.argv) > 1 and sys.argv[1] == "transcribe-file": + from voice_dictation.cli.transcribe_file import main as transcribe_main + + transcribe_main(sys.argv[2:]) + return + if len(sys.argv) > 1 and sys.argv[1] == "settings": from voice_dictation.ui.settings_cli import main as settings_main diff --git a/src/voice_dictation/cli/transcribe_file.py b/src/voice_dictation/cli/transcribe_file.py new file mode 100644 index 0000000..59a7101 --- /dev/null +++ b/src/voice_dictation/cli/transcribe_file.py @@ -0,0 +1,30 @@ +"""Explicit offline file transcription for beta diagnostics and benchmarks.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +from voice_dictation.core.model_manager import CATALOG, ModelManager +from voice_dictation.core.paths import AppPaths +from voice_dictation.core.transcription import RoutingTranscriber + + +def main(arguments: list[str] | None = None) -> None: + """Transcribe a user-selected file locally, without loading cloud keys.""" + parser = argparse.ArgumentParser(description="Локально распознать выбранный файл") + parser.add_argument("audio", type=Path) + parser.add_argument("--model", choices=[m.id for m in CATALOG], default="whisper-base") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--download", action="store_true", help="Скачать модель при необходимости") + args = parser.parse_args(arguments) + paths = AppPaths.default().ensure_exists() + manager = ModelManager(paths.models_dir) + if args.download and not manager.is_installed(args.model): + manager.download(args.model) + result = RoutingTranscriber("", paths.models_dir).transcribe( + args.audio, model=f"local:{args.model}", language="ru" + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(result.text, encoding="utf-8") + print(f"Локальная транскрипция завершена: {args.output}") diff --git a/src/voice_dictation/core/local_transcriber.py b/src/voice_dictation/core/local_transcriber.py index 41d8b66..6558116 100644 --- a/src/voice_dictation/core/local_transcriber.py +++ b/src/voice_dictation/core/local_transcriber.py @@ -133,7 +133,12 @@ class LocalTranscriber: @staticmethod def _run(command: list[str], timeout: float) -> None: try: - completed = subprocess.run(command, capture_output=True, timeout=timeout, check=False) + environment = os.environ.copy() + if hasattr(sys, "_MEIPASS"): + environment["GGML_BACKEND_PATH"] = str(Path(sys._MEIPASS) / "bin") + completed = subprocess.run( + command, capture_output=True, timeout=timeout, check=False, env=environment + ) except subprocess.TimeoutExpired as exc: raise TranscriptionError("Локальное распознавание превысило время ожидания") from exc except OSError as exc: diff --git a/src/voice_dictation/core/orchestrator.py b/src/voice_dictation/core/orchestrator.py index be20ebe..b1e7c2d 100644 --- a/src/voice_dictation/core/orchestrator.py +++ b/src/voice_dictation/core/orchestrator.py @@ -321,6 +321,14 @@ class DictationOrchestrator: "vad_noise_db": config.vad_noise_db, "dictionary": self._dictionary.build_prompt(), } + if local: + from voice_dictation.core.model_manager import CATALOG + + spec = next((item for item in CATALOG if item.id == config.local_model), None) + if spec is None: + raise TranscriptionError("Неизвестная локальная модель") + identity["model_sha256"] = spec.sha256 + identity["runtime"] = "whisper.cpp-cli-json-v1" previous = self._session_store.read(session_dir) old_identity = previous.get("transcription_identity") if old_identity is not None and old_identity != identity: @@ -416,8 +424,10 @@ class DictationOrchestrator: config: Config, ) -> ChunkingResult: if recording.duration_sec <= config.chunk_duration_sec: - if (config.transcription_backend != "local" - and audio_source.stat().st_size > WHISPER_FILE_SIZE_LIMIT_BYTES): + if ( + config.transcription_backend != "local" + and audio_source.stat().st_size > WHISPER_FILE_SIZE_LIMIT_BYTES + ): raise CompressionError("Аудиофайл больше 25 МБ, а нарезка не была выполнена") return ChunkingResult( chunks=(AudioChunk(0, audio_source, 0.0, recording.duration_sec),), @@ -511,8 +521,12 @@ class DictationOrchestrator: # Post-processing через активный пресет (если есть и не пустой) final_text = result.text active = self._resolve_active_preset(config) - if (config.transcription_backend != "local" - and active is not None and active.prompt.strip() and active.model.strip()): + if ( + config.transcription_backend != "local" + and active is not None + and active.prompt.strip() + and active.model.strip() + ): try: final_text = self._summarize(result.text, active) logger.info( diff --git a/src/voice_dictation/core/paths.py b/src/voice_dictation/core/paths.py index dc8147d..3099f58 100644 --- a/src/voice_dictation/core/paths.py +++ b/src/voice_dictation/core/paths.py @@ -43,8 +43,10 @@ class AppPaths: 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" + root = ( + Path(override).expanduser() + if override + else Path.home() / (".dictate-beta" if beta else ".dictate") ) return cls( root=root, diff --git a/src/voice_dictation/core/transcription.py b/src/voice_dictation/core/transcription.py index 719faa4..fa3f3f8 100644 --- a/src/voice_dictation/core/transcription.py +++ b/src/voice_dictation/core/transcription.py @@ -23,6 +23,10 @@ class Transcriber(Protocol): """Return recognized text or raise a transcription error.""" ... + def close(self) -> None: + """Release resources.""" + ... + class RoutingTranscriber: """Dispatch by model identity; local failures never fall back to cloud.""" @@ -49,17 +53,24 @@ class RoutingTranscriber: manager = ModelManager(self._models_dir) model_id = model.removeprefix("local:") - if not manager.is_installed(model_id): - raise TranscriptionError("Скачайте выбранную модель в Настройки → Распознавание") - engine = LocalTranscriber(manager.path_for(model_id)) + try: + with manager.use(model_id) as model_path: + local_engine = LocalTranscriber(model_path) + return local_engine.transcribe( + audio_path, prompt, language, model, duration_sec + ) + except RuntimeError as exc: + raise TranscriptionError(str(exc)) from exc else: from voice_dictation.core.transcriber import WhisperTranscriber if not self._api_key: - raise TranscriptionError("Для OpenAI укажите OPENAI_API_KEY или выберите локальный режим") + raise TranscriptionError( + "Для OpenAI укажите OPENAI_API_KEY или выберите локальный режим" + ) engine = WhisperTranscriber(api_key=self._api_key, model=model) try: return engine.transcribe(audio_path, prompt, language, model, duration_sec) finally: # Both concrete implementations own disposable resources. - engine.close() # type: ignore[attr-defined] + engine.close() diff --git a/src/voice_dictation/infrastructure/env_loader.py b/src/voice_dictation/infrastructure/env_loader.py index b209cfb..be86fc3 100644 --- a/src/voice_dictation/infrastructure/env_loader.py +++ b/src/voice_dictation/infrastructure/env_loader.py @@ -10,7 +10,6 @@ from pathlib import Path from dotenv import load_dotenv - @dataclass(frozen=True, slots=True) class EnvConfig: """Конфигурация из переменных окружения. diff --git a/src/voice_dictation/ui/recognition_tab.py b/src/voice_dictation/ui/recognition_tab.py index 3b1d938..732414e 100644 --- a/src/voice_dictation/ui/recognition_tab.py +++ b/src/voice_dictation/ui/recognition_tab.py @@ -24,19 +24,31 @@ def build_recognition_tab( 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") + 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.CTkOptionMenu(parent, values=["Локально", "OpenAI API"], variable=backend).pack( + anchor="w", padx=12 + ) ctk.CTkLabel( - parent, text="Локально: аудио и текст не отправляются в облако.\n" + parent, + text="Локально: аудио и текст не отправляются в облако.\n" "Облачные стили обработки отключены. Наш сервер — в следующем этапе.", - justify="left", wraplength=620, + 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) + 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) @@ -49,15 +61,27 @@ def build_recognition_tab( 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) + 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)) + events.put( + ( + "Модель установлена и проверена." + if installed + else "Модель ещё не скачана.", + 1 if installed else 0, + ) + ) except Exception as exc: events.put((str(exc), -1)) @@ -82,7 +106,9 @@ def build_recognition_tab( message, value = events.get_nowait() if message == "progress": bar.set(value) - status.configure(text=f"Скачивание: {value:.0%}. После загрузки — проверка файла.") + status.configure( + text=f"Скачивание: {value:.0%}. После загрузки — проверка файла." + ) else: status.configure(text=message) bar.set(max(0, value)) @@ -102,11 +128,24 @@ def build_recognition_tab( 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()]) + 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="+") + 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 001520f..b5c346d 100644 --- a/src/voice_dictation/ui/settings_window.py +++ b/src/voice_dictation/ui/settings_window.py @@ -286,7 +286,9 @@ class SettingsWindow: hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8) row += 1 - ctk.CTkLabel(parent, text="Модель OpenAI:").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