Nam Nguyen commited on
Commit
5c831db
·
1 Parent(s): e1ea810

Add application file

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchaudio
3
+ from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
4
+ import gradio as gr
5
+
6
+ # Load model and processor from your fine-tuned directory
7
+ MODEL_PATH = "C:\Users\Nam\My_First_ASR\imported_model" # Update this if needed
8
+ processor = Wav2Vec2Processor.from_pretrained(MODEL_PATH)
9
+ model = Wav2Vec2ForCTC.from_pretrained(MODEL_PATH).eval()
10
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ model.to(device)
12
+
13
+ # Define inference function
14
+ def transcribe(audio):
15
+ if audio is None:
16
+ return "No audio provided."
17
+
18
+ sr, data = audio
19
+
20
+ # Convert to mono and resample to 16kHz if needed
21
+ waveform = torch.tensor(data).unsqueeze(0)
22
+ if sr != 16000:
23
+ resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=16000)
24
+ waveform = resampler(waveform)
25
+ if waveform.shape[0] > 1:
26
+ waveform = waveform.mean(dim=0, keepdim=True)
27
+
28
+ # Inference
29
+ inputs = processor(waveform.squeeze().numpy(), sampling_rate=16000, return_tensors="pt", padding=True)
30
+ input_values = inputs.input_values.to(device)
31
+
32
+ with torch.no_grad():
33
+ logits = model(input_values).logits
34
+ predicted_ids = torch.argmax(logits, dim=-1)
35
+
36
+ transcription = processor.batch_decode(predicted_ids)[0]
37
+ return transcription.strip()
38
+
39
+ # Gradio interface
40
+ gr.Interface(
41
+ fn=transcribe,
42
+ inputs=gr.Audio(source="upload", type="numpy", label="Upload WAV/MP3 file"),
43
+ outputs=gr.Textbox(label="Transcription"),
44
+ title="🗣️ ASR Demo with Wav2Vec2",
45
+ description="Upload an audio file (WAV or MP3) and get the transcription using your fine-tuned model.",
46
+ live=False
47
+ ).launch()