"""Gemeinsame Fixtures fuer die SjAudioSearch-Tests. Die Tests erzeugen winzige echte WAV-Dateien und verwenden eine gefakte Transkriptions-Engine. Es wird nie ein Whisper-Modell heruntergeladen. """ from __future__ import annotations import os import wave from pathlib import Path from typing import Callable, Iterable, Sequence import pytest from sjaudiosearch.config import ProcessingConfig, SearchConfig from sjaudiosearch.core.models import AudioFileRecord, ScanCandidate from sjaudiosearch.database.repository import Repository from sjaudiosearch.transcription.models import TranscriptResult, TranscriptSegment, WordToken def write_wav(path: Path, seconds: float = 1.0, sample_rate: int = 8000) -> Path: """Schreibt eine stille WAV-Datei (gueltiges Audio, sehr klein).""" path.parent.mkdir(parents=True, exist_ok=True) frames = int(sample_rate * seconds) with wave.open(str(path), "wb") as handle: handle.setnchannels(1) handle.setsampwidth(2) handle.setframerate(sample_rate) handle.writeframes(b"\x00\x00" * frames) return path @pytest.fixture def repo(tmp_path: Path) -> Iterable[Repository]: repository = Repository.open(tmp_path / "sjaudiosearch.db") try: yield repository finally: repository.close() @pytest.fixture def processing() -> ProcessingConfig: return ProcessingConfig(compute_hash="auto") @pytest.fixture def search_config() -> SearchConfig: return SearchConfig( default_limit=50, default_min_score=70.0, context_words=50, exhaustive_fallback=True, ) @pytest.fixture def make_wav(tmp_path: Path) -> Callable[..., Path]: def factory(name: str, seconds: float = 1.0, sample_rate: int = 8000) -> Path: path = tmp_path / name return write_wav(path, seconds=seconds, sample_rate=sample_rate) return factory @pytest.fixture def add_audio(repo: Repository) -> Callable[..., AudioFileRecord]: def factory( path: str | Path, *, duration: float | None = 60.0, status: str = "pending", content_hash: str | None = None, duplicate_of: int | None = None, ) -> AudioFileRecord: file_path = Path(path) if not file_path.exists(): file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_bytes(b"\x00") candidate = ScanCandidate( path=str(file_path), filename=file_path.name, file_size=file_path.stat().st_size, modified_at=file_path.stat().st_mtime, duration=duration, content_hash=content_hash, ) audio_id = repo.insert_audio( candidate, status=status, duplicate_of=duplicate_of ) record = repo.get_audio(audio_id) assert record is not None return record return factory @pytest.fixture def store_transcript(repo: Repository) -> Callable[..., int]: """Speichert ein Transkript mit optionalen Wort-Zeitstempeln.""" def factory( audio_id: int, segments: Sequence[str | tuple[str, float, float]], *, language: str = "de", model: str = "test-model", with_words: bool = False, duration: float = 120.0, ) -> int: built: list[TranscriptSegment] = [] cursor = 0.0 for item in segments: if isinstance(item, str): text = item start = cursor end = cursor + 5.0 else: text, start, end = item cursor = end words: list[WordToken] = [] if with_words: tokens = text.split() step = (end - start) / max(1, len(tokens)) words = [ WordToken( word=token, start=start + index * step, end=start + (index + 1) * step, ) for index, token in enumerate(tokens) ] built.append( TranscriptSegment( text=text, start=float(start), end=float(end), confidence=0.9, words=words, ) ) full_text = " ".join(segment.text for segment in built) result = TranscriptResult( segments=built, full_text=full_text, language=language, language_probability=0.99, duration=duration, model=model, ) return repo.save_transcript( audio_id, language=result.language, model=result.model, full_text=result.full_text, segments=result.segments, duration=result.duration, ) return factory def set_mtime(path: Path, seconds: float) -> None: os.utime(path, (seconds, seconds))