File size: 28,162 Bytes
cacaeb4
 
5b423bf
cacaeb4
 
5b423bf
cacaeb4
5b423bf
 
 
 
 
cacaeb4
5b423bf
 
cacaeb4
 
5b423bf
cacaeb4
 
d0405eb
cacaeb4
b95781b
cacaeb4
 
3008fd1
cacaeb4
 
 
 
 
 
 
 
 
 
7ea83d4
3008fd1
cacaeb4
8133f1d
cacaeb4
 
 
 
 
 
 
 
 
d0405eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ea83d4
 
 
 
 
 
 
5b423bf
7ea83d4
 
 
 
 
 
 
5b423bf
7ea83d4
169758c
 
 
5b423bf
169758c
7ea83d4
169758c
 
5b423bf
169758c
 
5b423bf
169758c
 
5b423bf
7ea83d4
 
 
 
cacaeb4
5b423bf
cacaeb4
5b423bf
 
 
 
 
 
 
 
8133f1d
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
8133f1d
5b423bf
 
 
 
 
 
 
cacaeb4
 
5b423bf
 
 
 
 
 
cacaeb4
5b423bf
 
 
 
 
 
a5a9b7d
 
 
 
 
5b423bf
cacaeb4
5b423bf
 
 
 
 
 
 
 
cacaeb4
 
 
5b423bf
cacaeb4
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cacaeb4
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3008fd1
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cacaeb4
5b423bf
cacaeb4
 
5b423bf
 
 
 
 
 
 
 
cacaeb4
5b423bf
 
 
cacaeb4
 
5b423bf
cacaeb4
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3008fd1
 
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cacaeb4
 
 
 
5b423bf
 
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b423bf
cacaeb4
5b423bf
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ea4706
5b423bf
0ea4706
 
 
 
 
cacaeb4
 
 
 
 
 
 
 
 
 
 
5b423bf
0ea4706
5b423bf
 
 
 
 
cacaeb4
 
 
 
 
 
 
 
5b423bf
cacaeb4
 
 
 
 
 
 
5b423bf
 
 
 
 
0ea4706
5b423bf
 
 
 
0ea4706
5b423bf
 
cacaeb4
5b423bf
 
 
 
 
 
 
 
cacaeb4
5b423bf
 
 
 
 
cacaeb4
5b423bf
 
 
 
 
cacaeb4
5b423bf
 
 
 
 
 
 
 
 
0ea4706
5b423bf
 
 
 
 
0ea4706
5b423bf
 
0ea4706
 
 
5b423bf
0ea4706
 
 
5b423bf
 
 
 
 
0ea4706
5b423bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ea4706
5b423bf
0ea4706
 
 
5b423bf
0ea4706
 
 
 
 
5b423bf
0ea4706
 
5b423bf
0ea4706
cacaeb4
 
5b423bf
b95781b
 
0ea4706
5b423bf
 
 
 
 
 
 
 
 
cacaeb4
5b423bf
cacaeb4
 
 
5b423bf
cacaeb4
 
 
5b423bf
 
0ea4706
 
 
5b423bf
0ea4706
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169758c
cacaeb4
 
 
 
 
 
 
 
5b423bf
 
 
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b423bf
cacaeb4
5b423bf
cacaeb4
 
5b423bf
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b423bf
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f09549f
cacaeb4
 
 
 
f09549f
 
cacaeb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20de68
cacaeb4
d0405eb
b20de68
cacaeb4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
#!/usr/bin/env python3
"""
Fall Detection Gradio App (Batch Processing Pipeline)

YOLOv11-Pose + ST-GCN 2-stage ํŒŒ์ดํ”„๋ผ์ธ์„ ์‚ฌ์šฉํ•œ ๋‚™์ƒ ๊ฐ์ง€ ๋ฐ๋ชจ์ž…๋‹ˆ๋‹ค.
๋ฐฐ์น˜ ์ฒ˜๋ฆฌ๋กœ ์ตœ์ ํ™”๋˜์–ด ๋น ๋ฅธ ์ถ”๋ก  ์†๋„๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

Pipeline:
1. decord๋กœ ์ „์ฒด ํ”„๋ ˆ์ž„ ๋ฐฐ์น˜ ๋กœ๋“œ
2. YOLO Pose ๋ฐฐ์น˜ ์ถ”๋ก  โ†’ keypoints ๋ˆ„์ 
3. ์œˆ๋„์šฐ ๋‹จ์œ„ ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 
4. ๋‚™์ƒ ์‹œ์  -1s ~ +2s ๊ตฌ๊ฐ„๋งŒ ์‹œ๊ฐํ™”

์‚ฌ์šฉ๋ฒ• (๋กœ์ปฌ):
    python pipeline/demo_gradio/app.py

์ž‘์„ฑ์ž: Fall Detection Pipeline Team
์ž‘์„ฑ์ผ: 2025-11-27
"""

import json
import os
import subprocess
import sys
import tempfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Iterable, Optional, Tuple

