feat: add audio cache settings and history actions

This commit is contained in:
Ilgiz Kalmetyev 2026-04-10 14:10:19 +05:00
parent 8e5625573f
commit abf7e2cc4d
18 changed files with 1078 additions and 102 deletions

View File

@ -6,6 +6,7 @@ from pathlib import Path
from PySide6.QtWidgets import QApplication
from audio.audio_cache_service import AudioCacheService
from audio.capture_service import AudioCaptureService
from audio.device_service import AudioDeviceService
from asr.model_downloader import ModelDownloader
@ -23,6 +24,7 @@ from hotkeys.hotkey_service import HotkeyService
from injection.target_window_service import TargetWindowService
from injection.text_injector import TextInjector
from logging_ext.logging_service import LoggingService
from ui.history_dialog import HistoryDialog
from ui.main_window import MainWindow
from ui.ptt_controller import PttController
from ui.runtime_status_controller import RuntimeStatusController
@ -73,7 +75,8 @@ def main() -> int:
app = build_application()
window = MainWindow()
_tray_controller = TrayController(app, window)
_capture_service = AudioCaptureService()
_audio_cache_service = AudioCacheService(config.paths.audio_cache_directory, config.audio_cache_max_bytes)
_capture_service = AudioCaptureService(audio_cache_service=_audio_cache_service)
_audio_device_service = AudioDeviceService()
_target_window_service = TargetWindowService()
_text_injector = TextInjector(_target_window_service)
@ -99,6 +102,7 @@ def main() -> int:
runtime_refresh=_runtime_status_controller.refresh,
history_store=history_store,
history_pruner=history_pruner,
audio_cache_service=_audio_cache_service,
model_downloader=ModelDownloader(),
audio_device_service=_audio_device_service,
)
@ -132,6 +136,11 @@ def main() -> int:
_model_fallback_service,
logger,
model_downloader=_model_downloader,
history_dialog_factory=lambda history_store, parent=None: HistoryDialog(
history_store,
parent,
audio_cache_service=_audio_cache_service,
),
)
exit_code = _orchestrator.run()

View File

@ -0,0 +1,236 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import BinaryIO, Iterable
import uuid
import wave
CACHE_FILE_PREFIX = "voiceptt_audio"
CACHE_FILE_SUFFIX = ".wav"
class AudioCacheError(RuntimeError):
"""Raised when the audio cache cannot be created, written, or maintained safely."""
@dataclass(frozen=True, slots=True)
class AudioCachePruneResult:
cache_directory: Path
limit_bytes: int
total_before_bytes: int
total_after_bytes: int
removed_count: int
removed_bytes: int
removed_paths: tuple[Path, ...] = ()
@dataclass(slots=True)
class AudioCacheRecording:
cache_path: Path
_file_handle: BinaryIO
_wave_writer: wave.Wave_write
_closed: bool = False
def write_pcm_bytes(self, pcm_bytes: bytes) -> None:
if self._closed:
raise AudioCacheError("Audio cache recording is already closed.")
if not pcm_bytes:
return
self._wave_writer.writeframesraw(pcm_bytes)
def close(self) -> None:
if self._closed:
return
wave_error: Exception | None = None
file_error: Exception | None = None
try:
self._wave_writer.close()
except Exception as exc: # pragma: no cover - defensive cleanup guard
wave_error = exc
try:
self._file_handle.close()
except Exception as exc: # pragma: no cover - defensive cleanup guard
file_error = exc
self._closed = True
if wave_error is not None or file_error is not None:
message = "Unable to finalize audio cache file."
raise AudioCacheError(message) from wave_error or file_error
def discard(self) -> None:
path = self.cache_path
close_error: Exception | None = None
try:
self.close()
except Exception as exc: # pragma: no cover - defensive cleanup guard
close_error = exc
try:
path.unlink(missing_ok=True)
except Exception as exc: # pragma: no cover - defensive cleanup guard
raise AudioCacheError(f"Unable to remove incomplete audio cache file: {path}") from exc
if close_error is not None:
raise close_error
class AudioCacheService:
def __init__(self, cache_directory: str | Path, max_bytes: int) -> None:
self._cache_directory = Path(cache_directory)
self._max_bytes = self._normalize_limit(max_bytes)
@property
def cache_directory(self) -> Path:
return self._cache_directory
@property
def max_bytes(self) -> int:
return self._max_bytes
def update_settings(self, cache_directory: str | Path, max_bytes: int) -> None:
self._cache_directory = Path(cache_directory)
self._max_bytes = self._normalize_limit(max_bytes)
def create_recording(self, *, started_at_utc: datetime, sample_rate: int, channels: int) -> AudioCacheRecording:
if sample_rate <= 0:
raise AudioCacheError("sample_rate must be a positive integer.")
if channels <= 0:
raise AudioCacheError("channels must be a positive integer.")
started_at_utc = self._coerce_aware_utc_datetime(started_at_utc)
self._cache_directory.mkdir(parents=True, exist_ok=True)
cache_path = self._next_recording_path(started_at_utc)
file_handle: BinaryIO | None = None
wave_writer: wave.Wave_write | None = None
try:
file_handle = cache_path.open("wb")
wave_writer = wave.open(file_handle, "wb")
wave_writer.setnchannels(channels)
wave_writer.setsampwidth(2)
wave_writer.setframerate(sample_rate)
except Exception as exc:
try:
if wave_writer is not None:
wave_writer.close()
except Exception:
pass
try:
if file_handle is not None:
file_handle.close()
except Exception:
pass
try:
cache_path.unlink(missing_ok=True)
except Exception:
pass
raise AudioCacheError(f"Unable to open audio cache file: {cache_path}") from exc
return AudioCacheRecording(cache_path=cache_path, _file_handle=file_handle, _wave_writer=wave_writer)
def prune_cache(self) -> AudioCachePruneResult:
cache_files = self._managed_cache_files()
total_before_bytes = self._total_size(cache_files)
if total_before_bytes <= self._max_bytes:
return AudioCachePruneResult(
cache_directory=self._cache_directory,
limit_bytes=self._max_bytes,
total_before_bytes=total_before_bytes,
total_after_bytes=total_before_bytes,
removed_count=0,
removed_bytes=0,
)
remaining_files = list(cache_files)
removed_paths: list[Path] = []
removed_bytes = 0
total_after_bytes = total_before_bytes
while total_after_bytes > self._max_bytes and len(remaining_files) > 1:
path = remaining_files.pop(0)
try:
file_size = path.stat().st_size
except FileNotFoundError:
continue
path.unlink(missing_ok=True)
removed_paths.append(path)
removed_bytes += file_size
total_after_bytes -= file_size
return AudioCachePruneResult(
cache_directory=self._cache_directory,
limit_bytes=self._max_bytes,
total_before_bytes=total_before_bytes,
total_after_bytes=max(0, total_after_bytes),
removed_count=len(removed_paths),
removed_bytes=removed_bytes,
removed_paths=tuple(removed_paths),
)
def delete_cached_files(self, audio_cache_paths: Iterable[str | Path]) -> int:
removed_count = 0
for audio_cache_path in audio_cache_paths:
if not audio_cache_path:
continue
path = Path(audio_cache_path)
if not path.exists():
continue
if path.is_dir():
raise AudioCacheError(f"Expected audio cache file but found directory: {path}")
try:
path.unlink(missing_ok=True)
except OSError as exc:
raise AudioCacheError(f"Unable to delete audio cache file: {path}") from exc
removed_count += 1
return removed_count
def _managed_cache_files(self) -> list[Path]:
if not self._cache_directory.exists():
return []
files = [
path
for path in self._cache_directory.glob(f"{CACHE_FILE_PREFIX}_*{CACHE_FILE_SUFFIX}")
if path.is_file()
]
files.sort(key=lambda path: path.name)
return files
@staticmethod
def _total_size(paths: Iterable[Path]) -> int:
total = 0
for path in paths:
try:
total += path.stat().st_size
except FileNotFoundError:
continue
return total
def _next_recording_path(self, started_at_utc: datetime) -> Path:
timestamp = started_at_utc.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ")
for _ in range(100):
candidate = self._cache_directory / f"{CACHE_FILE_PREFIX}_{timestamp}_{uuid.uuid4().hex[:8]}{CACHE_FILE_SUFFIX}"
if not candidate.exists():
return candidate
raise AudioCacheError("Unable to generate a unique audio cache file path.")
@staticmethod
def _coerce_aware_utc_datetime(value: datetime) -> datetime:
if not isinstance(value, datetime):
raise AudioCacheError("started_at_utc must be a datetime instance.")
if value.tzinfo is None or value.utcoffset() is None:
raise AudioCacheError("started_at_utc must be timezone-aware.")
return value.astimezone(timezone.utc)
@staticmethod
def _normalize_limit(max_bytes: int) -> int:
try:
coerced = int(max_bytes)
except (TypeError, ValueError) as exc:
raise AudioCacheError("audio cache limit must be a positive integer.") from exc
if coerced <= 0:
raise AudioCacheError("audio cache limit must be a positive integer.")
return coerced

View File

@ -1,11 +1,18 @@
from __future__ import annotations
import importlib
import logging
import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from time import monotonic
from typing import Any, Callable, Protocol
from .audio_cache_service import AudioCacheError, AudioCacheRecording, AudioCacheService
logger = logging.getLogger(__name__)
class AudioCaptureError(RuntimeError):
"""Raised when audio capture cannot be started or stopped safely."""
@ -38,6 +45,7 @@ class AudioCaptureSegment:
stopped_at: float
total_frames: int
truncated: bool = False
audio_cache_path: str = ""
@property
def duration_seconds(self) -> float:
@ -57,6 +65,7 @@ class _StreamProtocol(Protocol):
StreamFactory = Callable[..., _StreamProtocol]
Clock = Callable[[], float]
UtcNow = Callable[[], datetime]
@dataclass(slots=True)
@ -69,13 +78,23 @@ class _CaptureSession:
frames_captured: int = 0
truncated: bool = False
finished: bool = False
cache_recording: AudioCacheRecording | None = None
cache_error: str = ""
class AudioCaptureService:
def __init__(self, stream_factory: StreamFactory | None = None, clock: Clock | None = None) -> None:
def __init__(
self,
stream_factory: StreamFactory | None = None,
clock: Clock | None = None,
audio_cache_service: AudioCacheService | None = None,
utc_now: UtcNow | None = None,
) -> None:
self._stream_factory = stream_factory or self._default_stream_factory
self._uses_default_stream_factory = stream_factory is None
self._clock = clock or monotonic
self._utc_now = utc_now or (lambda: datetime.now(timezone.utc))
self._audio_cache_service = audio_cache_service
self._lock = threading.Lock()
self._session: _CaptureSession | None = None
self._callback_stop_exception: type[BaseException] = RuntimeError
@ -112,6 +131,7 @@ class AudioCaptureService:
else:
self._callback_stop_exception = RuntimeError
cache_recording = self._create_cache_recording(request)
stream = self._stream_factory(
device=request.device,
samplerate=request.sample_rate,
@ -120,14 +140,21 @@ class AudioCaptureService:
dtype="int16",
callback=self._make_callback(request),
)
session = _CaptureSession(request=request, stream=stream, started_at=self._clock())
session = _CaptureSession(
request=request,
stream=stream,
started_at=self._clock(),
cache_recording=cache_recording,
)
self._session = session
try:
stream.start()
except Exception as exc:
self._discard_cache_recording(cache_recording)
with self._lock:
self._session = None
if self._session is session:
self._session = None
raise AudioCaptureError(f"Failed to start audio capture: {exc}") from exc
def stop_recording(self) -> AudioCaptureSegment:
@ -138,18 +165,39 @@ class AudioCaptureService:
self._session = None
session.stopped_at = self._clock()
session.finished = True
cache_recording = session.cache_recording
cache_error = session.cache_error
stream_error: Exception | None = None
try:
session.stream.stop()
except Exception as exc:
raise AudioCaptureError(f"Failed to stop audio capture: {exc}") from exc
stream_error = exc
finally:
try:
session.stream.close()
except Exception:
pass
except Exception as exc: # pragma: no cover - defensive cleanup guard
if stream_error is None:
stream_error = exc
return AudioCaptureSegment(
if stream_error is not None:
self._discard_cache_recording(cache_recording)
raise AudioCaptureError(f"Failed to stop audio capture: {stream_error}") from stream_error
if cache_error:
self._discard_cache_recording(cache_recording)
raise AudioCaptureError(f"Failed to write audio cache: {cache_error}")
audio_cache_path = ""
if cache_recording is not None:
try:
cache_recording.close()
audio_cache_path = str(cache_recording.cache_path)
except Exception as exc:
self._discard_cache_recording(cache_recording)
raise AudioCaptureError(f"Failed to finalize audio cache: {exc}") from exc
segment = AudioCaptureSegment(
pcm_bytes=bytes(session.buffer),
sample_rate=session.request.sample_rate,
channels=session.request.channels,
@ -158,8 +206,51 @@ class AudioCaptureService:
stopped_at=session.stopped_at,
total_frames=session.frames_captured,
truncated=session.truncated,
audio_cache_path=audio_cache_path,
)
self._prune_audio_cache()
return segment
def _create_cache_recording(self, request: AudioCaptureRequest) -> AudioCacheRecording | None:
if self._audio_cache_service is None:
return None
try:
return self._audio_cache_service.create_recording(
started_at_utc=self._utc_now(),
sample_rate=request.sample_rate,
channels=request.channels,
)
except AudioCacheError as exc:
raise AudioCaptureError(str(exc)) from exc
def _discard_cache_recording(self, cache_recording: AudioCacheRecording | None) -> None:
if cache_recording is None:
return
try:
cache_recording.discard()
except Exception as exc: # pragma: no cover - defensive cleanup guard
logger.warning("Unable to discard incomplete audio cache recording: %s", exc)
def _prune_audio_cache(self) -> None:
if self._audio_cache_service is None:
return
try:
result = self._audio_cache_service.prune_cache()
except AudioCacheError as exc:
logger.warning("Audio cache pruning failed: %s", exc)
return
if result.removed_count > 0:
logger.info(
"Audio cache pruned to %s bytes: removed %s file(s) and %s bytes.",
result.limit_bytes,
result.removed_count,
result.removed_bytes,
)
def _make_callback(self, request: AudioCaptureRequest):
max_frames = int(request.sample_rate * request.max_duration_seconds)
bytes_per_frame = request.channels * 2
@ -181,12 +272,26 @@ class AudioCaptureService:
raise self._callback_stop_exception()
if len(raw) > remaining_bytes:
session.buffer.extend(raw[:remaining_bytes])
if session.cache_recording is not None:
try:
session.cache_recording.write_pcm_bytes(raw[:remaining_bytes])
except Exception as exc:
session.cache_error = self._normalize_error_message(exc)
session.finished = True
raise self._callback_stop_exception()
session.frames_captured = max_frames
session.truncated = True
session.finished = True
raise self._callback_stop_exception()
session.buffer.extend(raw)
if session.cache_recording is not None:
try:
session.cache_recording.write_pcm_bytes(raw)
except Exception as exc:
session.cache_error = self._normalize_error_message(exc)
session.finished = True
raise self._callback_stop_exception()
session.frames_captured += frames
if max_frames > 0 and session.frames_captured >= max_frames:
session.truncated = True
@ -209,3 +314,8 @@ class AudioCaptureService:
return sounddevice.RawInputStream(**kwargs)
except Exception as exc:
raise AudioCaptureError(f"Unable to open RawInputStream: {exc}") from exc
@staticmethod
def _normalize_error_message(exc: Exception) -> str:
message = str(exc).strip()
return message or exc.__class__.__name__

View File

@ -1,4 +1,4 @@
"""Central configuration service for VoicePTT."""
"""Central configuration service for VoicePTT."""
from __future__ import annotations
@ -15,6 +15,7 @@ APP_DIRECTORY_NAME = "VoicePTT"
CONFIG_FILE_NAME = "config.json"
HISTORY_DB_FILE_NAME = "history.db"
LOGS_DIRECTORY_NAME = "logs"
AUDIO_CACHE_DIRECTORY_NAME = "audio_cache"
CONFIG_SCHEMA_VERSION = 1
@ -29,6 +30,7 @@ DEFAULT_LOG_BACKUP_COUNT = 5
DEFAULT_HISTORY_LIMIT = 1000
DEFAULT_INJECTION_MODE = "direct_typing"
DEFAULT_SELECTED_INPUT_DEVICE = ""
DEFAULT_AUDIO_CACHE_MAX_BYTES = 1024 * 1024 * 1024
class ConfigError(RuntimeError):
@ -41,6 +43,7 @@ class ConfigPaths:
logs_root_directory: str = ""
config_path: str = ""
history_db_path: str = ""
audio_cache_directory: str = ""
@dataclass(slots=True)
@ -62,6 +65,7 @@ class AppConfig:
logging: LoggingConfig = field(default_factory=LoggingConfig)
history_limit: int = DEFAULT_HISTORY_LIMIT
injection_mode: str = DEFAULT_INJECTION_MODE
audio_cache_max_bytes: int = DEFAULT_AUDIO_CACHE_MAX_BYTES
class ConfigService:
@ -95,6 +99,10 @@ class ConfigService:
def default_logs_root_directory(cls, app_data_root: Path | str | None = None) -> Path:
return cls._resolve_app_data_root(app_data_root) / LOGS_DIRECTORY_NAME
@classmethod
def default_audio_cache_directory(cls, app_data_root: Path | str | None = None) -> Path:
return cls._resolve_app_data_root(app_data_root) / AUDIO_CACHE_DIRECTORY_NAME
@classmethod
def default_history_db_path(cls, app_data_root: Path | str | None = None) -> Path:
return cls._resolve_app_data_root(app_data_root) / HISTORY_DB_FILE_NAME
@ -108,8 +116,10 @@ class ConfigService:
logs_root_directory=str(cls.default_logs_root_directory(root)),
config_path=str(cls.default_config_path(root)),
history_db_path=str(cls.default_history_db_path(root)),
audio_cache_directory=str(cls.default_audio_cache_directory(root)),
),
selected_input_device=DEFAULT_SELECTED_INPUT_DEVICE,
audio_cache_max_bytes=DEFAULT_AUDIO_CACHE_MAX_BYTES,
)
@property
@ -161,12 +171,15 @@ class ConfigService:
config.paths.config_path = str(self._config_path)
if not config.paths.history_db_path:
config.paths.history_db_path = defaults.paths.history_db_path
if not config.paths.audio_cache_directory:
config.paths.audio_cache_directory = defaults.paths.audio_cache_directory
config.hotkey = self._normalize_hotkey(config.hotkey, DEFAULT_HOTKEY)
def _ensure_directories(self, config: AppConfig) -> None:
self._config_path.parent.mkdir(parents=True, exist_ok=True)
Path(config.paths.logs_root_directory).mkdir(parents=True, exist_ok=True)
Path(config.paths.history_db_path).parent.mkdir(parents=True, exist_ok=True)
Path(config.paths.audio_cache_directory).mkdir(parents=True, exist_ok=True)
def _config_from_mapping(self, raw: Any) -> AppConfig:
if not isinstance(raw, dict):
@ -192,6 +205,9 @@ class ConfigService:
logs_root_directory=str(paths_raw.get("logs_root_directory", defaults.paths.logs_root_directory)),
config_path=str(paths_raw.get("config_path", self._config_path)),
history_db_path=str(paths_raw.get("history_db_path", defaults.paths.history_db_path)),
audio_cache_directory=str(
paths_raw.get("audio_cache_directory", defaults.paths.audio_cache_directory)
),
),
model_name=str(raw.get("model_name", defaults.model_name)),
backend_mode=str(raw.get("backend_mode", defaults.backend_mode)),
@ -211,6 +227,10 @@ class ConfigService:
),
history_limit=self._coerce_positive_int(raw.get("history_limit", defaults.history_limit), "history_limit"),
injection_mode=str(raw.get("injection_mode", defaults.injection_mode)),
audio_cache_max_bytes=self._coerce_positive_int(
raw.get("audio_cache_max_bytes", defaults.audio_cache_max_bytes),
"audio_cache_max_bytes",
),
)
def _config_to_mapping(self, config: AppConfig) -> dict[str, Any]:
@ -221,6 +241,7 @@ class ConfigService:
"logs_root_directory": config.paths.logs_root_directory,
"config_path": config.paths.config_path or str(self._config_path),
"history_db_path": config.paths.history_db_path,
"audio_cache_directory": config.paths.audio_cache_directory,
},
"model_name": config.model_name,
"backend_mode": config.backend_mode,
@ -234,6 +255,7 @@ class ConfigService:
},
"history_limit": config.history_limit,
"injection_mode": config.injection_mode,
"audio_cache_max_bytes": config.audio_cache_max_bytes,
}
@staticmethod

