Connect model leases and offline file diagnostics
This commit is contained in:
parent
ec51abcc10
commit
9c28557b74
9 changed files with 137 additions and 29 deletions
|
|
@ -20,6 +20,12 @@ def main() -> None:
|
||||||
|
|
||||||
Если в argv передана подкоманда `headless` или `stats` — делегирует CLI.
|
Если в 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":
|
if len(sys.argv) > 1 and sys.argv[1] == "settings":
|
||||||
from voice_dictation.ui.settings_cli import main as settings_main
|
from voice_dictation.ui.settings_cli import main as settings_main
|
||||||
|
|
||||||
|
|
|
||||||
30
src/voice_dictation/cli/transcribe_file.py
Normal file
30
src/voice_dictation/cli/transcribe_file.py
Normal file
|
|
@ -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}")
|
||||||
|
|
@ -133,7 +133,12 @@ class LocalTranscriber:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _run(command: list[str], timeout: float) -> None:
|
def _run(command: list[str], timeout: float) -> None:
|
||||||
try:
|
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:
|
except subprocess.TimeoutExpired as exc:
|
||||||
raise TranscriptionError("Локальное распознавание превысило время ожидания") from exc
|
raise TranscriptionError("Локальное распознавание превысило время ожидания") from exc
|
||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
|
|
|
||||||
|
|
@ -321,6 +321,14 @@ class DictationOrchestrator:
|
||||||
"vad_noise_db": config.vad_noise_db,
|
"vad_noise_db": config.vad_noise_db,
|
||||||
"dictionary": self._dictionary.build_prompt(),
|
"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)
|
previous = self._session_store.read(session_dir)
|
||||||
old_identity = previous.get("transcription_identity")
|
old_identity = previous.get("transcription_identity")
|
||||||
if old_identity is not None and old_identity != identity:
|
if old_identity is not None and old_identity != identity:
|
||||||
|
|
@ -416,8 +424,10 @@ class DictationOrchestrator:
|
||||||
config: Config,
|
config: Config,
|
||||||
) -> ChunkingResult:
|
) -> ChunkingResult:
|
||||||
if recording.duration_sec <= config.chunk_duration_sec:
|
if recording.duration_sec <= config.chunk_duration_sec:
|
||||||
if (config.transcription_backend != "local"
|
if (
|
||||||
and audio_source.stat().st_size > WHISPER_FILE_SIZE_LIMIT_BYTES):
|
config.transcription_backend != "local"
|
||||||
|
and audio_source.stat().st_size > WHISPER_FILE_SIZE_LIMIT_BYTES
|
||||||
|
):
|
||||||
raise CompressionError("Аудиофайл больше 25 МБ, а нарезка не была выполнена")
|
raise CompressionError("Аудиофайл больше 25 МБ, а нарезка не была выполнена")
|
||||||
return ChunkingResult(
|
return ChunkingResult(
|
||||||
chunks=(AudioChunk(0, audio_source, 0.0, recording.duration_sec),),
|
chunks=(AudioChunk(0, audio_source, 0.0, recording.duration_sec),),
|
||||||
|
|
@ -511,8 +521,12 @@ class DictationOrchestrator:
|
||||||
# Post-processing через активный пресет (если есть и не пустой)
|
# Post-processing через активный пресет (если есть и не пустой)
|
||||||
final_text = result.text
|
final_text = result.text
|
||||||
active = self._resolve_active_preset(config)
|
active = self._resolve_active_preset(config)
|
||||||
if (config.transcription_backend != "local"
|
if (
|
||||||
and active is not None and active.prompt.strip() and active.model.strip()):
|
config.transcription_backend != "local"
|
||||||
|
and active is not None
|
||||||
|
and active.prompt.strip()
|
||||||
|
and active.model.strip()
|
||||||
|
):
|
||||||
try:
|
try:
|
||||||
final_text = self._summarize(result.text, active)
|
final_text = self._summarize(result.text, active)
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|
|
||||||
|
|
@ -43,8 +43,10 @@ class AppPaths:
|
||||||
beta = bool(getattr(sys, "frozen", False)) and any(
|
beta = bool(getattr(sys, "frozen", False)) and any(
|
||||||
parent.name == "Voice Dictation Beta.app" for parent in Path(sys.executable).parents
|
parent.name == "Voice Dictation Beta.app" for parent in Path(sys.executable).parents
|
||||||
)
|
)
|
||||||
root = Path(override).expanduser() if override else Path.home() / (
|
root = (
|
||||||
".dictate-beta" if beta else ".dictate"
|
Path(override).expanduser()
|
||||||
|
if override
|
||||||
|
else Path.home() / (".dictate-beta" if beta else ".dictate")
|
||||||
)
|
)
|
||||||
return cls(
|
return cls(
|
||||||
root=root,
|
root=root,
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,10 @@ class Transcriber(Protocol):
|
||||||
"""Return recognized text or raise a transcription error."""
|
"""Return recognized text or raise a transcription error."""
|
||||||
...
|
...
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Release resources."""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
class RoutingTranscriber:
|
class RoutingTranscriber:
|
||||||
"""Dispatch by model identity; local failures never fall back to cloud."""
|
"""Dispatch by model identity; local failures never fall back to cloud."""
|
||||||
|
|
@ -49,17 +53,24 @@ class RoutingTranscriber:
|
||||||
|
|
||||||
manager = ModelManager(self._models_dir)
|
manager = ModelManager(self._models_dir)
|
||||||
model_id = model.removeprefix("local:")
|
model_id = model.removeprefix("local:")
|
||||||
if not manager.is_installed(model_id):
|
try:
|
||||||
raise TranscriptionError("Скачайте выбранную модель в Настройки → Распознавание")
|
with manager.use(model_id) as model_path:
|
||||||
engine = LocalTranscriber(manager.path_for(model_id))
|
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:
|
else:
|
||||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||||
|
|
||||||
if not self._api_key:
|
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)
|
engine = WhisperTranscriber(api_key=self._api_key, model=model)
|
||||||
try:
|
try:
|
||||||
return engine.transcribe(audio_path, prompt, language, model, duration_sec)
|
return engine.transcribe(audio_path, prompt, language, model, duration_sec)
|
||||||
finally:
|
finally:
|
||||||
# Both concrete implementations own disposable resources.
|
# Both concrete implementations own disposable resources.
|
||||||
engine.close() # type: ignore[attr-defined]
|
engine.close()
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ from pathlib import Path
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class EnvConfig:
|
class EnvConfig:
|
||||||
"""Конфигурация из переменных окружения.
|
"""Конфигурация из переменных окружения.
|
||||||
|
|
|
||||||
|
|
@ -24,19 +24,31 @@ def build_recognition_tab(
|
||||||
config = store.load()
|
config = store.load()
|
||||||
manager = ModelManager(paths.models_dir)
|
manager = ModelManager(paths.models_dir)
|
||||||
labels = {f"{m.name} — {m.size_bytes / 1048576:.0f} МБ": m.id for m in CATALOG}
|
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)))
|
initial_label = next(
|
||||||
backend = ctk.StringVar(value="Локально" if config.transcription_backend == "local" else "OpenAI API")
|
(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)
|
selected = ctk.StringVar(value=initial_label)
|
||||||
ctk.CTkLabel(parent, text="Где распознавать запись:").pack(anchor="w", padx=12, pady=(12, 4))
|
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(
|
ctk.CTkLabel(
|
||||||
parent, text="Локально: аудио и текст не отправляются в облако.\n"
|
parent,
|
||||||
|
text="Локально: аудио и текст не отправляются в облако.\n"
|
||||||
"Облачные стили обработки отключены. Наш сервер — в следующем этапе.",
|
"Облачные стили обработки отключены. Наш сервер — в следующем этапе.",
|
||||||
justify="left", wraplength=620,
|
justify="left",
|
||||||
|
wraplength=620,
|
||||||
).pack(anchor="w", padx=12, pady=8)
|
).pack(anchor="w", padx=12, pady=8)
|
||||||
ctk.CTkLabel(parent, text="Локальная модель (Whisper):").pack(anchor="w", padx=12)
|
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)
|
ctk.CTkOptionMenu(parent, values=list(labels), variable=selected, width=460).pack(
|
||||||
status = ctk.CTkLabel(parent, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620)
|
anchor="w", padx=12, pady=6
|
||||||
|
)
|
||||||
|
status = ctk.CTkLabel(
|
||||||
|
parent, text="Выберите модель и скачайте её перед первой диктовкой.", wraplength=620
|
||||||
|
)
|
||||||
status.pack(anchor="w", padx=12, pady=6)
|
status.pack(anchor="w", padx=12, pady=6)
|
||||||
bar = ctk.CTkProgressBar(parent, width=460)
|
bar = ctk.CTkProgressBar(parent, width=460)
|
||||||
bar.set(0)
|
bar.set(0)
|
||||||
|
|
@ -49,15 +61,27 @@ def build_recognition_tab(
|
||||||
def worker(action: str, model_id: str) -> None:
|
def worker(action: str, model_id: str) -> None:
|
||||||
try:
|
try:
|
||||||
if action == "download":
|
if action == "download":
|
||||||
manager.download(model_id, progress=lambda done, total: events.put(
|
manager.download(
|
||||||
("progress", done / total if total else 0)), cancel=cancel)
|
model_id,
|
||||||
|
progress=lambda done, total: events.put(
|
||||||
|
("progress", done / total if total else 0)
|
||||||
|
),
|
||||||
|
cancel=cancel,
|
||||||
|
)
|
||||||
events.put(("Модель скачана и проверена. Можно использовать.", 1))
|
events.put(("Модель скачана и проверена. Можно использовать.", 1))
|
||||||
elif action == "delete":
|
elif action == "delete":
|
||||||
manager.delete(model_id)
|
manager.delete(model_id)
|
||||||
events.put(("Модель удалена.", 0))
|
events.put(("Модель удалена.", 0))
|
||||||
else:
|
else:
|
||||||
installed = manager.is_installed(model_id)
|
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:
|
except Exception as exc:
|
||||||
events.put((str(exc), -1))
|
events.put((str(exc), -1))
|
||||||
|
|
||||||
|
|
@ -82,7 +106,9 @@ def build_recognition_tab(
|
||||||
message, value = events.get_nowait()
|
message, value = events.get_nowait()
|
||||||
if message == "progress":
|
if message == "progress":
|
||||||
bar.set(value)
|
bar.set(value)
|
||||||
status.configure(text=f"Скачивание: {value:.0%}. После загрузки — проверка файла.")
|
status.configure(
|
||||||
|
text=f"Скачивание: {value:.0%}. После загрузки — проверка файла."
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
status.configure(text=message)
|
status.configure(text=message)
|
||||||
bar.set(max(0, value))
|
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")
|
ctk.CTkButton(row, text="Отменить", width=100, command=cancel.set).pack(side="left")
|
||||||
|
|
||||||
def save() -> None:
|
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)
|
store.save(updated)
|
||||||
toast("Сохранено. Новый режим применяется к следующей записи.")
|
toast("Сохранено. Новый режим применяется к следующей записи.")
|
||||||
|
|
||||||
ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save).pack(anchor="w", padx=12, pady=12)
|
ctk.CTkButton(parent, text="Использовать выбранный режим и модель", command=save).pack(
|
||||||
ctk.CTkLabel(parent, text=f"Модели хранятся отдельно от приложения:\n{paths.models_dir}", justify="left", wraplength=620).pack(anchor="w", padx=12)
|
anchor="w", padx=12, pady=12
|
||||||
parent.bind("<Destroy>", lambda event: cancel.set() if event.widget == parent else None, add="+")
|
)
|
||||||
|
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)
|
parent.after(100, poll)
|
||||||
|
|
|
||||||
|
|
@ -286,7 +286,9 @@ class SettingsWindow:
|
||||||
hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8)
|
hotkey_box.grid(row=row, column=1, sticky="w", padx=8, pady=8)
|
||||||
|
|
||||||
row += 1
|
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)
|
model_var = ctk.StringVar(value=config.model)
|
||||||
ctk.CTkComboBox(parent, values=_MODELS, variable=model_var, width=240).grid(
|
ctk.CTkComboBox(parent, values=_MODELS, variable=model_var, width=240).grid(
|
||||||
row=row, column=1, sticky="w", padx=8, pady=8
|
row=row, column=1, sticky="w", padx=8, pady=8
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue