Spaces:
Sleeping
Sleeping
""" | |
Created By: ishwor subedi | |
Date: 2024-07-31 | |
""" | |
import torch | |
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline | |
class SpeechToText: | |
def __init__(self): | |
self.device = "cuda:0" if torch.cuda.is_available() else "cpu" | |
self.torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32 | |
model_id = "openai/whisper-large-v3" | |
self.model = AutoModelForSpeechSeq2Seq.from_pretrained( | |
model_id, torch_dtype=self.torch_dtype, low_cpu_mem_usage=True, use_safetensors=True | |
).to(self.device) | |
self.processor = AutoProcessor.from_pretrained(model_id) | |
self.speech_to_text_pipeline = self.pipeline() | |
def pipeline(self): | |
pipe = pipeline( | |
"automatic-speech-recognition", | |
model=self.model, | |
tokenizer=self.processor.tokenizer, | |
feature_extractor=self.processor.feature_extractor, | |
max_new_tokens=128, # max number of tokens to generate at a time | |
chunk_length_s=30, # length of audio chunks to process at a time | |
batch_size=16, # number of chunks to process at a time | |
return_timestamps=True, | |
torch_dtype=self.torch_dtype, | |
device=self.device, | |
) | |
return pipe | |
def transcribe_audio(self, audio, language: str = "en"): | |
""" | |
This function is for transcribing audio to text. | |
:param audio: upload your audio file | |
:param language: choose the languaage of the audio file | |
:return: | |
""" | |
result = self.speech_to_text_pipeline(audio, return_timestamps=True, | |
generate_kwargs={"language": language, "task": "translate"}) | |
return result["chunks"], result["text"] | |