View File

@ -1,13 +1,13 @@
from __future__ import annotations
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass, field
from datetime import datetime, timezone
import sqlite3
from pathlib import Path
from collections.abc import Iterable
import sqlite3
HISTORY_SCHEMA_VERSION = 1
HISTORY_SCHEMA_VERSION = 2
HISTORY_META_TABLE_NAME = "history_meta"
HISTORY_ENTRIES_TABLE_NAME = "history_entries"
HISTORY_SCHEMA_VERSION_KEY = "schema_version"
@ -27,6 +27,7 @@ class HistoryRecord:
transcript_text: str = ""
injection_status: str = ""
error_text: str = ""
audio_cache_path: str = ""
def __post_init__(self) -> None:
self.timestamp_utc = _coerce_aware_utc_datetime(self.timestamp_utc)
@ -36,9 +37,11 @@ class HistoryRecord:
self.transcript_text = str(self.transcript_text)
self.injection_status = str(self.injection_status)
self.error_text = str(self.error_text)
self.audio_cache_path = str(self.audio_cache_path)
@classmethod
def from_row(cls, row: sqlite3.Row) -> "HistoryRecord":
row_keys = set(row.keys())
return cls(
id=int(row["id"]),
timestamp_utc=datetime.fromisoformat(row["recorded_at_utc"]),
@ -48,6 +51,7 @@ class HistoryRecord:
transcript_text=str(row["transcript_text"]),
injection_status=str(row["injection_status"]),
error_text=str(row["error_text"]),
audio_cache_path=str(row["audio_cache_path"]) if "audio_cache_path" in row_keys else "",
)
@ -85,6 +89,7 @@ class HistoryStore:
transcript_text: str,
injection_status: str,
error_text: str = "",
audio_cache_path: str = "",
) -> int:
record = HistoryRecord(
timestamp_utc=timestamp_utc or datetime.now(timezone.utc),
@ -94,6 +99,7 @@ class HistoryStore:
transcript_text=transcript_text,
injection_status=injection_status,
error_text=error_text,
audio_cache_path=audio_cache_path,
)
return self.add_record(record)
@ -112,8 +118,9 @@ class HistoryStore:
audio_duration_seconds,
transcript_text,
injection_status,
error_text
) VALUES (?, ?, ?, ?, ?, ?, ?)
error_text,
audio_cache_path
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record.timestamp_utc.isoformat(timespec="milliseconds"),
@ -123,6 +130,7 @@ class HistoryStore:
record.transcript_text,
record.injection_status,
record.error_text,
record.audio_cache_path,
),
)
record_id = int(cursor.lastrowid or 0)
@ -144,7 +152,8 @@ class HistoryStore:
audio_duration_seconds,
transcript_text,
injection_status,
error_text
error_text,
audio_cache_path
FROM {HISTORY_ENTRIES_TABLE_NAME}
ORDER BY recorded_at_utc DESC, id DESC
"""
@ -176,7 +185,8 @@ class HistoryStore:
audio_duration_seconds,
transcript_text,
injection_status,
error_text
error_text,
audio_cache_path
FROM {HISTORY_ENTRIES_TABLE_NAME}
WHERE id = ?
""",
@ -264,7 +274,8 @@ class HistoryStore:
audio_duration_seconds REAL NOT NULL,
transcript_text TEXT NOT NULL,
injection_status TEXT NOT NULL,
error_text TEXT NOT NULL DEFAULT ''
error_text TEXT NOT NULL DEFAULT '',
audio_cache_path TEXT NOT NULL DEFAULT ''
)
"""
)
@ -289,11 +300,36 @@ class HistoryStore:
return
stored_version = int(row["value"])
if stored_version != HISTORY_SCHEMA_VERSION:
if stored_version == HISTORY_SCHEMA_VERSION:
return
if stored_version > HISTORY_SCHEMA_VERSION:
raise HistoryStoreError(
f"Unsupported history schema version: {stored_version} (expected {HISTORY_SCHEMA_VERSION})."
)
self._migrate_schema(connection, stored_version)
def _migrate_schema(self, connection: sqlite3.Connection, stored_version: int) -> None:
if stored_version == 1:
if not self._table_has_column(connection, HISTORY_ENTRIES_TABLE_NAME, "audio_cache_path"):
connection.execute(
f"ALTER TABLE {HISTORY_ENTRIES_TABLE_NAME} ADD COLUMN audio_cache_path TEXT NOT NULL DEFAULT ''"
)
connection.execute(
f"UPDATE {HISTORY_META_TABLE_NAME} SET value = ? WHERE key = ?",
(str(HISTORY_SCHEMA_VERSION), HISTORY_SCHEMA_VERSION_KEY),
)
return
raise HistoryStoreError(
f"Unsupported history schema version: {stored_version} (expected {HISTORY_SCHEMA_VERSION})."
)
@staticmethod
def _table_has_column(connection: sqlite3.Connection, table_name: str, column_name: str) -> bool:
rows = connection.execute(f"PRAGMA table_info({table_name})").fetchall()
return any(str(row[1]) == column_name for row in rows)
def _coerce_aware_utc_datetime(value: datetime) -> datetime:
if not isinstance(value, datetime):

View File

@ -0,0 +1,69 @@
from __future__ import annotations
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
import shutil
import wave
from audio.audio_cache_service import AudioCacheService
@contextmanager
def workspace_root(name: str):
root = Path.cwd() / ".tmp" / "tests" / "unit" / name
shutil.rmtree(root, ignore_errors=True)
root.mkdir(parents=True, exist_ok=True)
try:
yield root
finally:
shutil.rmtree(root, ignore_errors=True)
def test_audio_cache_service_creates_wav_recording_and_deletes_files() -> None:
with workspace_root("audio_cache_service_create") as root:
service = AudioCacheService(root / "cache", 1024 * 1024)
recording = service.create_recording(
started_at_utc=datetime(2026, 4, 8, 12, 30, 45, tzinfo=timezone.utc),
sample_rate=16000,
channels=1,
)
recording.write_pcm_bytes(bytes([1, 0, 2, 0]))
recording.close()
cache_path = recording.cache_path
assert cache_path.exists()
assert cache_path.parent == root / "cache"
with wave.open(str(cache_path), "rb") as wav_file:
assert wav_file.getnchannels() == 1
assert wav_file.getframerate() == 16000
assert wav_file.getsampwidth() == 2
assert wav_file.readframes(2) == bytes([1, 0, 2, 0])
removed_count = service.delete_cached_files([cache_path])
assert removed_count == 1
assert not cache_path.exists()
def test_audio_cache_service_prunes_oldest_managed_files_by_total_size() -> None:
with workspace_root("audio_cache_service_prune") as root:
cache_dir = root / "cache"
cache_dir.mkdir(parents=True, exist_ok=True)
first = cache_dir / "voiceptt_audio_20260408T120000_aaaa.wav"
second = cache_dir / "voiceptt_audio_20260408T120100_bbbb.wav"
third = cache_dir / "voiceptt_audio_20260408T120200_cccc.wav"
first.write_bytes(b"a" * 40)
second.write_bytes(b"b" * 50)
third.write_bytes(b"c" * 60)
service = AudioCacheService(cache_dir, 100)
result = service.prune_cache()
assert result.limit_bytes == 100
assert result.total_before_bytes == 150
assert result.total_after_bytes == 60
assert result.removed_count == 2
assert result.removed_paths == (first, second)
assert not first.exists()
assert not second.exists()
assert third.exists()

View File

@ -1,11 +1,14 @@
from __future__ import annotations
import shutil
import wave
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
import pytest
from audio.audio_cache_service import AudioCacheService
from audio.capture_service import (
AudioCaptureInProgressError,
AudioCaptureNotRunningError,
@ -60,7 +63,7 @@ class Clock:
return value
def test_capture_service_buffers_pcm_and_returns_segment() -> None:
def test_capture_service_buffers_pcm_and_writes_wav_cache_file() -> None:
created_streams: list[FakeStream] = []
def stream_factory(**kwargs):
@ -69,31 +72,47 @@ def test_capture_service_buffers_pcm_and_returns_segment() -> None:
return stream
clock = Clock(10.0, 12.5)
service = AudioCaptureService(stream_factory=stream_factory, clock=clock)
request = AudioCaptureRequest(device="USB Mic", sample_rate=16000, channels=1, blocksize=256, max_duration_seconds=5.0)
with workspace_root("audio_capture_service_cache") as root:
cache_service = AudioCacheService(root / "cache", 10_000_000)
service = AudioCaptureService(
stream_factory=stream_factory,
clock=clock,
audio_cache_service=cache_service,
utc_now=lambda: datetime(2026, 4, 8, 12, 30, 45, tzinfo=timezone.utc),
)
request = AudioCaptureRequest(device="USB Mic", sample_rate=16000, channels=1, blocksize=256, max_duration_seconds=5.0)
service.start_recording(request)
assert service.is_recording is True
assert service.current_device == "USB Mic"
service.start_recording(request)
assert service.is_recording is True
assert service.current_device == "USB Mic"
created_streams[0].emit(b"ab")
created_streams[0].emit(b"cd")
created_streams[0].emit(bytes([1, 0]))
created_streams[0].emit(bytes([2, 0]))
segment = service.stop_recording()
segment = service.stop_recording()
assert segment.pcm_bytes == b"abcd"
assert segment.sample_rate == 16000
assert segment.channels == 1
assert segment.device == "USB Mic"
assert segment.started_at == 10.0
assert segment.stopped_at == 12.5
assert segment.duration_seconds == 2.5
assert segment.total_frames == 2
assert segment.truncated is False
assert created_streams[0].started is True
assert created_streams[0].stopped is True
assert created_streams[0].closed is True
assert service.is_recording is False
assert segment.pcm_bytes == bytes([1, 0, 2, 0])
assert segment.sample_rate == 16000
assert segment.channels == 1
assert segment.device == "USB Mic"
assert segment.started_at == 10.0
assert segment.stopped_at == 12.5
assert segment.duration_seconds == 2.5
assert segment.total_frames == 2
assert segment.truncated is False
assert segment.audio_cache_path
cache_path = Path(segment.audio_cache_path)
assert cache_path.parent == root / "cache"
assert cache_path.exists()
with wave.open(str(cache_path), "rb") as wav_file:
assert wav_file.getnchannels() == 1
assert wav_file.getframerate() == 16000
assert wav_file.getsampwidth() == 2
assert wav_file.readframes(2) == bytes([1, 0, 2, 0])
assert created_streams[0].started is True
assert created_streams[0].stopped is True
assert created_streams[0].closed is True
assert service.is_recording is False
def test_capture_service_truncates_at_max_duration_and_marks_segment_truncated() -> None:
@ -105,18 +124,27 @@ def test_capture_service_truncates_at_max_duration_and_marks_segment_truncated()
return stream
clock = Clock(100.0, 101.0)
service = AudioCaptureService(stream_factory=stream_factory, clock=clock)
request = AudioCaptureRequest(sample_rate=1, channels=1, blocksize=2, max_duration_seconds=1.0)
with workspace_root("audio_capture_service_truncate") as root:
cache_service = AudioCacheService(root / "cache", 10_000_000)
service = AudioCaptureService(
stream_factory=stream_factory,
clock=clock,
audio_cache_service=cache_service,
utc_now=lambda: datetime(2026, 4, 8, 12, 30, 45, tzinfo=timezone.utc),
)
request = AudioCaptureRequest(sample_rate=1, channels=1, blocksize=2, max_duration_seconds=1.0)
service.start_recording(request)
with pytest.raises(RuntimeError):
created_streams[0].emit(b"aa")
service.start_recording(request)
with pytest.raises(RuntimeError):
created_streams[0].emit(b"aa")
segment = service.stop_recording()
segment = service.stop_recording()
assert segment.pcm_bytes == b"aa"
assert segment.total_frames == 1
assert segment.truncated is True
assert segment.pcm_bytes == b"aa"
assert segment.total_frames == 1
assert segment.truncated is True
assert segment.audio_cache_path
assert Path(segment.audio_cache_path).exists()
def test_capture_service_rejects_invalid_state_transitions() -> None:

View File

@ -11,6 +11,7 @@ from core.config_service import (
ConfigError,
ConfigService,
DEFAULT_BACKEND_MODE,
DEFAULT_AUDIO_CACHE_MAX_BYTES,
DEFAULT_HISTORY_LIMIT,
DEFAULT_HOTKEY,
DEFAULT_INJECTION_MODE,
@ -47,6 +48,7 @@ def test_default_config_uses_appdata_paths(monkeypatch: pytest.MonkeyPatch) -> N
assert config.paths.logs_root_directory == str(expected_root / "logs")
assert config.paths.config_path == str(expected_root / "config.json")
assert config.paths.history_db_path == str(expected_root / "history.db")
assert config.paths.audio_cache_directory == str(expected_root / "audio_cache")
assert config.model_name == DEFAULT_MODEL_NAME
assert config.backend_mode == DEFAULT_BACKEND_MODE
assert config.hotkey == DEFAULT_HOTKEY
@ -57,6 +59,7 @@ def test_default_config_uses_appdata_paths(monkeypatch: pytest.MonkeyPatch) -> N
assert config.logging.backup_count == DEFAULT_LOG_BACKUP_COUNT
assert config.history_limit == DEFAULT_HISTORY_LIMIT
assert config.injection_mode == DEFAULT_INJECTION_MODE
assert config.audio_cache_max_bytes == DEFAULT_AUDIO_CACHE_MAX_BYTES
def test_load_missing_file_returns_defaults_and_creates_directories(monkeypatch: pytest.MonkeyPatch) -> None:
@ -70,6 +73,7 @@ def test_load_missing_file_returns_defaults_and_creates_directories(monkeypatch:
assert service.config_path.parent.exists()
assert Path(config.paths.logs_root_directory).exists()
assert Path(config.paths.history_db_path).parent.exists()
assert Path(config.paths.audio_cache_directory).exists()
assert config.selected_input_device == DEFAULT_SELECTED_INPUT_DEVICE
@ -103,11 +107,13 @@ def test_load_partial_config_merges_defaults(monkeypatch: pytest.MonkeyPatch) ->
assert config.paths.logs_root_directory == str(appdata_root / "VoicePTT" / "logs")
assert config.paths.config_path == str(config_path)
assert config.paths.history_db_path == str(appdata_root / "VoicePTT" / "history.db")
assert config.paths.audio_cache_directory == str(appdata_root / "VoicePTT" / "audio_cache")
assert config.logging.level == "DEBUG"
assert config.logging.file_name == DEFAULT_LOG_FILE_NAME
assert config.model_name == "medium"
assert config.backend_mode == DEFAULT_BACKEND_MODE
assert config.history_limit == DEFAULT_HISTORY_LIMIT
assert config.audio_cache_max_bytes == DEFAULT_AUDIO_CACHE_MAX_BYTES
assert config.selected_input_device == DEFAULT_SELECTED_INPUT_DEVICE
assert config.hotkey == DEFAULT_HOTKEY
@ -121,9 +127,11 @@ def test_save_round_trip(monkeypatch: pytest.MonkeyPatch) -> None:
config.model_name = "base"
config.logging.backup_count = 7
config.paths.logs_root_directory = str(appdata_root / "VoicePTT" / "custom-logs")
config.paths.audio_cache_directory = str(appdata_root / "VoicePTT" / "custom-audio-cache")
config.paths.config_path = str(service.config_path)
config.selected_input_device = "USB Microphone"
config.hotkey = "shift + ctrl + space"
config.audio_cache_max_bytes = 23456789
service.save(config)
loaded = service.load()

View File

@ -1,17 +1,20 @@
from __future__ import annotations
import os
import shutil
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
import shutil
import wave
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMessageBox
from PySide6.QtWidgets import QApplication, QFileDialog, QMessageBox
from audio.audio_cache_service import AudioCacheService
from history.history_store import HistoryStore
from ui.history_audio_player import HistoryAudioPlaybackResult
from ui.history_dialog import HistoryDialog
@ -33,7 +36,21 @@ def _app() -> QApplication:
return QApplication([])
def _seed_history(store: HistoryStore) -> None:
def _write_wav_file(path: Path, frames: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(path), "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(16000)
wav_file.writeframes(frames)
def _seed_history(store: HistoryStore, root: Path) -> tuple[Path, Path]:
older_audio = root / "cache" / "voiceptt_audio_20260408T123000_older.wav"
newer_audio = root / "cache" / "voiceptt_audio_20260408T123500_newer.wav"
_write_wav_file(older_audio, bytes([1, 0, 2, 0]))
_write_wav_file(newer_audio, bytes([3, 0, 4, 0]))
store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 30, 0, tzinfo=timezone.utc),
selected_model="base",
@ -41,6 +58,7 @@ def _seed_history(store: HistoryStore) -> None:
audio_duration_seconds=4.0,
transcript_text="older transcript",
injection_status="success",
audio_cache_path=str(older_audio),
)
store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 35, 0, tzinfo=timezone.utc),
@ -49,18 +67,33 @@ def _seed_history(store: HistoryStore) -> None:
audio_duration_seconds=8.5,
transcript_text="newer transcript",
injection_status="success",
audio_cache_path=str(newer_audio),
)
return older_audio, newer_audio
def test_history_dialog_loads_records_and_copies_selected_transcript() -> None:
class FakeAudioPlayer:
def __init__(self, *, success: bool = True, error_message: str = "") -> None:
self.success = success
self.error_message = error_message
self.play_calls: list[Path] = []
def play(self, audio_path: Path) -> HistoryAudioPlaybackResult:
self.play_calls.append(audio_path)
if self.success:
return HistoryAudioPlaybackResult(success=True)
return HistoryAudioPlaybackResult(success=False, error_message=self.error_message or "playback failed")
def test_history_dialog_loads_records_and_supports_audio_actions(monkeypatch) -> None:
app = _app()
with workspace_root("history_dialog_load") as root:
store = HistoryStore(root / "history.db")
_seed_history(store)
_seed_history(store, root)
player = FakeAudioPlayer()
dialog = HistoryDialog(store, audio_player=player)
dialog = HistoryDialog(store)
assert dialog.history_table.columnCount() == 7
assert dialog.history_table.columnCount() == 10
assert dialog.history_table.rowCount() == 2
assert dialog.summary_label.text() == "2 transcription record(s) available."
assert dialog.selected_record() is not None
@ -69,9 +102,13 @@ def test_history_dialog_loads_records_and_copies_selected_transcript() -> None:
assert dialog.model_value.text() == "small"
assert dialog.backend_value.text() == "cuda"
assert dialog.duration_value.text() == "8.5s"
assert dialog.audio_cache_value.text().endswith("voiceptt_audio_20260408T123500_newer.wav")
assert dialog.transcription_value.toPlainText() == "newer transcript"
assert dialog.history_table.item(0, 0).checkState() == Qt.CheckState.Unchecked
assert dialog.history_table.horizontalHeader().check_state() == Qt.CheckState.Unchecked
assert dialog.history_table.item(0, 6).text() == "Cached"
assert dialog.history_table.cellWidget(0, 8).isEnabled()
assert dialog.history_table.cellWidget(0, 9).isEnabled()
dialog.history_table.horizontalHeader().sectionClicked.emit(0)
app.processEvents()
@ -94,65 +131,69 @@ def test_history_dialog_loads_records_and_copies_selected_transcript() -> None:
assert dialog.copy_selected_transcript() is True
assert clipboard.text() == "older transcript"
dialog.history_table.cellWidget(0, 8).click()
app.processEvents()
assert player.play_calls and player.play_calls[0].name.endswith("newer.wav")
export_path = root / "exports" / "copied.wav"
monkeypatch.setattr(QFileDialog, "getSaveFileName", lambda *args, **kwargs: (str(export_path), "WAV files (*.wav)"))
dialog.history_table.cellWidget(0, 9).click()
app.processEvents()
assert export_path.exists()
assert export_path.read_bytes() == player.play_calls[0].read_bytes()
dialog.close()
app.processEvents()
def test_history_dialog_deletes_selected_records_and_refreshes_view(monkeypatch) -> None:
def test_history_dialog_deletes_selected_records_and_removes_cached_files(monkeypatch) -> None:
app = _app()
with workspace_root("history_dialog_delete") as root:
store = HistoryStore(root / "history.db")
_seed_history(store)
older_audio, newer_audio = _seed_history(store, root)
audio_cache_service = AudioCacheService(root / "cache", 1024 * 1024)
dialog = HistoryDialog(store)
dialog = HistoryDialog(store, audio_cache_service=audio_cache_service)
dialog.set_all_records_checked(True)
dialog.history_table.selectRow(0)
app.processEvents()
monkeypatch.setattr(QMessageBox, "question", lambda *args, **kwargs: QMessageBox.StandardButton.Yes)
monkeypatch.setattr(QMessageBox, "warning", lambda *args, **kwargs: None)
monkeypatch.setattr(QMessageBox, "information", lambda *args, **kwargs: None)
assert dialog.delete_selected_records() is True
assert store.count() == 0
assert dialog.history_table.rowCount() == 0
assert dialog.selected_record() is None
assert dialog.history_table.horizontalHeader().check_state() == Qt.CheckState.Unchecked
assert not older_audio.exists()
assert not newer_audio.exists()
dialog.close()
app.processEvents()
def test_history_dialog_delete_button_deletes_only_checked_rows(monkeypatch) -> None:
def test_history_dialog_disables_audio_buttons_when_cache_missing() -> None:
app = _app()
with workspace_root("history_dialog_delete_selected") as root:
with workspace_root("history_dialog_missing_audio") as root:
store = HistoryStore(root / "history.db")
_seed_history(store)
store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 40, 0, tzinfo=timezone.utc),
selected_model="medium",
effective_backend="cuda",
audio_duration_seconds=12.0,
transcript_text="third transcript",
timestamp_utc=datetime(2026, 4, 8, 12, 30, 0, tzinfo=timezone.utc),
selected_model="base",
effective_backend="cpu",
audio_duration_seconds=4.0,
transcript_text="missing audio transcript",
injection_status="success",
audio_cache_path=str(root / "cache" / "missing.wav"),
)
dialog = HistoryDialog(store, audio_player=FakeAudioPlayer())
dialog = HistoryDialog(store)
dialog.history_table.item(0, 0).setCheckState(Qt.CheckState.Checked)
dialog.history_table.item(2, 0).setCheckState(Qt.CheckState.Checked)
dialog.history_table.selectRow(1)
app.processEvents()
monkeypatch.setattr(QMessageBox, "question", lambda *args, **kwargs: QMessageBox.StandardButton.Yes)
monkeypatch.setattr(QMessageBox, "warning", lambda *args, **kwargs: None)
assert dialog.delete_selected_records() is True
assert store.count() == 1
remaining = store.list_records()
assert len(remaining) == 1
assert remaining[0].selected_model == "small"
assert dialog.history_table.rowCount() == 1
assert dialog.selected_record() is not None
assert dialog.selected_record().selected_model == "small"
assert dialog.history_table.item(0, 6).text() == "Missing"
assert not dialog.history_table.cellWidget(0, 8).isEnabled()
assert not dialog.history_table.cellWidget(0, 9).isEnabled()
assert dialog.audio_cache_value.text().startswith("Missing:")
dialog.close()
app.processEvents()

View File

@ -1,9 +1,9 @@
from __future__ import annotations
from __future__ import annotations
import shutil
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
import shutil
import sqlite3
import pytest
@ -36,6 +36,7 @@ def test_history_store_initializes_schema_and_round_trips_records() -> None:
store = HistoryStore(db_path)
timestamp = datetime(2026, 4, 8, 12, 30, 45, tzinfo=timezone.utc)
audio_cache_path = str(root / "cache" / "recording.wav")
record_id = store.record_session(
timestamp_utc=timestamp,
selected_model="small",
@ -44,6 +45,7 @@ def test_history_store_initializes_schema_and_round_trips_records() -> None:
transcript_text="hello world",
injection_status="success",
error_text="",
audio_cache_path=audio_cache_path,
)
assert record_id == 1
@ -60,6 +62,7 @@ def test_history_store_initializes_schema_and_round_trips_records() -> None:
assert record.transcript_text == "hello world"
assert record.injection_status == "success"
assert record.error_text == ""
assert record.audio_cache_path == audio_cache_path
records = store.list_records()
assert records == [record]
@ -78,6 +81,10 @@ def test_history_store_initializes_schema_and_round_trips_records() -> None:
).fetchall()
assert {row[0] for row in table_row} == {HISTORY_META_TABLE_NAME, HISTORY_ENTRIES_TABLE_NAME}
columns = connection.execute(f"PRAGMA table_info({HISTORY_ENTRIES_TABLE_NAME})").fetchall()
column_names = {row[1] for row in columns}
assert "audio_cache_path" in column_names
def test_history_store_delete_and_clear() -> None:
with workspace_root("history_store_cleanup") as root:
@ -92,6 +99,7 @@ def test_history_store_delete_and_clear() -> None:
transcript_text="first",
injection_status="success",
error_text="",
audio_cache_path=str(root / "cache" / "first.wav"),
)
second_id = store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 31, 0, tzinfo=timezone.utc),
@ -101,6 +109,7 @@ def test_history_store_delete_and_clear() -> None:
transcript_text="second",
injection_status="failed",
error_text="transcription error",
audio_cache_path=str(root / "cache" / "second.wav"),
)
assert store.count() == 2
@ -125,6 +134,7 @@ def test_history_store_delete_multiple_records() -> None:
audio_duration_seconds=4.0,
transcript_text="first",
injection_status="success",
audio_cache_path=str(root / "cache" / "first.wav"),
)
second_id = store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 31, 0, tzinfo=timezone.utc),
@ -133,6 +143,7 @@ def test_history_store_delete_multiple_records() -> None:
audio_duration_seconds=5.0,
transcript_text="second",
injection_status="success",
audio_cache_path=str(root / "cache" / "second.wav"),
)
third_id = store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 31, 15, tzinfo=timezone.utc),
@ -141,6 +152,7 @@ def test_history_store_delete_multiple_records() -> None:
audio_duration_seconds=6.0,
transcript_text="third",
injection_status="success",
audio_cache_path=str(root / "cache" / "third.wav"),
)
deleted = store.delete_records([first_id, third_id, third_id])
@ -152,6 +164,83 @@ def test_history_store_delete_multiple_records() -> None:
assert store.delete_records([]) == 0
def test_history_store_migrates_v1_schema_to_v2() -> None:
with workspace_root("history_store_migration") as root:
db_path = root / "history.db"
with sqlite3.connect(db_path) as connection:
connection.execute(
f"""
CREATE TABLE {HISTORY_META_TABLE_NAME} (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
"""
)
connection.execute(
f"""
CREATE TABLE {HISTORY_ENTRIES_TABLE_NAME} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recorded_at_utc TEXT NOT NULL,
selected_model TEXT NOT NULL,
effective_backend TEXT NOT NULL,
audio_duration_seconds REAL NOT NULL,
transcript_text TEXT NOT NULL,
injection_status TEXT NOT NULL,
error_text TEXT NOT NULL DEFAULT ''
)
"""
)
connection.execute(
f"INSERT INTO {HISTORY_META_TABLE_NAME} (key, value) VALUES (?, ?)",
(HISTORY_SCHEMA_VERSION_KEY, "1"),
)
connection.execute(
f"""
INSERT INTO {HISTORY_ENTRIES_TABLE_NAME} (
recorded_at_utc,
selected_model,
effective_backend,
audio_duration_seconds,
transcript_text,
injection_status,
error_text
) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
datetime(2026, 4, 8, 12, 30, 45, tzinfo=timezone.utc).isoformat(timespec="milliseconds"),
"small",
"cpu",
1.0,
"legacy",
"success",
"",
),
)
connection.commit()
store = HistoryStore(db_path)
record = store.get_record(1)
assert record is not None
assert record.audio_cache_path == ""
assert store.record_session(
timestamp_utc=datetime(2026, 4, 8, 12, 35, 0, tzinfo=timezone.utc),
selected_model="small",
effective_backend="cpu",
audio_duration_seconds=2.0,
transcript_text="new",
injection_status="success",
audio_cache_path=str(root / "cache" / "new.wav"),
) == 2
with sqlite3.connect(db_path) as connection:
meta_row = connection.execute(
f"SELECT value FROM {HISTORY_META_TABLE_NAME} WHERE key = ?",
(HISTORY_SCHEMA_VERSION_KEY,),
).fetchone()
assert meta_row is not None
assert int(meta_row[0]) == HISTORY_SCHEMA_VERSION
def test_history_store_rejects_naive_timestamps() -> None:
with workspace_root("history_store_naive_timestamp") as root:
db_path = root / "history.db"

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
import os
from dataclasses import dataclass
@ -181,6 +181,9 @@ class FakeHistoryStore:
self.record_count = 0
return deleted
def list_records(self) -> list[object]:
return [object() for _ in range(self.record_count)]
class FakeHistoryPruner:
def __init__(self, history_limit: int = 0) -> None:
@ -191,6 +194,13 @@ class FakeHistoryPruner:
self.set_calls.append(history_limit)
self.history_limit = history_limit
class FakeAudioCacheService:
def __init__(self) -> None:
self.calls: list[tuple[str, int]] = []
def update_settings(self, audio_cache_directory: str, audio_cache_max_bytes: int) -> None:
self.calls.append((audio_cache_directory, audio_cache_max_bytes))
class FakeAudioDeviceService:
def __init__(self, discovery: AudioDeviceDiscoveryResult | None = None) -> None:
self.discovery = discovery or AudioDeviceDiscoveryResult(
@ -272,6 +282,7 @@ def _snapshot(hotkey: str = "shift + alt + space") -> SettingsDialogState:
hotkey=hotkey,
microphone_device="2",
logs_root_directory=r"D:\Logs",
audio_cache_directory=r"D:\Cache",
logging=LoggingConfig(
level="DEBUG",
file_name="voice_ptt.log",
@ -279,6 +290,7 @@ def _snapshot(hotkey: str = "shift + alt + space") -> SettingsDialogState:
backup_count=3,
),
history_limit=250,
audio_cache_max_bytes=1024 * 1024 * 1024,
config_path=r"D:\VoicePTT\config.json",
history_db_path=r"D:\VoicePTT\history.db",
)
@ -762,3 +774,48 @@ def test_apply_snapshot_updates_history_pruner_limit_on_save() -> None:
assert history_pruner.history_limit == 400
assert config.history_limit == 400
assert config_service.saved_configs == [config]
def test_apply_snapshot_updates_audio_cache_service_settings_on_save() -> None:
_app()
window = FakeWindow()
config = AppConfig()
config.paths.config_path = str(Path.cwd() / "tests" / "unit" / "settings_controller" / "config.json")
config.paths.history_db_path = str(Path.cwd() / "tests" / "unit" / "settings_controller" / "history.db")
config.paths.logs_root_directory = r"D:\Logs"
config.paths.models_root_directory = r"D:\Models"
config.paths.audio_cache_directory = r"D:\Cache"
config.hotkey = "Ctrl+Shift+Space"
config.model_name = "medium"
config.backend_mode = "cuda"
config.audio_cache_max_bytes = 1024 * 1024 * 1024
config_service = FakeConfigService()
hotkey_service = FakeHotkeyService()
model_manager = FakeModelManager(
loaded_model=_loaded_state("medium", r"D:\Models", "cuda", "cuda", "float16")
)
audio_cache_service = FakeAudioCacheService()
logging_service = FakeLoggingService()
controller = SettingsController(
window,
config_service,
config,
hotkey_service,
model_manager,
logging_service=logging_service,
audio_cache_service=audio_cache_service,
)
snapshot = _snapshot("Ctrl+Shift+Space")
snapshot.model_name = "medium"
snapshot.models_root_directory = r"D:\Models"
snapshot.backend_mode = "cuda"
snapshot.audio_cache_directory = r"D:\NewCache"
snapshot.audio_cache_max_bytes = 512 * 1024 * 1024
result = controller.apply_snapshot(snapshot)
assert result.success
assert audio_cache_service.calls == [(r"D:\NewCache", 512 * 1024 * 1024)]
assert config.paths.audio_cache_directory == r"D:\NewCache"
assert config.audio_cache_max_bytes == 512 * 1024 * 1024

