-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwav2vec2_inference.py
More file actions
27 lines (20 loc) · 946 Bytes
/
wav2vec2_inference.py
File metadata and controls
27 lines (20 loc) · 946 Bytes
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
import soundfile as sf
import torch
from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
class Wave2Vec2Inference():
def __init__(self,model_name):
self.processor = Wav2Vec2Processor.from_pretrained(model_name)
self.model = Wav2Vec2ForCTC.from_pretrained(model_name)
def buffer_to_text(self,audio_buffer):
if(len(audio_buffer)==0):
return ""
inputs = self.processor(torch.tensor(audio_buffer), sampling_rate=16_000, return_tensors="pt", padding=True)
with torch.no_grad():
logits = self.model(inputs.input_values).logits
predicted_ids = torch.argmax(logits, dim=-1)
transcription = self.processor.batch_decode(predicted_ids)[0]
return transcription.lower()
def file_to_text(self,filename):
audio_input, samplerate = sf.read(filename)
assert samplerate == 16000
return self.buffer_to_text(audio_input)