import cv2
import gradio as gr
import numpy as np
import plotly.graph_objects as go
import torch
from gradio.themes import Soft
from gradio.themes.utils import colors, fonts, sizes
from huggingface_hub import hf_hub_download
from visualization import visualize_fall_simple

# HF Spaces ๋ฐฐํฌ์šฉ: ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ ์„ค์ • ๋ถˆํ•„์š” (self-contained)

# Zero GPU ํ˜ธํ™˜ ์„ค์ •
try:
    import spaces
    SPACES_AVAILABLE = True
except ImportError:
    SPACES_AVAILABLE = False


# -----------------------------------------------------------------------------
# Authentication (multi-user support via environment variable)
# -----------------------------------------------------------------------------
def get_auth_credentials():
    """Load auth credentials from environment variable (multi-user support).

    Environment variable format: GRADIO_AUTH='[["user1","pass1"],["user2","pass2"]]'
    Returns None if not set (auth disabled for local development).
    """
    auth_json = os.environ.get("GRADIO_AUTH")

    if auth_json:
        try:
            auth_list = json.loads(auth_json)
            # [["user1","pass1"],["user2","pass2"]] -> [("user1","pass1"),("user2","pass2")]
            return [tuple(pair) for pair in auth_list]
        except json.JSONDecodeError:
            print("Warning: Invalid GRADIO_AUTH format, auth disabled")
            return None

    return None


# -----------------------------------------------------------------------------
# ์ปค์Šคํ…€ ํ…Œ๋งˆ (PRITHIVSAKTHIUR ์Šคํƒ€์ผ)
# -----------------------------------------------------------------------------
colors.custom_color = colors.Color(
    name="custom_color",
    c50="#EBF3F8", c100="#D3E5F0", c200="#A8CCE1",
    c300="#7DB3D2", c400="#529AC3", c500="#4682B4",
    c600="#3E72A0", c700="#36638C", c800="#2E5378",
    c900="#264364", c950="#1E3450",
)


class CustomTheme(Soft):
    def __init__(
        self,
        *,
        primary_hue: colors.Color | str = colors.gray,
        secondary_hue: colors.Color | str = colors.custom_color,
        neutral_hue: colors.Color | str = colors.slate,
        text_size: sizes.Size | str = sizes.text_lg,
        font: fonts.Font | str | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
        ),
        font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
        ),
    ):
        super().__init__(
            primary_hue=primary_hue,
            secondary_hue=secondary_hue,
            neutral_hue=neutral_hue,
            text_size=text_size,
            font=font,
            font_mono=font_mono,
        )
        super().set(
            background_fill_primary="*primary_50",
            body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
            button_primary_text_color="white",
            button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
            button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
            slider_color="*secondary_500",
            block_title_text_weight="600",
            block_border_width="3px",
            block_shadow="*shadow_drop_lg",
            button_primary_shadow="*shadow_drop_lg",
        )


custom_theme = CustomTheme()

# -----------------------------------------------------------------------------
# CSS ์Šคํƒ€์ผ
# -----------------------------------------------------------------------------
css = """
#col-container { margin: 0 auto; max-width: 1200px; }
#main-title h1 { font-size: 2.3em !important; }
.submit-btn {
    background-color: #4682B4 !important;
    color: white !important;
}
.submit-btn:hover {
    background-color: #5A9BD4 !important;
}
.result-label {
    font-size: 1.5em !important;
    font-weight: bold !important;
    padding: 10px !important;
    border-radius: 8px !important;
}
.fall-detected {
    background-color: #FF4444 !important;
    color: white !important;
}
.non-fall {
    background-color: #44BB44 !important;
    color: white !important;
}
"""

# -----------------------------------------------------------------------------
# ๋””๋ฐ”์ด์Šค ์„ค์ •
# -----------------------------------------------------------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


# -----------------------------------------------------------------------------
# GPU ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ (๋กœ์ปฌ/HF Spaces ํ˜ธํ™˜)
# -----------------------------------------------------------------------------
def gpu_decorator(duration: int = 120):
    """๋กœ์ปฌ์—์„œ๋Š” ๊ทธ๋ƒฅ ์‹คํ–‰, Spaces์—์„œ๋Š” GPU ํ• ๋‹น"""
    def decorator(func):
        if SPACES_AVAILABLE:
            return spaces.GPU(duration=duration)(func)
        return func
    return decorator


# -----------------------------------------------------------------------------
# ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ (HuggingFace Hub)
# -----------------------------------------------------------------------------
HF_MODEL_REPO = "YoungjaeDev/fall-detection-models"