View File

@ -27,6 +27,7 @@ def test_settings_dialog_shell_builds_all_tabs_and_loads_config() -> None:
config.hotkey = "shift + ctrl + space"
config.paths.models_root_directory = r"D:\Models"
config.paths.logs_root_directory = r"D:\Logs"
config.paths.audio_cache_directory = r"D:\AudioCache"
config.paths.config_path = r"D:\VoicePTT\config.json"
config.paths.history_db_path = r"D:\VoicePTT\history.db"
config.logging.level = "DEBUG"
@ -34,6 +35,7 @@ def test_settings_dialog_shell_builds_all_tabs_and_loads_config() -> None:
config.logging.rotation_bytes = 2048
config.logging.backup_count = 3
config.history_limit = 250
config.audio_cache_max_bytes = 1024 * 1024 * 1024
config.injection_mode = "direct_typing"
dialog = SettingsDialog(config)
@ -98,6 +100,8 @@ def test_settings_dialog_shell_builds_all_tabs_and_loads_config() -> None:
assert snapshot.hotkey == "Ctrl+Shift+Space"
assert snapshot.models_root_directory == r"D:\Models"
assert snapshot.logs_root_directory == r"D:\Logs"
assert snapshot.audio_cache_directory == r"D:\AudioCache"
assert snapshot.audio_cache_max_bytes == 1024 * 1024 * 1024
assert snapshot.logging.level == "DEBUG"
assert snapshot.history_limit == 250
assert snapshot.microphone_device == "1"

