Codex commited on
Commit
1a13652
·
1 Parent(s): a8c9a42

Add visual step-by-step DynaFall notebook

Browse files
Files changed (1) hide show
  1. notebooks/dynafall_step_by_step.ipynb +526 -0
notebooks/dynafall_step_by_step.ipynb ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "5b77cca7",
6
+ "metadata": {},
7
+ "source": [
8
+ "# DynaFall - notebook trực quan bằng data thật URFD/MCFD\n",
9
+ "\n",
10
+ "Notebook này được tổ chức như một bài học thực hành. Mỗi bước đều có phần quan sát trực quan: xem data gốc, xem khung xương trên ảnh/video, xem chuyển động skeleton, xem feature dynamics, rồi mới train/evaluate model.\n",
11
+ "\n",
12
+ "**Không dùng data tự tạo.** Tất cả mẫu trong notebook lấy từ `data/raw/URFD`, `data/raw/MCFD`, `data/poses/*_keypoints.pkl`, và `data/processed/*` đã tải từ Hugging Face."
13
+ ]
14
+ },
15
+ {
16
+ "cell_type": "markdown",
17
+ "id": "e45c5067",
18
+ "metadata": {},
19
+ "source": [
20
+ "## 1. Cài thư viện và chuẩn bị môi trường"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "cd135b78",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "from pathlib import Path\n",
31
+ "import os, sys, json, subprocess, pickle\n",
32
+ "\n",
33
+ "def find_repo_root():\n",
34
+ " candidates = [Path.cwd(), *Path.cwd().parents, Path('/root/fall')]\n",
35
+ " for candidate in candidates:\n",
36
+ " if (candidate / 'requirements.txt').exists() and (candidate / 'src' / 'dynafall').exists():\n",
37
+ " return candidate.resolve()\n",
38
+ " raise RuntimeError('Không tìm thấy repo root chứa requirements.txt và src/dynafall')\n",
39
+ "\n",
40
+ "ROOT = find_repo_root()\n",
41
+ "print('Repo root =', ROOT)\n",
42
+ "subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-q', '-r', str(ROOT / 'requirements.txt'), 'matplotlib', 'gradio', 'opencv-python-headless', 'ipywidgets'])\n",
43
+ "\n",
44
+ "os.chdir(ROOT)\n",
45
+ "sys.path.insert(0, str(ROOT / 'src'))\n",
46
+ "sys.path.insert(0, str(ROOT / 'scripts'))\n",
47
+ "\n",
48
+ "import cv2\n",
49
+ "import numpy as np\n",
50
+ "import pandas as pd\n",
51
+ "import matplotlib.pyplot as plt\n",
52
+ "from IPython.display import Video, display\n",
53
+ "\n",
54
+ "from common import load_config\n",
55
+ "from dynafall.data import load_pickle, FallClipDataset, save_pickle\n",
56
+ "from dynafall.features import COCO_BONES, body_aspect_ratio, bone_features, dynamics_features, normalize_pose, resample_or_pad\n",
57
+ "\n",
58
+ "cfg = load_config('configs/default.yaml')\n",
59
+ "print('ROOT =', ROOT)\n",
60
+ "print('clip_len =', cfg['clip_len'], '| stride =', cfg['stride'])"
61
+ ]
62
+ },
63
+ {
64
+ "cell_type": "markdown",
65
+ "id": "efae7ac8",
66
+ "metadata": {},
67
+ "source": [
68
+ "## 2. Kiểm tra data thật đã có\n",
69
+ "\n",
70
+ "Ta kiểm tra 3 tầng dữ liệu:\n",
71
+ "\n",
72
+ "1. `data/raw`: ảnh/video gốc.\n",
73
+ "2. `data/poses`: keypoints COCO-17 đã trích bằng YOLO pose.\n",
74
+ "3. `data/processed`: clip 32 frame đã normalize để đưa vào model."
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "execution_count": null,
80
+ "id": "89422656",
81
+ "metadata": {},
82
+ "outputs": [],
83
+ "source": [
84
+ "summary = []\n",
85
+ "for dataset in ['URFD', 'MCFD']:\n",
86
+ " recs = load_pickle(f'data/poses/{dataset}_keypoints.pkl')\n",
87
+ " row = {\n",
88
+ " 'dataset': dataset,\n",
89
+ " 'video_records': len(recs),\n",
90
+ " 'fall_records': sum(int(r['label']) == 1 for r in recs),\n",
91
+ " 'nonfall_records': sum(int(r['label']) == 0 for r in recs),\n",
92
+ " }\n",
93
+ " for split in ['train', 'val', 'test']:\n",
94
+ " rows = load_pickle(f'data/processed/{dataset}/{split}.pkl')\n",
95
+ " row[f'{split}_clips'] = len(rows)\n",
96
+ " summary.append(row)\n",
97
+ "\n",
98
+ "pd.DataFrame(summary)"
99
+ ]
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "execution_count": null,
104
+ "id": "aaa58a76",
105
+ "metadata": {},
106
+ "outputs": [],
107
+ "source": [
108
+ "for dataset in ['URFD', 'MCFD']:\n",
109
+ " recs = load_pickle(f'data/poses/{dataset}_keypoints.pkl')\n",
110
+ " print('\\n', dataset)\n",
111
+ " for rec in recs[:3]:\n",
112
+ " print(' ', rec['video_id'], '| label=', 'fall' if rec['label'] else 'nonfall', '| keypoints=', rec['keypoints'].shape, '| source=', rec['path'])"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "markdown",
117
+ "id": "286f0e9a",
118
+ "metadata": {},
119
+ "source": [
120
+ "## 3. Xem một số video/sequence gốc trong data\n",
121
+ "\n",
122
+ "Cell dưới tạo 4 video preview ngắn từ raw data thật:\n",
123
+ "\n",
124
+ "- 2 mẫu URFD fall\n",
125
+ "- 1 mẫu MCFD fall\n",
126
+ "- 1 mẫu URFD ADL non-fall rõ ràng\n",
127
+ "\n",
128
+ "Mỗi video có file `.npz` đi kèm chứa keypoints thật tương ứng."
129
+ ]
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "execution_count": null,
134
+ "id": "c8d7d24e",
135
+ "metadata": {},
136
+ "outputs": [],
137
+ "source": [
138
+ "def run(cmd):\n",
139
+ " print('$', ' '.join(cmd))\n",
140
+ " subprocess.run(cmd, check=True)\n",
141
+ "\n",
142
+ "run([sys.executable, 'scripts/create_real_demo_assets.py'])\n",
143
+ "preview_videos = sorted(Path('demo_assets_real').glob('*.mp4'))\n",
144
+ "for p in preview_videos:\n",
145
+ " meta = np.load(p.with_suffix('.npz'))\n",
146
+ " print(p.name, '| dataset=', str(meta['dataset']), '| label=', 'fall' if int(meta['label']) else 'nonfall')"
147
+ ]
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "execution_count": null,
152
+ "id": "15347920",
153
+ "metadata": {},
154
+ "outputs": [],
155
+ "source": [
156
+ "for p in preview_videos:\n",
157
+ " print('\\nRAW PREVIEW:', p.name)\n",
158
+ " display(Video(str(p), embed=True, width=460))"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "id": "0d0622d0",
164
+ "metadata": {},
165
+ "source": [
166
+ "## 4. Từ ảnh/video gốc sang khung xương\n",
167
+ "\n",
168
+ "Ở bước này ta đặt keypoints lên frame gốc để thấy rõ YOLO pose đã lấy những điểm nào trên người. Đây là cầu nối quan trọng giữa dữ liệu ảnh/video và dữ liệu skeleton mà model sử dụng."
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "execution_count": null,
174
+ "id": "09975748",
175
+ "metadata": {},
176
+ "outputs": [],
177
+ "source": [
178
+ "IMAGE_EXTS = {'.png', '.jpg', '.jpeg', '.bmp'}\n",
179
+ "\n",
180
+ "def load_raw_frame(source, frame_idx=0):\n",
181
+ " source = Path(source)\n",
182
+ " if source.is_dir():\n",
183
+ " images = sorted([p for p in source.iterdir() if p.suffix.lower() in IMAGE_EXTS])\n",
184
+ " frame_idx = min(frame_idx, len(images) - 1)\n",
185
+ " img = cv2.imread(str(images[frame_idx]))\n",
186
+ " return cv2.cvtColor(img, cv2.COLOR_BGR2RGB), frame_idx\n",
187
+ " cap = cv2.VideoCapture(str(source))\n",
188
+ " cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)\n",
189
+ " ok, frame = cap.read()\n",
190
+ " cap.release()\n",
191
+ " if not ok:\n",
192
+ " raise RuntimeError(f'Cannot read frame {frame_idx} from {source}')\n",
193
+ " return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), frame_idx\n",
194
+ "\n",
195
+ "def draw_pose_on_image(image, keypoints):\n",
196
+ " out = image.copy()\n",
197
+ " pts = keypoints[:, :2].astype(int)\n",
198
+ " conf = keypoints[:, 2]\n",
199
+ " for a, b in COCO_BONES:\n",
200
+ " if conf[a] > 0 and conf[b] > 0:\n",
201
+ " cv2.line(out, tuple(pts[a]), tuple(pts[b]), (255, 120, 20), 3, cv2.LINE_AA)\n",
202
+ " for j, p in enumerate(pts):\n",
203
+ " if conf[j] > 0:\n",
204
+ " cv2.circle(out, tuple(p), 5, (20, 20, 255), -1, cv2.LINE_AA)\n",
205
+ " return out\n",
206
+ "\n",
207
+ "def select_records_for_display():\n",
208
+ " wanted = [\n",
209
+ " ('URFD', 'fall/fall-01-cam0-rgb/fall-01-cam0-rgb'),\n",
210
+ " ('URFD', 'nonfall/adl-01-cam0-rgb/adl-01-cam0-rgb'),\n",
211
+ " ('MCFD', 'fall/chute01/chute01/cam1'),\n",
212
+ " ]\n",
213
+ " out = []\n",
214
+ " for dataset, video_id in wanted:\n",
215
+ " recs = load_pickle(f'data/poses/{dataset}_keypoints.pkl')\n",
216
+ " out.append(next(r for r in recs if r['video_id'] == video_id))\n",
217
+ " return out\n",
218
+ "\n",
219
+ "records_to_show = select_records_for_display()\n",
220
+ "fig, axes = plt.subplots(len(records_to_show), 2, figsize=(12, 12))\n",
221
+ "for row, rec in enumerate(records_to_show):\n",
222
+ " kpts = rec['keypoints']\n",
223
+ " frame_idx = min(len(kpts) // 2, len(kpts) - 1)\n",
224
+ " img, actual_idx = load_raw_frame(rec['path'], frame_idx)\n",
225
+ " overlay = draw_pose_on_image(img, kpts[actual_idx])\n",
226
+ " label = 'fall' if rec['label'] else 'nonfall'\n",
227
+ " axes[row, 0].imshow(img)\n",
228
+ " axes[row, 0].set_title(f\"{rec['video_id']} | raw | {label}\")\n",
229
+ " axes[row, 1].imshow(overlay)\n",
230
+ " axes[row, 1].set_title('raw + skeleton keypoints')\n",
231
+ " for ax in axes[row]:\n",
232
+ " ax.axis('off')\n",
233
+ "plt.tight_layout()"
234
+ ]
235
+ },
236
+ {
237
+ "cell_type": "markdown",
238
+ "id": "16f9eb71",
239
+ "metadata": {},
240
+ "source": [
241
+ "## 5. Chuyển động khung xương theo thời gian\n",
242
+ "\n",
243
+ "Sau khi trích keypoints, mỗi video trở thành chuỗi `(T, 17, 3)`:\n",
244
+ "\n",
245
+ "- `T`: số frame\n",
246
+ "- `17`: số keypoints COCO\n",
247
+ "- `3`: `(x, y, confidence)`\n",
248
+ "\n",
249
+ "Cell dưới render lại chuyển động skeleton để học sinh thấy model thực sự nhìn chuỗi khung xương chứ không nhìn trực tiếp ảnh RGB."
250
+ ]
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "execution_count": null,
255
+ "id": "7c66fb78",
256
+ "metadata": {},
257
+ "outputs": [],
258
+ "source": [
259
+ "def skeleton_points(frame, width=420, height=420):\n",
260
+ " xy = frame[:, :2].copy()\n",
261
+ " x = (xy[:, 0] + 1.8) / 3.6 * width\n",
262
+ " y = (xy[:, 1] + 1.8) / 3.6 * height\n",
263
+ " pts = np.stack([x, y], axis=1)\n",
264
+ " return np.clip(pts, 0, [width - 1, height - 1]).astype(np.int32)\n",
265
+ "\n",
266
+ "def render_skeleton_preview(keypoints, out_path, fps=15, width=420, height=420):\n",
267
+ " out_path = Path(out_path)\n",
268
+ " writer = cv2.VideoWriter(str(out_path), cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))\n",
269
+ " for idx, frame in enumerate(keypoints):\n",
270
+ " canvas = np.full((height, width, 3), 248, dtype=np.uint8)\n",
271
+ " pts = skeleton_points(frame, width, height)\n",
272
+ " cv2.putText(canvas, f'frame {idx+1}/{len(keypoints)}', (14, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (60,60,60), 2, cv2.LINE_AA)\n",
273
+ " for a, b in COCO_BONES:\n",
274
+ " if frame[a, 2] > 0 and frame[b, 2] > 0:\n",
275
+ " cv2.line(canvas, tuple(pts[a]), tuple(pts[b]), (36, 115, 220), 3, cv2.LINE_AA)\n",
276
+ " for j, point in enumerate(pts):\n",
277
+ " if frame[j, 2] > 0:\n",
278
+ " cv2.circle(canvas, tuple(point), 5, (20,20,20), -1, cv2.LINE_AA)\n",
279
+ " writer.write(canvas)\n",
280
+ " writer.release()\n",
281
+ " return out_path\n",
282
+ "\n",
283
+ "skeleton_dir = Path('demo_assets_real/skeleton_previews')\n",
284
+ "skeleton_dir.mkdir(exist_ok=True)\n",
285
+ "for video_path in preview_videos:\n",
286
+ " data = np.load(video_path.with_suffix('.npz'))\n",
287
+ " keypoints = data['keypoints'].astype(np.float32)\n",
288
+ " out_path = skeleton_dir / f'{video_path.stem}_skeleton.mp4'\n",
289
+ " render_skeleton_preview(keypoints, out_path)\n",
290
+ " print('\\nSKELETON MOTION:', video_path.name)\n",
291
+ " display(Video(str(out_path), embed=True, width=420))"
292
+ ]
293
+ },
294
+ {
295
+ "cell_type": "markdown",
296
+ "id": "30389b06",
297
+ "metadata": {},
298
+ "source": [
299
+ "## 6. Chuẩn hóa pose và cắt clip 32 frame\n",
300
+ "\n",
301
+ "Model không dùng tọa độ pixel gốc trực tiếp. Pipeline chuẩn hóa pose theo bounding box người trong từng frame, sau đó resample/pad thành clip 32 frame. Nhờ vậy model ít phụ thuộc vào kích thước ảnh, vị trí camera, hoặc người đứng xa/gần."
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "code",
306
+ "execution_count": null,
307
+ "id": "7ce210d1",
308
+ "metadata": {},
309
+ "outputs": [],
310
+ "source": [
311
+ "raw_rec = records_to_show[0]\n",
312
+ "raw_kpts = raw_rec['keypoints'].astype(np.float32)\n",
313
+ "norm_kpts = normalize_pose(raw_kpts)\n",
314
+ "clip = resample_or_pad(norm_kpts, cfg['clip_len'])\n",
315
+ "\n",
316
+ "print('Raw keypoints:', raw_kpts.shape, 'range x/y:', raw_kpts[..., :2].min(), raw_kpts[..., :2].max())\n",
317
+ "print('Normalized keypoints:', norm_kpts.shape, 'range x/y:', round(float(norm_kpts[..., :2].min()), 3), round(float(norm_kpts[..., :2].max()), 3))\n",
318
+ "print('Model clip:', clip.shape)\n",
319
+ "\n",
320
+ "fig, axes = plt.subplots(1, 2, figsize=(10, 4))\n",
321
+ "axes[0].scatter(raw_kpts[0,:,0], raw_kpts[0,:,1], c=raw_kpts[0,:,2], cmap='viridis')\n",
322
+ "axes[0].invert_yaxis(); axes[0].set_title('Frame 0: pixel coordinates'); axes[0].grid(alpha=.25)\n",
323
+ "axes[1].scatter(norm_kpts[0,:,0], norm_kpts[0,:,1], c=norm_kpts[0,:,2], cmap='viridis')\n",
324
+ "axes[1].invert_yaxis(); axes[1].set_title('Frame 0: normalized coordinates'); axes[1].grid(alpha=.25)\n",
325
+ "plt.tight_layout()"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "markdown",
330
+ "id": "358af3d7",
331
+ "metadata": {},
332
+ "source": [
333
+ "## 7. Joint, bone và dynamics features\n",
334
+ "\n",
335
+ "DynaFall không chỉ nhìn tọa độ khớp (`joint`). Pipeline còn tạo:\n",
336
+ "\n",
337
+ "- `bone`: vector giữa các khớp nối theo COCO skeleton\n",
338
+ "- `dynamics`: vận tốc, gia tốc, center motion, hip drop, torso angle, body aspect ratio\n",
339
+ "\n",
340
+ "Các tín hiệu động học này giúp phân biệt chuyển động ngã với hoạt động bình thường."
341
+ ]
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "execution_count": null,
346
+ "id": "09eb9bb6",
347
+ "metadata": {},
348
+ "outputs": [],
349
+ "source": [
350
+ "joint = clip\n",
351
+ "bone = bone_features(joint)\n",
352
+ "dyn = dynamics_features(joint)\n",
353
+ "print('joint:', joint.shape, '| bone:', bone.shape, '| dyn:', dyn.shape)\n",
354
+ "\n",
355
+ "xy = joint[..., :2]\n",
356
+ "conf = joint[..., 2:3]\n",
357
+ "center_y = (xy[..., 1:2] * conf).sum(axis=1).squeeze(-1) / (conf.sum(axis=1).squeeze(-1) + 1e-6)\n",
358
+ "hip_y = xy[:, [11, 12], 1].mean(axis=1)\n",
359
+ "aspect = body_aspect_ratio(xy, conf).squeeze(1)\n",
360
+ "speed = np.linalg.norm(dyn[:, :, :2], axis=2).mean(axis=1)\n",
361
+ "\n",
362
+ "fig, axes = plt.subplots(2, 2, figsize=(12, 7))\n",
363
+ "axes[0,0].plot(center_y, label='body center y'); axes[0,0].plot(hip_y, label='hip y'); axes[0,0].legend(); axes[0,0].set_title('Vertical motion')\n",
364
+ "axes[0,1].plot(aspect, color='tab:purple'); axes[0,1].set_title('Body aspect ratio')\n",
365
+ "axes[1,0].plot(speed, color='tab:orange'); axes[1,0].set_title('Mean keypoint speed')\n",
366
+ "axes[1,1].imshow(joint[...,2].T, aspect='auto', cmap='viridis', vmin=0, vmax=1); axes[1,1].set_title('Keypoint confidence heatmap')\n",
367
+ "for ax in axes.ravel(): ax.grid(alpha=.25)\n",
368
+ "plt.tight_layout()"
369
+ ]
370
+ },
371
+ {
372
+ "cell_type": "markdown",
373
+ "id": "2d58ea54",
374
+ "metadata": {},
375
+ "source": [
376
+ "## 8. Xem batch đầu vào model\n",
377
+ "\n",
378
+ "DataLoader trả về dictionary có `joint`, `bone`, `dyn`, `label`. Đây là đúng format mà các model trong `src/dynafall/models.py` nhận vào."
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "execution_count": null,
384
+ "id": "117769ea",
385
+ "metadata": {},
386
+ "outputs": [],
387
+ "source": [
388
+ "train_ds = FallClipDataset('data/processed/URFD/train.pkl')\n",
389
+ "item = train_ds[0]\n",
390
+ "for key, value in item.items():\n",
391
+ " if hasattr(value, 'shape'):\n",
392
+ " print(key, tuple(value.shape))\n",
393
+ " else:\n",
394
+ " print(key, value)\n"
395
+ ]
396
+ },
397
+ {
398
+ "cell_type": "markdown",
399
+ "id": "53d0db4c",
400
+ "metadata": {},
401
+ "source": [
402
+ "## 9. Train nhanh trên URFD thật\n",
403
+ "\n",
404
+ "Để notebook chạy nhanh, cell này train 4 epoch. Khi làm thí nghiệm đầy đủ, tăng epoch hoặc chạy `scripts/run_experiments.py`."
405
+ ]
406
+ },
407
+ {
408
+ "cell_type": "code",
409
+ "execution_count": null,
410
+ "id": "851945ee",
411
+ "metadata": {},
412
+ "outputs": [],
413
+ "source": [
414
+ "run([sys.executable, 'scripts/train.py', '--dataset', 'URFD', '--method', 'dynafall', '--epochs', '4'])\n",
415
+ "run([sys.executable, 'scripts/evaluate.py', '--dataset', 'URFD', '--method', 'dynafall'])"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "markdown",
420
+ "id": "66c5024e",
421
+ "metadata": {},
422
+ "source": [
423
+ "## 10. Trực quan hóa training history và metric"
424
+ ]
425
+ },
426
+ {
427
+ "cell_type": "code",
428
+ "execution_count": null,
429
+ "id": "422fd8d2",
430
+ "metadata": {},
431
+ "outputs": [],
432
+ "source": [
433
+ "history = pd.read_json('results/URFD/dynafall/history.json')\n",
434
+ "metrics = json.loads(Path('results/URFD/dynafall/metrics_test_clean.json').read_text())\n",
435
+ "display(history)\n",
436
+ "display(pd.DataFrame([metrics]))\n",
437
+ "\n",
438
+ "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n",
439
+ "axes[0].plot(history['epoch'], history['loss'], marker='o'); axes[0].set_title('Train loss'); axes[0].grid(alpha=.25)\n",
440
+ "for col in ['val_accuracy', 'val_f1', 'val_recall', 'val_precision']:\n",
441
+ " if col in history:\n",
442
+ " axes[1].plot(history['epoch'], history[col], marker='o', label=col)\n",
443
+ "axes[1].legend(); axes[1].set_ylim(0, 1.05); axes[1].set_title('Validation metrics'); axes[1].grid(alpha=.25)\n",
444
+ "plt.tight_layout()\n",
445
+ "\n",
446
+ "metric_names = ['accuracy', 'precision', 'recall', 'specificity', 'f1', 'macro_f1']\n",
447
+ "plt.figure(figsize=(8, 4))\n",
448
+ "plt.bar(metric_names, [metrics[m] for m in metric_names])\n",
449
+ "plt.ylim(0, 1.05); plt.title('Test metrics'); plt.grid(axis='y', alpha=.25); plt.xticks(rotation=30); plt.tight_layout()"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "markdown",
454
+ "id": "fc0302e8",
455
+ "metadata": {},
456
+ "source": [
457
+ "## 11. Dùng checkpoint đã train sẵn để demo\n",
458
+ "\n",
459
+ "Repo có checkpoint benchmark đã train sẵn. App demo tự chọn checkpoint theo dataset của mẫu:\n",
460
+ "\n",
461
+ "- URFD sample -> `results/main/seed_7/URFD/dynafall/best.pt`\n",
462
+ "- MCFD sample -> `results/main/seed_7/MCFD/dynafall/best.pt`"
463
+ ]
464
+ },
465
+ {
466
+ "cell_type": "code",
467
+ "execution_count": null,
468
+ "id": "3c6571e0",
469
+ "metadata": {},
470
+ "outputs": [],
471
+ "source": [
472
+ "from app_demo import predict, DEFAULT_CHECKPOINT\n",
473
+ "\n",
474
+ "rows = []\n",
475
+ "for p in preview_videos:\n",
476
+ " summary, skeleton_video, fig, details_json = predict(str(p), str(DEFAULT_CHECKPOINT), 'dynafall')\n",
477
+ " details = json.loads(details_json)\n",
478
+ " rows.append(details)\n",
479
+ "pd.DataFrame(rows)"
480
+ ]
481
+ },
482
+ {
483
+ "cell_type": "markdown",
484
+ "id": "0035275e",
485
+ "metadata": {},
486
+ "source": [
487
+ "## 12. Mở giao diện demo Gradio\n",
488
+ "\n",
489
+ "Giao diện cho phép chọn video có sẵn hoặc upload video mới. Với video mới, app sẽ tự chạy YOLO pose để trích keypoints rồi dự đoán."
490
+ ]
491
+ },
492
+ {
493
+ "cell_type": "code",
494
+ "execution_count": null,
495
+ "id": "cb6d110b",
496
+ "metadata": {},
497
+ "outputs": [],
498
+ "source": [
499
+ "from app_demo import build_app\n",
500
+ "app = build_app()\n",
501
+ "app.launch(server_name='127.0.0.1', server_port=7860, inline=False)"
502
+ ]
503
+ }
504
+ ],
505
+ "metadata": {
506
+ "kernelspec": {
507
+ "display_name": "Python3 (ipykernel)",
508
+ "language": "python",
509
+ "name": "python3"
510
+ },
511
+ "language_info": {
512
+ "codemirror_mode": {
513
+ "name": "ipython",
514
+ "version": 3
515
+ },
516
+ "file_extension": ".py",
517
+ "mimetype": "text/x-python",
518
+ "name": "python",
519
+ "nbconvert_exporter": "python",
520
+ "pygments_lexer": "ipython3",
521
+ "version": "3.12.13"
522
+ }
523
+ },
524
+ "nbformat": 4,
525
+ "nbformat_minor": 5
526
+ }