avi292423 commited on
Commit
b8f5939
·
verified ·
1 Parent(s): 102ebb5

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +54 -0
  2. models/model_wav2vec.py +48 -0
  3. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from models.model_wav2vec import Wav2VecIntent
4
+ from huggingface_hub import hf_hub_download
5
+ import torch
6
+ import soundfile as sf
7
+ import librosa
8
+
9
+ app = FastAPI()
10
+
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_credentials=True,
15
+ allow_methods=["*"],
16
+ allow_headers=["*"],
17
+ )
18
+
19
+ MODEL_PATH = hf_hub_download(repo_id="avi292423/speech-intent-recognition-project", filename="wav2vec_best_model.pt")
20
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+
22
+ label_map = {
23
+ "activate_lamp": 0, "activate_lights": 1, "activate_lights_bedroom": 2, "activate_lights_kitchen": 3,
24
+ "activate_lights_washroom": 4, "activate_music": 5, "bring_juice": 6, "bring_newspaper": 7,
25
+ "bring_shoes": 8, "bring_socks": 9, "change_language_Chinese": 10, "change_language_English": 11,
26
+ "change_language_German": 12, "change_language_Korean": 13, "change_language_none": 14,
27
+ "deactivate_lamp": 15, "deactivate_lights": 16, "deactivate_lights_bedroom": 17, "deactivate_lights_kitchen": 18,
28
+ "deactivate_lights_washroom": 19, "deactivate_music": 20, "decrease_heat": 21, "decrease_heat_bedroom": 22,
29
+ "decrease_heat_kitchen": 23, "decrease_heat_washroom": 24, "decrease_volume": 25, "increase_heat": 26,
30
+ "increase_heat_bedroom": 27, "increase_heat_kitchen": 28, "increase_heat_washroom": 29, "increase_volume": 30
31
+ }
32
+ index_to_label = {v: k for k, v in label_map.items()}
33
+
34
+ num_classes = 31
35
+ pretrained_model = "facebook/wav2vec2-large"
36
+ model = Wav2VecIntent(num_classes=num_classes, pretrained_model=pretrained_model).to(device)
37
+ state_dict = torch.load(MODEL_PATH, map_location=device)
38
+ model.load_state_dict(state_dict)
39
+ model.eval()
40
+
41
+ @app.post("/predict")
42
+ async def predict(file: UploadFile = File(...)):
43
+ audio_bytes = await file.read()
44
+ with open("temp.wav", "wb") as f:
45
+ f.write(audio_bytes)
46
+ audio, sample_rate = sf.read("temp.wav")
47
+ if sample_rate != 16000:
48
+ audio = librosa.resample(audio.astype(float), orig_sr=sample_rate, target_sr=16000)
49
+ waveform = torch.tensor(audio, dtype=torch.float32).unsqueeze(0).to(device)
50
+ with torch.no_grad():
51
+ output = model(waveform)
52
+ predicted_class = torch.argmax(output, dim=1).item()
53
+ predicted_label = index_to_label.get(predicted_class, "Unknown Class")
54
+ return {"prediction": predicted_label}
models/model_wav2vec.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import Wav2Vec2Model
5
+
6
+ class Wav2VecIntent(nn.Module):
7
+ def __init__(self, num_classes=31, pretrained_model="facebook/wav2vec2-large"):
8
+ super().__init__()
9
+ # Load pretrained wav2vec model
10
+ self.wav2vec = Wav2Vec2Model.from_pretrained(pretrained_model)
11
+
12
+ # Get hidden size from model config
13
+ hidden_size = self.wav2vec.config.hidden_size
14
+
15
+ # Add layer normalization
16
+ self.layer_norm = nn.LayerNorm(hidden_size)
17
+
18
+ # Add attention mechanism
19
+ self.attention = nn.Linear(hidden_size, 1)
20
+
21
+ # Add dropout for regularization
22
+ self.dropout = nn.Dropout(p=0.5)
23
+
24
+ # Classification head
25
+ self.fc = nn.Linear(hidden_size, num_classes)
26
+
27
+ def forward(self, input_values, attention_mask=None):
28
+ # Get wav2vec features
29
+ outputs = self.wav2vec(
30
+ input_values,
31
+ attention_mask=attention_mask,
32
+ return_dict=True
33
+ )
34
+ hidden_states = outputs.last_hidden_state # [batch, sequence, hidden]
35
+
36
+ # Apply layer normalization
37
+ hidden_states = self.layer_norm(hidden_states)
38
+
39
+ # Apply attention
40
+ attn_weights = F.softmax(self.attention(hidden_states), dim=1)
41
+ x = torch.sum(hidden_states * attn_weights, dim=1) # Weighted sum
42
+
43
+ # Apply dropout
44
+ x = self.dropout(x)
45
+
46
+ # Final classification
47
+ x = self.fc(x)
48
+ return x
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ torch
3
+ soundfile
4
+ huggingface_hub
5
+ transformers
6
+ gunicorn
7
+ numpy
8
+ uvicorn
9
+ gradio
10
+ librosa