View File

@ -286,6 +286,7 @@ def test_ptt_to_transcription_flow_updates_transcript_status_and_inserts_target_
"transcript_text": "Hello world",
"injection_status": "success",
"error_text": "",
"audio_cache_path": "",
}
]
assert history_pruner.calls == 1
@ -411,6 +412,7 @@ def test_ptt_to_transcription_flow_reports_missing_model_error() -> None:
"transcript_text": "",
"injection_status": "failed",
"error_text": "No model is loaded.",
"audio_cache_path": "",
}
]
assert history_pruner.calls == 1
@ -447,6 +449,7 @@ def test_capture_failure_is_persisted_to_history() -> None:
"transcript_text": "",
"injection_status": "failed",
"error_text": "microphone unavailable",
"audio_cache_path": "",
}
]
assert history_pruner.calls == 1

View File

@ -0,0 +1,52 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from PySide6.QtCore import QUrl
@dataclass(frozen=True, slots=True)
class HistoryAudioPlaybackResult:
success: bool
error_message: str = ""
class HistoryAudioPlayer:
def play(self, audio_path: Path) -> HistoryAudioPlaybackResult:
raise NotImplementedError
class QtHistoryAudioPlayer(HistoryAudioPlayer):
def __init__(self, parent=None) -> None:
self._available = False
self._error_message = ""
self._player = None
self._audio_output = None
try:
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
except Exception as exc: # pragma: no cover - depends on optional Qt module availability
self._error_message = f"Qt multimedia is unavailable: {exc}"
return
self._audio_output = QAudioOutput(parent)
self._player = QMediaPlayer(parent)
self._player.setAudioOutput(self._audio_output)
self._available = True
def play(self, audio_path: Path) -> HistoryAudioPlaybackResult:
if not self._available or self._player is None:
return HistoryAudioPlaybackResult(success=False, error_message=self._error_message or "Audio playback is unavailable.")
if not audio_path.exists():
return HistoryAudioPlaybackResult(success=False, error_message=f"Audio cache file does not exist: {audio_path}")
try:
self._player.stop()
self._player.setSource(QUrl.fromLocalFile(str(audio_path)))
self._player.play()
except Exception as exc: # pragma: no cover - depends on Qt runtime state
return HistoryAudioPlaybackResult(success=False, error_message=str(exc).strip() or exc.__class__.__name__)
return HistoryAudioPlaybackResult(success=True)

