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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
#!/usr/bin/env python3
"""
Fall Detection Gradio App

YOLOv11-Pose + ST-GCN 2-stage νŒŒμ΄ν”„λΌμΈμ„ μ‚¬μš©ν•œ 낙상 감지 데λͺ¨μž…λ‹ˆλ‹€.
HF Spaces Zero GPU ν™˜κ²½μ—μ„œ μ‹€ν–‰λ©λ‹ˆλ‹€.

μ‚¬μš©λ²• (둜컬):
    python demo_gradio/app.py

μ‚¬μš©λ²• (HF Spaces):
    μžλ™μœΌλ‘œ app.pyκ°€ μ‹€ν–‰λ©λ‹ˆλ‹€.

μž‘μ„±μž: Fall Detection Pipeline Team
μž‘μ„±μΌ: 2025-11-26
"""

import os
import sys
import tempfile
import time
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

# ν”„λ‘œμ νŠΈ 루트λ₯Ό Python path에 μΆ”κ°€
# pipeline/demo_gradio/app.py -> pipeline -> project_root
PROJECT_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

# Zero GPU ν˜Έν™˜ μ„€μ •
try:
    import spaces
    SPACES_AVAILABLE = True
except ImportError:
    SPACES_AVAILABLE = False


# -----------------------------------------------------------------------------
# μ»€μŠ€ν…€ ν…Œλ§ˆ (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


# -----------------------------------------------------------------------------
# νŒŒμ΄ν”„λΌμΈ μ΄ˆκΈ°ν™” (μ§€μ—° λ‘œλ”©)
# -----------------------------------------------------------------------------
_pipeline = None


def get_pipeline():
    """νŒŒμ΄ν”„λΌμΈ 싱글톀 λ°˜ν™˜ (μ§€μ—° λ‘œλ”©)"""
    global _pipeline
    if _pipeline is None:
        from pipeline.core.pipeline import FallDetectionPipeline

        # HF Spacesμ—μ„œλŠ” models ν΄λ”μ—μ„œ λ‘œλ“œ
        pose_model_path = "pipeline/demo_gradio/models/yolo11m-pose.pt"
        stgcn_checkpoint = "pipeline/demo_gradio/models/best_acc.pth"

        # 둜컬 경둜 폴백
        if not Path(pose_model_path).exists():
            pose_model_path = "yolo11m-pose.pt"
        if not Path(stgcn_checkpoint).exists():
            stgcn_checkpoint = "runs/stgcn_binary_exp2_fixed_graph/best_acc.pth"

        _pipeline = FallDetectionPipeline(
            pose_model_path=pose_model_path,
            stgcn_checkpoint=stgcn_checkpoint,
            window_size=60,
            conf_threshold=0.5,
            fall_threshold=0.7,
            temporal_window=5,
            stgcn_stride=5,
            alert_duration=150,
            post_fall_frames=3,
            device=str(device),
            debug=False,
            headless=False,
            viz_keypoints="all",
            viz_scale=1.0,
            viz_optimized=True
        )
    return _pipeline


