"""Safe faster-whisper wrapper for short NovaGuide voice queries.""" from __future__ import annotations import logging from typing import Any try: from faster_whisper import WhisperModel except ImportError: WhisperModel = None # type: ignore[assignment] from src.config import Settings, get_settings from src.preprocessing.audio_processor import AudioProcessor from src.utils.sanitization import sanitize_text from src.utils.timing import elapsed_ms, now_ms LOGGER = logging.getLogger(__name__) class SpeechToText: """Transcribe validated audio without invoking downstream NLU components.""" def __init__( self, settings: Settings | None = None, audio_processor: AudioProcessor | None = None, model: Any | None = None, ) -> None: self.settings = settings or get_settings() self.audio_processor = audio_processor or AudioProcessor(self.settings) self.model = model @property def model_name(self) -> str: return f"faster-whisper-{self.settings.whisper_model_size}" def load(self) -> bool: """Load the configured faster-whisper model, returning false on failure.""" if self.model is not None: return True if WhisperModel is None: return False try: self.model = WhisperModel( self.settings.whisper_model_size, device=self.settings.whisper_device, compute_type=self.settings.whisper_compute_type, ) return True except (OSError, RuntimeError, ValueError) as exc: LOGGER.warning("Could not load faster-whisper model: %s", exc) self.model = None return False def is_available(self) -> bool: """Return whether a model instance is loaded.""" return self.model is not None @staticmethod def _failure(error: str, processing_time_ms: int = 0) -> dict[str, Any]: return { "success": False, "transcribed_text": "", "language": None, "duration_seconds": None, "model_used": None, "processing_time_ms": processing_time_ms, "segments": [], "error": error, } def transcribe(self, file_path: str | None) -> dict[str, Any]: """Validate and transcribe one audio file into sanitized text and segments.""" start = now_ms() prepared = self.audio_processor.prepare_audio(file_path) if not prepared["valid"] or not prepared["within_limit"]: return self._failure(prepared["error"] or "Audio input is not valid.", elapsed_ms(start)) if not self.load(): return self._failure("faster-whisper model is unavailable.", elapsed_ms(start)) try: segment_stream, info = self.model.transcribe(prepared["file_path"], beam_size=5) segments: list[dict[str, Any]] = [] text_parts: list[str] = [] for segment in segment_stream: clean = sanitize_text(str(segment.text).strip()) segments.append({ "start": float(segment.start), "end": float(segment.end), "text": clean, }) if clean: text_parts.append(clean) text = sanitize_text(" ".join(text_parts)) duration = prepared["duration_seconds"] if duration is None: duration = getattr(info, "duration", None) return { "success": True, "transcribed_text": text, "language": getattr(info, "language", None), "duration_seconds": float(duration) if duration is not None else None, "model_used": self.model_name, "processing_time_ms": elapsed_ms(start), "segments": segments, "error": None, } except (OSError, RuntimeError, TypeError, ValueError) as exc: LOGGER.warning("Speech transcription failed: %s", exc) return self._failure(f"Speech transcription failed: {exc}", elapsed_ms(start))