View File

@ -1,6 +1,8 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import shutil
from PySide6.QtCore import Qt
from PySide6.QtGui import QPainter
@ -8,9 +10,11 @@ from PySide6.QtWidgets import (
QApplication,
QDialog,
QDialogButtonBox,
QFileDialog,
QFormLayout,
QFrame,
QHeaderView,
QHBoxLayout,
QLabel,
QMessageBox,
QPushButton,
@ -24,7 +28,9 @@ from PySide6.QtWidgets import (
QWidget,
)
from history.history_store import HistoryRecord, HistoryStore
from audio.audio_cache_service import AudioCacheService
from history.history_store import HistoryRecord, HistoryStore, HistoryStoreError
from ui.history_audio_player import HistoryAudioPlayer, QtHistoryAudioPlayer
class SelectAllHeaderView(QHeaderView):
@ -66,13 +72,21 @@ class SelectAllHeaderView(QHeaderView):
class HistoryDialog(QDialog):
def __init__(self, history_store: HistoryStore, parent: QWidget | None = None) -> None:
def __init__(
self,
history_store: HistoryStore,
parent: QWidget | None = None,
audio_cache_service: AudioCacheService | None = None,
audio_player: HistoryAudioPlayer | None = None,
) -> None:
super().__init__(parent)
self.setWindowTitle("History")
self.setModal(True)
self.resize(1100, 720)
self.resize(1260, 760)
self._history_store = history_store
self._audio_cache_service = audio_cache_service
self._audio_player = audio_player or QtHistoryAudioPlayer(self)
self._records: list[HistoryRecord] = []
self._selected_record_index: int = -1
@ -89,7 +103,7 @@ class HistoryDialog(QDialog):
title.setWordWrap(True)
subtitle = QLabel(
"Browse stored transcription sessions, inspect transcripts, copy text, or delete selected records."
"Browse stored transcription sessions, inspect transcripts, play cached audio, copy text, export WAVs, or delete selected records."
)
subtitle.setObjectName("historySubtitle")
subtitle.setWordWrap(True)
@ -108,7 +122,7 @@ class HistoryDialog(QDialog):
self.summary_label = QLabel("")
self.summary_label.setWordWrap(True)
self.history_table = QTableWidget(0, 7, self)
self.history_table = QTableWidget(0, 10, self)
self.history_table.setHorizontalHeaderLabels([
"",
"Recorded at",
@ -116,7 +130,10 @@ class HistoryDialog(QDialog):
"Backend",
"Duration",
"Injection",
"Audio",
"Error",
"Play",
"Save As",
])
self.history_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
self.history_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
@ -128,6 +145,8 @@ class HistoryDialog(QDialog):
header.sectionClicked.connect(self._on_header_section_clicked)
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
header.resizeSection(0, 42)
header.setSectionResizeMode(8, QHeaderView.ResizeMode.ResizeToContents)
header.setSectionResizeMode(9, QHeaderView.ResizeMode.ResizeToContents)
self.history_table.itemChanged.connect(self._sync_checkbox_state_from_table)
self.history_table.itemSelectionChanged.connect(self._sync_selection_from_table)
@ -149,8 +168,10 @@ class HistoryDialog(QDialog):
self.backend_value = QLabel("-")
self.duration_value = QLabel("-")
self.injection_value = QLabel("-")
self.audio_cache_value = QLabel("-")
self.error_value = QLabel("-")
self.error_value.setWordWrap(True)
self.audio_cache_value.setWordWrap(True)
details_layout.addRow("Record ID", self.record_id_value)
details_layout.addRow("Recorded at", self.timestamp_value)
@ -158,6 +179,7 @@ class HistoryDialog(QDialog):
details_layout.addRow("Backend", self.backend_value)
details_layout.addRow("Duration", self.duration_value)
details_layout.addRow("Injection", self.injection_value)
details_layout.addRow("Audio cache", self.audio_cache_value)
details_layout.addRow("Error", self.error_value)
self.transcription_value = QPlainTextEdit(self)
@ -174,7 +196,7 @@ class HistoryDialog(QDialog):
splitter.addWidget(right_panel)
splitter.setStretchFactor(0, 3)
splitter.setStretchFactor(1, 4)
splitter.setSizes([480, 620])
splitter.setSizes([640, 620])
root_layout.addWidget(splitter, 1)
root_layout.addWidget(self._build_footer())
@ -199,7 +221,12 @@ class HistoryDialog(QDialog):
return button_box
def refresh_records(self) -> None:
self._records = list(self._history_store.list_records())
try:
self._records = list(self._history_store.list_records())
except HistoryStoreError as exc:
QMessageBox.warning(self, "History", f"Unable to load history records: {exc}")
self._records = []
self.history_table.blockSignals(True)
self.history_table.setRowCount(0)
self.history_table.setRowCount(len(self._records))
@ -209,6 +236,8 @@ class HistoryDialog(QDialog):
self.history_table.resizeColumnsToContents()
self.history_table.setColumnWidth(0, 42)
self.history_table.setColumnWidth(8, 90)
self.history_table.setColumnWidth(9, 100)
self.history_table.blockSignals(False)
self.summary_label.setText(self._format_summary())
@ -261,11 +290,53 @@ class HistoryDialog(QDialog):
clipboard.setText(record.transcript_text)
return True
def play_record_audio(self, record: HistoryRecord) -> bool:
audio_path = self._resolve_audio_cache_path(record)
if audio_path is None:
QMessageBox.warning(self, "Play audio", "This history record does not have a cached audio file.")
return False
result = self._audio_player.play(audio_path)
if not result.success:
QMessageBox.warning(self, "Play audio", result.error_message or "Unable to play the cached audio file.")
return False
return True
def save_record_audio(self, record: HistoryRecord) -> bool:
source_path = self._resolve_audio_cache_path(record)
if source_path is None:
QMessageBox.warning(self, "Save audio", "This history record does not have a cached audio file.")
return False
default_name = self._default_export_file_name(record)
destination_text, _selected_filter = QFileDialog.getSaveFileName(
self,
"Save cached audio",
str(Path.cwd() / default_name),
"WAV files (*.wav);;All files (*.*)",
)
if not destination_text:
return False
destination = Path(destination_text)
if destination.suffix.lower() != ".wav":
destination = destination.with_suffix(".wav")
try:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source_path, destination)
except OSError as exc:
QMessageBox.warning(self, "Save audio", f"Unable to save cached audio: {exc}")
return False
return True
def delete_selected_records(self) -> bool:
checked_record_ids = self.checked_record_ids()
if not checked_record_ids:
return False
selected_records = [record for record in self._records if record.id in checked_record_ids]
record_count = len(checked_record_ids)
if record_count == 1:
message = "Delete the selected history record? This cannot be undone."
@ -292,6 +363,20 @@ class HistoryDialog(QDialog):
if deleted_count <= 0:
return False
if self._audio_cache_service is not None and deleted_count == record_count:
try:
removed_count = self._audio_cache_service.delete_cached_files(
record.audio_cache_path for record in selected_records
)
if removed_count > 0:
QMessageBox.information(
self,
"Audio cache",
f"Removed {removed_count} cached audio file(s).",
)
except Exception as exc:
QMessageBox.warning(self, "Audio cache", f"Unable to delete cached audio files: {exc}")
self.refresh_records()
return True
@ -311,7 +396,18 @@ class HistoryDialog(QDialog):
self.history_table.setItem(row_index, 3, QTableWidgetItem(record.effective_backend or "-"))
self.history_table.setItem(row_index, 4, QTableWidgetItem(self._format_duration(record.audio_duration_seconds)))
self.history_table.setItem(row_index, 5, QTableWidgetItem(record.injection_status or "-"))
self.history_table.setItem(row_index, 6, QTableWidgetItem(record.error_text or ""))
self.history_table.setItem(row_index, 6, QTableWidgetItem(self._format_audio_cache_status(record)))
self.history_table.setItem(row_index, 7, QTableWidgetItem(record.error_text or ""))
play_button = QPushButton("Play", self.history_table)
play_button.setEnabled(self._resolve_audio_cache_path(record) is not None)
play_button.clicked.connect(lambda _checked=False, rec=record: self.play_record_audio(rec))
self.history_table.setCellWidget(row_index, 8, play_button)
save_button = QPushButton("Save As", self.history_table)
save_button.setEnabled(self._resolve_audio_cache_path(record) is not None)
save_button.clicked.connect(lambda _checked=False, rec=record: self.save_record_audio(rec))
self.history_table.setCellWidget(row_index, 9, save_button)
def _sync_selection_from_table(self) -> None:
row = self.history_table.currentRow()
@ -351,6 +447,7 @@ class HistoryDialog(QDialog):
self.backend_value.setText(record.effective_backend or "-")
self.duration_value.setText(self._format_duration(record.audio_duration_seconds))
self.injection_value.setText(record.injection_status or "-")
self.audio_cache_value.setText(self._format_audio_cache_detail(record))
self.error_value.setText(record.error_text or "No error")
self.transcription_value.setPlainText(record.transcript_text or "")
@ -361,6 +458,7 @@ class HistoryDialog(QDialog):
self.backend_value.setText("-")
self.duration_value.setText("-")
self.injection_value.setText("-")
self.audio_cache_value.setText("-")
self.error_value.setText("-")
self.transcription_value.clear()
@ -388,6 +486,16 @@ class HistoryDialog(QDialog):
return "No transcription history records are stored yet."
return f"{count} transcription record(s) available."
def _resolve_audio_cache_path(self, record: HistoryRecord) -> Path | None:
audio_cache_path = record.audio_cache_path.strip()
if not audio_cache_path:
return None
path = Path(audio_cache_path)
if not path.exists() or not path.is_file():
return None
return path
@staticmethod
def _format_timestamp(value: datetime) -> str:
return value.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
@ -395,3 +503,27 @@ class HistoryDialog(QDialog):
@staticmethod
def _format_duration(seconds: float) -> str:
return f"{seconds:.1f}s"
def _format_audio_cache_status(self, record: HistoryRecord) -> str:
audio_path = record.audio_cache_path.strip()
if not audio_path:
return "Not cached"
path = Path(audio_path)
if path.exists() and path.is_file():
return "Cached"
return "Missing"
def _format_audio_cache_detail(self, record: HistoryRecord) -> str:
audio_path = record.audio_cache_path.strip()
if not audio_path:
return "No cached audio file."
path = Path(audio_path)
if path.exists() and path.is_file():
return str(path)
return f"Missing: {path}"
@staticmethod
def _default_export_file_name(record: HistoryRecord) -> str:
timestamp = record.timestamp_utc.astimezone(timezone.utc).strftime("%Y%m%d_%H%M%S")
record_id = record.id if record.id is not None else "record"
return f"voiceptt_export_{timestamp}_{record_id}.wav"

