ananyakarn commited on
Commit
05ee77c
·
verified ·
1 Parent(s): 359752f

first working app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+ import requests
4
+ import numpy as np
5
+ import pandas as pd
6
+ import librosa
7
+ import torch
8
+ import gradio as gr
9
+
10
+ from transformers import AutoTokenizer, AutoModel
11
+ from sklearn.ensemble import RandomForestClassifier
12
+ from sklearn.preprocessing import StandardScaler
13
+
14
+ # =========================
15
+ # 1. DOWNLOAD DATASET
16
+ # =========================
17
+ url = "https://huggingface.co/datasets/ananyakarn/DAIC_WOZ_Data/resolve/main/DAIC_WOZ_Data.zip"
18
+ zip_path = "data.zip"
19
+ extract_path = "DAIC_WOZ"
20
+
21
+ if not os.path.exists(extract_path):
22
+ print("Downloading dataset...")
23
+ r = requests.get(url, stream=True)
24
+ with open(zip_path, "wb") as f:
25
+ for chunk in r.iter_content(8192):
26
+ f.write(chunk)
27
+
28
+ print("Extracting dataset...")
29
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
30
+ zip_ref.extractall(extract_path)
31
+
32
+ # =========================
33
+ # 2. LOAD BERT
34
+ # =========================
35
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36
+
37
+ tokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
38
+ bert = AutoModel.from_pretrained("bert-base-multilingual-cased").to(device)
39
+ bert.eval()
40
+
41
+ # =========================
42
+ # FEATURE FUNCTIONS
43
+ # =========================
44
+ def get_text_embedding(text):
45
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=128).to(device)
46
+ with torch.no_grad():
47
+ outputs = bert(**inputs)
48
+ return outputs.last_hidden_state.mean(dim=1).squeeze().cpu().numpy()
49
+
50
+ def get_audio_features(folder):
51
+ try:
52
+ file = [f for f in os.listdir(folder) if f.endswith("_AUDIO.wav")][0]
53
+ y, sr = librosa.load(os.path.join(folder, file), sr=16000)
54
+ mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=20)
55
+ return np.mean(mfcc.T, axis=0)
56
+ except:
57
+ return np.zeros(20)
58
+
59
+ def load_text(folder):
60
+ try:
61
+ file = [f for f in os.listdir(folder) if "TRANSCRIPT" in f][0]
62
+ df = pd.read_csv(os.path.join(folder, file))
63
+ return " ".join(df.iloc[:, -1].astype(str).tolist())
64
+ except:
65
+ return ""
66
+
67
+ def get_label(folder):
68
+ return 1 if "_P" in folder else 0
69
+
70
+ # =========================
71
+ # 3. TRAIN MODEL (LIGHT)
72
+ # =========================
73
+ print("Training model...")
74
+
75
+ X, y = [], []
76
+ folders = os.listdir(extract_path)[:20] # 🔥 only 20 samples
77
+
78
+ for folder in folders:
79
+ path = os.path.join(extract_path, folder)
80
+
81
+ if not os.path.isdir(path):
82
+ continue
83
+
84
+ text = load_text(path)
85
+ text_feat = get_text_embedding(text)
86
+ audio_feat = get_audio_features(path)
87
+
88
+ combined = np.concatenate([text_feat, audio_feat])
89
+
90
+ X.append(combined)
91
+ y.append(get_label(folder))
92
+
93
+ X = np.array(X)
94
+ y = np.array(y)
95
+
96
+ scaler = StandardScaler()
97
+ X = scaler.fit_transform(X)
98
+
99
+ model = RandomForestClassifier(n_estimators=50)
100
+ model.fit(X, y)
101
+
102
+ print("Model ready!")
103
+
104
+ # =========================
105
+ # 4. PREDICTION FUNCTION
106
+ # =========================
107
+ def predict(text, audio):
108
+
109
+ text_feat = get_text_embedding(text)
110
+
111
+ if audio:
112
+ y_audio, sr = librosa.load(audio, sr=16000)
113
+ mfcc = librosa.feature.mfcc(y=y_audio, sr=sr, n_mfcc=20)
114
+ audio_feat = np.mean(mfcc.T, axis=0)
115
+ else:
116
+ audio_feat = np.zeros(20)
117
+
118
+ x = np.concatenate([text_feat, audio_feat])
119
+ x = scaler.transform([x])
120
+
121
+ pred = model.predict(x)[0]
122
+
123
+ return "Depression Detected ⚠️" if pred == 1 else "No Depression ✅"
124
+
125
+ # =========================
126
+ # 5. UI
127
+ # =========================
128
+ app = gr.Interface(
129
+ fn=predict,
130
+ inputs=[
131
+ gr.Textbox(label="Enter Text"),
132
+ gr.Audio(type="filepath", label="Upload Audio (optional)")
133
+ ],
134
+ outputs="text",
135
+ title="Multimodal Depression Detection",
136
+ description="Training + inference demo using text and audio"
137
+ )
138
+
139
+ app.launch()