def download_models() -> tuple[str, str]:
    """HuggingFace Hub์—์„œ ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ (์บ์‹œ๋จ)"""
    # ๋กœ์ปฌ ๊ฒฝ๋กœ ์šฐ์„  ํ™•์ธ (๊ฐœ๋ฐœ ํ™˜๊ฒฝ)
    local_pose = Path("yolo11m-pose.pt")
    local_stgcn = Path("runs/stgcn_binary_exp2_fixed_graph/best_acc.pth")

    if local_pose.exists() and local_stgcn.exists():
        return str(local_pose), str(local_stgcn)

    # HuggingFace Hub์—์„œ ๋‹ค์šด๋กœ๋“œ
    token = os.environ.get("HF_TOKEN")
    if token is None:
        raise RuntimeError(
            "HF_TOKEN ํ™˜๊ฒฝ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. "
            "Private ๋ชจ๋ธ ์ €์žฅ์†Œ ์ ‘๊ทผ์„ ์œ„ํ•ด HF_TOKEN์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค."
        )

    try:
        pose_model_path = hf_hub_download(
            repo_id=HF_MODEL_REPO, filename="yolo11m-pose.pt", token=token
        )
        stgcn_checkpoint = hf_hub_download(
            repo_id=HF_MODEL_REPO, filename="best_acc.pth", token=token
        )
    except Exception as e:
        raise RuntimeError(f"๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ ์‹คํŒจ: {e}") from e

    return pose_model_path, stgcn_checkpoint


# -----------------------------------------------------------------------------
# ๋ชจ๋ธ ์‹ฑ๊ธ€ํ†ค (์ง€์—ฐ ๋กœ๋”ฉ)
# -----------------------------------------------------------------------------
_pose_estimator = None
_stgcn_classifier = None


def get_pose_estimator():
    """PoseEstimator ์‹ฑ๊ธ€ํ†ค ๋ฐ˜ํ™˜"""
    global _pose_estimator
    if _pose_estimator is None:
        from models.pose_estimator import PoseEstimator
        pose_model_path, _ = download_models()
        _pose_estimator = PoseEstimator(
            model_path=pose_model_path,
            conf_threshold=0.5,
            device=str(device)
        )
    return _pose_estimator


def get_stgcn_classifier():
    """STGCNClassifier ์‹ฑ๊ธ€ํ†ค ๋ฐ˜ํ™˜"""
    global _stgcn_classifier
    if _stgcn_classifier is None:
        from models.stgcn_classifier import STGCNClassifier
        _, stgcn_checkpoint = download_models()
        _stgcn_classifier = STGCNClassifier(
            checkpoint_path=stgcn_checkpoint,
            fall_threshold=0.7,
            device=str(device)
        )
    return _stgcn_classifier


# -----------------------------------------------------------------------------
# ํ”„๋ ˆ์ž„ ๋กœ๋“œ (cv2 ์‚ฌ์šฉ - ๋Œ€๋ถ€๋ถ„์˜ ๋น„๋””์˜ค์—์„œ ๋” ๋น ๋ฆ„)
# -----------------------------------------------------------------------------
def load_video_frames(video_path: str) -> Tuple[np.ndarray, float]:
    """
    ๋น„๋””์˜ค์—์„œ ์ „์ฒด ํ”„๋ ˆ์ž„ ๋กœ๋“œ (cv2 ์‚ฌ์šฉ)

    Returns:
        frames: (N, H, W, C) numpy array (BGR)
        fps: ํ”„๋ ˆ์ž„ ๋ ˆ์ดํŠธ
    """
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS)

    # ์ผ๋ถ€ ๋น„๋””์˜ค ์ปจํ…Œ์ด๋„ˆ๋Š” FPS ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š์•„ 0์„ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Œ
    if not fps or fps <= 0:
        fps = 30.0  # ๊ธฐ๋ณธ๊ฐ’ (ZeroDivisionError ๋ฐฉ์ง€)

    frames = []

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        frames.append(frame)

    cap.release()
    return np.array(frames), fps


# -----------------------------------------------------------------------------
# ๋ฐฐ์น˜ Pose ์ถ”๋ก 
# -----------------------------------------------------------------------------
def extract_all_keypoints(
    frames: np.ndarray,
    pose_estimator,
    batch_size: int = 8,
    progress_callback=None
) -> list[Optional[np.ndarray]]:
    """
    ์ „์ฒด ํ”„๋ ˆ์ž„์— ๋Œ€ํ•ด ๋ฐฐ์น˜ Pose ์ถ”๋ก 

    Args:
        frames: (N, H, W, C) ์ „์ฒด ๋น„๋””์˜ค ํ”„๋ ˆ์ž„
        pose_estimator: PoseEstimator ์ธ์Šคํ„ด์Šค
        batch_size: ๋ฐฐ์น˜ ํฌ๊ธฐ
        progress_callback: ์ง„ํ–‰๋ฅ  ์ฝœ๋ฐฑ ํ•จ์ˆ˜

    Returns:
        keypoints_list: [(17, 3) or None, ...] N๊ฐœ์˜ keypoints
    """
    n_frames = len(frames)
    all_keypoints = []

    for i in range(0, n_frames, batch_size):
        batch = list(frames[i:i+batch_size])
        batch_keypoints = pose_estimator.extract_batch(batch)
        all_keypoints.extend(batch_keypoints)

        if progress_callback:
            progress_callback(min(i + batch_size, n_frames), n_frames)

    return all_keypoints


