ananyakarn commited on
Commit
299d9e4
·
verified ·
1 Parent(s): 8563a27

fixed errors

Browse files
Files changed (1) hide show
  1. app.py +75 -76
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # =========================
2
- # 1. DOWNLOAD BOTH DATASETS
3
  # =========================
4
  import os, requests, zipfile
5
 
@@ -10,24 +10,65 @@ urls = [
10
 
11
  os.makedirs("data", exist_ok=True)
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  for i, url in enumerate(urls):
14
- zip_path = f"data_{i}.zip"
 
 
 
 
 
 
15
 
16
- if not os.path.exists(zip_path):
17
- print(f"Downloading dataset {i+1}...")
18
- r = requests.get(url, stream=True)
19
- with open(zip_path, "wb") as f:
20
- for chunk in r.iter_content(8192):
21
- f.write(chunk)
22
 
23
- print(f"Extracting dataset {i+1}...")
24
- with zipfile.ZipFile(zip_path, "r") as zip_ref:
25
- zip_ref.extractall(f"data/set_{i}")
26
 
27
  # =========================
28
- # 2. GET ALL PARTICIPANTS
29
  # =========================
30
- def get_all_participant_paths():
31
  paths = []
32
  for root, dirs, _ in os.walk("data"):
33
  for d in dirs:
@@ -35,14 +76,13 @@ def get_all_participant_paths():
35
  paths.append(os.path.join(root, d))
36
  return paths
37
 
38
- ALL_PATHS = get_all_participant_paths()
39
- print("Total participant folders:", len(ALL_PATHS))
40
 
41
  # =========================
42
- # 3. IMPORT LIBRARIES
43
  # =========================
44
  import numpy as np
45
- import pandas as pd
46
  import librosa
47
  import torch
48
  import torch.nn as nn
@@ -53,29 +93,7 @@ from sklearn.metrics import accuracy_score, f1_score
53
  from sklearn.preprocessing import StandardScaler
54
 
55
  # =========================
56
- # 4. LOAD SPLITS
57
- # =========================
58
- def load_split(csv_file):
59
- df = pd.read_csv(csv_file)
60
- df.columns = df.columns.str.strip()
61
-
62
- split = {}
63
- for _, row in df.iterrows():
64
- try:
65
- pid = str(int(row["Participant_ID"]))
66
- split[pid] = int(row["PHQ8_Binary"])
67
- except:
68
- continue
69
- return split
70
-
71
- train_labels = load_split("train_split_Depression_AVEC2017.csv")
72
- dev_labels = load_split("dev_split_Depression_AVEC2017.csv")
73
-
74
- print("Train labels:", len(train_labels))
75
- print("Dev labels:", len(dev_labels))
76
-
77
- # =========================
78
- # 5. LOAD TEXT MODEL
79
  # =========================
80
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
81
 
@@ -84,7 +102,7 @@ bert = AutoModel.from_pretrained("distilbert-base-uncased").to(device)
84
  bert.eval()
85
 
86
  # =========================
87
- # 6. FEATURE FUNCTIONS
88
  # =========================
89
  def load_text(folder):
90
  try:
@@ -132,10 +150,10 @@ def get_visual_features(folder):
132
  return np.concatenate(feats)
133
 
134
  # =========================
135
- # 7. BUILD DATASETS
136
  # =========================
137
- def build_dataset(label_dict):
138
- X_t, X_a, X_v, y = [], [], [], []
139
 
140
  for path in tqdm(ALL_PATHS):
141
  pid = os.path.basename(path).split("_")[0]
@@ -143,27 +161,21 @@ def build_dataset(label_dict):
143
  if pid not in label_dict:
144
  continue
145
 
146
- X_t.append(get_text_embedding(load_text(path)))
147
- X_a.append(get_audio_features(path))
148
- X_v.append(get_visual_features(path))
149
  y.append(label_dict[pid])
150
 
151
- return np.array(X_t), np.array(X_a), np.array(X_v), np.array(y)
152
-
153
- print("\nBuilding train...")
154
- Xt, Xa, Xv, y_train = build_dataset(train_labels)
155
 
156
- print("Building dev...")
157
- Xt_test, Xa_test, Xv_test, y_test = build_dataset(dev_labels)
158
 
159
  print("Train size:", len(y_train))
160
  print("Test size:", len(y_test))
161
 
162
- if len(y_train) == 0 or len(y_test) == 0:
163
- raise Exception("Dataset still empty → check upload")
164
-
165
  # =========================
166
- # 8. NORMALIZE
167
  # =========================
168
  sc_t, sc_a, sc_v = StandardScaler(), StandardScaler(), StandardScaler()
169
 
@@ -176,16 +188,14 @@ Xa_test = sc_a.transform(Xa_test)
176
  Xv_test = sc_v.transform(Xv_test)
177
 
178
  # =========================
179
- # 9. MODEL
180
  # =========================
181
  class Model(nn.Module):
182
  def __init__(self, vdim):
183
  super().__init__()
184
-
185
  self.t = nn.Sequential(nn.Linear(768,128), nn.ReLU())
186
  self.a = nn.Sequential(nn.Linear(40,32), nn.ReLU())
187
  self.v = nn.Sequential(nn.Linear(vdim,64), nn.ReLU())
188
-
189
  self.f = nn.Sequential(
190
  nn.Linear(224,64),
191
  nn.ReLU(),
@@ -194,10 +204,7 @@ class Model(nn.Module):
194
  )
195
 
196
  def forward(self, t,a,v):
197
- t = self.t(t)
198
- a = self.a(a)
199
- v = self.v(v)
200
- return self.f(torch.cat([t,a,v],1))
201
 
202
  model = Model(Xv.shape[1]).to(device)
203
 
@@ -214,30 +221,22 @@ Xa_test = torch.tensor(Xa_test, dtype=torch.float32).to(device)
214
  Xv_test = torch.tensor(Xv_test, dtype=torch.float32).to(device)
215
 
216
  # =========================
217
- # 10. TRAIN
218
  # =========================
219
- print("\nTraining...")
220
-
221
  for e in range(10):
222
  model.train()
223
  opt.zero_grad()
224
-
225
- out = model(Xt,Xa,Xv).squeeze()
226
- loss = loss_fn(out, yt)
227
-
228
  loss.backward()
229
  opt.step()
230
-
231
  print(f"Epoch {e+1}: {loss.item():.4f}")
232
 
233
  # =========================
234
- # 11. EVAL
235
  # =========================
236
  model.eval()
237
-
238
  with torch.no_grad():
239
- out = model(Xt_test,Xa_test,Xv_test).squeeze()
240
- pred = (torch.sigmoid(out)>0.5).int().cpu().numpy()
241
 
242
  print("\nRESULTS")
243
  print("Accuracy:", accuracy_score(y_test, pred))
 
1
  # =========================
2
+ # 1. DOWNLOAD + SELECTIVE EXTRACT
3
  # =========================
4
  import os, requests, zipfile
5
 
 
10
 
11
  os.makedirs("data", exist_ok=True)
12
 
13
+ # =========================
14
+ # 2. LOAD LABELS FIRST
15
+ # =========================
16
+ import pandas as pd
17
+
18
+ def load_split(csv_file):
19
+ df = pd.read_csv(csv_file)
20
+ df.columns = df.columns.str.strip()
21
+
22
+ split = {}
23
+ for _, row in df.iterrows():
24
+ try:
25
+ pid = str(int(row["Participant_ID"]))
26
+ split[pid] = int(row["PHQ8_Binary"])
27
+ except:
28
+ continue
29
+ return split
30
+
31
+ train_labels = load_split("train_split_Depression_AVEC2017.csv")
32
+ dev_labels = load_split("dev_split_Depression_AVEC2017.csv")
33
+
34
+ ALL_REQUIRED_IDS = set(list(train_labels.keys()) + list(dev_labels.keys()))
35
+
36
+ print("Total required participants:", len(ALL_REQUIRED_IDS))
37
+
38
+ # =========================
39
+ # 3. SELECTIVE EXTRACTION
40
+ # =========================
41
+ def extract_needed(zip_path):
42
+ with zipfile.ZipFile(zip_path, "r") as zip_ref:
43
+ for file in zip_ref.namelist():
44
+
45
+ # extract only participant folders we need
46
+ for pid in ALL_REQUIRED_IDS:
47
+ if f"{pid}_" in file:
48
+ zip_ref.extract(file, "data")
49
+ break
50
+
51
+ # =========================
52
+ # 4. DOWNLOAD + EXTRACT
53
+ # =========================
54
  for i, url in enumerate(urls):
55
+ zip_path = f"temp_{i}.zip"
56
+
57
+ print(f"Downloading dataset {i+1}...")
58
+ r = requests.get(url, stream=True)
59
+ with open(zip_path, "wb") as f:
60
+ for chunk in r.iter_content(8192):
61
+ f.write(chunk)
62
 
63
+ print(f"Extracting required files from dataset {i+1}...")
64
+ extract_needed(zip_path)
 
 
 
 
65
 
66
+ os.remove(zip_path) # 🔥 VERY IMPORTANT
 
 
67
 
68
  # =========================
69
+ # 5. GET PARTICIPANTS
70
  # =========================
71
+ def get_all_paths():
72
  paths = []
73
  for root, dirs, _ in os.walk("data"):
74
  for d in dirs:
 
76
  paths.append(os.path.join(root, d))
77
  return paths
78
 
79
+ ALL_PATHS = get_all_paths()
80
+ print("Extracted participant folders:", len(ALL_PATHS))
81
 
82
  # =========================
83
+ # 6. IMPORT LIBRARIES
84
  # =========================
85
  import numpy as np
 
86
  import librosa
87
  import torch
88
  import torch.nn as nn
 
93
  from sklearn.preprocessing import StandardScaler
94
 
95
  # =========================
96
+ # 7. TEXT MODEL
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  # =========================
98
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
99
 
 
102
  bert.eval()
103
 
104
  # =========================
105
+ # 8. FEATURE FUNCTIONS
106
  # =========================
107
  def load_text(folder):
108
  try:
 
150
  return np.concatenate(feats)
151
 
152
  # =========================
153
+ # 9. BUILD DATA
154
  # =========================
155
+ def build(label_dict):
156
+ Xt, Xa, Xv, y = [], [], [], []
157
 
158
  for path in tqdm(ALL_PATHS):
159
  pid = os.path.basename(path).split("_")[0]
 
161
  if pid not in label_dict:
162
  continue
163
 
164
+ Xt.append(get_text_embedding(load_text(path)))
165
+ Xa.append(get_audio_features(path))
166
+ Xv.append(get_visual_features(path))
167
  y.append(label_dict[pid])
168
 
169
+ return np.array(Xt), np.array(Xa), np.array(Xv), np.array(y)
 
 
 
170
 
171
+ Xt, Xa, Xv, y_train = build(train_labels)
172
+ Xt_test, Xa_test, Xv_test, y_test = build(dev_labels)
173
 
174
  print("Train size:", len(y_train))
175
  print("Test size:", len(y_test))
176
 
 
 
 
177
  # =========================
178
+ # 10. NORMALIZE
179
  # =========================
180
  sc_t, sc_a, sc_v = StandardScaler(), StandardScaler(), StandardScaler()
181
 
 
188
  Xv_test = sc_v.transform(Xv_test)
189
 
190
  # =========================
191
+ # 11. MODEL
192
  # =========================
193
  class Model(nn.Module):
194
  def __init__(self, vdim):
195
  super().__init__()
 
196
  self.t = nn.Sequential(nn.Linear(768,128), nn.ReLU())
197
  self.a = nn.Sequential(nn.Linear(40,32), nn.ReLU())
198
  self.v = nn.Sequential(nn.Linear(vdim,64), nn.ReLU())
 
199
  self.f = nn.Sequential(
200
  nn.Linear(224,64),
201
  nn.ReLU(),
 
204
  )
205
 
206
  def forward(self, t,a,v):
207
+ return self.f(torch.cat([self.t(t), self.a(a), self.v(v)],1))
 
 
 
208
 
209
  model = Model(Xv.shape[1]).to(device)
210
 
 
221
  Xv_test = torch.tensor(Xv_test, dtype=torch.float32).to(device)
222
 
223
  # =========================
224
+ # 12. TRAIN
225
  # =========================
 
 
226
  for e in range(10):
227
  model.train()
228
  opt.zero_grad()
229
+ loss = loss_fn(model(Xt,Xa,Xv).squeeze(), yt)
 
 
 
230
  loss.backward()
231
  opt.step()
 
232
  print(f"Epoch {e+1}: {loss.item():.4f}")
233
 
234
  # =========================
235
+ # 13. EVAL
236
  # =========================
237
  model.eval()
 
238
  with torch.no_grad():
239
+ pred = (torch.sigmoid(model(Xt_test,Xa_test,Xv_test).squeeze())>0.5).int().cpu().numpy()
 
240
 
241
  print("\nRESULTS")
242
  print("Accuracy:", accuracy_score(y_test, pred))