Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import Wav2Vec2Processor
|
3 |
+
import torch
|
4 |
+
import librosa
|
5 |
+
import numpy as np
|
6 |
+
from huggingface_hub import hf_hub_download
|
7 |
+
|
8 |
+
class Wav2Vec2Classifier(torch.nn.Module):
|
9 |
+
def __init__(self, num_classes):
|
10 |
+
super().__init__()
|
11 |
+
from transformers import Wav2Vec2Model
|
12 |
+
self.wav2vec2 = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base")
|
13 |
+
self.dropout = torch.nn.Dropout(0.3)
|
14 |
+
self.classifier = torch.nn.Linear(self.wav2vec2.config.hidden_size, num_classes)
|
15 |
+
|
16 |
+
def forward(self, input_values, attention_mask=None):
|
17 |
+
outputs = self.wav2vec2(input_values, attention_mask=attention_mask)
|
18 |
+
pooled_output = outputs.last_hidden_state.mean(dim=1)
|
19 |
+
pooled_output = self.dropout(pooled_output)
|
20 |
+
logits = self.classifier(pooled_output)
|
21 |
+
return logits
|
22 |
+
|
23 |
+
processor = Wav2Vec2Processor.from_pretrained("hrid0yyy/BornoNet")
|
24 |
+
num_classes = 50
|
25 |
+
model = Wav2Vec2Classifier(num_classes=num_classes)
|
26 |
+
model.load_state_dict(torch.load(hf_hub_download("hrid0yyy/BornoNet", "pytorch_model.bin"), map_location="cpu"))
|
27 |
+
model.eval()
|
28 |
+
le_classes = np.load(hf_hub_download("hrid0yyy/BornoNet", "label_encoder_classes.npy"), allow_pickle=True)
|
29 |
+
|
30 |
+
def predict(audio):
|
31 |
+
try:
|
32 |
+
y, sr = librosa.load(audio, sr=16000)
|
33 |
+
inputs = processor(y, sampling_rate=sr, return_tensors="pt", padding=True)
|
34 |
+
with torch.no_grad():
|
35 |
+
logits = model(inputs.input_values)
|
36 |
+
predicted = le_classes[torch.argmax(logits, dim=1).item()]
|
37 |
+
return f"Predicted character: {predicted}"
|
38 |
+
except Exception as e:
|
39 |
+
return f"Error processing audio: {str(e)}"
|
40 |
+
|
41 |
+
iface = gr.Interface(
|
42 |
+
fn=predict,
|
43 |
+
inputs=gr.Audio(type="filepath", label="Upload an MP3 file (16kHz)"),
|
44 |
+
outputs=gr.Textbox(label="Prediction"),
|
45 |
+
title="BornoNet: Bengali Speech Recognition",
|
46 |
+
description="Upload a 16kHz MP3 file to classify Bengali speech into characters (e.g., ত, অ, ক)."
|
47 |
+
)
|
48 |
+
iface.launch()
|