k22056537 commited on
Commit
a12e47d
·
1 Parent(s): 3d8b199

remove old duplicate folders

Browse files
data_preparation/explore_collected_data.ipynb DELETED
@@ -1,414 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# FocusGuard — Collected Data Explorer\n",
8
- "Load `.npz` files from `collect_features.py` and inspect the data before training."
9
- ]
10
- },
11
- {
12
- "cell_type": "code",
13
- "execution_count": null,
14
- "metadata": {},
15
- "outputs": [
16
- {
17
- "ename": "FileNotFoundError",
18
- "evalue": "No .npz files in /content/collected — run collect_features.py first",
19
- "output_type": "error",
20
- "traceback": [
21
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
22
- "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
23
- "\u001b[0;32m/tmp/ipython-input-251140757.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mnpz_files\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 11\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mFileNotFoundError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf\"No .npz files in {COLLECTED_DIR} — run collect_features.py first\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0mNPZ_PATH\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnpz_files\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;31m# latest file\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
24
- "\u001b[0;31mFileNotFoundError\u001b[0m: No .npz files in /content/collected — run collect_features.py first"
25
- ]
26
- }
27
- ],
28
- "source": [
29
- "import numpy as np\n",
30
- "import matplotlib.pyplot as plt\n",
31
- "import os\n",
32
- "import glob\n",
33
- "\n",
34
- "# auto-find the latest .npz in collected/, or set manually\n",
35
- "COLLECTED_DIR = os.path.join(os.path.dirname(os.path.abspath(\"__file__\")), \"collected\")\n",
36
- "npz_files = sorted(glob.glob(os.path.join(COLLECTED_DIR, \"*.npz\")))\n",
37
- "\n",
38
- "if not npz_files:\n",
39
- " raise FileNotFoundError(f\"No .npz files in {COLLECTED_DIR} — run collect_features.py first\")\n",
40
- "\n",
41
- "NPZ_PATH = npz_files[-1] # latest file\n",
42
- "print(f\"Using: {NPZ_PATH}\")\n",
43
- "\n",
44
- "data = np.load(NPZ_PATH, allow_pickle=True)\n",
45
- "features = data['features']\n",
46
- "labels = data['labels']\n",
47
- "names = list(data['feature_names'])\n",
48
- "\n",
49
- "print(f\"Loaded: {NPZ_PATH}\")\n",
50
- "print(f\"Samples: {len(labels)}\")\n",
51
- "print(f\"Features: {features.shape[1]} -> {names}\")\n",
52
- "print(f\"Labels: 0={int((labels==0).sum())}, 1={int((labels==1).sum())}\")"
53
- ]
54
- },
55
- {
56
- "cell_type": "markdown",
57
- "metadata": {},
58
- "source": [
59
- "## 1. Basic Stats"
60
- ]
61
- },
62
- {
63
- "cell_type": "code",
64
- "execution_count": null,
65
- "metadata": {},
66
- "outputs": [],
67
- "source": [
68
- "import pandas as pd\n",
69
- "\n",
70
- "df = pd.DataFrame(features, columns=names)\n",
71
- "df['label'] = labels\n",
72
- "\n",
73
- "print(\"=\" * 60)\n",
74
- "print(\"FEATURE STATISTICS\")\n",
75
- "print(\"=\" * 60)\n",
76
- "df.describe().round(4)"
77
- ]
78
- },
79
- {
80
- "cell_type": "code",
81
- "execution_count": null,
82
- "metadata": {},
83
- "outputs": [],
84
- "source": [
85
- "# NaN check\n",
86
- "nan_counts = df.isna().sum()\n",
87
- "if nan_counts.sum() == 0:\n",
88
- " print(\"No NaN values found\")\n",
89
- "else:\n",
90
- " print(\"NaN counts:\")\n",
91
- " print(nan_counts[nan_counts > 0])"
92
- ]
93
- },
94
- {
95
- "cell_type": "markdown",
96
- "metadata": {},
97
- "source": [
98
- "## 2. Label Distribution"
99
- ]
100
- },
101
- {
102
- "cell_type": "code",
103
- "execution_count": null,
104
- "metadata": {},
105
- "outputs": [],
106
- "source": [
107
- "n0 = int((labels == 0).sum())\n",
108
- "n1 = int((labels == 1).sum())\n",
109
- "total = len(labels)\n",
110
- "\n",
111
- "fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n",
112
- "\n",
113
- "# bar chart\n",
114
- "axes[0].bar(['Unfocused (0)', 'Focused (1)'], [n0, n1], color=['#EF476F', '#06D6A0'])\n",
115
- "axes[0].set_ylabel('Samples')\n",
116
- "axes[0].set_title('Label Distribution')\n",
117
- "for i, v in enumerate([n0, n1]):\n",
118
- " axes[0].text(i, v + total*0.01, f'{v} ({v/total*100:.1f}%)', ha='center', fontsize=10)\n",
119
- "\n",
120
- "# label over time\n",
121
- "axes[1].plot(labels, color='#00B4D8', linewidth=0.5)\n",
122
- "axes[1].fill_between(range(len(labels)), labels, alpha=0.3, color='#06D6A0')\n",
123
- "axes[1].set_xlabel('Frame')\n",
124
- "axes[1].set_ylabel('Label')\n",
125
- "axes[1].set_title('Label Over Time')\n",
126
- "axes[1].set_yticks([0, 1])\n",
127
- "axes[1].set_yticklabels(['Unfocused', 'Focused'])\n",
128
- "\n",
129
- "plt.tight_layout()\n",
130
- "plt.show()\n",
131
- "\n",
132
- "# transitions\n",
133
- "transitions = int(np.sum(np.diff(labels) != 0))\n",
134
- "print(f\"Transitions: {transitions}\")\n",
135
- "print(f\"Avg segment: {total/max(transitions,1):.0f} frames ({total/max(transitions,1)/30:.1f}s)\")\n",
136
- "if transitions < 10:\n",
137
- " print(\"⚠️ Too few transitions — switch every 10-30s when re-recording\")"
138
- ]
139
- },
140
- {
141
- "cell_type": "markdown",
142
- "metadata": {},
143
- "source": [
144
- "## 3. Feature Distributions (Focused vs Unfocused)"
145
- ]
146
- },
147
- {
148
- "cell_type": "code",
149
- "execution_count": null,
150
- "metadata": {},
151
- "outputs": [],
152
- "source": [
153
- "n_features = features.shape[1]\n",
154
- "cols = 3\n",
155
- "rows = (n_features + cols - 1) // cols\n",
156
- "\n",
157
- "fig, axes = plt.subplots(rows, cols, figsize=(14, rows * 2.5))\n",
158
- "axes = axes.flatten()\n",
159
- "\n",
160
- "for i in range(n_features):\n",
161
- " ax = axes[i]\n",
162
- " f0 = features[labels == 0, i]\n",
163
- " f1 = features[labels == 1, i]\n",
164
- " ax.hist(f0, bins=40, alpha=0.6, color='#EF476F', label='Unfocused', density=True)\n",
165
- " ax.hist(f1, bins=40, alpha=0.6, color='#06D6A0', label='Focused', density=True)\n",
166
- " ax.set_title(names[i], fontsize=10, fontweight='bold')\n",
167
- " ax.tick_params(labelsize=8)\n",
168
- " if i == 0:\n",
169
- " ax.legend(fontsize=8)\n",
170
- "\n",
171
- "# hide empty axes\n",
172
- "for i in range(n_features, len(axes)):\n",
173
- " axes[i].set_visible(False)\n",
174
- "\n",
175
- "plt.suptitle('Feature Distributions by Label', fontsize=14, fontweight='bold', y=1.01)\n",
176
- "plt.tight_layout()\n",
177
- "plt.show()"
178
- ]
179
- },
180
- {
181
- "cell_type": "markdown",
182
- "metadata": {},
183
- "source": [
184
- "## 4. Feature-Label Correlations"
185
- ]
186
- },
187
- {
188
- "cell_type": "code",
189
- "execution_count": null,
190
- "metadata": {},
191
- "outputs": [],
192
- "source": [
193
- "correlations = [np.corrcoef(features[:, i], labels)[0, 1] for i in range(n_features)]\n",
194
- "sort_idx = np.argsort(np.abs(correlations))[::-1]\n",
195
- "\n",
196
- "fig, ax = plt.subplots(figsize=(10, 5))\n",
197
- "colors = ['#06D6A0' if c > 0 else '#EF476F' for c in [correlations[i] for i in sort_idx]]\n",
198
- "bars = ax.barh([names[i] for i in sort_idx],\n",
199
- " [correlations[i] for i in sort_idx],\n",
200
- " color=colors)\n",
201
- "ax.set_xlabel('Correlation with Label (focused=1)')\n",
202
- "ax.set_title('Feature-Label Correlations (sorted by |r|)')\n",
203
- "ax.axvline(0, color='gray', linewidth=0.5)\n",
204
- "\n",
205
- "for bar, idx in zip(bars, sort_idx):\n",
206
- " r = correlations[idx]\n",
207
- " ax.text(r + (0.01 if r >= 0 else -0.01), bar.get_y() + bar.get_height()/2,\n",
208
- " f'{r:.3f}', va='center', ha='left' if r >= 0 else 'right', fontsize=9)\n",
209
- "\n",
210
- "plt.tight_layout()\n",
211
- "plt.show()\n",
212
- "\n",
213
- "print(\"\\nTop predictive features:\")\n",
214
- "for i in sort_idx[:5]:\n",
215
- " print(f\" {names[i]:<20} r = {correlations[i]:+.4f}\")"
216
- ]
217
- },
218
- {
219
- "cell_type": "markdown",
220
- "metadata": {},
221
- "source": [
222
- "## 5. Feature Correlation Matrix"
223
- ]
224
- },
225
- {
226
- "cell_type": "code",
227
- "execution_count": null,
228
- "metadata": {},
229
- "outputs": [],
230
- "source": [
231
- "corr_matrix = np.corrcoef(features.T)\n",
232
- "\n",
233
- "fig, ax = plt.subplots(figsize=(10, 8))\n",
234
- "im = ax.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1)\n",
235
- "ax.set_xticks(range(n_features))\n",
236
- "ax.set_yticks(range(n_features))\n",
237
- "ax.set_xticklabels(names, rotation=45, ha='right', fontsize=9)\n",
238
- "ax.set_yticklabels(names, fontsize=9)\n",
239
- "ax.set_title('Feature Correlation Matrix')\n",
240
- "plt.colorbar(im, ax=ax, shrink=0.8)\n",
241
- "\n",
242
- "# annotate\n",
243
- "for i in range(n_features):\n",
244
- " for j in range(n_features):\n",
245
- " val = corr_matrix[i, j]\n",
246
- " if abs(val) > 0.5 and i != j:\n",
247
- " ax.text(j, i, f'{val:.2f}', ha='center', va='center', fontsize=7,\n",
248
- " color='white' if abs(val) > 0.7 else 'black')\n",
249
- "\n",
250
- "plt.tight_layout()\n",
251
- "plt.show()"
252
- ]
253
- },
254
- {
255
- "cell_type": "markdown",
256
- "metadata": {},
257
- "source": [
258
- "## 6. Features Over Time"
259
- ]
260
- },
261
- {
262
- "cell_type": "code",
263
- "execution_count": null,
264
- "metadata": {},
265
- "outputs": [],
266
- "source": [
267
- "# Plot key features over time with label shading\n",
268
- "key_features = ['s_face', 's_eye', 'ear_avg', 'yaw', 'pitch']\n",
269
- "# filter to only features that exist in this file\n",
270
- "key_features = [f for f in key_features if f in names]\n",
271
- "\n",
272
- "fig, axes = plt.subplots(len(key_features) + 1, 1, figsize=(14, (len(key_features)+1) * 1.8),\n",
273
- " sharex=True)\n",
274
- "\n",
275
- "# label timeline\n",
276
- "axes[0].fill_between(range(len(labels)), labels, alpha=0.4, color='#06D6A0', step='mid')\n",
277
- "axes[0].set_ylabel('Label')\n",
278
- "axes[0].set_yticks([0, 1])\n",
279
- "axes[0].set_yticklabels(['Unfocused', 'Focused'], fontsize=9)\n",
280
- "axes[0].set_title('Label + Key Features Over Time', fontsize=12, fontweight='bold')\n",
281
- "\n",
282
- "for i, feat in enumerate(key_features):\n",
283
- " idx = names.index(feat)\n",
284
- " ax = axes[i + 1]\n",
285
- " ax.plot(features[:, idx], linewidth=0.8, color='#00B4D8')\n",
286
- " # shade focused regions\n",
287
- " ax.fill_between(range(len(labels)), ax.get_ylim()[0], ax.get_ylim()[1],\n",
288
- " where=labels == 1, alpha=0.1, color='green')\n",
289
- " ax.set_ylabel(feat, fontsize=9)\n",
290
- "\n",
291
- "axes[-1].set_xlabel('Frame')\n",
292
- "plt.tight_layout()\n",
293
- "plt.show()"
294
- ]
295
- },
296
- {
297
- "cell_type": "markdown",
298
- "metadata": {},
299
- "source": [
300
- "## 7. Quality Summary"
301
- ]
302
- },
303
- {
304
- "cell_type": "code",
305
- "execution_count": null,
306
- "metadata": {},
307
- "outputs": [],
308
- "source": [
309
- "duration_sec = len(labels) / 30.0\n",
310
- "balance = n1 / max(total, 1)\n",
311
- "\n",
312
- "checks = {\n",
313
- " 'Duration >= 2 min': duration_sec >= 120,\n",
314
- " 'Samples >= 3000': total >= 3000,\n",
315
- " 'Balance 30-70%': 0.3 <= balance <= 0.7,\n",
316
- " 'Transitions >= 10': transitions >= 10,\n",
317
- " 'No NaN values': int(np.isnan(features).sum()) == 0,\n",
318
- " 'No constant features': all(features[:, i].std() > 0.001 for i in range(n_features)),\n",
319
- "}\n",
320
- "\n",
321
- "print(\"DATA QUALITY CHECKLIST\")\n",
322
- "print(\"=\" * 40)\n",
323
- "for check, passed in checks.items():\n",
324
- " icon = '✅' if passed else '❌'\n",
325
- " print(f\" {icon} {check}\")\n",
326
- "\n",
327
- "passed = sum(checks.values())\n",
328
- "print(f\"\\n {passed}/{len(checks)} checks passed\")\n",
329
- "if passed == len(checks):\n",
330
- " print(\" Ready for training!\")\n",
331
- "else:\n",
332
- " print(\" Re-record or collect more data.\")"
333
- ]
334
- },
335
- {
336
- "cell_type": "markdown",
337
- "metadata": {},
338
- "source": [
339
- "## 8. Merge Multiple Sessions (Optional)\n",
340
- "Run this if you have multiple `.npz` files from different team members."
341
- ]
342
- },
343
- {
344
- "cell_type": "code",
345
- "execution_count": null,
346
- "metadata": {},
347
- "outputs": [],
348
- "source": [
349
- "COLLECTED_DIR = \"data_preparation/collected/\"\n",
350
- "\n",
351
- "all_features = []\n",
352
- "all_labels = []\n",
353
- "all_participants = [] # for participant-aware splitting\n",
354
- "\n",
355
- "npz_files = sorted([f for f in os.listdir(COLLECTED_DIR) if f.endswith('.npz')])\n",
356
- "print(f\"Found {len(npz_files)} .npz files:\\n\")\n",
357
- "\n",
358
- "for i, fname in enumerate(npz_files):\n",
359
- " d = np.load(os.path.join(COLLECTED_DIR, fname), allow_pickle=True)\n",
360
- " f, l = d['features'], d['labels']\n",
361
- " n = len(l)\n",
362
- " n1 = int((l == 1).sum())\n",
363
- " trans = int(np.sum(np.diff(l) != 0))\n",
364
- " print(f\" [{i}] {fname}\")\n",
365
- " print(f\" {n} samples, {n1/n*100:.0f}% focused, {trans} transitions, {n/30:.0f}s\")\n",
366
- " \n",
367
- " all_features.append(f)\n",
368
- " all_labels.append(l)\n",
369
- " all_participants.append(np.full(n, i, dtype=np.int32))\n",
370
- "\n",
371
- "if len(all_features) > 0:\n",
372
- " merged_features = np.concatenate(all_features)\n",
373
- " merged_labels = np.concatenate(all_labels)\n",
374
- " merged_participants = np.concatenate(all_participants)\n",
375
- " \n",
376
- " print(f\"\\nMerged: {len(merged_labels)} total samples\")\n",
377
- " print(f\" Focused: {int((merged_labels==1).sum())} ({(merged_labels==1).mean()*100:.1f}%)\")\n",
378
- " print(f\" Unfocused: {int((merged_labels==0).sum())} ({(merged_labels==0).mean()*100:.1f}%)\")\n",
379
- " \n",
380
- " # Save merged\n",
381
- " out_path = os.path.join(COLLECTED_DIR, \"merged_all.npz\")\n",
382
- " np.savez(out_path,\n",
383
- " features=merged_features,\n",
384
- " labels=merged_labels,\n",
385
- " participants=merged_participants,\n",
386
- " feature_names=d['feature_names'])\n",
387
- " print(f\" Saved -> {out_path}\")\n",
388
- "else:\n",
389
- " print(\"No .npz files found\")"
390
- ]
391
- }
392
- ],
393
- "metadata": {
394
- "kernelspec": {
395
- "display_name": "venv",
396
- "language": "python",
397
- "name": "python3"
398
- },
399
- "language_info": {
400
- "codemirror_mode": {
401
- "name": "ipython",
402
- "version": 3
403
- },
404
- "file_extension": ".py",
405
- "mimetype": "text/x-python",
406
- "name": "python",
407
- "nbconvert_exporter": "python",
408
- "pygments_lexer": "ipython3",
409
- "version": "3.13.7"
410
- }
411
- },
412
- "nbformat": 4,
413
- "nbformat_minor": 4
414
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data_preparation/eye_crops/test/closed/.gitkeep DELETED
File without changes
data_preparation/eye_crops/test/open/.gitkeep DELETED
File without changes
data_preparation/eye_crops/train/closed/.gitkeep DELETED
File without changes
data_preparation/eye_crops/train/open/.gitkeep DELETED
File without changes
data_preparation/eye_crops/val/closed/.gitkeep DELETED
File without changes
data_preparation/eye_crops/val/open/.gitkeep DELETED
File without changes
evaluation/evaluate.py DELETED
@@ -1 +0,0 @@
1
- # stub
 
 
evaluation/metrics.py DELETED
@@ -1 +0,0 @@
1
- # stub
 
 
models/attention_model/__init__.py DELETED
File without changes
models/attention_model/attention_classifier.py DELETED
@@ -1 +0,0 @@
1
- # stub
 
 
models/attention_model/collect_features.py DELETED
@@ -1,403 +0,0 @@
1
- # Collect labeled face mesh features from webcam for training
2
- #
3
- # Run the demo, press 1 = focused, 0 = not focused, p = pause, q = save & quit.
4
- # Each labeled frame saves 17 features (geometric + temporal) + label.
5
- # Expect 5-10 min per person. Switch focus/unfocus every 10-30 seconds.
6
- #
7
- # Usage:
8
- # python models/attention_model/collect_features.py
9
- # python models/attention_model/collect_features.py --name alice --duration 600
10
-
11
- import argparse
12
- import collections
13
- import math
14
- import os
15
- import sys
16
- import time
17
-
18
- import cv2
19
- import numpy as np
20
-
21
- _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
- if _PROJECT_ROOT not in sys.path:
23
- sys.path.insert(0, _PROJECT_ROOT)
24
-
25
- from models.face_mesh.face_mesh import FaceMeshDetector
26
- from models.face_orientation.head_pose import HeadPoseEstimator
27
- from models.eye_behaviour.eye_scorer import EyeBehaviourScorer, compute_gaze_ratio, compute_mar
28
-
29
- FONT = cv2.FONT_HERSHEY_SIMPLEX
30
- GREEN = (0, 255, 0)
31
- RED = (0, 0, 255)
32
- WHITE = (255, 255, 255)
33
- YELLOW = (0, 255, 255)
34
- ORANGE = (0, 165, 255)
35
- GRAY = (120, 120, 120)
36
-
37
- # ---------------------------------------------------------------------------
38
- # 17 features: geometric (11) + derived (2) + temporal (4)
39
- # ---------------------------------------------------------------------------
40
- FEATURE_NAMES = [
41
- # --- geometric (from landmarks each frame) ---
42
- "ear_left", # 0 Left Eye Aspect Ratio
43
- "ear_right", # 1 Right Eye Aspect Ratio
44
- "ear_avg", # 2 Mean EAR
45
- "h_gaze", # 3 Horizontal iris position
46
- "v_gaze", # 4 Vertical iris position
47
- "mar", # 5 Mouth Aspect Ratio
48
- "yaw", # 6 Head horizontal rotation (degrees)
49
- "pitch", # 7 Head vertical tilt (degrees)
50
- "roll", # 8 Head lateral tilt (degrees)
51
- "s_face", # 9 Cosine-decay head pose score [0,1]
52
- "s_eye", # 10 Geometric eye score [0,1]
53
- # --- derived ---
54
- "gaze_offset", # 11 Distance from gaze centre: sqrt((h-0.5)^2 + (v-0.5)^2)
55
- "head_deviation", # 12 sqrt(yaw^2 + pitch^2)
56
- # --- temporal (rolling window) ---
57
- "perclos", # 13 % eye closure over last 60 frames
58
- "blink_rate", # 14 Blinks per minute (30s window)
59
- "closure_duration", # 15 Current sustained eye closure (seconds)
60
- "yawn_duration", # 16 Current sustained yawn (seconds)
61
- ]
62
-
63
- NUM_FEATURES = len(FEATURE_NAMES)
64
- assert NUM_FEATURES == 17
65
-
66
-
67
- # ---------------------------------------------------------------------------
68
- # Temporal tracker — keeps rolling history for PERCLOS, blink rate, etc.
69
- # ---------------------------------------------------------------------------
70
- class TemporalTracker:
71
- """Track temporal signals across frames."""
72
-
73
- EAR_BLINK_THRESH = 0.21 # EAR below this = eyes closed
74
- MAR_YAWN_THRESH = 0.04 # MAR above this = yawning
75
- PERCLOS_WINDOW = 60 # frames for PERCLOS
76
- BLINK_WINDOW_SEC = 30.0 # seconds for blink rate
77
-
78
- def __init__(self):
79
- self.ear_history = collections.deque(maxlen=self.PERCLOS_WINDOW)
80
- self.blink_timestamps = collections.deque() # list of blink end times
81
- self._eyes_closed = False
82
- self._closure_start = None # time when eyes first closed
83
- self._yawn_start = None # time when yawn started
84
-
85
- def update(self, ear_avg, mar, now=None):
86
- """Call once per frame. Returns (perclos, blink_rate, closure_dur, yawn_dur)."""
87
- if now is None:
88
- now = time.time()
89
-
90
- # --- PERCLOS ---
91
- closed = ear_avg < self.EAR_BLINK_THRESH
92
- self.ear_history.append(1.0 if closed else 0.0)
93
- perclos = sum(self.ear_history) / len(self.ear_history) if self.ear_history else 0.0
94
-
95
- # --- Blink detection (closed -> open transition) ---
96
- if self._eyes_closed and not closed:
97
- # blink just ended
98
- self.blink_timestamps.append(now)
99
- self._eyes_closed = closed
100
-
101
- # prune old blinks
102
- cutoff = now - self.BLINK_WINDOW_SEC
103
- while self.blink_timestamps and self.blink_timestamps[0] < cutoff:
104
- self.blink_timestamps.popleft()
105
- blink_rate = len(self.blink_timestamps) * (60.0 / self.BLINK_WINDOW_SEC)
106
-
107
- # --- Closure duration ---
108
- if closed:
109
- if self._closure_start is None:
110
- self._closure_start = now
111
- closure_dur = now - self._closure_start
112
- else:
113
- self._closure_start = None
114
- closure_dur = 0.0
115
-
116
- # --- Yawn duration ---
117
- yawning = mar > self.MAR_YAWN_THRESH
118
- if yawning:
119
- if self._yawn_start is None:
120
- self._yawn_start = now
121
- yawn_dur = now - self._yawn_start
122
- else:
123
- self._yawn_start = None
124
- yawn_dur = 0.0
125
-
126
- return perclos, blink_rate, closure_dur, yawn_dur
127
-
128
-
129
- # ---------------------------------------------------------------------------
130
- # Feature extraction (one frame -> 17-dim vector)
131
- # ---------------------------------------------------------------------------
132
- def extract_features(landmarks, w, h, head_pose, eye_scorer, temporal):
133
- """Extract 17 features from one frame's landmarks."""
134
- from models.eye_behaviour.eye_scorer import _LEFT_EYE_EAR, _RIGHT_EYE_EAR, compute_ear
135
-
136
- # --- geometric ---
137
- ear_left = compute_ear(landmarks, _LEFT_EYE_EAR)
138
- ear_right = compute_ear(landmarks, _RIGHT_EYE_EAR)
139
- ear_avg = (ear_left + ear_right) / 2.0
140
- h_gaze, v_gaze = compute_gaze_ratio(landmarks)
141
- mar = compute_mar(landmarks)
142
-
143
- angles = head_pose.estimate(landmarks, w, h)
144
- yaw = angles[0] if angles else 0.0
145
- pitch = angles[1] if angles else 0.0
146
- roll = angles[2] if angles else 0.0
147
-
148
- s_face = head_pose.score(landmarks, w, h)
149
- s_eye = eye_scorer.score(landmarks)
150
-
151
- # --- derived ---
152
- gaze_offset = math.sqrt((h_gaze - 0.5) ** 2 + (v_gaze - 0.5) ** 2)
153
- head_deviation = math.sqrt(yaw ** 2 + pitch ** 2)
154
-
155
- # --- temporal ---
156
- perclos, blink_rate, closure_dur, yawn_dur = temporal.update(ear_avg, mar)
157
-
158
- return np.array([
159
- ear_left, ear_right, ear_avg,
160
- h_gaze, v_gaze,
161
- mar,
162
- yaw, pitch, roll,
163
- s_face, s_eye,
164
- gaze_offset,
165
- head_deviation,
166
- perclos, blink_rate, closure_dur, yawn_dur,
167
- ], dtype=np.float32)
168
-
169
-
170
- # ---------------------------------------------------------------------------
171
- # Quality checks — run at save time
172
- # ---------------------------------------------------------------------------
173
- def quality_report(labels):
174
- """Print warnings about data quality issues."""
175
- n = len(labels)
176
- n1 = int((labels == 1).sum())
177
- n0 = n - n1
178
- transitions = int(np.sum(np.diff(labels) != 0))
179
- duration_sec = n / 30.0 # approximate at 30fps
180
-
181
- warnings = []
182
-
183
- print(f"\n{'='*50}")
184
- print(f" DATA QUALITY REPORT")
185
- print(f"{'='*50}")
186
- print(f" Total samples : {n}")
187
- print(f" Focused : {n1} ({n1/max(n,1)*100:.1f}%)")
188
- print(f" Unfocused : {n0} ({n0/max(n,1)*100:.1f}%)")
189
- print(f" Duration : {duration_sec:.0f}s ({duration_sec/60:.1f} min)")
190
- print(f" Transitions : {transitions}")
191
- if transitions > 0:
192
- print(f" Avg segment : {n/transitions:.0f} frames ({n/transitions/30:.1f}s)")
193
-
194
- # checks
195
- if duration_sec < 120:
196
- warnings.append(f"TOO SHORT: {duration_sec:.0f}s — aim for 5-10 minutes (300-600s)")
197
-
198
- if n < 3000:
199
- warnings.append(f"LOW SAMPLE COUNT: {n} frames — aim for 9000+ (5 min at 30fps)")
200
-
201
- balance = n1 / max(n, 1)
202
- if balance < 0.3 or balance > 0.7:
203
- warnings.append(f"IMBALANCED: {balance:.0%} focused — aim for 35-65% focused")
204
-
205
- if transitions < 10:
206
- warnings.append(f"TOO FEW TRANSITIONS: {transitions} — switch every 10-30s, aim for 20+")
207
-
208
- if transitions == 1:
209
- warnings.append("SINGLE BLOCK: you recorded one unfocused + one focused block — "
210
- "model will learn temporal position, not focus patterns")
211
-
212
- if warnings:
213
- print(f"\n ⚠️ WARNINGS ({len(warnings)}):")
214
- for w in warnings:
215
- print(f" • {w}")
216
- print(f"\n Consider re-recording this session.")
217
- else:
218
- print(f"\n ✅ All checks passed!")
219
-
220
- print(f"{'='*50}\n")
221
- return len(warnings) == 0
222
-
223
-
224
- # ---------------------------------------------------------------------------
225
- # Main
226
- # ---------------------------------------------------------------------------
227
- def main():
228
- parser = argparse.ArgumentParser(description="Collect labeled attention data from webcam")
229
- parser.add_argument("--name", type=str, default="session",
230
- help="Your name or session ID")
231
- parser.add_argument("--camera", type=int, default=0,
232
- help="Camera index")
233
- parser.add_argument("--duration", type=int, default=600,
234
- help="Max recording time (seconds, default 10 min)")
235
- parser.add_argument("--output-dir", type=str,
236
- default=os.path.join(_PROJECT_ROOT, "data_preparation", "collected"),
237
- help="Where to save .npz files")
238
- args = parser.parse_args()
239
-
240
- os.makedirs(args.output_dir, exist_ok=True)
241
-
242
- detector = FaceMeshDetector()
243
- head_pose = HeadPoseEstimator()
244
- eye_scorer = EyeBehaviourScorer()
245
- temporal = TemporalTracker()
246
-
247
- cap = cv2.VideoCapture(args.camera)
248
- if not cap.isOpened():
249
- print("[COLLECT] ERROR: can't open camera")
250
- return
251
-
252
- print("[COLLECT] Data Collection Tool")
253
- print(f"[COLLECT] Session: {args.name}, max {args.duration}s")
254
- print(f"[COLLECT] Features per frame: {NUM_FEATURES}")
255
- print("[COLLECT] Controls:")
256
- print(" 1 = FOCUSED (looking at screen normally)")
257
- print(" 0 = NOT FOCUSED (phone, away, eyes closed, yawning)")
258
- print(" p = pause")
259
- print(" q = save & quit")
260
- print()
261
- print("[COLLECT] TIPS for good data:")
262
- print(" • Switch between 1 and 0 every 10-30 seconds")
263
- print(" • Aim for 20+ transitions total")
264
- print(" • Act out varied scenarios: reading, phone, talking, drowsy")
265
- print(" • Record at least 5 minutes")
266
- print()
267
-
268
- features_list = []
269
- labels_list = []
270
- label = None # None = paused
271
- transitions = 0 # count label switches
272
- prev_label = None
273
- status = "PAUSED -- press 1 (focused) or 0 (not focused)"
274
- t_start = time.time()
275
- prev_time = time.time()
276
- fps = 0.0
277
-
278
- try:
279
- while True:
280
- elapsed = time.time() - t_start
281
- if elapsed > args.duration:
282
- print(f"[COLLECT] Time limit ({args.duration}s)")
283
- break
284
-
285
- ret, frame = cap.read()
286
- if not ret:
287
- break
288
-
289
- h, w = frame.shape[:2]
290
- landmarks = detector.process(frame)
291
- face_ok = landmarks is not None
292
-
293
- # record if labeling + face visible
294
- if face_ok and label is not None:
295
- vec = extract_features(landmarks, w, h, head_pose, eye_scorer, temporal)
296
- features_list.append(vec)
297
- labels_list.append(label)
298
-
299
- # count transitions
300
- if prev_label is not None and label != prev_label:
301
- transitions += 1
302
- prev_label = label
303
-
304
- now = time.time()
305
- fps = 0.9 * fps + 0.1 * (1.0 / max(now - prev_time, 1e-6))
306
- prev_time = now
307
-
308
- # --- draw UI ---
309
- n = len(labels_list)
310
- n1 = sum(1 for x in labels_list if x == 1)
311
- n0 = n - n1
312
- remaining = max(0, args.duration - elapsed)
313
-
314
- # top bar
315
- bar_color = GREEN if label == 1 else (RED if label == 0 else (80, 80, 80))
316
- cv2.rectangle(frame, (0, 0), (w, 70), (0, 0, 0), -1)
317
- cv2.putText(frame, status, (10, 22), FONT, 0.55, bar_color, 2, cv2.LINE_AA)
318
- cv2.putText(frame, f"Samples: {n} (F:{n1} U:{n0}) Switches: {transitions}",
319
- (10, 48), FONT, 0.42, WHITE, 1, cv2.LINE_AA)
320
- cv2.putText(frame, f"FPS:{fps:.0f}", (w - 80, 22), FONT, 0.45, WHITE, 1, cv2.LINE_AA)
321
- cv2.putText(frame, f"{int(remaining)}s left", (w - 80, 48), FONT, 0.42, YELLOW, 1, cv2.LINE_AA)
322
-
323
- # balance bar
324
- if n > 0:
325
- bar_w = min(w - 20, 300)
326
- bar_x = w - bar_w - 10
327
- bar_y = 58
328
- frac = n1 / n
329
- cv2.rectangle(frame, (bar_x, bar_y), (bar_x + bar_w, bar_y + 8), (40, 40, 40), -1)
330
- cv2.rectangle(frame, (bar_x, bar_y), (bar_x + int(bar_w * frac), bar_y + 8), GREEN, -1)
331
- cv2.putText(frame, f"{frac:.0%}F", (bar_x + bar_w + 4, bar_y + 8),
332
- FONT, 0.3, GRAY, 1, cv2.LINE_AA)
333
-
334
- if not face_ok:
335
- cv2.putText(frame, "NO FACE", (w // 2 - 60, h // 2), FONT, 0.7, RED, 2, cv2.LINE_AA)
336
-
337
- # red dot = recording
338
- if label is not None and face_ok:
339
- cv2.circle(frame, (w - 20, 80), 8, RED, -1)
340
-
341
- # live warnings
342
- warn_y = h - 35
343
- if n > 100 and transitions < 3:
344
- cv2.putText(frame, "! Switch more often (aim for 20+ transitions)",
345
- (10, warn_y), FONT, 0.38, ORANGE, 1, cv2.LINE_AA)
346
- warn_y -= 18
347
- if elapsed > 30 and n > 0:
348
- bal = n1 / n
349
- if bal < 0.25 or bal > 0.75:
350
- cv2.putText(frame, f"! Imbalanced ({bal:.0%} focused) - record more of the other",
351
- (10, warn_y), FONT, 0.38, ORANGE, 1, cv2.LINE_AA)
352
- warn_y -= 18
353
-
354
- cv2.putText(frame, "1:focused 0:unfocused p:pause q:save+quit",
355
- (10, h - 10), FONT, 0.38, GRAY, 1, cv2.LINE_AA)
356
-
357
- cv2.imshow("FocusGuard -- Data Collection", frame)
358
-
359
- key = cv2.waitKey(1) & 0xFF
360
- if key == ord("1"):
361
- label = 1
362
- status = "Recording: FOCUSED"
363
- print(f"[COLLECT] -> FOCUSED (n={n}, transitions={transitions})")
364
- elif key == ord("0"):
365
- label = 0
366
- status = "Recording: NOT FOCUSED"
367
- print(f"[COLLECT] -> NOT FOCUSED (n={n}, transitions={transitions})")
368
- elif key == ord("p"):
369
- label = None
370
- status = "PAUSED"
371
- print(f"[COLLECT] paused (n={n})")
372
- elif key == ord("q"):
373
- break
374
-
375
- finally:
376
- cap.release()
377
- cv2.destroyAllWindows()
378
- detector.close()
379
-
380
- if len(features_list) > 0:
381
- feats = np.stack(features_list)
382
- labs = np.array(labels_list, dtype=np.int64)
383
-
384
- ts = time.strftime("%Y%m%d_%H%M%S")
385
- fname = f"{args.name}_{ts}.npz"
386
- fpath = os.path.join(args.output_dir, fname)
387
- np.savez(fpath,
388
- features=feats,
389
- labels=labs,
390
- feature_names=np.array(FEATURE_NAMES))
391
-
392
- print(f"\n[COLLECT] Saved {len(labs)} samples -> {fpath}")
393
- print(f" Shape: {feats.shape} ({NUM_FEATURES} features)")
394
-
395
- quality_report(labs)
396
- else:
397
- print("\n[COLLECT] No data collected")
398
-
399
- print("[COLLECT] Done")
400
-
401
-
402
- if __name__ == "__main__":
403
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/attention_model/train_attention.py DELETED
@@ -1 +0,0 @@
1
- # stub
 
 
models/attention_score_fusion/.gitkeep DELETED
File without changes
models/attention_score_fusion/__init__.py DELETED
File without changes
models/attention_score_fusion/fusion.py DELETED
@@ -1 +0,0 @@
1
- # stub
 
 
models/eye_behaviour/__init__.py DELETED
File without changes
models/eye_behaviour/eye_attention_model.py DELETED
@@ -1,48 +0,0 @@
1
- # MobileNetV2 eye attention classifier (attentive vs inattentive)
2
-
3
- import torch
4
- import torch.nn as nn
5
- import torchvision.models as models
6
-
7
-
8
- class EyeAttentionModel(nn.Module):
9
- def __init__(
10
- self,
11
- pretrained: bool = True,
12
- dropout1: float = 0.3,
13
- dropout2: float = 0.2,
14
- ):
15
- super().__init__()
16
-
17
- weights = models.MobileNet_V2_Weights.DEFAULT if pretrained else None
18
- backbone = models.mobilenet_v2(weights=weights)
19
-
20
- self.features = backbone.features
21
- self.pool = nn.AdaptiveAvgPool2d(1)
22
- self.classifier = nn.Sequential(
23
- nn.Dropout(dropout1),
24
- nn.Linear(1280, 256),
25
- nn.ReLU(),
26
- nn.Dropout(dropout2),
27
- nn.Linear(256, 2),
28
- )
29
-
30
- def forward(self, x: torch.Tensor) -> torch.Tensor:
31
- x = self.features(x)
32
- x = self.pool(x).flatten(1)
33
- return self.classifier(x)
34
-
35
- def predict_score(self, x: torch.Tensor) -> torch.Tensor:
36
- logits = self.forward(x)
37
- probs = torch.softmax(logits, dim=1)
38
- return probs[:, 1]
39
-
40
- def freeze_backbone(self):
41
- for param in self.features.parameters():
42
- param.requires_grad = False
43
-
44
- def unfreeze_last_blocks(self, n: int = 4):
45
- total_blocks = len(self.features)
46
- for i in range(max(0, total_blocks - n), total_blocks):
47
- for param in self.features[i].parameters():
48
- param.requires_grad = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/eye_behaviour/eye_classifier.py DELETED
@@ -1,149 +0,0 @@
1
- # Swappable eye classifier: geometric only, MobileNetV2 (96x96), or YOLO open/closed (224x224)
2
-
3
- from __future__ import annotations
4
-
5
- from abc import ABC, abstractmethod
6
-
7
- import cv2
8
- import numpy as np
9
-
10
-
11
- class EyeClassifier(ABC):
12
- @property
13
- @abstractmethod
14
- def name(self) -> str:
15
- pass
16
-
17
- @abstractmethod
18
- def predict_score(self, crops_bgr: list[np.ndarray]) -> float:
19
- # crops_bgr: [left_crop, right_crop] BGR; returns score in [0,1], 1 = attentive (open)
20
- pass
21
-
22
-
23
- class GeometricOnlyClassifier(EyeClassifier):
24
- @property
25
- def name(self) -> str:
26
- return "geometric"
27
-
28
- def predict_score(self, crops_bgr: list[np.ndarray]) -> float:
29
- return 1.0
30
-
31
-
32
- class MobileNetV2Classifier(EyeClassifier):
33
- # 96x96 crops, ImageNet norm
34
- def __init__(self, checkpoint_path: str, device: str = "cpu"):
35
- import torch
36
-
37
- from models.eye_behaviour.eye_attention_model import EyeAttentionModel
38
- from models.eye_behaviour.eye_crop import crop_to_tensor, CROP_SIZE
39
-
40
- self._crop_to_tensor = crop_to_tensor
41
- self._crop_size = CROP_SIZE
42
- self._device = torch.device(device)
43
-
44
- self._model = EyeAttentionModel(pretrained=False).to(self._device)
45
- self._model.load_state_dict(
46
- torch.load(checkpoint_path, map_location=self._device, weights_only=True)
47
- )
48
- self._model.eval()
49
-
50
- @property
51
- def name(self) -> str:
52
- return "mobilenet"
53
-
54
- def predict_score(self, crops_bgr: list[np.ndarray]) -> float:
55
- import torch
56
-
57
- if not crops_bgr:
58
- return 1.0
59
- tensors = []
60
- for crop in crops_bgr:
61
- resized = cv2.resize(crop, (self._crop_size, self._crop_size), interpolation=cv2.INTER_AREA)
62
- tensors.append(self._crop_to_tensor(resized))
63
- batch = torch.stack(tensors).to(self._device)
64
- with torch.no_grad():
65
- scores = self._model.predict_score(batch)
66
- return scores.mean().item()
67
-
68
-
69
- class YOLOv11Classifier(EyeClassifier):
70
- # YOLO open/closed; resizes to 224x224 internally
71
- def __init__(self, checkpoint_path: str, device: str = "cpu"):
72
- from ultralytics import YOLO
73
-
74
- self._model = YOLO(checkpoint_path)
75
- self._device = device
76
-
77
- names = self._model.names
78
- self._attentive_idx = None
79
- for idx, cls_name in names.items():
80
- if cls_name in ("open", "attentive"):
81
- self._attentive_idx = idx
82
- break
83
- if self._attentive_idx is None:
84
- self._attentive_idx = max(names.keys())
85
- print(f"[YOLO] Classes: {names}, attentive_idx={self._attentive_idx}")
86
-
87
- @property
88
- def name(self) -> str:
89
- return "yolo"
90
-
91
- def predict_score(self, crops_bgr: list[np.ndarray]) -> float:
92
- if not crops_bgr:
93
- return 1.0
94
- results = self._model.predict(crops_bgr, device=self._device, verbose=False)
95
- scores = [float(r.probs.data[self._attentive_idx]) for r in results]
96
- return sum(scores) / len(scores) if scores else 1.0
97
-
98
-
99
- def _is_yolo_checkpoint(path: str) -> bool:
100
- try:
101
- import torch
102
-
103
- data = torch.load(path, map_location="cpu", weights_only=False)
104
- if isinstance(data, dict):
105
- model_obj = data.get("model")
106
- if model_obj is not None and "Model" in type(model_obj).__name__:
107
- return True
108
- if "train_args" in data and "model" in data:
109
- return True
110
- except Exception:
111
- pass
112
- return False
113
-
114
-
115
- def load_eye_classifier(
116
- path: str | None = None,
117
- backend: str = "auto",
118
- device: str = "cpu",
119
- ) -> EyeClassifier:
120
- if path is None or backend == "geometric":
121
- return GeometricOnlyClassifier()
122
-
123
- if backend == "yolo":
124
- try:
125
- return YOLOv11Classifier(path, device=device)
126
- except ImportError:
127
- print("[CLASSIFIER] ultralytics required. pip install ultralytics")
128
- raise
129
-
130
- if backend == "mobilenet":
131
- return MobileNetV2Classifier(path, device=device)
132
-
133
- if _is_yolo_checkpoint(path):
134
- try:
135
- return YOLOv11Classifier(path, device=device)
136
- except ImportError:
137
- print("[CLASSIFIER] YOLO checkpoint needs ultralytics. pip install ultralytics")
138
- raise
139
- try:
140
- return MobileNetV2Classifier(path, device=device)
141
- except Exception as exc:
142
- err = str(exc)
143
- if "Weights only load failed" in err and "ultralytics" in err:
144
- try:
145
- return YOLOv11Classifier(path, device=device)
146
- except ImportError:
147
- print("[CLASSIFIER] pip install ultralytics for this checkpoint")
148
- raise
149
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/eye_behaviour/eye_crop.py DELETED
@@ -1,70 +0,0 @@
1
- # Eye region extraction from Face Mesh landmarks
2
-
3
- import cv2
4
- import numpy as np
5
-
6
- LEFT_EYE_CONTOUR = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246]
7
- RIGHT_EYE_CONTOUR = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398]
8
-
9
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
10
- IMAGENET_STD = (0.229, 0.224, 0.225)
11
-
12
- CROP_SIZE = 96
13
-
14
-
15
- def _bbox_from_landmarks(
16
- landmarks: np.ndarray,
17
- indices: list[int],
18
- frame_w: int,
19
- frame_h: int,
20
- expand: float = 0.4,
21
- ) -> tuple[int, int, int, int]:
22
- pts = landmarks[indices, :2]
23
- px = pts[:, 0] * frame_w
24
- py = pts[:, 1] * frame_h
25
-
26
- x_min, x_max = px.min(), px.max()
27
- y_min, y_max = py.min(), py.max()
28
- w = x_max - x_min
29
- h = y_max - y_min
30
- cx = (x_min + x_max) / 2
31
- cy = (y_min + y_max) / 2
32
-
33
- size = max(w, h) * (1 + expand)
34
- half = size / 2
35
-
36
- x1 = int(max(cx - half, 0))
37
- y1 = int(max(cy - half, 0))
38
- x2 = int(min(cx + half, frame_w))
39
- y2 = int(min(cy + half, frame_h))
40
-
41
- return x1, y1, x2, y2
42
-
43
-
44
- def extract_eye_crops(
45
- frame: np.ndarray,
46
- landmarks: np.ndarray,
47
- expand: float = 0.4,
48
- crop_size: int = CROP_SIZE,
49
- ) -> tuple[np.ndarray, np.ndarray, tuple, tuple]:
50
- h, w = frame.shape[:2]
51
-
52
- left_bbox = _bbox_from_landmarks(landmarks, LEFT_EYE_CONTOUR, w, h, expand)
53
- right_bbox = _bbox_from_landmarks(landmarks, RIGHT_EYE_CONTOUR, w, h, expand)
54
-
55
- left_crop = frame[left_bbox[1] : left_bbox[3], left_bbox[0] : left_bbox[2]]
56
- right_crop = frame[right_bbox[1] : right_bbox[3], right_bbox[0] : right_bbox[2]]
57
-
58
- left_crop = cv2.resize(left_crop, (crop_size, crop_size), interpolation=cv2.INTER_AREA)
59
- right_crop = cv2.resize(right_crop, (crop_size, crop_size), interpolation=cv2.INTER_AREA)
60
-
61
- return left_crop, right_crop, left_bbox, right_bbox
62
-
63
-
64
- def crop_to_tensor(crop_bgr: np.ndarray):
65
- import torch
66
-
67
- rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0
68
- for c in range(3):
69
- rgb[:, :, c] = (rgb[:, :, c] - IMAGENET_MEAN[c]) / IMAGENET_STD[c]
70
- return torch.from_numpy(rgb.transpose(2, 0, 1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/eye_behaviour/eye_scorer.py DELETED
@@ -1,167 +0,0 @@
1
- # EAR + gaze from landmarks -> S_eye (no model)
2
-
3
- import math
4
-
5
- import numpy as np
6
-
7
- _LEFT_EYE_EAR = [33, 160, 158, 133, 153, 145]
8
- _RIGHT_EYE_EAR = [362, 385, 387, 263, 373, 380]
9
-
10
- _LEFT_IRIS_CENTER = 468
11
- _RIGHT_IRIS_CENTER = 473
12
-
13
- _LEFT_EYE_INNER = 133
14
- _LEFT_EYE_OUTER = 33
15
- _RIGHT_EYE_INNER = 362
16
- _RIGHT_EYE_OUTER = 263
17
-
18
- _LEFT_EYE_TOP = 159
19
- _LEFT_EYE_BOTTOM = 145
20
- _RIGHT_EYE_TOP = 386
21
- _RIGHT_EYE_BOTTOM = 374
22
-
23
- # Mouth (MAR) — inner lip landmarks
24
- _MOUTH_TOP = 13
25
- _MOUTH_BOTTOM = 14
26
- _MOUTH_LEFT = 78
27
- _MOUTH_RIGHT = 308
28
- _MOUTH_UPPER_1 = 82
29
- _MOUTH_UPPER_2 = 312
30
- _MOUTH_LOWER_1 = 87
31
- _MOUTH_LOWER_2 = 317
32
-
33
- MAR_YAWN_THRESHOLD = 0.55 # MAR above this = mouth open (e.g. yawning / sleepy)
34
-
35
-
36
- def _distance(p1: np.ndarray, p2: np.ndarray) -> float:
37
- return float(np.linalg.norm(p1 - p2))
38
-
39
-
40
- def compute_ear(landmarks: np.ndarray, eye_indices: list[int]) -> float:
41
- p1 = landmarks[eye_indices[0], :2]
42
- p2 = landmarks[eye_indices[1], :2]
43
- p3 = landmarks[eye_indices[2], :2]
44
- p4 = landmarks[eye_indices[3], :2]
45
- p5 = landmarks[eye_indices[4], :2]
46
- p6 = landmarks[eye_indices[5], :2]
47
-
48
- vertical1 = _distance(p2, p6)
49
- vertical2 = _distance(p3, p5)
50
- horizontal = _distance(p1, p4)
51
-
52
- if horizontal < 1e-6:
53
- return 0.0
54
-
55
- return (vertical1 + vertical2) / (2.0 * horizontal)
56
-
57
-
58
- def compute_avg_ear(landmarks: np.ndarray) -> float:
59
- left_ear = compute_ear(landmarks, _LEFT_EYE_EAR)
60
- right_ear = compute_ear(landmarks, _RIGHT_EYE_EAR)
61
- return (left_ear + right_ear) / 2.0
62
-
63
-
64
- def compute_gaze_ratio(landmarks: np.ndarray) -> tuple[float, float]:
65
- left_iris = landmarks[_LEFT_IRIS_CENTER, :2]
66
- left_inner = landmarks[_LEFT_EYE_INNER, :2]
67
- left_outer = landmarks[_LEFT_EYE_OUTER, :2]
68
- left_top = landmarks[_LEFT_EYE_TOP, :2]
69
- left_bottom = landmarks[_LEFT_EYE_BOTTOM, :2]
70
-
71
- right_iris = landmarks[_RIGHT_IRIS_CENTER, :2]
72
- right_inner = landmarks[_RIGHT_EYE_INNER, :2]
73
- right_outer = landmarks[_RIGHT_EYE_OUTER, :2]
74
- right_top = landmarks[_RIGHT_EYE_TOP, :2]
75
- right_bottom = landmarks[_RIGHT_EYE_BOTTOM, :2]
76
-
77
- left_h_total = _distance(left_inner, left_outer)
78
- right_h_total = _distance(right_inner, right_outer)
79
-
80
- if left_h_total < 1e-6 or right_h_total < 1e-6:
81
- return 0.5, 0.5
82
-
83
- left_h_ratio = _distance(left_outer, left_iris) / left_h_total
84
- right_h_ratio = _distance(right_outer, right_iris) / right_h_total
85
- h_ratio = (left_h_ratio + right_h_ratio) / 2.0
86
-
87
- left_v_total = _distance(left_top, left_bottom)
88
- right_v_total = _distance(right_top, right_bottom)
89
-
90
- if left_v_total < 1e-6 or right_v_total < 1e-6:
91
- return h_ratio, 0.5
92
-
93
- left_v_ratio = _distance(left_top, left_iris) / left_v_total
94
- right_v_ratio = _distance(right_top, right_iris) / right_v_total
95
- v_ratio = (left_v_ratio + right_v_ratio) / 2.0
96
-
97
- return float(np.clip(h_ratio, 0, 1)), float(np.clip(v_ratio, 0, 1))
98
-
99
-
100
- def compute_mar(landmarks: np.ndarray) -> float:
101
- # Mouth aspect ratio: high = mouth open (yawning / sleepy)
102
- top = landmarks[_MOUTH_TOP, :2]
103
- bottom = landmarks[_MOUTH_BOTTOM, :2]
104
- left = landmarks[_MOUTH_LEFT, :2]
105
- right = landmarks[_MOUTH_RIGHT, :2]
106
- upper1 = landmarks[_MOUTH_UPPER_1, :2]
107
- lower1 = landmarks[_MOUTH_LOWER_1, :2]
108
- upper2 = landmarks[_MOUTH_UPPER_2, :2]
109
- lower2 = landmarks[_MOUTH_LOWER_2, :2]
110
-
111
- horizontal = _distance(left, right)
112
- if horizontal < 1e-6:
113
- return 0.0
114
- v1 = _distance(upper1, lower1)
115
- v2 = _distance(top, bottom)
116
- v3 = _distance(upper2, lower2)
117
- return (v1 + v2 + v3) / (2.0 * horizontal)
118
-
119
-
120
- class EyeBehaviourScorer:
121
- def __init__(
122
- self,
123
- ear_open: float = 0.30,
124
- ear_closed: float = 0.16,
125
- gaze_max_offset: float = 0.28,
126
- ):
127
- self.ear_open = ear_open
128
- self.ear_closed = ear_closed
129
- self.gaze_max_offset = gaze_max_offset
130
-
131
- def _ear_score(self, ear: float) -> float:
132
- if ear >= self.ear_open:
133
- return 1.0
134
- if ear <= self.ear_closed:
135
- return 0.0
136
- return (ear - self.ear_closed) / (self.ear_open - self.ear_closed)
137
-
138
- def _gaze_score(self, h_ratio: float, v_ratio: float) -> float:
139
- h_offset = abs(h_ratio - 0.5)
140
- v_offset = abs(v_ratio - 0.5)
141
- offset = math.sqrt(h_offset**2 + v_offset**2)
142
- t = min(offset / self.gaze_max_offset, 1.0)
143
- return 0.5 * (1.0 + math.cos(math.pi * t))
144
-
145
- def score(self, landmarks: np.ndarray) -> float:
146
- ear = compute_avg_ear(landmarks)
147
- ear_s = self._ear_score(ear)
148
- if ear_s < 0.3:
149
- return ear_s
150
- h_ratio, v_ratio = compute_gaze_ratio(landmarks)
151
- gaze_s = self._gaze_score(h_ratio, v_ratio)
152
- return ear_s * gaze_s
153
-
154
- def detailed_score(self, landmarks: np.ndarray) -> dict:
155
- ear = compute_avg_ear(landmarks)
156
- ear_s = self._ear_score(ear)
157
- h_ratio, v_ratio = compute_gaze_ratio(landmarks)
158
- gaze_s = self._gaze_score(h_ratio, v_ratio)
159
- s_eye = ear_s if ear_s < 0.3 else ear_s * gaze_s
160
- return {
161
- "ear": round(ear, 4),
162
- "ear_score": round(ear_s, 4),
163
- "h_gaze": round(h_ratio, 4),
164
- "v_gaze": round(v_ratio, 4),
165
- "gaze_score": round(gaze_s, 4),
166
- "s_eye": round(s_eye, 4),
167
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/face_mesh/.gitkeep DELETED
File without changes
models/face_mesh/__init__.py DELETED
@@ -1 +0,0 @@
1
- # face mesh (stage 1)
 
 
models/face_mesh/face_mesh.py DELETED
@@ -1,95 +0,0 @@
1
- """MediaPipe FaceLandmarker — 478 landmarks (incl. iris)."""
2
-
3
- import os
4
- from pathlib import Path
5
- from urllib.request import urlretrieve
6
-
7
- import cv2
8
- import numpy as np
9
- import mediapipe as mp
10
- from mediapipe.tasks.python.vision import FaceLandmarkerOptions, FaceLandmarker, RunningMode
11
- from mediapipe.tasks import python as mp_tasks
12
-
13
- _MODEL_URL = (
14
- "https://storage.googleapis.com/mediapipe-models/face_landmarker/"
15
- "face_landmarker/float16/latest/face_landmarker.task"
16
- )
17
-
18
-
19
- def _ensure_model() -> str:
20
- cache_dir = Path(os.environ.get(
21
- "FOCUSGUARD_CACHE_DIR",
22
- Path.home() / ".cache" / "focusguard",
23
- ))
24
- model_path = cache_dir / "face_landmarker.task"
25
- if model_path.exists():
26
- return str(model_path)
27
- cache_dir.mkdir(parents=True, exist_ok=True)
28
- print(f"[FACE_MESH] Downloading model to {model_path}...")
29
- urlretrieve(_MODEL_URL, model_path)
30
- print("[FACE_MESH] Download complete.")
31
- return str(model_path)
32
-
33
-
34
- class FaceMeshDetector:
35
-
36
- # indices for eyes/iris (for downstream)
37
- LEFT_EYE_INDICES = [33, 7, 163, 144, 145, 153, 154, 155, 133, 173, 157, 158, 159, 160, 161, 246]
38
- RIGHT_EYE_INDICES = [362, 382, 381, 380, 374, 373, 390, 249, 263, 466, 388, 387, 386, 385, 384, 398]
39
- LEFT_IRIS_INDICES = [468, 469, 470, 471, 472]
40
- RIGHT_IRIS_INDICES = [473, 474, 475, 476, 477]
41
-
42
- def __init__(
43
- self,
44
- max_num_faces: int = 1,
45
- min_detection_confidence: float = 0.5,
46
- min_tracking_confidence: float = 0.5,
47
- ):
48
- model_path = _ensure_model()
49
- options = FaceLandmarkerOptions(
50
- base_options=mp_tasks.BaseOptions(model_asset_path=model_path),
51
- num_faces=max_num_faces,
52
- min_face_detection_confidence=min_detection_confidence,
53
- min_face_presence_confidence=min_detection_confidence,
54
- min_tracking_confidence=min_tracking_confidence,
55
- running_mode=RunningMode.VIDEO,
56
- )
57
- self._landmarker = FaceLandmarker.create_from_options(options)
58
- self._frame_ts = 0 # ms, for video API
59
-
60
- def process(self, bgr_frame: np.ndarray) -> np.ndarray | None:
61
- # BGR in -> (478,3) norm x,y,z or None
62
- rgb = cv2.cvtColor(bgr_frame, cv2.COLOR_BGR2RGB)
63
- mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
64
- self._frame_ts += 33 # ~30fps
65
- result = self._landmarker.detect_for_video(mp_image, self._frame_ts)
66
-
67
- if not result.face_landmarks:
68
- return None
69
-
70
- face = result.face_landmarks[0]
71
- return np.array([(lm.x, lm.y, lm.z) for lm in face], dtype=np.float32)
72
-
73
- def get_pixel_landmarks(self, landmarks: np.ndarray, frame_w: int, frame_h: int) -> np.ndarray:
74
- # norm -> pixel (x,y)
75
- pixel = np.zeros((landmarks.shape[0], 2), dtype=np.int32)
76
- pixel[:, 0] = (landmarks[:, 0] * frame_w).astype(np.int32)
77
- pixel[:, 1] = (landmarks[:, 1] * frame_h).astype(np.int32)
78
- return pixel
79
-
80
- def get_3d_landmarks(self, landmarks: np.ndarray, frame_w: int, frame_h: int) -> np.ndarray:
81
- # norm -> pixel-scale x,y,z (z scaled by width)
82
- pts = np.zeros_like(landmarks)
83
- pts[:, 0] = landmarks[:, 0] * frame_w
84
- pts[:, 1] = landmarks[:, 1] * frame_h
85
- pts[:, 2] = landmarks[:, 2] * frame_w
86
- return pts
87
-
88
- def close(self):
89
- self._landmarker.close()
90
-
91
- def __enter__(self):
92
- return self
93
-
94
- def __exit__(self, *args):
95
- self.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/face_orientation/__init__.py DELETED
File without changes
models/face_orientation/head_pose.py DELETED
@@ -1,114 +0,0 @@
1
- # Head pose from 6 Face Mesh landmarks (solvePnP) -> yaw/pitch/roll, S_face
2
-
3
- import math
4
-
5
- import cv2
6
- import numpy as np
7
-
8
- _LANDMARK_INDICES = [1, 152, 33, 263, 61, 291]
9
-
10
- _MODEL_POINTS = np.array(
11
- [
12
- [0.0, 0.0, 0.0],
13
- [0.0, -330.0, -65.0],
14
- [-225.0, 170.0, -135.0],
15
- [225.0, 170.0, -135.0],
16
- [-150.0, -150.0, -125.0],
17
- [150.0, -150.0, -125.0],
18
- ],
19
- dtype=np.float64,
20
- )
21
-
22
-
23
- class HeadPoseEstimator:
24
- def __init__(self, max_angle: float = 30.0, roll_weight: float = 0.5):
25
- self.max_angle = max_angle
26
- self.roll_weight = roll_weight
27
- self._camera_matrix = None
28
- self._frame_size = None
29
- self._dist_coeffs = np.zeros((4, 1), dtype=np.float64)
30
-
31
- def _get_camera_matrix(self, frame_w: int, frame_h: int) -> np.ndarray:
32
- if self._camera_matrix is not None and self._frame_size == (frame_w, frame_h):
33
- return self._camera_matrix
34
- focal_length = float(frame_w)
35
- cx, cy = frame_w / 2.0, frame_h / 2.0
36
- self._camera_matrix = np.array(
37
- [[focal_length, 0, cx], [0, focal_length, cy], [0, 0, 1]],
38
- dtype=np.float64,
39
- )
40
- self._frame_size = (frame_w, frame_h)
41
- return self._camera_matrix
42
-
43
- def _solve(self, landmarks: np.ndarray, frame_w: int, frame_h: int):
44
- image_points = np.array(
45
- [
46
- [landmarks[i, 0] * frame_w, landmarks[i, 1] * frame_h]
47
- for i in _LANDMARK_INDICES
48
- ],
49
- dtype=np.float64,
50
- )
51
- camera_matrix = self._get_camera_matrix(frame_w, frame_h)
52
- success, rvec, tvec = cv2.solvePnP(
53
- _MODEL_POINTS,
54
- image_points,
55
- camera_matrix,
56
- self._dist_coeffs,
57
- flags=cv2.SOLVEPNP_ITERATIVE,
58
- )
59
- return success, rvec, tvec, image_points
60
-
61
- def estimate(
62
- self, landmarks: np.ndarray, frame_w: int, frame_h: int
63
- ) -> tuple[float, float, float] | None:
64
- success, rvec, tvec, _ = self._solve(landmarks, frame_w, frame_h)
65
- if not success:
66
- return None
67
-
68
- rmat, _ = cv2.Rodrigues(rvec)
69
- nose_dir = rmat @ np.array([0.0, 0.0, 1.0])
70
- face_up = rmat @ np.array([0.0, 1.0, 0.0])
71
-
72
- yaw = math.degrees(math.atan2(nose_dir[0], -nose_dir[2]))
73
- pitch = math.degrees(math.asin(np.clip(-nose_dir[1], -1.0, 1.0)))
74
- roll = math.degrees(math.atan2(face_up[0], -face_up[1]))
75
-
76
- return (yaw, pitch, roll)
77
-
78
- def score(self, landmarks: np.ndarray, frame_w: int, frame_h: int) -> float:
79
- angles = self.estimate(landmarks, frame_w, frame_h)
80
- if angles is None:
81
- return 0.0
82
-
83
- yaw, pitch, roll = angles
84
- deviation = math.sqrt(yaw**2 + pitch**2 + (self.roll_weight * roll) ** 2)
85
- t = min(deviation / self.max_angle, 1.0)
86
- return 0.5 * (1.0 + math.cos(math.pi * t))
87
-
88
- def draw_axes(
89
- self,
90
- frame: np.ndarray,
91
- landmarks: np.ndarray,
92
- axis_length: float = 50.0,
93
- ) -> np.ndarray:
94
- h, w = frame.shape[:2]
95
- success, rvec, tvec, image_points = self._solve(landmarks, w, h)
96
- if not success:
97
- return frame
98
-
99
- camera_matrix = self._get_camera_matrix(w, h)
100
- nose = tuple(image_points[0].astype(int))
101
-
102
- axes_3d = np.float64(
103
- [[axis_length, 0, 0], [0, axis_length, 0], [0, 0, axis_length]]
104
- )
105
- projected, _ = cv2.projectPoints(
106
- axes_3d, rvec, tvec, camera_matrix, self._dist_coeffs
107
- )
108
-
109
- colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0)]
110
- for i, color in enumerate(colors):
111
- pt = tuple(projected[i].ravel().astype(int))
112
- cv2.line(frame, nose, pt, color, 2)
113
-
114
- return frame
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/train.py DELETED
@@ -1,186 +0,0 @@
1
- # Run from repo root: python -m models.train (or cd models && python train.py)
2
-
3
- import json
4
- import os
5
- import random
6
-
7
- import numpy as np as np
8
- import torch
9
- import torch.nn as nn
10
- import torch.optim as optim
11
-
12
- from prepare_dataset import get_dataloaders
13
-
14
- CFG = {
15
- "model_name": "face_orientation", # "face_orientation" or "eye_behaviour"
16
- "epochs": 30,
17
- "batch_size": 32,
18
- "lr": 1e-3,
19
- "seed": 42,
20
- "split_ratios": (0.7, 0.15, 0.15),
21
- "checkpoints_dir": {
22
- "face_orientation": os.path.join(os.path.dirname(__file__), "face_orientation_model"),
23
- "eye_behaviour": os.path.join(os.path.dirname(__file__), "eye_behaviour_model"),
24
- },
25
- "logs_dir": os.path.join(os.path.dirname(__file__), "..", "evaluation", "logs"),
26
- }
27
-
28
-
29
- def set_seed(seed: int):
30
- random.seed(seed)
31
- np.random.seed(seed)
32
- torch.manual_seed(seed)
33
- if torch.cuda.is_available():
34
- torch.cuda.manual_seed_all(seed)
35
-
36
-
37
- class BaseModel(nn.Module):
38
- def __init__(self, num_features: int, num_classes: int):
39
- super().__init__()
40
- self.network = nn.Sequential(
41
- nn.Linear(num_features, 64),
42
- nn.ReLU(),
43
- nn.Linear(64, 32),
44
- nn.ReLU(),
45
- nn.Linear(32, num_classes),
46
- )
47
-
48
- def forward(self, x):
49
- return self.network(x)
50
-
51
- def training_step(self, loader, optimizer, criterion, device):
52
- self.train()
53
- total_loss = 0.0
54
- correct = 0
55
- total = 0
56
-
57
- for features, labels in loader:
58
- features, labels = features.to(device), labels.to(device)
59
-
60
- optimizer.zero_grad()
61
- outputs = self(features)
62
- loss = criterion(outputs, labels)
63
- loss.backward()
64
- optimizer.step()
65
-
66
- total_loss += loss.item() * features.size(0)
67
- correct += (outputs.argmax(dim=1) == labels).sum().item()
68
- total += features.size(0)
69
-
70
- return total_loss / total, correct / total
71
-
72
- @torch.no_grad()
73
- def validation_step(self, loader, criterion, device):
74
- self.eval()
75
- total_loss = 0.0
76
- correct = 0
77
- total = 0
78
-
79
- for features, labels in loader:
80
- features, labels = features.to(device), labels.to(device)
81
- outputs = self(features)
82
- loss = criterion(outputs, labels)
83
-
84
- total_loss += loss.item() * features.size(0)
85
- correct += (outputs.argmax(dim=1) == labels).sum().item()
86
- total += features.size(0)
87
-
88
- return total_loss / total, correct / total
89
-
90
- @torch.no_grad()
91
- def test_step(self, loader, criterion, device):
92
- self.eval()
93
- total_loss = 0.0
94
- correct = 0
95
- total = 0
96
-
97
- for features, labels in loader:
98
- features, labels = features.to(device), labels.to(device)
99
- outputs = self(features)
100
- loss = criterion(outputs, labels)
101
-
102
- total_loss += loss.item() * features.size(0)
103
- correct += (outputs.argmax(dim=1) == labels).sum().item()
104
- total += features.size(0)
105
-
106
- return total_loss / total, correct / total
107
-
108
-
109
- def main():
110
- set_seed(CFG["seed"])
111
-
112
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
113
- print(f"[TRAIN] Device: {device}")
114
- print(f"[TRAIN] Model: {CFG['model_name']}")
115
-
116
- train_loader, val_loader, test_loader, num_features, num_classes = get_dataloaders(
117
- model_name=CFG["model_name"],
118
- batch_size=CFG["batch_size"],
119
- split_ratios=CFG["split_ratios"],
120
- seed=CFG["seed"],
121
- )
122
-
123
- model = BaseModel(num_features, num_classes).to(device)
124
- criterion = nn.CrossEntropyLoss()
125
- optimizer = optim.Adam(model.parameters(), lr=CFG["lr"])
126
-
127
- print(f"[TRAIN] Parameters: {sum(p.numel() for p in model.parameters()):,}")
128
-
129
- ckpt_dir = CFG["checkpoints_dir"][CFG["model_name"]]
130
- os.makedirs(ckpt_dir, exist_ok=True)
131
- best_ckpt_path = os.path.join(ckpt_dir, "best_model.pt")
132
-
133
- history = {
134
- "model_name": CFG["model_name"],
135
- "epochs": [],
136
- "train_loss": [],
137
- "train_acc": [],
138
- "val_loss": [],
139
- "val_acc": [],
140
- }
141
-
142
- best_val_acc = 0.0
143
-
144
- print(f"\n{'Epoch':>6} | {'Train Loss':>10} | {'Train Acc':>9} | {'Val Loss':>10} | {'Val Acc':>9}")
145
- print("-" * 60)
146
-
147
- for epoch in range(1, CFG["epochs"] + 1):
148
- train_loss, train_acc = model.training_step(train_loader, optimizer, criterion, device)
149
- val_loss, val_acc = model.validation_step(val_loader, criterion, device)
150
-
151
- history["epochs"].append(epoch)
152
- history["train_loss"].append(round(train_loss, 4))
153
- history["train_acc"].append(round(train_acc, 4))
154
- history["val_loss"].append(round(val_loss, 4))
155
- history["val_acc"].append(round(val_acc, 4))
156
-
157
- marker = ""
158
- if val_acc > best_val_acc:
159
- best_val_acc = val_acc
160
- torch.save(model.state_dict(), best_ckpt_path)
161
- marker = " *"
162
-
163
- print(f"{epoch:>6} | {train_loss:>10.4f} | {train_acc:>8.2%} | {val_loss:>10.4f} | {val_acc:>8.2%}{marker}")
164
-
165
- print(f"\nBest validation accuracy: {best_val_acc:.2%}")
166
- print(f"Checkpoint saved to: {best_ckpt_path}")
167
-
168
- model.load_state_dict(torch.load(best_ckpt_path, weights_only=True))
169
- test_loss, test_acc = model.test_step(test_loader, criterion, device)
170
- print(f"\n[TEST] Loss: {test_loss:.4f} | Accuracy: {test_acc:.2%}")
171
-
172
- history["test_loss"] = round(test_loss, 4)
173
- history["test_acc"] = round(test_acc, 4)
174
-
175
- logs_dir = CFG["logs_dir"]
176
- os.makedirs(logs_dir, exist_ok=True)
177
- log_path = os.path.join(logs_dir, f"{CFG['model_name']}_training_log.json")
178
-
179
- with open(log_path, "w") as f:
180
- json.dump(history, f, indent=2)
181
-
182
- print(f"[LOG] Training history saved to: {log_path}")
183
-
184
-
185
- if __name__ == "__main__":
186
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/train_eye_cnn.py DELETED
@@ -1 +0,0 @@
1
- # stub