Keep recording destination stable and enforce offline recovery
This commit is contained in:
parent
c41bca5ddc
commit
dd92bf9f3e
6 changed files with 228 additions and 6 deletions
|
|
@ -144,8 +144,9 @@ def plan_chunk_ranges(
|
|||
def _find_ffmpeg() -> str | None:
|
||||
"""Ищет ffmpeg: сначала PATH, потом стандартные локации homebrew/macports."""
|
||||
from voice_dictation.core.ffmpeg_setup import find_ffmpeg
|
||||
from voice_dictation.core.paths import AppPaths
|
||||
|
||||
found = find_ffmpeg(Path.home() / ".dictate" / "bin")
|
||||
found = find_ffmpeg(AppPaths.default().bin_dir)
|
||||
if found:
|
||||
return found
|
||||
for path in _FFMPEG_FALLBACK_PATHS:
|
||||
|
|
|
|||
|
|
@ -188,6 +188,8 @@ def _config_from_dict(data: dict[str, object]) -> Config:
|
|||
if isinstance(item, dict)
|
||||
]
|
||||
|
||||
if kwargs.get("transcription_backend", "openai") not in {"openai", "local"}:
|
||||
raise ValueError("Неизвестный движок распознавания")
|
||||
known = {f.name for f in dataclasses.fields(Config)}
|
||||
filtered = {k: v for k, v in kwargs.items() if k in known}
|
||||
return Config(**filtered) # type: ignore[arg-type]
|
||||
|
|
@ -217,9 +219,9 @@ class ConfigStore:
|
|||
if not isinstance(data, dict):
|
||||
raise TypeError("Конфигурация должна быть JSON-объектом")
|
||||
self._current = _config_from_dict(data)
|
||||
except (json.JSONDecodeError, TypeError) as exc:
|
||||
except (OSError, ValueError, TypeError) as exc:
|
||||
logger.warning("Не удалось загрузить конфиг, использую дефолтный: %s", exc)
|
||||
self._current = Config()
|
||||
self._current = self._current or Config(transcription_backend="local")
|
||||
else:
|
||||
self._current = Config()
|
||||
return self._current
|
||||
|
|
|
|||
|
|
@ -26,6 +26,9 @@ def discover_executable(name: str) -> Path:
|
|||
bundle_root / filename,
|
||||
Path(sys.executable).parent.parent / "Resources" / "bin" / filename,
|
||||
]
|
||||
from voice_dictation.core.paths import AppPaths
|
||||
|
||||
candidates.append(AppPaths.default().root / "bin" / filename)
|
||||
found = shutil.which(filename)
|
||||
if found:
|
||||
candidates.append(Path(found))
|
||||
|
|
|
|||
|
|
@ -20,8 +20,14 @@ from voice_dictation.core.compressor import (
|
|||
AudioChunk,
|
||||
AudioCompressor,
|
||||
ChunkingResult,
|
||||
plan_chunk_ranges,
|
||||
)
|
||||
from voice_dictation.core.config import (
|
||||
Config,
|
||||
SummaryPreset,
|
||||
_config_from_dict,
|
||||
_config_to_dict,
|
||||
)
|
||||
from voice_dictation.core.config import Config, SummaryPreset
|
||||
from voice_dictation.core.dictionary import Dictionary
|
||||
from voice_dictation.core.enums import RecordingState, SoundKind
|
||||
from voice_dictation.core.models import RecordingResult, TranscriptionResult, UsageRecord
|
||||
|
|
@ -104,6 +110,7 @@ class DictationOrchestrator:
|
|||
self._lock = threading.Lock()
|
||||
self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="whisper")
|
||||
self._current_future: Future[None] | None = None
|
||||
self._recording_config: Config | None = None
|
||||
|
||||
config = self._config_provider()
|
||||
removed = self._session_store.cleanup_completed_audio(config.audio_retention_days)
|
||||
|
|
@ -150,7 +157,13 @@ class DictationOrchestrator:
|
|||
def _start_recording(self) -> None:
|
||||
"""Запускает запись (вызывается внутри lock)."""
|
||||
config = self._config_provider()
|
||||
config = _config_from_dict(_config_to_dict(config))
|
||||
self._recording_config = config
|
||||
output_path = self._session_store.create()
|
||||
self._session_store.update(
|
||||
output_path.parent,
|
||||
recording_config=_config_to_dict(config),
|
||||
)
|
||||
try:
|
||||
self._recorder.start(output_path)
|
||||
except RecorderError as exc:
|
||||
|
|
@ -169,7 +182,8 @@ class DictationOrchestrator:
|
|||
|
||||
def _stop_recording(self) -> None:
|
||||
"""Останавливает запись и запускает транскрипцию (вызывается внутри lock)."""
|
||||
config = self._config_provider()
|
||||
config = self._recording_config or self._config_provider()
|
||||
self._recording_config = None
|
||||
try:
|
||||
recording = self._recorder.stop()
|
||||
except RecorderError as exc:
|
||||
|
|
@ -206,6 +220,8 @@ class DictationOrchestrator:
|
|||
"""
|
||||
session_dir = recording.path.parent
|
||||
try:
|
||||
if config.transcription_backend not in {"local", "openai"}:
|
||||
raise TranscriptionError("Неизвестный движок: выберите локальный режим или OpenAI")
|
||||
result = self._transcribe_session(recording, config)
|
||||
self._on_transcription_success(
|
||||
result,
|
||||
|
|
@ -247,6 +263,18 @@ class DictationOrchestrator:
|
|||
def _recover_sessions(self, session_dirs: list[Path], config: Config) -> None:
|
||||
for session_dir in session_dirs:
|
||||
manifest = self._session_store.read(session_dir)
|
||||
saved_config = manifest.get("recording_config")
|
||||
if not isinstance(saved_config, dict):
|
||||
self._session_store.mark_failed(
|
||||
session_dir,
|
||||
"Сессия без настроек происхождения: автоматическое восстановление запрещено",
|
||||
)
|
||||
continue
|
||||
try:
|
||||
session_config = _config_from_dict(saved_config)
|
||||
except (TypeError, ValueError):
|
||||
self._session_store.mark_failed(session_dir, "Повреждены настройки сессии")
|
||||
continue
|
||||
source_wav = session_dir / "source.wav"
|
||||
source_ogg = session_dir / "source.ogg"
|
||||
source = source_wav if source_wav.exists() else source_ogg
|
||||
|
|
@ -262,7 +290,7 @@ class DictationOrchestrator:
|
|||
continue
|
||||
self._process_recording(
|
||||
RecordingResult(path=source, duration_sec=duration_sec),
|
||||
config,
|
||||
session_config,
|
||||
finalize_state=False,
|
||||
allow_auto_paste=False,
|
||||
)
|
||||
|
|
@ -423,6 +451,8 @@ class DictationOrchestrator:
|
|||
audio_source: Path,
|
||||
config: Config,
|
||||
) -> ChunkingResult:
|
||||
if config.transcription_backend == "local" and audio_source.suffix.lower() == ".wav":
|
||||
return self._local_pcm_chunks(recording, audio_source, config)
|
||||
if recording.duration_sec <= config.chunk_duration_sec:
|
||||
if (
|
||||
config.transcription_backend != "local"
|
||||
|
|
@ -453,6 +483,42 @@ class DictationOrchestrator:
|
|||
vad_noise_db=config.vad_noise_db,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _local_pcm_chunks(
|
||||
recording: RecordingResult,
|
||||
source: Path,
|
||||
config: Config,
|
||||
) -> ChunkingResult:
|
||||
"""Slice lossless recorder WAV locally without an ffmpeg installation."""
|
||||
if recording.duration_sec <= config.chunk_duration_sec:
|
||||
return ChunkingResult(
|
||||
(AudioChunk(0, source, 0, recording.duration_sec),), "local_pcm_single", 0, 0
|
||||
)
|
||||
ranges, _ = plan_chunk_ranges(
|
||||
recording.duration_sec,
|
||||
config.chunk_duration_sec,
|
||||
config.chunk_overlap_sec,
|
||||
)
|
||||
output_dir = source.parent / "chunks"
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
chunks: list[AudioChunk] = []
|
||||
try:
|
||||
with wave.open(str(source), "rb") as reader:
|
||||
rate = reader.getframerate()
|
||||
for index, (start, end) in enumerate(ranges):
|
||||
destination = output_dir / f"chunk_{index:04d}.wav"
|
||||
# Rewrite atomically: never reuse partial chunks after a crash.
|
||||
temporary = destination.with_suffix(".wav.part")
|
||||
reader.setpos(min(int(start * rate), reader.getnframes()))
|
||||
with wave.open(str(temporary), "wb") as writer:
|
||||
writer.setparams(reader.getparams())
|
||||
writer.writeframes(reader.readframes(int((end - start) * rate)))
|
||||
temporary.replace(destination)
|
||||
chunks.append(AudioChunk(index, destination, start, end - start))
|
||||
except (OSError, EOFError, wave.Error) as exc:
|
||||
raise CompressionError("Не удалось нарезать локальный WAV; исходник сохранён") from exc
|
||||
return ChunkingResult(tuple(chunks), "local_pcm_fixed", 0, 0)
|
||||
|
||||
@staticmethod
|
||||
def _chunk_prompt(base_prompt: str, previous_text: str) -> str:
|
||||
if not previous_text:
|
||||
|
|
|
|||
|
|
@ -74,3 +74,6 @@ class RoutingTranscriber:
|
|||
finally:
|
||||
# Both concrete implementations own disposable resources.
|
||||
engine.close()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Each recognition call closes its own concrete engine."""
|
||||
|
|
|
|||
147
tests/unit/test_local_pipeline.py
Normal file
147
tests/unit/test_local_pipeline.py
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
"""Offline guarantees across routing, recovery and the full success path."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from tests.fakes.fake_components import FakeClipboard, FakeTranscriber
|
||||
from tests.unit.test_orchestrator import _make_orchestrator
|
||||
from voice_dictation.core.config import Config, ConfigStore
|
||||
from voice_dictation.core.paths import AppPaths
|
||||
from voice_dictation.core.transcription import RoutingTranscriber
|
||||
from voice_dictation.infrastructure.env_loader import load_env
|
||||
from voice_dictation.infrastructure.errors import TranscriptionError
|
||||
|
||||
|
||||
def _wait(orchestrator):
|
||||
if orchestrator._current_future:
|
||||
orchestrator._current_future.result(timeout=5)
|
||||
|
||||
|
||||
def _no_network(*args, **kwargs):
|
||||
raise AssertionError("Offline scenario attempted network access")
|
||||
|
||||
|
||||
def test_local_success_never_calls_network_or_postprocessing(tmp_paths, monkeypatch):
|
||||
monkeypatch.setattr(socket, "create_connection", _no_network)
|
||||
monkeypatch.setattr(httpx.Client, "send", _no_network)
|
||||
clipboard = FakeClipboard()
|
||||
config = Config(transcription_backend="local", active_preset="Тезисы", paste_delay_ms=0)
|
||||
orchestrator = _make_orchestrator(tmp_paths, clipboard=clipboard, config=config)
|
||||
monkeypatch.setattr(orchestrator, "_summarize", _no_network)
|
||||
monkeypatch.setattr("voice_dictation.core.fx.get_rate", _no_network)
|
||||
orchestrator.toggle()
|
||||
orchestrator.toggle()
|
||||
_wait(orchestrator)
|
||||
assert clipboard.copy_calls == ["Тестовый текст"]
|
||||
orchestrator.shutdown()
|
||||
|
||||
|
||||
def test_local_recording_keeps_mode_when_settings_change(tmp_paths):
|
||||
config = Config(transcription_backend="local", paste_delay_ms=0)
|
||||
engine = FakeTranscriber()
|
||||
orchestrator = _make_orchestrator(tmp_paths, transcriber=engine, config=config)
|
||||
orchestrator.toggle()
|
||||
# Simulate separate settings process returning a new config object.
|
||||
orchestrator._config_provider = lambda: Config(transcription_backend="openai")
|
||||
orchestrator.toggle()
|
||||
_wait(orchestrator)
|
||||
manifest = next(tmp_paths.sessions_dir.glob("*/manifest.json"))
|
||||
saved = json.loads(manifest.read_text())
|
||||
assert saved["transcription_identity"]["engine"] == "local"
|
||||
assert saved["recording_config"]["transcription_backend"] == "local"
|
||||
orchestrator.shutdown()
|
||||
|
||||
|
||||
def test_recovery_uses_recording_config_not_current_cloud(tmp_paths, monkeypatch):
|
||||
config = Config(transcription_backend="local", paste_delay_ms=0)
|
||||
first = _make_orchestrator(tmp_paths, config=config)
|
||||
first.toggle()
|
||||
# Simulate interrupted process with an intact source WAV.
|
||||
session = next(tmp_paths.sessions_dir.iterdir())
|
||||
first._session_store.mark_recorded(session / "source.wav", 2.0)
|
||||
second = _make_orchestrator(tmp_paths, config=Config(transcription_backend="openai"))
|
||||
monkeypatch.setattr(second, "_summarize", _no_network)
|
||||
assert second.resume_pending_sessions() == 1
|
||||
_wait(second)
|
||||
saved = second._session_store.read(session)
|
||||
assert saved["transcription_identity"]["engine"] == "local"
|
||||
first.shutdown()
|
||||
second.shutdown()
|
||||
|
||||
|
||||
def test_legacy_recording_never_automatically_uploaded(tmp_paths):
|
||||
engine = FakeTranscriber()
|
||||
orchestrator = _make_orchestrator(tmp_paths, transcriber=engine)
|
||||
source = orchestrator._session_store.create()
|
||||
source.write_bytes(b"audio")
|
||||
orchestrator._session_store.mark_recorded(source, 2.0)
|
||||
assert orchestrator.resume_pending_sessions() == 1
|
||||
_wait(orchestrator)
|
||||
assert not engine.calls
|
||||
assert "автоматическое" in orchestrator._session_store.read(source.parent)["last_error"]
|
||||
orchestrator.shutdown()
|
||||
|
||||
|
||||
def test_local_missing_model_cannot_construct_cloud(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("voice_dictation.core.transcriber.WhisperTranscriber", _no_network)
|
||||
with pytest.raises(TranscriptionError):
|
||||
RoutingTranscriber("", tmp_path).transcribe(
|
||||
tmp_path / "audio.wav", model="local:whisper-base"
|
||||
)
|
||||
|
||||
|
||||
def test_cloud_missing_key_is_actionable(tmp_path):
|
||||
with pytest.raises(TranscriptionError, match="OPENAI_API_KEY"):
|
||||
RoutingTranscriber("", tmp_path).transcribe(tmp_path / "audio.wav", model="whisper-1")
|
||||
|
||||
|
||||
def test_keyless_env_and_beta_paths_are_isolated(tmp_path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
monkeypatch.setenv("VOICE_DICTATION_HOME", str(tmp_path / "beta"))
|
||||
assert load_env().api_key == ""
|
||||
assert AppPaths.default().root == tmp_path / "beta"
|
||||
|
||||
|
||||
def test_settings_file_changes_are_loaded_for_next_recording(tmp_path):
|
||||
store = ConfigStore(tmp_path / "config.json")
|
||||
store.save(Config(transcription_backend="openai"))
|
||||
other = ConfigStore(store._path)
|
||||
other.save(Config(transcription_backend="local"))
|
||||
assert store.load().transcription_backend == "local"
|
||||
|
||||
|
||||
def test_corrupt_local_config_never_switches_to_cloud(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
store = ConfigStore(path)
|
||||
store.save(Config(transcription_backend="local"))
|
||||
path.write_text("{broken")
|
||||
assert store.load().transcription_backend == "local"
|
||||
assert ConfigStore(path).load().transcription_backend == "local"
|
||||
path.write_text('{"transcription_backend": "server"}')
|
||||
assert ConfigStore(path).load().transcription_backend == "local"
|
||||
|
||||
|
||||
def test_local_long_wav_splits_without_ffmpeg(tmp_paths):
|
||||
import wave
|
||||
|
||||
from voice_dictation.core.models import RecordingResult
|
||||
|
||||
config = Config(transcription_backend="local", chunk_duration_sec=60)
|
||||
orchestrator = _make_orchestrator(tmp_paths, config=config)
|
||||
source = orchestrator._session_store.create()
|
||||
with wave.open(str(source), "wb") as audio:
|
||||
audio.setparams((1, 2, 16000, 0, "NONE", "not compressed"))
|
||||
audio.writeframes(b"\0\0" * 16000 * 125)
|
||||
chunks = orchestrator._prepare_chunks(RecordingResult(source, 125), source, config)
|
||||
assert len(chunks.chunks) == 3
|
||||
assert chunks.mode == "local_pcm_fixed"
|
||||
for chunk in chunks.chunks:
|
||||
with wave.open(str(chunk.path), "rb") as audio:
|
||||
assert audio.getnframes() / audio.getframerate() <= 60.001
|
||||
orchestrator.shutdown()
|
||||
Loading…
Reference in a new issue