Norphel commited on
Commit
60d0c64
·
verified ·
1 Parent(s): 4411f74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -3
app.py CHANGED
@@ -2,6 +2,7 @@ import numpy as np
2
  import torch
3
  import gradio as gr
4
  from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
 
5
 
6
  # Load ASR model & processor
7
  asr_model_id = "Norphel/wav2vec2-large-mms-1b-dzo-colab"
@@ -17,15 +18,33 @@ asr_model.to(device)
17
  def generate_text(audio):
18
  if audio is None:
19
  return "No audio received"
20
-
21
- sr, data = audio
22
  data = data.astype(np.float32)
23
- input_dict = asr_processor(data, sampling_rate=16_000, return_tensors="pt", padding=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  logits = asr_model(input_dict.input_values.to(device)).logits
25
  pred_ids = torch.argmax(logits, dim=-1)[0]
26
 
 
27
  return asr_processor.decode(pred_ids)
28
 
 
29
  input_audio = gr.Audio(
30
  sources=["microphone"],
31
  waveform_options=gr.WaveformOptions(
 
2
  import torch
3
  import gradio as gr
4
  from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5
+ import librosa
6
 
7
  # Load ASR model & processor
8
  asr_model_id = "Norphel/wav2vec2-large-mms-1b-dzo-colab"
 
18
  def generate_text(audio):
19
  if audio is None:
20
  return "No audio received"
21
+
22
+ sr, data = audio # Unpack the tuple
23
  data = data.astype(np.float32)
24
+
25
+ # Resample to 16kHz if the sample rate is not 16kHz
26
+ target_sr = 16_000
27
+ if sr != target_sr:
28
+ data = librosa.resample(data, orig_sr=sr, target_sr=target_sr)
29
+ sr = target_sr # Update the sample rate to 16kHz
30
+
31
+ # Check if audio is too short and apply padding
32
+ min_length = 16000 # 1 second of audio at 16kHz sample rate
33
+ if len(data) < min_length:
34
+ padding_length = min_length - len(data)
35
+ data = np.pad(data, (0, padding_length), mode='constant')
36
+
37
+ # Process the audio with the processor
38
+ input_dict = asr_processor(data, sampling_rate=sr, return_tensors="pt", padding=True)
39
+
40
+ # Ensure that the input tensor is moved to the correct device (GPU or CPU)
41
  logits = asr_model(input_dict.input_values.to(device)).logits
42
  pred_ids = torch.argmax(logits, dim=-1)[0]
43
 
44
+ # Decode the prediction
45
  return asr_processor.decode(pred_ids)
46
 
47
+
48
  input_audio = gr.Audio(
49
  sources=["microphone"],
50
  waveform_options=gr.WaveformOptions(