Spaces:
Running
on
Zero
Running
on
Zero
File size: 22,456 Bytes
cacaeb4 b95781b cacaeb4 7ea83d4 cacaeb4 7ea83d4 169758c 7ea83d4 169758c 7ea83d4 169758c 7ea83d4 cacaeb4 7ea83d4 cacaeb4 b95781b cacaeb4 b95781b cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 b95781b 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 f50f28a cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 0ea4706 cacaeb4 b95781b 0ea4706 f50f28a cacaeb4 0ea4706 cacaeb4 169758c cacaeb4 b95781b cacaeb4 b95781b cacaeb4 b95781b cacaeb4 b95781b cacaeb4 169758c 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 |
#!/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 subprocess
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
from huggingface_hub import hf_hub_download
# νλ‘μ νΈ λ£¨νΈλ₯Ό 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
# -----------------------------------------------------------------------------
# λͺ¨λΈ λ€μ΄λ‘λ (HuggingFace Hub)
# -----------------------------------------------------------------------------
HF_MODEL_REPO = "YoungjaeDev/fall-detection-models"
def download_models() -> tuple[str, str]:
"""
HuggingFace Hubμμ λͺ¨λΈ λ€μ΄λ‘λ (μΊμλ¨)
Returns:
tuple: (pose_model_path, stgcn_checkpoint_path)
Raises:
RuntimeError: λͺ¨λΈ λ€μ΄λ‘λ λλ κ²μ¦ μ€ν¨ μ
"""
# λ‘컬 κ²½λ‘ μ°μ νμΈ (κ°λ° νκ²½)
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μμ λ€μ΄λ‘λ (Private repoλ HF_TOKEN νκ²½λ³μ νμ)
token = os.environ.get("HF_TOKEN")
# Private μ μ₯μ μ κ·Όμ μν ν ν° νμΈ
if token is None:
raise RuntimeError(
"HF_TOKEN νκ²½λ³μκ° μ€μ λμ§ μμμ΅λλ€. "
"Private λͺ¨λΈ μ μ₯μ μ κ·Όμ μν΄ HF_TOKENμ΄ νμν©λλ€. "
"HF Spacesμ κ²½μ° Settings > Secretsμμ μ€μ νμΈμ."
)
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}\n"
f"μ μ₯μ: {HF_MODEL_REPO}\n"
f"HF_TOKENμ΄ μ¬λ°λ₯΄κ² μ€μ λμλμ§ νμΈνμΈμ."
) from e
# λ€μ΄λ‘λλ νμΌ κ²μ¦
pose_path = Path(pose_model_path)
stgcn_path = Path(stgcn_checkpoint)
if not pose_path.exists():
raise RuntimeError(f"Pose λͺ¨λΈ νμΌμ΄ μ‘΄μ¬νμ§ μμ΅λλ€: {pose_model_path}")
if not stgcn_path.exists():
raise RuntimeError(f"ST-GCN 체ν¬ν¬μΈνΈ νμΌμ΄ μ‘΄μ¬νμ§ μμ΅λλ€: {stgcn_checkpoint}")
# νμΌ ν¬κΈ° κ²μ¦ (λ무 μμΌλ©΄ μμλ νμΌμΌ κ°λ₯μ±)
pose_size = pose_path.stat().st_size
stgcn_size = stgcn_path.stat().st_size
if pose_size < 1_000_000: # 1MB λ―Έλ§
raise RuntimeError(f"Pose λͺ¨λΈ νμΌμ΄ λ무 μμ΅λλ€: {pose_size} bytes")
if stgcn_size < 1_000_000: # 1MB λ―Έλ§
raise RuntimeError(f"ST-GCN 체ν¬ν¬μΈνΈ νμΌμ΄ λ무 μμ΅λλ€: {stgcn_size} bytes")
return pose_model_path, stgcn_checkpoint
# -----------------------------------------------------------------------------
# νμ΄νλΌμΈ μ΄κΈ°ν (μ§μ° λ‘λ©)
# -----------------------------------------------------------------------------
_pipeline = None
def get_pipeline():
"""νμ΄νλΌμΈ μ±κΈν€ λ°ν (μ§μ° λ‘λ©)"""
global _pipeline
if _pipeline is None:
from pipeline.core.pipeline import FallDetectionPipeline
# λͺ¨λΈ λ€μ΄λ‘λ (μΊμλ¨)
pose_model_path, stgcn_checkpoint = download_models()
_pipeline = FallDetectionPipeline(
pose_model_path=pose_model_path,
stgcn_checkpoint=stgcn_checkpoint,
window_size=60,
conf_threshold=0.5,
fall_threshold=0.85, # κ°μ΄λλΌμΈ κΆμ₯: 0.8-0.9 (false positive <5%)
temporal_window=5,
stgcn_stride=5,
alert_duration=150,
post_fall_frames=15, # 2.5μ΄ @ 30fps with stride=5 (κ°μ΄λλΌμΈ: 2-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
# -----------------------------------------------------------------------------
# μ€λ§νΈ ν΄λ¦½ μΆμΆ μ€μ (Issue #82)
# -----------------------------------------------------------------------------
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]:
"""
λΉλμ€ μ²λ¦¬ λ° λμ κ°μ§ (μ€λ§νΈ ν΄λ¦½ μΆμΆ)
Issue #82: λμ κ°μ§ ꡬκ°λ§ ν΄λ¦½μΌλ‘ μΆμΆνμ¬ μΈμ½λ© μκ° λν κ°μ
- λμ κ°μ§ μ: λμ μ 1μ΄ + λμ ν 2μ΄ κ΅¬κ°λ§ μΆμΆ
- λΉλμ μ: λμ λ―Έκ°μ§ λ©μμ§ λ°ν
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:
# νμ΄νλΌμΈ λ‘λ
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))
# λΉλμ€ κΈΈμ΄ κ²μ¦ (120s GPU νμμμ λλΉ)
if fps > 0:
video_duration = total_frames / fps
# μ²λ¦¬ μκ° μΆμ : λλ΅ μ€μκ°μ 1.5λ°° + μΈμ½λ© 10μ΄
estimated_time = video_duration * 1.5 + 10
if estimated_time > 110: # 120s νμμμμ μ¬μ λκΈ°
cap.release()
return None, None, (
f"λΉλμ€κ° λ무 κΉλλ€. "
f"λΉλμ€ κΈΈμ΄: {video_duration:.1f}μ΄, "
f"μμ μ²λ¦¬ μκ°: {estimated_time:.1f}μ΄ (μ ν: 110μ΄). "
f"60μ΄ μ΄λ΄μ λΉλμ€λ₯Ό μ
λ‘λνμΈμ."
)
# ν΄λ¦½ μΆμΆμ μν νλ μ μ κ³μ°
pre_fall_frames = int(fps * CLIP_PRE_FALL_SECONDS)
post_fall_frames = int(fps * CLIP_POST_FALL_SECONDS)
# μ²λ¦¬ 루ν - νλ μ λ²νΌλ§ + λμ κ°μ§
frame_idx = 0
frame_indices = []
probabilities = []
max_confidence = 0.0
# λμ κ°μ§ μΆμ
first_fall_frame = None # 첫 λμ κ°μ§ νλ μ
fall_detected = False
# μκ°ν νλ μ λ²νΌ (ν΄λ¦½ μΆμΆμ©)
vis_frame_buffer = []
raw_frame_buffer = [] # μλ³Έ νλ μ λ²νΌ (μ¬μ²λ¦¬μ©)
while True:
# νλ μ μ½κΈ°
with pipeline.profiler.profile('video_read'):
ret, frame = cap.read()
if not ret:
break
# μλ³Έ νλ μ λ²νΌμ μ μ₯ (ν΄λ¦½ μΆμΆμ νμ)
raw_frame_buffer.append(frame.copy())
# νλ μ μ²λ¦¬
vis_frame, info = pipeline.process_frame(frame, frame_idx)
# μκ°ν νλ μ λ²νΌμ μ μ₯
vis_frame_buffer.append(vis_frame)
# νλ₯ κΈ°λ‘
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'] and first_fall_frame is None:
first_fall_frame = frame_idx
fall_detected = True
frame_idx += 1
# μ§νλ₯ μ
λ°μ΄νΈ
if frame_idx % 10 == 0:
progress_val = 0.2 + 0.6 * (frame_idx / total_frames)
progress(progress_val, desc=f"λΆμ μ€... ({frame_idx}/{total_frames})")
cap.release()
# νλ₯ κ·Έλν μμ± (νμ μμ±)
progress(0.85, desc="κ·Έλν μμ± μ€...")
if frame_indices and probabilities:
fig = create_probability_graph(frame_indices, probabilities, fall_threshold)
else:
fig = None
# λμ λ―Έκ°μ§ μ ν΄λ¦½ μμ΄ λ°ν
if not fall_detected or first_fall_frame is None:
progress(1.0, desc="μλ£!")
result_text = (
f"[Non-Fall] λμμ΄ κ°μ§λμ§ μμμ΅λλ€.\n"
f"μ΅λ νλ₯ : {max_confidence:.1%}\n"
f"λΆμ νλ μ: {total_frames}κ°"
)
return None, fig, result_text
# ν΄λ¦½ κ΅¬κ° κ³μ°
clip_start = max(0, first_fall_frame - pre_fall_frames)
clip_end = min(len(vis_frame_buffer), first_fall_frame + post_fall_frames)
clip_frames = vis_frame_buffer[clip_start:clip_end]
if not clip_frames:
progress(1.0, desc="μλ£!")
return None, fig, "ν΄λ¦½ μΆμΆμ μ€ν¨νμ΅λλ€."
# ν΄λ¦½ λΉλμ€ μμ± (νλ μ μ κ°μλ‘ μΈμ½λ© μκ° λν κ°μ)
progress(0.9, desc="ν΄λ¦½ μΈμ½λ© μ€...")
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
output_path = tmp.name
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# Info panel μΆκ°λ‘ λμ΄ 80px μ¦κ°
clip_height, clip_width = clip_frames[0].shape[:2]
out = cv2.VideoWriter(output_path, fourcc, fps, (clip_width, clip_height))
for vis_frame in clip_frames:
out.write(vis_frame)
out.release()
# H.264 μ½λ±μΌλ‘ μ¬μΈμ½λ© (λΈλΌμ°μ νΈν)
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
output_h264 = tmp.name
with pipeline.profiler.profile('ffmpeg_encode'):
subprocess.run(
[
'ffmpeg', '-y', '-i', output_path,
'-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
output_h264, '-loglevel', 'quiet'
],
check=False,
capture_output=True
)
# 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(1.0, desc="μλ£!")
fall_time = first_fall_frame / fps if fps > 0 else 0
clip_duration = len(clip_frames) / fps if fps > 0 else 0
result_text = (
f"[FALL DETECTED] λμμ΄ κ°μ§λμμ΅λλ€!\n"
f"λμ μμ : {fall_time:.2f}μ΄ (νλ μ #{first_fall_frame})\n"
f"μ΅λ νλ₯ : {max_confidence:.1%}\n"
f"ν΄λ¦½ κΈΈμ΄: {clip_duration:.1f}μ΄ ({len(clip_frames)}νλ μ)\n"
f"μλ³Έ λλΉ: {len(clip_frames)}/{total_frames}νλ μ "
f"({len(clip_frames)/total_frames*100:.1f}% μΈμ½λ©)"
)
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)
- 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.7,
maximum=0.95,
value=0.85,
step=0.05,
label="λμ νμ μκ³κ°",
info="κΆμ₯: 0.8-0.9 (false positive <5% λͺ©ν)"
)
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.85, "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=True,
show_error=True,
)
|