# -----------------------------------------------------------------------------
# ν™•λ₯  κ·Έλž˜ν”„ 생성
# -----------------------------------------------------------------------------
def create_probability_graph(
    frame_indices: list,
    probabilities: list,
    fall_threshold: float = 0.7
) -> go.Figure:
    """
    낙상 ν™•λ₯  κ·Έλž˜ν”„ 생성

    Args:
        frame_indices: ν”„λ ˆμž„ 인덱슀 리슀트
        probabilities: 낙상 ν™•λ₯  리슀트 (0.0-1.0)
        fall_threshold: 낙상 νŒμ • μž„κ³„κ°’

    Returns:
        Plotly Figure 객체
    """
    fig = go.Figure()

    # ν™•λ₯  라인
    fig.add_trace(go.Scatter(
        x=frame_indices,
        y=probabilities,
        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="Frame",
        yaxis_title="Probability",
        yaxis=dict(range=[0, 1]),
        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


# -----------------------------------------------------------------------------
# 메인 μΆ”λ‘  ν•¨μˆ˜
# -----------------------------------------------------------------------------
@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]:
    """
    λΉ„λ””μ˜€ 처리 및 낙상 감지

    Args:
        video_path: μž…λ ₯ λΉ„λ””μ˜€ 경둜
        fall_threshold: 낙상 νŒμ • μž„κ³„κ°’ (0.0-1.0)
        viz_keypoints: ν‚€ν¬μΈνŠΈ ν‘œμ‹œ λͺ¨λ“œ ('all' λ˜λŠ” 'major')
        progress: Gradio μ§„ν–‰λ₯  ν‘œμ‹œ

    Returns:
        output_video_path: κ²°κ³Ό λΉ„λ””μ˜€ 경둜
        probability_graph: ν™•λ₯  κ·Έλž˜ν”„
        result_text: μ΅œμ’… νŒμ • ν…μŠ€νŠΈ
    """
    if video_path is None:
        return None, None, "λΉ„λ””μ˜€λ₯Ό μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”."

    try:
        # νŒŒμ΄ν”„λΌμΈ λ‘œλ“œ
        progress(0.1, desc="λͺ¨λΈ λ‘œλ”© 쀑...")
        pipeline = get_pipeline()
        pipeline.fall_threshold = fall_threshold
        pipeline.stgcn_classifier.fall_threshold = fall_threshold
        pipeline.viz_keypoints = viz_keypoints
        pipeline.reset()

        # λΉ„λ””μ˜€ μ—΄κΈ°
        progress(0.2, desc="λΉ„λ””μ˜€ μ—΄κΈ°...")
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            return None, None, "λΉ„λ””μ˜€λ₯Ό μ—΄ 수 μ—†μŠ΅λ‹ˆλ‹€."

        # λΉ„λ””μ˜€ 정보
        fps = cap.get(cv2.CAP_PROP_FPS)
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

        # 좜λ ₯ λΉ„λ””μ˜€ μ„€μ •
        output_path = tempfile.mktemp(suffix=".mp4")
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        # Info panel μΆ”κ°€λ‘œ 높이 80px 증가
        out = cv2.VideoWriter(output_path, fourcc, fps, (width, height + 80))

        # 처리 루프
        frame_idx = 0
        frame_indices = []
        probabilities = []
        fall_detected = False
        max_confidence = 0.0

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

            # ν”„λ ˆμž„ 처리
            vis_frame, info = pipeline.process_frame(frame, frame_idx)

            # ν™•λ₯  기둝
            if info['confidence'] is not None:
                frame_indices.append(frame_idx)
                probabilities.append(info['confidence'])
                max_confidence = max(max_confidence, info['confidence'])

            # 낙상 감지 확인
            if info['alert']:
                fall_detected = True

            # 좜λ ₯ μ €μž₯
            out.write(vis_frame)

            frame_idx += 1

            # μ§„ν–‰λ₯  μ—…λ°μ΄νŠΈ
            if frame_idx % 10 == 0:
                progress_val = 0.2 + 0.7 * (frame_idx / total_frames)
                progress(progress_val, desc=f"처리 쀑... ({frame_idx}/{total_frames})")

        # λ¦¬μ†ŒμŠ€ ν•΄μ œ
        cap.release()
        out.release()

        # H.264 μ½”λ±μœΌλ‘œ μž¬μΈμ½”λ”© (λΈŒλΌμš°μ € ν˜Έν™˜)
        progress(0.9, desc="λΉ„λ””μ˜€ 인코딩 쀑...")
        output_h264 = tempfile.mktemp(suffix=".mp4")
        os.system(f'ffmpeg -y -i "{output_path}" -c:v libx264 -preset fast -crf 23 "{output_h264}" -loglevel quiet')

        # mp4v μž„μ‹œ 파일 μ‚­μ œ
        if os.path.exists(output_path):
            os.remove(output_path)

        # H.264 λ³€ν™˜ 성곡 μ—¬λΆ€ 확인
        if os.path.exists(output_h264):
            final_output = output_h264
        else:
            final_output = output_path  # 폴백

        # ν™•λ₯  κ·Έλž˜ν”„ 생성
        progress(0.95, desc="κ·Έλž˜ν”„ 생성 쀑...")
        if frame_indices and probabilities:
            fig = create_probability_graph(frame_indices, probabilities, fall_threshold)
        else:
            fig = None

        # μ΅œμ’… νŒμ •
        progress(1.0, desc="μ™„λ£Œ!")
        if fall_detected:
            result_text = f"[FALL DETECTED] 낙상이 κ°μ§€λ˜μ—ˆμŠ΅λ‹ˆλ‹€! (μ΅œλŒ€ ν™•λ₯ : {max_confidence:.1%})"
        else:
            result_text = f"[Non-Fall] 낙상이 κ°μ§€λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. (μ΅œλŒ€ ν™•λ₯ : {max_confidence:.1%})"

        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() as demo:
        gr.Markdown(
            """
            # Fall Detection Demo

            YOLOv11-Pose + ST-GCN 2-stage νŒŒμ΄ν”„λΌμΈμ„ μ‚¬μš©ν•œ μ‹€μ‹œκ°„ 낙상 감지 데λͺ¨μž…λ‹ˆλ‹€.
            λΉ„λ””μ˜€λ₯Ό μ—…λ‘œλ“œν•˜λ©΄ 낙상 μ—¬λΆ€λ₯Ό λΆ„μ„ν•˜κ³ , κ²°κ³Ό λΉ„λ””μ˜€μ™€ ν™•λ₯  κ·Έλž˜ν”„λ₯Ό μ œκ³΅ν•©λ‹ˆλ‹€.

            **νŒŒμ΄ν”„λΌμΈ ꡬ성:**
            - Stage 1: YOLOv11m-pose (Pose Estimation)
            - Stage 2: ST-GCN (Temporal Classification)
            - Window Size: 60 frames (2초 @ 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="이 κ°’ μ΄μƒμ˜ ν™•λ₯ μ΄λ©΄ λ‚™μƒμœΌλ‘œ νŒμ •ν•©λ‹ˆλ‹€."
                    )
                    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=2,
                    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 examples[:3]],
                inputs=[video_input, fall_threshold, viz_keypoints],
                outputs=[video_output, prob_graph, result_text],
                fn=process_video,
                cache_examples=False,
            )

        # 이벀트 μ—°κ²°
        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,
        show_error=True,
        theme=custom_theme,
        css=css,
    )