"""Backend ASR par défaut : faster-whisper (CTranslate2), CPU int8.

Extrait tel quel de l'ancien `VoiceEngine.load()`/`_transcribe()` — comportement
inchangé (c'est le défaut tant que `asr_engine != "onnx"`).
"""

from __future__ import annotations

from typing import Any


class WhisperBackend:
    def __init__(self, cfg: dict[str, Any]):
        self.cfg = cfg
        self._model = None

    def load(self) -> None:
        from faster_whisper import WhisperModel

        self._model = WhisperModel(
            self.cfg["whisper_model"], device="cpu", compute_type="int8"
        )

    def transcribe(self, audio_int16) -> str:
        import numpy as np

        audio_f32 = audio_int16.astype(np.float32) / 32768.0
        segments, _ = self._model.transcribe(
            audio_f32,
            language=self.cfg.get("language", "fr"),
            task="transcribe",
            beam_size=3,
            vad_filter=True,
            initial_prompt="Transcription en français.",
        )
        return " ".join(seg.text for seg in segments).strip()