View File

@ -9,6 +9,7 @@ from PySide6.QtWidgets import QDialog, QMessageBox, QWidget
from asr.model_downloader import ModelDownloadCancelled, ModelDownloadError, ModelDownloadRequest, ModelDownloader
from asr.model_manager import LoadedModelState, ModelManager, ModelManagerError, ModelNotInstalledError
from audio.audio_cache_service import AudioCacheService
from audio.device_service import AudioDeviceService, AudioInputDevice
from core.config_service import AppConfig, ConfigError, ConfigPaths, ConfigService, LoggingConfig
from core.error_messages import ErrorMessageService
@ -45,6 +46,7 @@ class SettingsController(QObject):
logging_service: LoggingService | None = None,
history_store: HistoryStore | None = None,
history_pruner: HistoryPruner | None = None,
audio_cache_service: AudioCacheService | None = None,
model_downloader: ModelDownloader | None = None,
model_download_dialog_factory: Callable[[str, str, QWidget | None], ModelDownloadProgressDialog] | None = None,
microphone_test_dialog_factory: Callable[[AudioInputDevice | None, QWidget | None], MicrophoneTestDialog] | None = None,
@ -62,6 +64,7 @@ class SettingsController(QObject):
self._logging_service = logging_service or LoggingService()
self._history_store = history_store
self._history_pruner = history_pruner
self._audio_cache_service = audio_cache_service
self._model_downloader = model_downloader
self._model_download_dialog_factory = model_download_dialog_factory or ModelDownloadProgressDialog
self._microphone_test_dialog_factory = microphone_test_dialog_factory or MicrophoneTestDialog
@ -164,6 +167,7 @@ class SettingsController(QObject):
self._apply_saved_config(candidate)
self._sync_history_pruner_limit(candidate.history_limit)
self._sync_audio_cache_settings(candidate)
if self._runtime_refresh is not None:
self._runtime_refresh()
else:
@ -222,7 +226,8 @@ class SettingsController(QObject):
return
try:
record_count = self._history_store.count()
records = self._history_store.list_records()
record_count = len(records)
except HistoryStoreError as exc:
message = self._error_messages.history_read_failure(str(exc))
self._logger.warning(message)
@ -253,6 +258,14 @@ class SettingsController(QObject):
QMessageBox.warning(self._window, "History", message)
return
if self._audio_cache_service is not None:
try:
removed_cache_files = self._audio_cache_service.delete_cached_files(record.audio_cache_path for record in records)
if removed_cache_files > 0:
self._logger.info("Removed %s cached audio file(s) while clearing history.", removed_cache_files)
except Exception as exc:
self._logger.warning("Unable to remove cached audio files while clearing history: %s", exc)
dialog.set_history_usage_summary(0)
message = f"Cleared {deleted} history record(s)."
self._window.set_status_message(message)
@ -266,6 +279,7 @@ class SettingsController(QObject):
logs_root_directory=snapshot.logs_root_directory,
config_path=snapshot.config_path or self._config.paths.config_path,
history_db_path=snapshot.history_db_path or self._config.paths.history_db_path,
audio_cache_directory=snapshot.audio_cache_directory or self._config.paths.audio_cache_directory,
),
model_name=snapshot.model_name,
backend_mode=snapshot.backend_mode,
@ -279,6 +293,7 @@ class SettingsController(QObject):
),
history_limit=snapshot.history_limit,
injection_mode=snapshot.injection_mode,
audio_cache_max_bytes=snapshot.audio_cache_max_bytes,
)
AudioDeviceService.set_selected_input_device(candidate, snapshot.microphone_device)
return candidate
@ -340,7 +355,8 @@ class SettingsController(QObject):
return
try:
record_count = self._history_store.count()
records = self._history_store.list_records()
record_count = len(records)
except HistoryStoreError as exc:
self._logger.warning("Unable to read history usage: %s", exc)
dialog.set_history_usage_summary(None)
@ -348,6 +364,18 @@ class SettingsController(QObject):
dialog.set_history_usage_summary(record_count)
def _sync_audio_cache_settings(self, candidate: AppConfig) -> None:
if self._audio_cache_service is None:
return
try:
self._audio_cache_service.update_settings(
candidate.paths.audio_cache_directory,
candidate.audio_cache_max_bytes,
)
except Exception as exc:
self._logger.warning("Unable to update audio cache settings: %s", exc)
def _sync_history_pruner_limit(self, history_limit: int) -> None:
if self._history_pruner is None:
return
@ -399,6 +427,7 @@ class SettingsController(QObject):
self._config.paths.logs_root_directory = saved.paths.logs_root_directory
self._config.paths.config_path = saved.paths.config_path
self._config.paths.history_db_path = saved.paths.history_db_path
self._config.paths.audio_cache_directory = saved.paths.audio_cache_directory
self._config.model_name = saved.model_name
self._config.backend_mode = saved.backend_mode
self._config.hotkey = saved.hotkey
@ -406,6 +435,7 @@ class SettingsController(QObject):
self._config.logging = replace(saved.logging)
self._config.history_limit = saved.history_limit
self._config.injection_mode = saved.injection_mode
self._config.audio_cache_max_bytes = saved.audio_cache_max_bytes