# -----------------------------------------------------------------------------
# ์œˆ๋„์šฐ ์ƒ์„ฑ ๋ฐ ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 
# -----------------------------------------------------------------------------
def create_windows_and_predict(
    keypoints_list: list[Optional[np.ndarray]],
    stgcn_classifier,
    window_size: int = 60,
    stride: int = 5,
    fall_threshold: float = 0.7
) -> Tuple[list[int], list[float], Optional[int]]:
    """
    keypoints์—์„œ ์œˆ๋„์šฐ ์ƒ์„ฑ ํ›„ ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 

    Args:
        keypoints_list: ํ”„๋ ˆ์ž„๋ณ„ keypoints ๋ฆฌ์ŠคํŠธ
        stgcn_classifier: STGCNClassifier ์ธ์Šคํ„ด์Šค
        window_size: ์œˆ๋„์šฐ ํฌ๊ธฐ (ํ”„๋ ˆ์ž„ ์ˆ˜)
        stride: ์ถ”๋ก  ๊ฐ„๊ฒฉ (N ํ”„๋ ˆ์ž„๋งˆ๋‹ค 1๋ฒˆ)
        fall_threshold: ๋‚™์ƒ ํŒ์ • ์ž„๊ณ„๊ฐ’

    Returns:
        frame_indices: ST-GCN ์˜ˆ์ธก์ด ์žˆ๋Š” ํ”„๋ ˆ์ž„ ์ธ๋ฑ์Šค
        fall_probs: ๊ฐ ํ”„๋ ˆ์ž„์˜ ๋‚™์ƒ ํ™•๋ฅ  (class 1 ํ™•๋ฅ )
        first_fall_frame: ์ฒซ ๋‚™์ƒ ๊ฐ์ง€ ํ”„๋ ˆ์ž„ ์ธ๋ฑ์Šค (์—†์œผ๋ฉด None)
    """
    n_frames = len(keypoints_list)

    # None์„ ๋นˆ keypoints๋กœ ๋Œ€์ฒด
    processed_keypoints = []
    for kpts in keypoints_list:
        if kpts is None:
            processed_keypoints.append(np.zeros((17, 3), dtype=np.float32))
        else:
            processed_keypoints.append(kpts)

    # ์œˆ๋„์šฐ ์ƒ์„ฑ (stride ๊ฐ„๊ฒฉ์œผ๋กœ)
    frame_indices = []
    windows = []

    for frame_idx in range(window_size - 1, n_frames, stride):
        # ์ด์ „ window_size ํ”„๋ ˆ์ž„์œผ๋กœ ์œˆ๋„์šฐ ๊ตฌ์„ฑ
        window_keypoints = processed_keypoints[frame_idx - window_size + 1:frame_idx + 1]

        # (T, V, C) -> (C, T, V, M) ๋ณ€ํ™˜
        window = np.array(window_keypoints)  # (T=60, V=17, C=3)
        window = window.transpose(2, 0, 1)   # (C=3, T=60, V=17)
        window = np.expand_dims(window, -1)  # (C=3, T=60, V=17, M=1)

        frame_indices.append(frame_idx)
        windows.append(window.astype(np.float32))

    if not windows:
        return [], [], None

    # ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 
    predictions, confidences, fall_probs = stgcn_classifier.predict_batch(windows)

    # ์ฒซ ๋‚™์ƒ ๊ฐ์ง€ ํ”„๋ ˆ์ž„ ์ฐพ๊ธฐ
    first_fall_frame = None
    for i, (pred, fall_prob) in enumerate(zip(predictions, fall_probs)):
        if pred == 1 and fall_prob >= fall_threshold:
            first_fall_frame = frame_indices[i]
            break

    return frame_indices, fall_probs.tolist(), first_fall_frame


# -----------------------------------------------------------------------------
# ์‹œ๊ฐํ™” ์›Œ์ปค ํ•จ์ˆ˜ (ThreadPoolExecutor์šฉ - HF Spaces daemon ํ”„๋กœ์„ธ์Šค ํ˜ธํ™˜)
# -----------------------------------------------------------------------------
# FALL DETECTED ํ…์ŠคํŠธ ํ‘œ์‹œ ์ง€์† ์‹œ๊ฐ„ (์ดˆ)
FALL_DISPLAY_DURATION = 2.0


def _visualize_single_frame(args: tuple) -> Tuple[int, np.ndarray]:
    """๋‹จ์ผ ํ”„๋ ˆ์ž„ ์‹œ๊ฐํ™” ์›Œ์ปค (๊ฐ„์†Œํ™”๋œ ๋ฒ„์ „)"""
    (frame_idx, frame, keypoints, show_fall_text,
     viz_keypoints, viz_scale) = args

    vis_frame = visualize_fall_simple(
        frame=frame,
        keypoints=keypoints if keypoints is not None and keypoints.sum() > 0 else None,
        show_fall_text=show_fall_text,
        keypoint_mode=viz_keypoints,
        output_scale=viz_scale
    )

    return frame_idx, vis_frame


