Upload folder using huggingface_hub
Browse files- .gitattributes +39 -35
- README.md +13 -0
- app.py +304 -0
- fall_detection_transformer.tflite +3 -0
- fall_example_1.mp4 +3 -0
- fall_example_2.mp4 +3 -0
- fall_example_3.mp4 +3 -0
- fall_example_4.mp4 +3 -0
- requirements.txt +6 -0
- yolo26n-pose.pt +3 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,39 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
fall_example_1.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
fall_example_2.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
fall_example_3.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
fall_example_4.mp4 filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Fall Detection
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.28.0
|
| 8 |
+
python_version: '3.12'
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from ai_edge_litert.interpreter import Interpreter as tflite_Interpreter
|
| 5 |
+
from collections import deque
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from ultralytics import YOLO
|
| 11 |
+
|
| 12 |
+
# Fix harmless asyncio cleanup crash on Windows (WinError 10054)
|
| 13 |
+
if sys.platform == "win32":
|
| 14 |
+
import asyncio
|
| 15 |
+
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
| 16 |
+
|
| 17 |
+
# --- Configuration ---
|
| 18 |
+
MODEL_PATH = "fall_detection_transformer.tflite"
|
| 19 |
+
YOLO_POSE_MODEL = "yolo26n-pose.pt"
|
| 20 |
+
INPUT_TIMESTEPS = 30
|
| 21 |
+
FALL_CONFIDENCE_THRESHOLD = 0.90
|
| 22 |
+
MIN_KEYPOINT_CONFIDENCE_FOR_NORMALIZATION = 0.3
|
| 23 |
+
FALL_EVENT_COOLDOWN = 10
|
| 24 |
+
|
| 25 |
+
# YOLO26-pose outputs 17 COCO keypoints in this order:
|
| 26 |
+
YOLO_KEYPOINT_NAMES = [
|
| 27 |
+
"Nose", "Left Eye", "Right Eye", "Left Ear", "Right Ear",
|
| 28 |
+
"Left Shoulder", "Right Shoulder", "Left Elbow", "Right Elbow",
|
| 29 |
+
"Left Wrist", "Right Wrist", "Left Hip", "Right Hip",
|
| 30 |
+
"Left Knee", "Right Knee", "Left Ankle", "Right Ankle",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
YOUR_KEYPOINT_NAMES_TRAINING = [
|
| 34 |
+
"Nose", "Left Eye", "Right Eye", "Left Ear", "Right Ear",
|
| 35 |
+
"Left Shoulder", "Right Shoulder", "Left Elbow", "Right Elbow",
|
| 36 |
+
"Left Wrist", "Right Wrist", "Left Hip", "Right Hip",
|
| 37 |
+
"Left Knee", "Right Knee", "Left Ankle", "Right Ankle"
|
| 38 |
+
]
|
| 39 |
+
SORTED_YOUR_KEYPOINT_NAMES = sorted(YOUR_KEYPOINT_NAMES_TRAINING)
|
| 40 |
+
KEYPOINT_DICT_TRAINING = {name: i for i, name in enumerate(SORTED_YOUR_KEYPOINT_NAMES)}
|
| 41 |
+
NUM_KEYPOINTS_TRAINING = len(KEYPOINT_DICT_TRAINING)
|
| 42 |
+
NUM_FEATURES = NUM_KEYPOINTS_TRAINING * 3
|
| 43 |
+
|
| 44 |
+
YOLO_IDX_TO_NAME = {i: name for i, name in enumerate(YOLO_KEYPOINT_NAMES)
|
| 45 |
+
if name in KEYPOINT_DICT_TRAINING}
|
| 46 |
+
|
| 47 |
+
print("--- Initializing ---")
|
| 48 |
+
print(f"NUM_FEATURES: {NUM_FEATURES}")
|
| 49 |
+
|
| 50 |
+
# --- Load YOLO26 Pose Model ---
|
| 51 |
+
print(f"Loading YOLO26 pose model: {YOLO_POSE_MODEL}")
|
| 52 |
+
yolo_pose = YOLO(YOLO_POSE_MODEL)
|
| 53 |
+
print("YOLO26 pose model loaded.")
|
| 54 |
+
|
| 55 |
+
# --- Load TFLite Transformer Model ---
|
| 56 |
+
interpreter = tflite_Interpreter(model_path=MODEL_PATH)
|
| 57 |
+
interpreter.allocate_tensors()
|
| 58 |
+
input_details = interpreter.get_input_details()
|
| 59 |
+
output_details = interpreter.get_output_details()
|
| 60 |
+
print(f"TFLite Model Loaded: {MODEL_PATH}")
|
| 61 |
+
model_expected_shape = tuple(input_details[0]["shape"])
|
| 62 |
+
print(f"Model expected input shape: {model_expected_shape}")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_kpt_indices_training_order(keypoint_name):
|
| 66 |
+
kp_idx = KEYPOINT_DICT_TRAINING[keypoint_name]
|
| 67 |
+
return kp_idx * 3, kp_idx * 3 + 1, kp_idx * 3 + 2
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def normalize_skeleton_frame(frame_features_sorted, min_confidence=MIN_KEYPOINT_CONFIDENCE_FOR_NORMALIZATION):
|
| 71 |
+
normalized_frame = np.copy(frame_features_sorted)
|
| 72 |
+
try:
|
| 73 |
+
ls_x_idx, ls_y_idx, ls_c_idx = get_kpt_indices_training_order("Left Shoulder")
|
| 74 |
+
rs_x_idx, rs_y_idx, rs_c_idx = get_kpt_indices_training_order("Right Shoulder")
|
| 75 |
+
lh_x_idx, lh_y_idx, lh_c_idx = get_kpt_indices_training_order("Left Hip")
|
| 76 |
+
rh_x_idx, rh_y_idx, rh_c_idx = get_kpt_indices_training_order("Right Hip")
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return frame_features_sorted
|
| 79 |
+
|
| 80 |
+
ls_c = frame_features_sorted[ls_c_idx]
|
| 81 |
+
rs_c = frame_features_sorted[rs_c_idx]
|
| 82 |
+
lh_c = frame_features_sorted[lh_c_idx]
|
| 83 |
+
rh_c = frame_features_sorted[rh_c_idx]
|
| 84 |
+
ls_x, ls_y = frame_features_sorted[ls_x_idx], frame_features_sorted[ls_y_idx]
|
| 85 |
+
rs_x, rs_y = frame_features_sorted[rs_x_idx], frame_features_sorted[rs_y_idx]
|
| 86 |
+
lh_x, lh_y = frame_features_sorted[lh_x_idx], frame_features_sorted[lh_y_idx]
|
| 87 |
+
rh_x, rh_y = frame_features_sorted[rh_x_idx], frame_features_sorted[rh_y_idx]
|
| 88 |
+
|
| 89 |
+
mid_shoulder_x, mid_shoulder_y = np.nan, np.nan
|
| 90 |
+
valid_ls = ls_c > min_confidence
|
| 91 |
+
valid_rs = rs_c > min_confidence
|
| 92 |
+
if valid_ls and valid_rs:
|
| 93 |
+
mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2
|
| 94 |
+
elif valid_ls:
|
| 95 |
+
mid_shoulder_x, mid_shoulder_y = ls_x, ls_y
|
| 96 |
+
elif valid_rs:
|
| 97 |
+
mid_shoulder_x, mid_shoulder_y = rs_x, rs_y
|
| 98 |
+
|
| 99 |
+
mid_hip_x, mid_hip_y = np.nan, np.nan
|
| 100 |
+
valid_lh = lh_c > min_confidence
|
| 101 |
+
valid_rh = rh_c > min_confidence
|
| 102 |
+
if valid_lh and valid_rh:
|
| 103 |
+
mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2
|
| 104 |
+
elif valid_lh:
|
| 105 |
+
mid_hip_x, mid_hip_y = lh_x, lh_y
|
| 106 |
+
elif valid_rh:
|
| 107 |
+
mid_hip_x, mid_hip_y = rh_x, rh_y
|
| 108 |
+
|
| 109 |
+
ref_x, ref_y = np.nan, np.nan
|
| 110 |
+
if not np.isnan(mid_shoulder_x) and not np.isnan(mid_hip_x):
|
| 111 |
+
ref_x = (mid_shoulder_x + mid_hip_x) / 2
|
| 112 |
+
ref_y = (mid_shoulder_y + mid_hip_y) / 2
|
| 113 |
+
elif not np.isnan(mid_shoulder_x):
|
| 114 |
+
ref_x, ref_y = mid_shoulder_x, mid_shoulder_y
|
| 115 |
+
elif not np.isnan(mid_hip_x):
|
| 116 |
+
ref_x, ref_y = mid_hip_x, mid_hip_y
|
| 117 |
+
|
| 118 |
+
scale = 1.0
|
| 119 |
+
if not np.isnan(mid_shoulder_x) and not np.isnan(mid_hip_x):
|
| 120 |
+
torso_height = np.sqrt((mid_shoulder_x - mid_hip_x)**2 + (mid_shoulder_y - mid_hip_y)**2)
|
| 121 |
+
if torso_height > 1e-6:
|
| 122 |
+
scale = torso_height
|
| 123 |
+
|
| 124 |
+
if np.isnan(ref_x):
|
| 125 |
+
return frame_features_sorted
|
| 126 |
+
|
| 127 |
+
for kp_name in SORTED_YOUR_KEYPOINT_NAMES:
|
| 128 |
+
x_idx, y_idx, c_idx = get_kpt_indices_training_order(kp_name)
|
| 129 |
+
if frame_features_sorted[c_idx] > min_confidence:
|
| 130 |
+
normalized_frame[x_idx] = (frame_features_sorted[x_idx] - ref_x) / scale
|
| 131 |
+
normalized_frame[y_idx] = (frame_features_sorted[y_idx] - ref_y) / scale
|
| 132 |
+
else:
|
| 133 |
+
normalized_frame[x_idx] = 0.0
|
| 134 |
+
normalized_frame[y_idx] = 0.0
|
| 135 |
+
|
| 136 |
+
return normalized_frame
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def extract_features_from_yolo_result(result, frame_width, frame_height):
|
| 140 |
+
frame_features = np.zeros(NUM_FEATURES, dtype=np.float32)
|
| 141 |
+
|
| 142 |
+
if result.keypoints is None or len(result.keypoints) == 0:
|
| 143 |
+
return frame_features
|
| 144 |
+
|
| 145 |
+
if result.boxes is not None and len(result.boxes) > 0:
|
| 146 |
+
areas = result.boxes.xywh[:, 2] * result.boxes.xywh[:, 3]
|
| 147 |
+
best_idx = int(areas.argmax())
|
| 148 |
+
else:
|
| 149 |
+
best_idx = 0
|
| 150 |
+
|
| 151 |
+
kps = result.keypoints[best_idx]
|
| 152 |
+
kps_data = kps.data[0].cpu().numpy() # (17, 3)
|
| 153 |
+
|
| 154 |
+
for yolo_idx, kp_name in YOLO_IDX_TO_NAME.items():
|
| 155 |
+
x_norm = kps_data[yolo_idx, 0] / frame_width
|
| 156 |
+
y_norm = kps_data[yolo_idx, 1] / frame_height
|
| 157 |
+
conf = float(kps_data[yolo_idx, 2])
|
| 158 |
+
x_idx, y_idx, c_idx = get_kpt_indices_training_order(kp_name)
|
| 159 |
+
frame_features[x_idx] = x_norm
|
| 160 |
+
frame_features[y_idx] = y_norm
|
| 161 |
+
frame_features[c_idx] = conf
|
| 162 |
+
|
| 163 |
+
frame_features = normalize_skeleton_frame(frame_features)
|
| 164 |
+
return frame_features
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@spaces.GPU(duration=300) # allocate GPU for the full video processing window
|
| 168 |
+
def run_fall_detection_on_video(video_path, progress=gr.Progress(track_tqdm=True)):
|
| 169 |
+
if video_path is None:
|
| 170 |
+
return None, "Please upload a video file."
|
| 171 |
+
|
| 172 |
+
cap = cv2.VideoCapture(video_path)
|
| 173 |
+
if not cap.isOpened():
|
| 174 |
+
return None, f"Error: Cannot open video: {video_path}"
|
| 175 |
+
|
| 176 |
+
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 177 |
+
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 178 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
|
| 179 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 180 |
+
|
| 181 |
+
# Unique temp file per request — prevents concurrent users overwriting each other
|
| 182 |
+
fd, output_path = tempfile.mkstemp(suffix=".mp4", prefix="fall_detection_", dir=tempfile.gettempdir())
|
| 183 |
+
os.close(fd)
|
| 184 |
+
fourcc = cv2.VideoWriter_fourcc(*"avc1") # H.264 — playable in browsers
|
| 185 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))
|
| 186 |
+
# Fallback: if avc1 is unavailable (OpenCV build without H.264), try mp4v
|
| 187 |
+
if not out.isOpened():
|
| 188 |
+
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
|
| 189 |
+
out = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))
|
| 190 |
+
|
| 191 |
+
frame_buffer = deque(maxlen=INPUT_TIMESTEPS)
|
| 192 |
+
fall_event_count = 0
|
| 193 |
+
last_fall_frame = -FALL_EVENT_COOLDOWN * fps
|
| 194 |
+
frame_idx = 0
|
| 195 |
+
fall_detected_this_frame = False
|
| 196 |
+
fall_confidence_val = 0.0
|
| 197 |
+
|
| 198 |
+
print(f"Processing video: {video_path} ({total_frames} frames, {fps:.1f} fps)")
|
| 199 |
+
|
| 200 |
+
while True:
|
| 201 |
+
ret, frame = cap.read()
|
| 202 |
+
if not ret:
|
| 203 |
+
break
|
| 204 |
+
|
| 205 |
+
frame_idx += 1
|
| 206 |
+
fall_detected_this_frame = False
|
| 207 |
+
|
| 208 |
+
results = yolo_pose(frame, verbose=False, device="cuda")
|
| 209 |
+
result = results[0]
|
| 210 |
+
|
| 211 |
+
features = extract_features_from_yolo_result(result, frame_width, frame_height)
|
| 212 |
+
frame_buffer.append(features)
|
| 213 |
+
|
| 214 |
+
if len(frame_buffer) == INPUT_TIMESTEPS:
|
| 215 |
+
input_seq = np.array(frame_buffer, dtype=np.float32)[np.newaxis, ...]
|
| 216 |
+
interpreter.set_tensor(input_details[0]["index"], input_seq)
|
| 217 |
+
interpreter.invoke()
|
| 218 |
+
output_data = interpreter.get_tensor(output_details[0]["index"])
|
| 219 |
+
fall_confidence_val = float(output_data[0][0])
|
| 220 |
+
|
| 221 |
+
if (fall_confidence_val >= FALL_CONFIDENCE_THRESHOLD and
|
| 222 |
+
(frame_idx - last_fall_frame) >= FALL_EVENT_COOLDOWN * fps):
|
| 223 |
+
fall_detected_this_frame = True
|
| 224 |
+
fall_event_count += 1
|
| 225 |
+
last_fall_frame = frame_idx
|
| 226 |
+
print(f" FALL DETECTED at frame {frame_idx} | confidence: {fall_confidence_val:.4f}")
|
| 227 |
+
|
| 228 |
+
annotated_frame = result.plot(kpt_radius=4, line_width=2)
|
| 229 |
+
|
| 230 |
+
status_text = "FALL DETECTED!" if fall_detected_this_frame else "Normal"
|
| 231 |
+
conf_text = f"Conf: {fall_confidence_val:.2f}" if len(frame_buffer) == INPUT_TIMESTEPS else "Warming up..."
|
| 232 |
+
overlay_color = (0, 0, 255) if fall_detected_this_frame else (0, 200, 0)
|
| 233 |
+
|
| 234 |
+
cv2.rectangle(annotated_frame, (0, 0), (350, 70), (0, 0, 0), -1)
|
| 235 |
+
cv2.putText(annotated_frame, status_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, overlay_color, 2)
|
| 236 |
+
cv2.putText(annotated_frame, conf_text, (10, 58), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 1)
|
| 237 |
+
cv2.rectangle(annotated_frame, (frame_width - 200, 0), (frame_width, 40), (0, 0, 0), -1)
|
| 238 |
+
cv2.putText(annotated_frame, f"Falls: {fall_event_count}", (frame_width - 190, 28),
|
| 239 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 140, 255), 2)
|
| 240 |
+
|
| 241 |
+
out.write(annotated_frame)
|
| 242 |
+
|
| 243 |
+
cap.release()
|
| 244 |
+
out.release()
|
| 245 |
+
|
| 246 |
+
summary = (
|
| 247 |
+
f"Processing complete!\n"
|
| 248 |
+
f"Total frames processed : {frame_idx}\n"
|
| 249 |
+
f"Fall events detected : {fall_event_count}\n"
|
| 250 |
+
f"Threshold used : {FALL_CONFIDENCE_THRESHOLD:.0%}\n"
|
| 251 |
+
f"Model : YOLO26-pose + TFLite Transformer"
|
| 252 |
+
)
|
| 253 |
+
print(summary)
|
| 254 |
+
return output_path, summary
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
EXAMPLE_VIDEOS = [f for f in [
|
| 258 |
+
"fall_example_1.mp4", "fall_example_2.mp4",
|
| 259 |
+
"fall_example_3.mp4", "fall_example_4.mp4"
|
| 260 |
+
] if os.path.exists(f)]
|
| 261 |
+
|
| 262 |
+
with gr.Blocks(
|
| 263 |
+
title="Fall Detection - YOLO26 + Transformer",
|
| 264 |
+
theme=gr.themes.Soft(primary_hue="red"),
|
| 265 |
+
css="footer { display: none !important; }",
|
| 266 |
+
) as demo:
|
| 267 |
+
|
| 268 |
+
gr.Markdown(
|
| 269 |
+
"""
|
| 270 |
+
# Fall Detection System
|
| 271 |
+
### YOLO26-pose keypoint extraction + TFLite Transformer classifier
|
| 272 |
+
Upload a video. The system extracts 17-keypoint poses with YOLO26,
|
| 273 |
+
feeds a 30-frame sliding window into the Transformer, and flags falls >= 90% confidence.
|
| 274 |
+
"""
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
with gr.Row():
|
| 278 |
+
with gr.Column(scale=1):
|
| 279 |
+
video_input = gr.Video(label="Upload Video", sources=["upload"])
|
| 280 |
+
run_btn = gr.Button("Detect Falls", variant="primary", size="lg")
|
| 281 |
+
gr.Markdown(
|
| 282 |
+
f"**Pose Extractor:** YOLO26n-pose \n"
|
| 283 |
+
f"**Classifier:** TFLite Transformer \n"
|
| 284 |
+
f"**Sequence:** {INPUT_TIMESTEPS} frames \n"
|
| 285 |
+
f"**Threshold:** {FALL_CONFIDENCE_THRESHOLD:.0%} \n"
|
| 286 |
+
f"**Keypoints:** {NUM_KEYPOINTS_TRAINING} (COCO-17)"
|
| 287 |
+
)
|
| 288 |
+
with gr.Column(scale=1):
|
| 289 |
+
video_output = gr.Video(label="Annotated Output")
|
| 290 |
+
summary_output = gr.Textbox(label="Detection Summary", lines=6, interactive=False)
|
| 291 |
+
|
| 292 |
+
if EXAMPLE_VIDEOS:
|
| 293 |
+
gr.Markdown("### Example Videos")
|
| 294 |
+
gr.Examples(examples=[[v] for v in EXAMPLE_VIDEOS], inputs=video_input, label="Click to load")
|
| 295 |
+
|
| 296 |
+
run_btn.click(
|
| 297 |
+
fn=run_fall_detection_on_video,
|
| 298 |
+
inputs=[video_input],
|
| 299 |
+
outputs=[video_output, summary_output],
|
| 300 |
+
show_progress=True
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
if __name__ == "__main__":
|
| 304 |
+
demo.launch()
|
fall_detection_transformer.tflite
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c66659c3ac6d37c60469bee4d6f88cb2ac4976928bde6d46b19e7f851e8980b0
|
| 3 |
+
size 320912
|
fall_example_1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e56e913b1f25ac729706f14e5dd10075486502df255f4264848fa55118444554
|
| 3 |
+
size 1403572
|
fall_example_2.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f5465d2026051e583c7822fd7afe20dc919bd166400ca57204e23a6fb415b15e
|
| 3 |
+
size 1761879
|
fall_example_3.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3c3b0a93abe26f70ee2b46664dc06c65da0854c0a070389c051d2b2028cafa66
|
| 3 |
+
size 1175099
|
fall_example_4.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b3d7b18bd56e1ff54b9ad4c6368a7a5bd322b7c44abc6574bcf9167c535f89c
|
| 3 |
+
size 1710071
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spaces
|
| 2 |
+
gradio
|
| 3 |
+
opencv-python-headless
|
| 4 |
+
ultralytics
|
| 5 |
+
numpy
|
| 6 |
+
ai-edge-litert
|
yolo26n-pose.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb3bb8268828aeaf515cec23a4bfafd793944a86fe9af94ba7823609c14522a9
|
| 3 |
+
size 7878574
|