Route transcription explicitly and isolate local processing from cloud
This commit is contained in:
parent
0c173c167a
commit
ecc356be46
5 changed files with 125 additions and 32 deletions
|
|
@ -97,9 +97,9 @@ def main() -> None:
|
|||
print(f"[ОШИБКА] {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||
from voice_dictation.core.transcription import RoutingTranscriber
|
||||
|
||||
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||
transcriber = RoutingTranscriber(api_key=env.api_key, models_dir=paths.models_dir)
|
||||
|
||||
from voice_dictation.core.compressor import AudioCompressor
|
||||
|
||||
|
|
@ -135,7 +135,7 @@ def main() -> None:
|
|||
auto_paste=platform_bundle.auto_paste,
|
||||
sound_player=platform_bundle.sound_player,
|
||||
notifier=platform_bundle.notifier,
|
||||
config_provider=config_store.current,
|
||||
config_provider=config_store.load,
|
||||
paths=paths,
|
||||
state_listener=_state_changed,
|
||||
usage_db=usage_db,
|
||||
|
|
@ -213,20 +213,20 @@ def main() -> None:
|
|||
shutdown_event.set()
|
||||
|
||||
def _select_preset(name: str) -> None:
|
||||
cfg = config_store.current()
|
||||
cfg = config_store.load()
|
||||
cfg.active_preset = name
|
||||
config_store.save(cfg)
|
||||
platform_bundle.notifier.show("Voice Dictation", f"Режим: {name}")
|
||||
logger.info("Preset выбран: %s", name)
|
||||
|
||||
def _get_active_preset() -> str:
|
||||
return config_store.current().active_preset
|
||||
return config_store.load().active_preset
|
||||
|
||||
def _get_preset_names() -> list[str]:
|
||||
return [p.name for p in config_store.current().summary_presets]
|
||||
return [p.name for p in config_store.load().summary_presets]
|
||||
|
||||
def _toggle_splash() -> bool:
|
||||
cfg = config_store.current()
|
||||
cfg = config_store.load()
|
||||
cfg.splash_enabled = not cfg.splash_enabled
|
||||
config_store.save(cfg)
|
||||
state = "включён" if cfg.splash_enabled else "выключен"
|
||||
|
|
@ -235,7 +235,7 @@ def main() -> None:
|
|||
return cfg.splash_enabled
|
||||
|
||||
def _get_splash_state() -> bool:
|
||||
return config_store.current().splash_enabled
|
||||
return config_store.load().splash_enabled
|
||||
|
||||
tray = TrayApp(
|
||||
on_toggle=orchestrator.toggle,
|
||||
|
|
|
|||
|
|
@ -76,9 +76,9 @@ def main() -> None:
|
|||
sys.exit(1)
|
||||
|
||||
# 8. Transcriber
|
||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||
from voice_dictation.core.transcription import RoutingTranscriber
|
||||
|
||||
transcriber = WhisperTranscriber(api_key=env.api_key, model=config.model)
|
||||
transcriber = RoutingTranscriber(api_key=env.api_key, models_dir=paths.models_dir)
|
||||
|
||||
# 8.1. Audio compressor (опционально — если ffmpeg есть)
|
||||
from voice_dictation.core.compressor import AudioCompressor
|
||||
|
|
@ -111,7 +111,7 @@ def main() -> None:
|
|||
auto_paste=platform_bundle.auto_paste,
|
||||
sound_player=platform_bundle.sound_player,
|
||||
notifier=platform_bundle.notifier,
|
||||
config_provider=config_store.current,
|
||||
config_provider=config_store.load,
|
||||
paths=paths,
|
||||
state_listener=_state_changed,
|
||||
usage_db=usage_db,
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ from voice_dictation.core.models import RecordingResult, TranscriptionResult, Us
|
|||
from voice_dictation.core.paths import AppPaths
|
||||
from voice_dictation.core.session_store import SessionStore
|
||||
from voice_dictation.core.text_stitcher import stitch_transcripts
|
||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||
from voice_dictation.core.transcription import Transcriber
|
||||
from voice_dictation.core.usage_db import UsageDB
|
||||
from voice_dictation.infrastructure.errors import (
|
||||
CompressionError,
|
||||
|
|
@ -73,7 +73,7 @@ class DictationOrchestrator:
|
|||
def __init__(
|
||||
self,
|
||||
recorder: AudioRecorder,
|
||||
transcriber: WhisperTranscriber,
|
||||
transcriber: Transcriber,
|
||||
dictionary: Dictionary,
|
||||
clipboard: Clipboard,
|
||||
auto_paste: AutoPaste,
|
||||
|
|
@ -287,11 +287,13 @@ class DictationOrchestrator:
|
|||
"""Транскрибирует сессию по частям и сохраняет каждый успешный ответ."""
|
||||
session_dir = recording.path.parent
|
||||
archive_path = session_dir / "source.ogg"
|
||||
local = config.transcription_backend == "local"
|
||||
effective_model = f"local:{config.local_model}" if local else config.model
|
||||
audio_source = recording.path
|
||||
|
||||
if archive_path.exists() and archive_path.stat().st_size > 0:
|
||||
if not local and archive_path.exists() and archive_path.stat().st_size > 0:
|
||||
audio_source = archive_path
|
||||
elif self._compressor is not None and self._compressor.is_available():
|
||||
elif not local and self._compressor is not None and self._compressor.is_available():
|
||||
self._compressor.compress(recording.path, archive_path)
|
||||
wav_size = recording.path.stat().st_size
|
||||
ogg_size = archive_path.stat().st_size
|
||||
|
|
@ -303,12 +305,41 @@ class DictationOrchestrator:
|
|||
)
|
||||
audio_source = archive_path
|
||||
|
||||
if local:
|
||||
from dataclasses import replace
|
||||
|
||||
config = replace(config, chunk_duration_sec=min(config.chunk_duration_sec, 60.0))
|
||||
identity = {
|
||||
"engine": config.transcription_backend,
|
||||
"model": effective_model,
|
||||
"language": config.language,
|
||||
"chunk_duration_sec": config.chunk_duration_sec,
|
||||
"chunk_overlap_sec": config.chunk_overlap_sec,
|
||||
"vad_enabled": config.vad_enabled,
|
||||
"vad_search_window_sec": config.vad_search_window_sec,
|
||||
"vad_min_silence_sec": config.vad_min_silence_sec,
|
||||
"vad_noise_db": config.vad_noise_db,
|
||||
"dictionary": self._dictionary.build_prompt(),
|
||||
}
|
||||
previous = self._session_store.read(session_dir)
|
||||
old_identity = previous.get("transcription_identity")
|
||||
if old_identity is not None and old_identity != identity:
|
||||
raise TranscriptionError(
|
||||
"Настройки незавершённой сессии изменились. Верните прежний движок, "
|
||||
"модель и настройки нарезки для безопасного продолжения. Аудио сохранено."
|
||||
)
|
||||
if old_identity is None and previous.get("chunks"):
|
||||
raise TranscriptionError(
|
||||
"Старая сессия без идентификатора движка: автоматическое продолжение "
|
||||
"отключено. Аудио сохранено для ручного восстановления."
|
||||
)
|
||||
chunking = self._prepare_chunks(recording, audio_source, config)
|
||||
chunks = chunking.chunks
|
||||
self._session_store.update(
|
||||
session_dir,
|
||||
status="processing",
|
||||
model=config.model,
|
||||
transcription_identity=identity,
|
||||
model=effective_model,
|
||||
chunk_duration_sec=config.chunk_duration_sec,
|
||||
chunk_overlap_sec=config.chunk_overlap_sec,
|
||||
chunking_mode=chunking.mode,
|
||||
|
|
@ -350,7 +381,7 @@ class DictationOrchestrator:
|
|||
chunk.path,
|
||||
prompt=prompt,
|
||||
language=config.language,
|
||||
model=config.model,
|
||||
model=effective_model,
|
||||
duration_sec=chunk.duration_sec,
|
||||
)
|
||||
self._session_store.save_chunk_result(session_dir, chunk.index, result)
|
||||
|
|
@ -365,7 +396,7 @@ class DictationOrchestrator:
|
|||
return TranscriptionResult(
|
||||
text=stitch.text,
|
||||
duration_sec=recording.duration_sec,
|
||||
model=config.model,
|
||||
model=effective_model,
|
||||
language=next(
|
||||
(result.language for result in results if result.language),
|
||||
config.language,
|
||||
|
|
@ -385,7 +416,8 @@ class DictationOrchestrator:
|
|||
config: Config,
|
||||
) -> ChunkingResult:
|
||||
if recording.duration_sec <= config.chunk_duration_sec:
|
||||
if 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),),
|
||||
|
|
@ -479,7 +511,8 @@ class DictationOrchestrator:
|
|||
# Post-processing через активный пресет (если есть и не пустой)
|
||||
final_text = result.text
|
||||
active = self._resolve_active_preset(config)
|
||||
if 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(
|
||||
|
|
@ -503,7 +536,9 @@ class DictationOrchestrator:
|
|||
|
||||
chars = len(final_text)
|
||||
summary_parts = [f"{result.duration_sec:.1f}с · {chars} симв."]
|
||||
if config.show_cost_in_notification:
|
||||
if config.transcription_backend == "local":
|
||||
summary_parts.append("локально · без API")
|
||||
elif config.show_cost_in_notification:
|
||||
rate = get_rate()
|
||||
cost_rub = usd_to_rub(result.cost_usd, rate)
|
||||
cost_part = f"${result.cost_usd:.4f}"
|
||||
|
|
|
|||
65
src/voice_dictation/core/transcription.py
Normal file
65
src/voice_dictation/core/transcription.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"""Engine-neutral transcription contract and explicit local/cloud routing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from voice_dictation.core.models import TranscriptionResult
|
||||
from voice_dictation.infrastructure.errors import TranscriptionError
|
||||
|
||||
|
||||
class Transcriber(Protocol):
|
||||
"""Recognize an audio file using an explicitly selected model."""
|
||||
|
||||
def transcribe(
|
||||
self,
|
||||
audio_path: Path,
|
||||
prompt: str = "",
|
||||
language: str | None = None,
|
||||
model: str | None = None,
|
||||
duration_sec: float | None = None,
|
||||
) -> TranscriptionResult:
|
||||
"""Return recognized text or raise a transcription error."""
|
||||
...
|
||||
|
||||
|
||||
class RoutingTranscriber:
|
||||
"""Dispatch by model identity; local failures never fall back to cloud."""
|
||||
|
||||
def __init__(self, api_key: str, models_dir: Path) -> None:
|
||||
self._api_key = api_key
|
||||
self._models_dir = models_dir
|
||||
|
||||
def transcribe(
|
||||
self,
|
||||
audio_path: Path,
|
||||
prompt: str = "",
|
||||
language: str | None = None,
|
||||
model: str | None = None,
|
||||
duration_sec: float | None = None,
|
||||
) -> TranscriptionResult:
|
||||
"""Recognize locally for local: model IDs, otherwise use OpenAI."""
|
||||
if model is None:
|
||||
raise TranscriptionError("Не выбрана модель распознавания")
|
||||
engine: Transcriber
|
||||
if model.startswith("local:"):
|
||||
from voice_dictation.core.local_transcriber import LocalTranscriber
|
||||
from voice_dictation.core.model_manager import ModelManager
|
||||
|
||||
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))
|
||||
else:
|
||||
from voice_dictation.core.transcriber import WhisperTranscriber
|
||||
|
||||
if not self._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]
|
||||
|
|
@ -9,7 +9,6 @@ from pathlib import Path
|
|||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from voice_dictation.infrastructure.errors import ConfigError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
|
@ -17,7 +16,7 @@ class EnvConfig:
|
|||
"""Конфигурация из переменных окружения.
|
||||
|
||||
Args:
|
||||
api_key: OpenAI API ключ (обязательный).
|
||||
api_key: OpenAI API ключ; пустой допустим для локального режима.
|
||||
admin_api_key: OpenAI Admin API ключ (опциональный, для баланса).
|
||||
"""
|
||||
|
||||
|
|
@ -34,9 +33,9 @@ def load_env() -> EnvConfig:
|
|||
Returns:
|
||||
EnvConfig с ключами API.
|
||||
|
||||
Raises:
|
||||
ConfigError: Если OPENAI_API_KEY не задан или пустой.
|
||||
"""
|
||||
from voice_dictation.core.paths import AppPaths
|
||||
|
||||
# Ищем .env: рядом с exe (для PyInstaller-сборки) → cwd → ~/.dictate/
|
||||
is_frozen = bool(getattr(sys, "frozen", False))
|
||||
candidates = []
|
||||
|
|
@ -45,7 +44,7 @@ def load_env() -> EnvConfig:
|
|||
candidates.extend(
|
||||
[
|
||||
Path.cwd() / ".env",
|
||||
Path.home() / ".dictate" / ".env",
|
||||
AppPaths.default().root / ".env",
|
||||
]
|
||||
)
|
||||
for candidate in candidates:
|
||||
|
|
@ -57,12 +56,6 @@ def load_env() -> EnvConfig:
|
|||
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)
|
||||
|
|
|
|||
Loading…
Reference in a new issue