voice-dictation/src/voice_dictation/ui/recognition_tab.py

222 lines
9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

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

"""Recognition preferences and asynchronous model downloads."""
from __future__ import annotations
import queue
import threading
import time
from collections.abc import Callable
from dataclasses import replace
from datetime import datetime
import customtkinter as ctk
from voice_dictation.core.config import ConfigStore
from voice_dictation.core.model_manager import CATALOG, DownloadCancelled, ModelError, 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 = {m.name: 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; только CPU/Metal, macOS arm64 beta):"
).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
started = 0.0
received = 0
total_bytes = 0
last_update = 0.0
buttons: list[ctk.CTkButton] = []
journal = ctk.CTkTextbox(parent, width=620, height=100)
journal.pack(anchor="w", padx=12, pady=6)
journal.configure(state="disabled")
def note(message: str) -> None:
journal.configure(state="normal")
journal.insert("end", f"{datetime.now():%H:%M:%S} {message}\n")
if int(journal.index("end-1c").split(".")[0]) > 100:
journal.delete("1.0", "2.0")
journal.see("end")
journal.configure(state="disabled")
stages = {
"checking": "Проверяю установленную модель…",
"connecting": "Подключаюсь к серверу моделей…",
"downloading": "Получаю файл модели…",
"verifying": "Проверяю целостность скачанного файла…",
}
def progress(done: int, total: int) -> None:
nonlocal received, total_bytes, last_update
received, total_bytes = done, total
now = time.monotonic()
if now - last_update >= 0.2 or done == total:
events.put(("progress", done / total if total else 0))
last_update = now
def worker(action: str, model_id: str) -> None:
try:
if action == "download":
manager.download(
model_id,
progress=progress,
stage=lambda name: events.put((stages[name], -2)),
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 DownloadCancelled:
events.put(("Загрузка отменена. Незавершённый файл удалён.", 0))
except ModelError as exc:
events.put((str(exc), -1))
except Exception:
events.put(("Не удалось выполнить операцию. Подробности — в журнале приложения.", -1))
def start(action: str) -> None:
nonlocal busy, started, received, total_bytes, last_update
if busy:
return
busy = True
started = time.monotonic()
received = total_bytes = 0
last_update = 0.0
cancel.clear()
cancel_button.configure(state="normal" if action == "download" else "disabled")
for button in buttons:
button.configure(state="disabled")
message = {
"check": "Проверяю модель…",
"download": "Подготавливаю загрузку…",
"delete": "Удаляю модель…",
}[action]
status.configure(text=message)
bar.set(0)
note(f"{selected.get()}: {message}")
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)
elapsed = max(0.1, time.monotonic() - started)
if not cancel.is_set():
status.configure(
text=f"Скачивание: {value:.1%} · {received / 1_000_000:.1f} / "
f"{total_bytes / 1_000_000:.1f} МБ · "
f"{received / elapsed / 1_000_000:.1f} МБ/с"
)
elif value == -2:
note(message)
if not cancel.is_set():
status.configure(text=message)
else:
note(message)
cancel_button.configure(state="disabled")
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)
def request_cancel() -> None:
if not busy or cancel.is_set():
return
cancel.set()
status.configure(text="Отменяю загрузку… Закрываю соединение и удаляю временный файл.")
note("Отмена запрошена; ожидаю завершения операции…")
cancel_button.configure(state="disabled")
cancel_button = ctk.CTkButton(
row, text="Отменить", width=100, command=request_cancel, state="disabled"
)
cancel_button.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(
"<Destroy>", lambda event: cancel.set() if event.widget == parent else None, add="+"
)
parent.after(100, poll)