def visualize_clip_parallel(
    frames: np.ndarray,
    keypoints_list: list[Optional[np.ndarray]],
    frame_indices: list[int],
    fall_probs: list[float],
    clip_start: int,
    clip_end: int,
    fps: float,
    first_fall_frame: Optional[int] = None,
    fall_threshold: float = 0.7,
    viz_keypoints: str = "all",
    viz_scale: float = 1.0,
    num_workers: int = 4
) -> list[np.ndarray]:
    """
    ํด๋ฆฝ ๊ตฌ๊ฐ„ ๋ณ‘๋ ฌ ์‹œ๊ฐํ™” (๊ฐ„์†Œํ™”๋œ ๋ฒ„์ „)

    Args:
        frames: ์ „์ฒด ํ”„๋ ˆ์ž„
        keypoints_list: ์ „์ฒด keypoints
        frame_indices: ST-GCN ์˜ˆ์ธก ํ”„๋ ˆ์ž„ ์ธ๋ฑ์Šค
        fall_probs: ํ”„๋ ˆ์ž„๋ณ„ ๋‚™์ƒ ํ™•๋ฅ 
        clip_start: ํด๋ฆฝ ์‹œ์ž‘ ์ธ๋ฑ์Šค
        clip_end: ํด๋ฆฝ ์ข…๋ฃŒ ์ธ๋ฑ์Šค
        fps: ํ”„๋ ˆ์ž„ ๋ ˆ์ดํŠธ
        first_fall_frame: ์ฒซ ๋‚™์ƒ ๊ฐ์ง€ ํ”„๋ ˆ์ž„ (๊นœ๋นก์ž„ ๋ฐฉ์ง€์šฉ)
        fall_threshold: ๋‚™์ƒ ํŒ์ • ์ž„๊ณ„๊ฐ’
        viz_keypoints: ํ‚คํฌ์ธํŠธ ํ‘œ์‹œ ๋ชจ๋“œ
        viz_scale: ์ถœ๋ ฅ ์Šค์ผ€์ผ
        num_workers: ๋ณ‘๋ ฌ ์›Œ์ปค ์ˆ˜

    Returns:
        vis_frames: ์‹œ๊ฐํ™”๋œ ํ”„๋ ˆ์ž„ ๋ฆฌ์ŠคํŠธ
    """
    # ๊นœ๋นก์ž„ ๋ฐฉ์ง€: ์ฒซ ๋‚™์ƒ ํ›„ N์ดˆ๊ฐ„ FALL DETECTED ํ‘œ์‹œ
    fall_display_end_frame = None
    if first_fall_frame is not None:
        fall_display_end_frame = first_fall_frame + int(fps * FALL_DISPLAY_DURATION)

    # ์‹œ๊ฐํ™” ์ธ์ž ์ค€๋น„
    viz_args = []
    for i in range(clip_start, clip_end):
        frame = frames[i]
        keypoints = keypoints_list[i]

        # FALL DETECTED ํ…์ŠคํŠธ ํ‘œ์‹œ ์—ฌ๋ถ€ ๊ฒฐ์ • (๊นœ๋นก์ž„ ๋ฐฉ์ง€)
        show_fall_text = False
        if first_fall_frame is not None and fall_display_end_frame is not None:
            if first_fall_frame <= i <= fall_display_end_frame:
                show_fall_text = True

        args = (
            i,              # frame_idx
            frame,          # frame
            keypoints,      # keypoints
            show_fall_text, # show_fall_text (๊นœ๋นก์ž„ ๋ฐฉ์ง€ ์ ์šฉ)
            viz_keypoints,  # viz_keypoints
            viz_scale       # viz_scale
        )
        viz_args.append(args)

    # ๋ณ‘๋ ฌ ์‹œ๊ฐํ™” (ThreadPoolExecutor ์‚ฌ์šฉ - HF Spaces daemon ํ”„๋กœ์„ธ์Šค ํ˜ธํ™˜)
    with ThreadPoolExecutor(max_workers=num_workers) as executor:
        results = list(executor.map(_visualize_single_frame, viz_args))

    # ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ
    results.sort(key=lambda x: x[0])
    vis_frames = [frame for _, frame in results]

    return vis_frames


# -----------------------------------------------------------------------------
# ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
# -----------------------------------------------------------------------------
def create_probability_graph(
    frame_indices: list[int],
    fall_probs: list[float],
    fall_threshold: float = 0.7,
    fps: float = 30.0
) -> go.Figure:
    """๋‚™์ƒ ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ (X์ถ•: ์‹œ๊ฐ„)"""
    # ํ”„๋ ˆ์ž„ ์ธ๋ฑ์Šค -> ์‹œ๊ฐ„(์ดˆ) ๋ณ€ํ™˜
    time_seconds = [idx / fps for idx in frame_indices]

    fig = go.Figure()

    # ํ™•๋ฅ  ๋ผ์ธ
    fig.add_trace(go.Scatter(
        x=time_seconds,
        y=fall_probs,
        mode='lines',
        name='Fall Probability',
        line=dict(color='#4682B4', width=2),
        fill='tozeroy',
        fillcolor='rgba(70, 130, 180, 0.3)'
    ))

    # ์ž„๊ณ„๊ฐ’ ๋ผ์ธ
    fig.add_hline(
        y=fall_threshold,
        line_dash="dash",
        line_color="red",
        annotation_text=f"Threshold ({fall_threshold})",
        annotation_position="right"
    )

    # ๋ ˆ์ด์•„์›ƒ
    fig.update_layout(
        title="Fall Detection Probability Over Time",
        xaxis_title="Time (seconds)",
        yaxis_title="Probability",
        yaxis=dict(range=[0, 1.05]),
        template="plotly_white",
        height=300,
        margin=dict(l=50, r=50, t=50, b=50),
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1
        )
    )

    return fig


