vakodiya commited on
Commit
a9059e8
1 Parent(s): 545ec70

Create audio_to_text.py

Browse files
Files changed (1) hide show
  1. audio_to_text.py +23 -0
audio_to_text.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import WhisperProcessor, WhisperForConditionalGeneration
2
+ import torchaudio
3
+
4
+
5
+ # load model and processor
6
+ processor = WhisperProcessor.from_pretrained("openai/whisper-tiny")
7
+ model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny")
8
+ model.config.forced_decoder_ids = None
9
+
10
+
11
+ def audio_to_text(file_path_abs):
12
+ # Load the audio and resample it
13
+ waveform, sample_rate = torchaudio.load(file_path_abs)
14
+ resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)
15
+ waveform = resampler(waveform)
16
+ waveform = waveform.squeeze().numpy()
17
+ input_features = processor(waveform, sampling_rate=16000, return_tensors="pt").input_features
18
+
19
+ # generate token ids
20
+ predicted_ids = model.generate(input_features)
21
+ # decode token ids to text
22
+ transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)
23
+ return transcription