def transcribe(
self,
audio: bytes,
*,
format: str = "wav",
language: Optional[str] = None,
hotwords: Optional[str] = None,
) -> TranscriptionResult:
"""Transcribe audio bytes using Faster-Whisper."""
try:
model = self._ensure_model()
# Write audio to a temp file (faster-whisper needs a file path).
# delete=False + manual unlink: on Windows an open
# NamedTemporaryFile holds an exclusive handle, so PyAV's reopen
# of tmp.name inside model.transcribe() fails with EACCES.
suffix = f".{format}" if not format.startswith(".") else format
tmp = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
try:
with tmp:
tmp.write(audio)
kwargs: dict = {}
if language:
kwargs["language"] = language
# Older supported Faster-Whisper releases lack this keyword.
if hotwords and "hotwords" in signature(model.transcribe).parameters:
# A vocabulary hint fixes names Whisper otherwise
# mishears ("Jarvis" -> "Charis", "Service"). On its own
# it can make the model "hear" the hinted word in noise,
# so it always comes with the VAD filter (#1301).
kwargs["hotwords"] = hotwords
kwargs["vad_filter"] = True
segments_iter, info = model.transcribe(tmp.name, **kwargs)
segments_list = list(segments_iter)
finally:
try:
os.unlink(tmp.name)
except OSError as unlink_exc:
logger.debug(
"Could not remove temp audio file %s: %s",
tmp.name,
unlink_exc,
)
except Exception as exc:
self._last_error = str(exc)
raise
# Build result
text = "".join(seg.text for seg in segments_list).strip()
segments = [
Segment(
text=seg.text.strip(),
start=seg.start,
end=seg.end,
confidence=None,
)
for seg in segments_list
]
self._last_error = None
return TranscriptionResult(
text=text,
language=getattr(info, "language", None),
confidence=getattr(info, "language_probability", None),
duration_seconds=getattr(info, "duration", 0.0),
segments=segments,
)