# -----------------------------------------------------------------------------
# ์Šค๋งˆํŠธ ํด๋ฆฝ ์ถ”์ถœ ์„ค์ •
# -----------------------------------------------------------------------------
CLIP_PRE_FALL_SECONDS = 1.0   # ๋‚™์ƒ ์ „ 1์ดˆ
CLIP_POST_FALL_SECONDS = 2.0  # ๋‚™์ƒ ํ›„ 2์ดˆ


# -----------------------------------------------------------------------------
# ๋ฉ”์ธ ์ถ”๋ก  ํ•จ์ˆ˜
# -----------------------------------------------------------------------------
@gpu_decorator(duration=120)
def process_video(
    video_path: str,
    fall_threshold: float,
    viz_keypoints: str,
    progress: gr.Progress = gr.Progress()
) -> Tuple[Optional[str], Optional[go.Figure], str]:
    """
    ๋น„๋””์˜ค ์ฒ˜๋ฆฌ ๋ฐ ๋‚™์ƒ ๊ฐ์ง€ (๋ฐฐ์น˜ ์ฒ˜๋ฆฌ ํŒŒ์ดํ”„๋ผ์ธ)

    Pipeline:
    1. decord๋กœ ์ „์ฒด ํ”„๋ ˆ์ž„ ๋ฐฐ์น˜ ๋กœ๋“œ
    2. YOLO Pose ๋ฐฐ์น˜ ์ถ”๋ก  โ†’ keypoints ๋ˆ„์ 
    3. ์œˆ๋„์šฐ ๋‹จ์œ„ ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 
    4. ๋‚™์ƒ ์‹œ์  -1s ~ +2s ๊ตฌ๊ฐ„๋งŒ ์‹œ๊ฐํ™”

    Args:
        video_path: ์ž…๋ ฅ ๋น„๋””์˜ค ๊ฒฝ๋กœ
        fall_threshold: ๋‚™์ƒ ํŒ์ • ์ž„๊ณ„๊ฐ’ (0.0-1.0)
        viz_keypoints: ํ‚คํฌ์ธํŠธ ํ‘œ์‹œ ๋ชจ๋“œ ('all' ๋˜๋Š” 'major')
        progress: Gradio ์ง„ํ–‰๋ฅ  ํ‘œ์‹œ

    Returns:
        output_video_path: ๊ฒฐ๊ณผ ํด๋ฆฝ ๊ฒฝ๋กœ (๋‚™์ƒ ๊ฐ์ง€ ์‹œ) ๋˜๋Š” None
        probability_graph: ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„
        result_text: ์ตœ์ข… ํŒ์ • ํ…์ŠคํŠธ
    """
    if video_path is None:
        return None, None, "๋น„๋””์˜ค๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

    try:
        # Stage 0: ๋ชจ๋ธ ๋กœ๋“œ
        progress(0.05, desc="๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")
        pose_estimator = get_pose_estimator()
        stgcn_classifier = get_stgcn_classifier()
        stgcn_classifier.fall_threshold = fall_threshold

        # Stage 1: ํ”„๋ ˆ์ž„ ๋กœ๋“œ (decord)
        progress(0.1, desc="๋น„๋””์˜ค ๋กœ๋”ฉ ์ค‘...")
        frames, fps = load_video_frames(video_path)
        n_frames = len(frames)

        if n_frames == 0:
            return None, None, "๋น„๋””์˜ค๋ฅผ ์ฝ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."

        # ๋น„๋””์˜ค ๊ธธ์ด ๊ฒ€์ฆ (120s GPU ํƒ€์ž„์•„์›ƒ ๋Œ€๋น„)
        video_duration = n_frames / fps
        if video_duration > 60:
            return None, None, (
                f"๋น„๋””์˜ค๊ฐ€ ๋„ˆ๋ฌด ๊น๋‹ˆ๋‹ค. "
                f"๋น„๋””์˜ค ๊ธธ์ด: {video_duration:.1f}์ดˆ (์ œํ•œ: 60์ดˆ). "
                f"60์ดˆ ์ด๋‚ด์˜ ๋น„๋””์˜ค๋ฅผ ์—…๋กœ๋“œํ•˜์„ธ์š”."
            )

        # Stage 2: ๋ฐฐ์น˜ Pose ์ถ”๋ก 
        progress(0.15, desc="Pose ์ถ”์ถœ ์ค‘...")
        def pose_progress(current, total):
            pct = 0.15 + 0.35 * (current / total)
            progress(pct, desc=f"Pose ์ถ”์ถœ ์ค‘... ({current}/{total})")

        keypoints_list = extract_all_keypoints(
            frames, pose_estimator,
            batch_size=8,
            progress_callback=pose_progress
        )

        # Stage 3: ST-GCN ๋ฐฐ์น˜ ์ถ”๋ก 
        progress(0.55, desc="๋‚™์ƒ ๋ถ„์„ ์ค‘...")
        frame_indices, fall_probs, first_fall_frame = create_windows_and_predict(
            keypoints_list,
            stgcn_classifier,
            window_size=60,
            stride=5,
            fall_threshold=fall_threshold
        )

        # ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ
        progress(0.7, desc="๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ ์ค‘...")
        fig = None
        if frame_indices and fall_probs:
            fig = create_probability_graph(frame_indices, fall_probs, fall_threshold, fps)

        # ๋‚™์ƒ ๋ฏธ๊ฐ์ง€ ์‹œ
        if first_fall_frame is None:
            progress(1.0, desc="์™„๋ฃŒ!")
            result_text = (
                f"[Non-Fall] ๋‚™์ƒ์ด ๊ฐ์ง€๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.\n"
                f"๋ถ„์„ ํ”„๋ ˆ์ž„: {n_frames}๊ฐœ"
            )
            return None, fig, result_text

        # Stage 4: ๋‚™์ƒ ๊ตฌ๊ฐ„๋งŒ ์‹œ๊ฐํ™”
        progress(0.75, desc="ํด๋ฆฝ ์‹œ๊ฐํ™” ์ค‘...")
        pre_fall_frames = int(fps * CLIP_PRE_FALL_SECONDS)
        post_fall_frames = int(fps * CLIP_POST_FALL_SECONDS)

        clip_start = max(0, first_fall_frame - pre_fall_frames)
        clip_end = min(n_frames, first_fall_frame + post_fall_frames)

        vis_frames = visualize_clip_parallel(
            frames=frames,
            keypoints_list=keypoints_list,
            frame_indices=frame_indices,
            fall_probs=fall_probs,
            clip_start=clip_start,
            clip_end=clip_end,
            fps=fps,
            first_fall_frame=first_fall_frame,  # ๊นœ๋นก์ž„ ๋ฐฉ์ง€์šฉ
            fall_threshold=fall_threshold,
            viz_keypoints=viz_keypoints,
            viz_scale=1.0,
            num_workers=4
        )

        if not vis_frames:
            progress(1.0, desc="์™„๋ฃŒ!")
            return None, fig, "ํด๋ฆฝ ์ถ”์ถœ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."

        # Stage 5: ๋น„๋””์˜ค ์ธ์ฝ”๋”ฉ
        progress(0.9, desc="ํด๋ฆฝ ์ธ์ฝ”๋”ฉ ์ค‘...")
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
            output_path = tmp.name

        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        clip_height, clip_width = vis_frames[0].shape[:2]
        out = cv2.VideoWriter(output_path, fourcc, fps, (clip_width, clip_height))

        for vis_frame in vis_frames:
            out.write(vis_frame)
        out.release()

        # H.264 ์žฌ์ธ์ฝ”๋”ฉ (๋ธŒ๋ผ์šฐ์ € ํ˜ธํ™˜)
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
            output_h264 = tmp.name

        subprocess.run(
            [
                'ffmpeg', '-y', '-i', output_path,
                '-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
                output_h264, '-loglevel', 'quiet'
            ],
            check=False,
            capture_output=True
        )

        # ์ž„์‹œ ํŒŒ์ผ ์ •๋ฆฌ
        if os.path.exists(output_path):
            os.remove(output_path)

        final_output = output_h264 if os.path.exists(output_h264) else None

        # ์ตœ์ข… ํŒ์ •
        progress(1.0, desc="์™„๋ฃŒ!")
        fall_time = first_fall_frame / fps
        clip_duration = len(vis_frames) / fps
        result_text = (
            f"[FALL DETECTED] ๋‚™์ƒ์ด ๊ฐ์ง€๋˜์—ˆ์Šต๋‹ˆ๋‹ค!\n"
            f"๋‚™์ƒ ์‹œ์ : {fall_time:.2f}์ดˆ (ํ”„๋ ˆ์ž„ #{first_fall_frame})\n"
            f"ํด๋ฆฝ ๊ธธ์ด: {clip_duration:.1f}์ดˆ ({len(vis_frames)}ํ”„๋ ˆ์ž„)"
        )

        return final_output, fig, result_text

    except Exception as e:
        import traceback
        error_msg = f"์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}\n{traceback.format_exc()}"
        return None, None, error_msg