View File

@ -1,4 +1,4 @@
from __future__ import annotations
from __future__ import annotations
from dataclasses import dataclass
@ -7,8 +7,10 @@ from PySide6.QtWidgets import (
QComboBox,
QDialog,
QDialogButtonBox,
QFileDialog,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
@ -33,6 +35,8 @@ class SettingsDialogState:
hotkey: str
microphone_device: str
logs_root_directory: str
audio_cache_directory: str
audio_cache_max_bytes: int
logging: LoggingConfig
history_limit: int
config_path: str
@ -44,7 +48,7 @@ class SettingsDialog(QDialog):
super().__init__(parent)
self.setWindowTitle("Settings")
self.setModal(True)
self.resize(860, 640)
self.resize(900, 700)
self._config = config or AppConfig()
self._model_registry = ModelRegistry()
@ -93,6 +97,16 @@ class SettingsDialog(QDialog):
self.config_path_edit = self._line_edit(read_only=True)
self.history_db_path_edit = self._line_edit(read_only=True)
self.audio_cache_directory_widget, self.audio_cache_directory_edit, self.audio_cache_directory_button = self._directory_selector(
browse_text="Browse",
browse_tooltip="Choose the directory where cached WAV recordings are stored.",
dialog_title="Select audio cache directory",
)
self.audio_cache_directory_edit.setToolTip("Directory used to store cached WAV recordings.")
self.audio_cache_max_bytes_spin = QSpinBox(self)
self.audio_cache_max_bytes_spin.setRange(1, 2_147_483_647)
self.audio_cache_max_bytes_spin.setSingleStep(1024 * 1024)
self.audio_cache_max_bytes_spin.setSuffix(" bytes")
self.injection_mode_combo = QComboBox(self)
self.injection_mode_combo.addItems(["direct_typing", "clipboard_paste"])
self.backend_mode_combo = QComboBox(self)
@ -100,6 +114,8 @@ class SettingsDialog(QDialog):
form.addRow("Config path", self.config_path_edit)
form.addRow("History DB path", self.history_db_path_edit)
form.addRow("Audio cache directory", self.audio_cache_directory_widget)
form.addRow("Audio cache max size", self.audio_cache_max_bytes_spin)
form.addRow("Injection mode", self.injection_mode_combo)
form.addRow("Backend mode", self.backend_mode_combo)
@ -254,10 +270,32 @@ class SettingsDialog(QDialog):
edit.setReadOnly(read_only)
return edit
def _directory_selector(self, *, browse_text: str, browse_tooltip: str, dialog_title: str) -> tuple[QWidget, QLineEdit, QPushButton]:
container = QWidget(self)
layout = QHBoxLayout(container)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(8)
edit = QLineEdit(container)
button = QPushButton(browse_text, container)
button.setToolTip(browse_tooltip)
button.clicked.connect(lambda: self._choose_directory(edit, dialog_title))
layout.addWidget(edit, 1)
layout.addWidget(button, 0)
return container, edit, button
def _choose_directory(self, target_edit: QLineEdit, title: str) -> None:
directory = QFileDialog.getExistingDirectory(self, title, target_edit.text() or str(self._config.paths.audio_cache_directory))
if directory:
target_edit.setText(directory)
def apply_config(self, config: AppConfig) -> None:
self._config = config
self.config_path_edit.setText(config.paths.config_path)
self.history_db_path_edit.setText(config.paths.history_db_path)
self.audio_cache_directory_edit.setText(config.paths.audio_cache_directory)
self.audio_cache_max_bytes_spin.setValue(config.audio_cache_max_bytes)
self.injection_mode_combo.setCurrentText(config.injection_mode)
self.backend_mode_combo.setCurrentText(config.backend_mode)
self.model_name_combo.setCurrentText(config.model_name)
@ -292,6 +330,8 @@ class SettingsDialog(QDialog):
hotkey=self._validated_hotkey,
microphone_device=microphone_device,
logs_root_directory=self.log_directory_edit.text(),
audio_cache_directory=self.audio_cache_directory_edit.text(),
audio_cache_max_bytes=self.audio_cache_max_bytes_spin.value(),
logging=LoggingConfig(
level=self.log_level_combo.currentText(),
file_name=self.log_file_name_edit.text(),
@ -432,4 +472,3 @@ class SettingsDialog(QDialog):
if self._ok_button is not None:
self._ok_button.setEnabled(True)
return True

View File

@ -100,6 +100,7 @@ class TranscriptionFlowController(QObject):
transcript_text="",
injection_status="failed",
error_text=message,
audio_cache_path=segment.audio_cache_path,
)
self._prune_history()
if self._runtime_refresh is not None:
@ -119,6 +120,7 @@ class TranscriptionFlowController(QObject):
transcript_text="",
injection_status="failed",
error_text=message,
audio_cache_path="",
)
self._prune_history()
if self._runtime_refresh is not None:
@ -194,6 +196,7 @@ class TranscriptionFlowController(QObject):
transcript_text=result.transcript_text,
injection_status=injection_status,
error_text=injection_error,
audio_cache_path=self._current_audio_cache_path(),
)
self._prune_history()
if self._runtime_refresh is not None:
@ -212,6 +215,7 @@ class TranscriptionFlowController(QObject):
transcript_text="",
injection_status="failed",
error_text=message,
audio_cache_path=self._current_audio_cache_path(),
)
self._prune_history()
if self._runtime_refresh is not None:
@ -236,6 +240,7 @@ class TranscriptionFlowController(QObject):
transcript_text: str,
injection_status: str,
error_text: str,
audio_cache_path: str,
) -> None:
if self._history_store is None:
return
@ -248,6 +253,7 @@ class TranscriptionFlowController(QObject):
transcript_text=transcript_text,
injection_status=injection_status,
error_text=error_text,
audio_cache_path=audio_cache_path,
)
except HistoryStoreError as exc:
logger.warning("History write failed: %s", exc)
@ -282,6 +288,11 @@ class TranscriptionFlowController(QObject):
return loaded_model.effective_backend
return self._worker.default_backend_mode
def _current_audio_cache_path(self) -> str:
if self._last_segment is None:
return ""
return self._last_segment.audio_cache_path
def _current_audio_duration_seconds(self) -> float:
if self._last_segment is None:
return 0.0