submaster/whisper_project/infra/faster_whisper_adapter.py

61 lines
2.3 KiB
Python

"""Adapter wrapping faster-whisper into a small transcriber class.
Provides a `FasterWhisperTranscriber` with a stable `transcribe` API that
other code can depend on. Uses the implementation in
`whisper_project.infra.transcribe`.
"""
from typing import Optional
from whisper_project.infra.transcribe import transcribe_faster_whisper, write_srt
class FasterWhisperTranscriber:
def __init__(self, model: str = "base", compute_type: str = "int8") -> None:
self.model = model
self.compute_type = compute_type
def transcribe(self, file_path: str, srt_out: Optional[str] = None):
"""Transcribe the given audio file.
If `srt_out` is provided, writes an SRT file using `write_srt`.
Returns the segments list (as returned by faster-whisper wrapper).
"""
segments = transcribe_faster_whisper(file_path, self.model, compute_type=self.compute_type)
if srt_out and segments:
write_srt(segments, srt_out)
return segments
__all__ = ["FasterWhisperTranscriber"]
from typing import List
from ..core.models import Segment
class FasterWhisperTranscriber:
"""Adaptador que usa faster-whisper para transcribir y escribir SRT."""
def __init__(self, model: str = "base", compute_type: str = "int8"):
self.model = model
self.compute_type = compute_type
def transcribe(self, audio_path: str, srt_out: str) -> List[Segment]:
# Importar localmente para evitar coste al importar el módulo
from faster_whisper import WhisperModel
from whisper_project.transcribe import write_srt, dedupe_adjacent_segments
model_obj = WhisperModel(self.model, device="cpu", compute_type=self.compute_type)
segments_gen, info = model_obj.transcribe(audio_path, beam_size=5)
segments = list(segments_gen)
# Convertir a nuestros Segment dataclass
result_segments = []
for s in segments:
# faster-whisper segment tiene .start, .end, .text
seg = Segment(start=float(s.start), end=float(s.end), text=str(s.text))
result_segments.append(seg)
# escribir SRT usando la función existente (acepta objetos con .start/.end/.text)
segments_to_write = dedupe_adjacent_segments(result_segments)
write_srt(segments_to_write, srt_out)
return result_segments