# -----------------------------------------------------------------------------
# Gradio UI
# -----------------------------------------------------------------------------
def create_demo() -> gr.Blocks:
    """Gradio ๋ฐ๋ชจ ์ƒ์„ฑ"""

    with gr.Blocks(theme=custom_theme, css=css) as demo:
        gr.Markdown(
            """
            # Fall Detection Demo

            YOLOv11-Pose + ST-GCN 2-stage ํŒŒ์ดํ”„๋ผ์ธ์„ ์‚ฌ์šฉํ•œ ์‹ค์‹œ๊ฐ„ ๋‚™์ƒ ๊ฐ์ง€ ๋ฐ๋ชจ์ž…๋‹ˆ๋‹ค.
            ๋น„๋””์˜ค๋ฅผ ์—…๋กœ๋“œํ•˜๋ฉด ๋‚™์ƒ ์—ฌ๋ถ€๋ฅผ ๋ถ„์„ํ•˜๊ณ , ๊ฒฐ๊ณผ ๋น„๋””์˜ค์™€ ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

            **ํŒŒ์ดํ”„๋ผ์ธ ๊ตฌ์„ฑ:**
            - Stage 1: YOLOv11m-pose (Pose Estimation) - Batch Processing
            - Stage 2: ST-GCN (Temporal Classification) - Batch Processing
            - Window Size: 60 frames (2s @ 30fps)
            """,
            elem_id="main-title"
        )

        with gr.Row():
            with gr.Column(scale=1):
                # ์ž…๋ ฅ ์„น์…˜
                gr.Markdown("### ์ž…๋ ฅ")
                video_input = gr.Video(
                    label="๋น„๋””์˜ค ์—…๋กœ๋“œ",
                    sources=["upload"],
                )

                with gr.Accordion("๊ณ ๊ธ‰ ์„ค์ •", open=False):
                    fall_threshold = gr.Slider(
                        minimum=0.5,
                        maximum=0.95,
                        value=0.7,
                        step=0.05,
                        label="๋‚™์ƒ ํŒ์ • ์ž„๊ณ„๊ฐ’",
                        info="๊ถŒ์žฅ: 0.7-0.85"
                    )
                    viz_keypoints = gr.Radio(
                        choices=["all", "major"],
                        value="all",
                        label="ํ‚คํฌ์ธํŠธ ํ‘œ์‹œ",
                        info="all: ์ „์ฒด 17๊ฐœ, major: ์ฃผ์š” 9๊ฐœ"
                    )

                submit_btn = gr.Button(
                    "๋ถ„์„ ์‹œ์ž‘",
                    variant="primary",
                    elem_classes="submit-btn"
                )

            with gr.Column(scale=1):
                # ์ถœ๋ ฅ ์„น์…˜
                gr.Markdown("### ๊ฒฐ๊ณผ")
                result_text = gr.Textbox(
                    label="ํŒ์ • ๊ฒฐ๊ณผ",
                    lines=3,
                    interactive=False
                )
                video_output = gr.Video(
                    label="๊ฒฐ๊ณผ ๋น„๋””์˜ค",
                )
                prob_graph = gr.Plot(
                    label="๋‚™์ƒ ํ™•๋ฅ  ๊ทธ๋ž˜ํ”„",
                )

        # ์˜ˆ์ œ ๋น„๋””์˜ค
        gr.Markdown("### ์˜ˆ์ œ ๋น„๋””์˜ค")
        example_dir = Path(__file__).parent / "examples"
        examples = []
        if example_dir.exists():
            for ext in ["*.mp4", "*.avi", "*.mov"]:
                examples.extend([str(p) for p in example_dir.glob(ext)])

        if examples:
            gr.Examples(
                examples=[[ex, 0.7, "all"] for ex in sorted(examples)],
                inputs=[video_input, fall_threshold, viz_keypoints],
                outputs=[video_output, prob_graph, result_text],
                fn=process_video,
                cache_examples=False,
                examples_per_page=4,
                label="์˜ˆ์ œ ๋น„๋””์˜ค",
            )

        # ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
        submit_btn.click(
            fn=process_video,
            inputs=[video_input, fall_threshold, viz_keypoints],
            outputs=[video_output, prob_graph, result_text],
        )

        # ํ‘ธํ„ฐ
        gr.Markdown(
            """
            ---
            **References:**
            - [YOLOv11](https://github.com/ultralytics/ultralytics) - Pose Estimation
            - [ST-GCN](https://arxiv.org/abs/1801.07455) - Spatial Temporal Graph Convolutional Networks
            - AI Hub Fall Detection Dataset
            """
        )

    return demo


# -----------------------------------------------------------------------------
# ๋ฉ”์ธ ์‹คํ–‰
# -----------------------------------------------------------------------------
if __name__ == "__main__":
    demo = create_demo()
    demo.queue(max_size=10).launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,  # HF Spaces์—์„œ๋Š” ์ด๋ฏธ public URL ์ œ๊ณต
        show_error=True,
        auth=get_auth_credentials(),
        ssr_mode=False,  # svelte-i18n locale ์—๋Ÿฌ ๋ฐฉ์ง€
    )