File size: 1,801 Bytes
b368e21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
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"]