Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,37 +4,26 @@ import pandas as pd
|
|
| 4 |
import numpy as np
|
| 5 |
from collections import deque
|
| 6 |
import traceback
|
|
|
|
| 7 |
|
| 8 |
# --- Load Required Files ---
|
| 9 |
try:
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
print("Model, scaler, encoder, and feature names loaded successfully.")
|
| 15 |
except FileNotFoundError as e:
|
| 16 |
print(f"Error: Missing file: {e}")
|
| 17 |
exit()
|
| 18 |
|
| 19 |
-
# ---
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
categorical_bases = set()
|
| 26 |
-
for col in feature_names:
|
| 27 |
-
if "_" in col and not col.startswith("rolling") and not col.replace('_', '').isdigit():
|
| 28 |
-
base = col.split("_")[0]
|
| 29 |
-
categorical_bases.add(base)
|
| 30 |
-
|
| 31 |
-
categorical_bases = list(categorical_bases)
|
| 32 |
-
|
| 33 |
-
# Build a dict: base feature name -> list of categories from encoder
|
| 34 |
-
categories_map = {}
|
| 35 |
-
for i, base in enumerate(['Movement Activity', 'Location', 'day_of_week']):
|
| 36 |
-
if i < len(encoder.categories_):
|
| 37 |
-
categories_map[base] = encoder.categories_[i].tolist()
|
| 38 |
|
| 39 |
# --- Rolling Window for Time-Series Features ---
|
| 40 |
ROLLING_WINDOW = 3
|
|
@@ -43,34 +32,40 @@ feature_histories = {name: deque(maxlen=ROLLING_WINDOW) for name in feature_name
|
|
| 43 |
# --- Prediction Function ---
|
| 44 |
def predict_fall(**kwargs):
|
| 45 |
try:
|
|
|
|
| 46 |
data = {name: 0 for name in feature_names}
|
| 47 |
|
| 48 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
for key, value in kwargs.items():
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
col_name = f"{key}_{cat}"
|
| 55 |
-
data[col_name] = 0
|
| 56 |
-
# Set selected category to 1
|
| 57 |
-
selected_col = f"{key}_{value}"
|
| 58 |
-
if selected_col in data:
|
| 59 |
-
data[selected_col] = 1
|
| 60 |
-
else:
|
| 61 |
-
# Numerical or rolling features
|
| 62 |
-
if key in data:
|
| 63 |
-
data[key] = value
|
| 64 |
-
|
| 65 |
-
# Rolling mean calculations
|
| 66 |
for fname in feature_histories.keys():
|
| 67 |
base_name = fname.replace("rolling_", "").replace("_mean", "")
|
| 68 |
if base_name in kwargs:
|
| 69 |
feature_histories[fname].append(kwargs[base_name])
|
| 70 |
data[fname] = np.mean(feature_histories[fname]) if len(feature_histories[fname]) > 0 else 0
|
| 71 |
|
|
|
|
| 72 |
df = pd.DataFrame([data])[feature_names]
|
|
|
|
|
|
|
| 73 |
df_scaled = scaler.transform(df)
|
|
|
|
|
|
|
| 74 |
prediction_encoded = model.predict(df_scaled)
|
| 75 |
prediction_label = encoder.inverse_transform(prediction_encoded)
|
| 76 |
|
|
@@ -79,34 +74,40 @@ def predict_fall(**kwargs):
|
|
| 79 |
except Exception as e:
|
| 80 |
return f"Error: {str(e)}\nTraceback:\n{traceback.format_exc()}"
|
| 81 |
|
| 82 |
-
# --- Gradio
|
| 83 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 84 |
gr.Markdown("# Fall Detection Model")
|
| 85 |
gr.Markdown("Enter sensor data to check for fall detection.")
|
| 86 |
|
| 87 |
inputs = []
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
value=categories_map[feature][0]
|
| 97 |
-
)
|
| 98 |
)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
else:
|
| 103 |
-
|
| 104 |
-
if "hour" in feature.lower():
|
| 105 |
-
inputs.append(gr.Slider(0, 23, step=1, label=feature))
|
| 106 |
-
elif "day" in feature.lower():
|
| 107 |
-
inputs.append(gr.Slider(0, 6, step=1, label=feature))
|
| 108 |
-
else:
|
| 109 |
-
inputs.append(gr.Number(label=feature))
|
| 110 |
|
| 111 |
output = gr.Textbox(label="Prediction Result")
|
| 112 |
gr.Button("Run Prediction").click(fn=predict_fall, inputs=inputs, outputs=output)
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
from collections import deque
|
| 6 |
import traceback
|
| 7 |
+
import os
|
| 8 |
|
| 9 |
# --- Load Required Files ---
|
| 10 |
try:
|
| 11 |
+
app_dir = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
model = joblib.load(os.path.join(app_dir, "fall_detection_model.joblib"))
|
| 13 |
+
scaler = joblib.load(os.path.join(app_dir, "scaler.joblib"))
|
| 14 |
+
encoder = joblib.load(os.path.join(app_dir, "encoder.joblib"))
|
| 15 |
+
feature_names = joblib.load(os.path.join(app_dir, "feature_names.joblib")) # List of features in correct order
|
| 16 |
print("Model, scaler, encoder, and feature names loaded successfully.")
|
| 17 |
except FileNotFoundError as e:
|
| 18 |
print(f"Error: Missing file: {e}")
|
| 19 |
exit()
|
| 20 |
|
| 21 |
+
# --- Categorical Features and Their Categories ---
|
| 22 |
+
categorical_features = ['Movement Activity', 'Location', 'day_of_week']
|
| 23 |
+
categories_map = {
|
| 24 |
+
cat_feat: encoder.categories_[i].tolist()
|
| 25 |
+
for i, cat_feat in enumerate(categorical_features)
|
| 26 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
# --- Rolling Window for Time-Series Features ---
|
| 29 |
ROLLING_WINDOW = 3
|
|
|
|
| 32 |
# --- Prediction Function ---
|
| 33 |
def predict_fall(**kwargs):
|
| 34 |
try:
|
| 35 |
+
# Initialize all features with 0
|
| 36 |
data = {name: 0 for name in feature_names}
|
| 37 |
|
| 38 |
+
# Set categorical one-hot columns based on dropdown selections
|
| 39 |
+
for cat_feat in categorical_features:
|
| 40 |
+
selected_value = kwargs.get(cat_feat)
|
| 41 |
+
# Reset all one-hot columns for this feature to 0
|
| 42 |
+
for category in categories_map[cat_feat]:
|
| 43 |
+
col_name = f"{cat_feat}_{category}"
|
| 44 |
+
data[col_name] = 0
|
| 45 |
+
# Set selected category to 1 if column exists
|
| 46 |
+
selected_col = f"{cat_feat}_{selected_value}"
|
| 47 |
+
if selected_col in data:
|
| 48 |
+
data[selected_col] = 1
|
| 49 |
+
|
| 50 |
+
# Set numeric and rolling features
|
| 51 |
for key, value in kwargs.items():
|
| 52 |
+
if key not in categorical_features:
|
| 53 |
+
data[key] = value
|
| 54 |
+
|
| 55 |
+
# Compute rolling averages for rolling features
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
for fname in feature_histories.keys():
|
| 57 |
base_name = fname.replace("rolling_", "").replace("_mean", "")
|
| 58 |
if base_name in kwargs:
|
| 59 |
feature_histories[fname].append(kwargs[base_name])
|
| 60 |
data[fname] = np.mean(feature_histories[fname]) if len(feature_histories[fname]) > 0 else 0
|
| 61 |
|
| 62 |
+
# Create dataframe with exact feature columns
|
| 63 |
df = pd.DataFrame([data])[feature_names]
|
| 64 |
+
|
| 65 |
+
# Scale numerical features
|
| 66 |
df_scaled = scaler.transform(df)
|
| 67 |
+
|
| 68 |
+
# Predict
|
| 69 |
prediction_encoded = model.predict(df_scaled)
|
| 70 |
prediction_label = encoder.inverse_transform(prediction_encoded)
|
| 71 |
|
|
|
|
| 74 |
except Exception as e:
|
| 75 |
return f"Error: {str(e)}\nTraceback:\n{traceback.format_exc()}"
|
| 76 |
|
| 77 |
+
# --- Build Gradio Interface ---
|
| 78 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 79 |
gr.Markdown("# Fall Detection Model")
|
| 80 |
gr.Markdown("Enter sensor data to check for fall detection.")
|
| 81 |
|
| 82 |
inputs = []
|
| 83 |
|
| 84 |
+
# Add categorical dropdowns first
|
| 85 |
+
for cat_feat in categorical_features:
|
| 86 |
+
inputs.append(
|
| 87 |
+
gr.Dropdown(
|
| 88 |
+
label=cat_feat,
|
| 89 |
+
choices=categories_map[cat_feat],
|
| 90 |
+
value=categories_map[cat_feat][0]
|
|
|
|
|
|
|
| 91 |
)
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
# Add remaining numeric inputs (skip one-hot columns)
|
| 95 |
+
one_hot_cols = []
|
| 96 |
+
for cat_feat in categorical_features:
|
| 97 |
+
one_hot_cols.extend([f"{cat_feat}_{cat}" for cat in categories_map[cat_feat]])
|
| 98 |
+
|
| 99 |
+
for feature in feature_names:
|
| 100 |
+
if feature in one_hot_cols:
|
| 101 |
+
continue # skip one-hot encoded columns as they come from dropdowns
|
| 102 |
+
if feature in categorical_features:
|
| 103 |
+
continue # skip base categorical features (already added as dropdown)
|
| 104 |
+
# Add slider for hour/day features
|
| 105 |
+
if "hour" in feature.lower():
|
| 106 |
+
inputs.append(gr.Slider(0, 23, step=1, label=feature))
|
| 107 |
+
elif "day" in feature.lower():
|
| 108 |
+
inputs.append(gr.Slider(0, 6, step=1, label=feature))
|
| 109 |
else:
|
| 110 |
+
inputs.append(gr.Number(label=feature))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
output = gr.Textbox(label="Prediction Result")
|
| 113 |
gr.Button("Run Prediction").click(fn=predict_fall, inputs=inputs, outputs=output)
|