Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,117 +3,105 @@ import joblib
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
from collections import deque
|
| 6 |
-
import traceback
|
| 7 |
import os
|
|
|
|
| 8 |
|
| 9 |
-
# --- Load
|
| 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")) #
|
| 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 |
-
# ---
|
| 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 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
ROLLING_WINDOW = 3
|
| 30 |
feature_histories = {name: deque(maxlen=ROLLING_WINDOW) for name in feature_names if "rolling" in name}
|
| 31 |
|
| 32 |
-
# --- Prediction
|
| 33 |
-
def predict_fall(*
|
| 34 |
try:
|
| 35 |
-
# Initialize all features with 0
|
| 36 |
data = {name: 0 for name in feature_names}
|
| 37 |
|
| 38 |
-
# Set
|
| 39 |
-
for cat_feat in categorical_features:
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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 |
-
#
|
| 51 |
-
for
|
| 52 |
-
|
| 53 |
-
data[key] = value
|
| 54 |
|
| 55 |
-
#
|
| 56 |
for fname in feature_histories.keys():
|
| 57 |
base_name = fname.replace("rolling_", "").replace("_mean", "")
|
| 58 |
-
if base_name in
|
| 59 |
-
feature_histories[fname].append(
|
| 60 |
data[fname] = np.mean(feature_histories[fname]) if len(feature_histories[fname]) > 0 else 0
|
| 61 |
|
| 62 |
-
# Create
|
| 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 |
|
| 72 |
return f"Prediction: {prediction_label[0]}"
|
| 73 |
|
| 74 |
except Exception as e:
|
| 75 |
-
import traceback
|
| 76 |
tb = traceback.format_exc()
|
| 77 |
-
|
| 78 |
-
|
| 79 |
|
| 80 |
-
|
| 81 |
-
# --- Build Gradio Interface ---
|
| 82 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 83 |
gr.Markdown("# Fall Detection Model")
|
| 84 |
-
gr.Markdown("
|
| 85 |
|
| 86 |
inputs = []
|
| 87 |
|
| 88 |
-
# Add categorical dropdowns
|
| 89 |
for cat_feat in categorical_features:
|
| 90 |
inputs.append(
|
| 91 |
-
gr.Dropdown(
|
| 92 |
-
label=cat_feat,
|
| 93 |
-
choices=categories_map[cat_feat],
|
| 94 |
-
value=categories_map[cat_feat][0]
|
| 95 |
-
)
|
| 96 |
)
|
| 97 |
|
| 98 |
-
# Add
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
continue # skip one-hot encoded columns as they come from dropdowns
|
| 106 |
-
if feature in categorical_features:
|
| 107 |
-
continue # skip base categorical features (already added as dropdown)
|
| 108 |
-
# Add slider for hour/day features
|
| 109 |
-
if "hour" in feature.lower():
|
| 110 |
-
inputs.append(gr.Slider(0, 23, step=1, label=feature))
|
| 111 |
-
elif "day" in feature.lower():
|
| 112 |
-
inputs.append(gr.Slider(0, 6, step=1, label=feature))
|
| 113 |
else:
|
| 114 |
-
inputs.append(gr.Number(label=
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
output = gr.Textbox(label="Prediction Result")
|
| 117 |
gr.Button("Run Prediction").click(fn=predict_fall, inputs=inputs, outputs=output)
|
| 118 |
|
| 119 |
if __name__ == "__main__":
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
from collections import deque
|
|
|
|
| 6 |
import os
|
| 7 |
+
import traceback
|
| 8 |
|
| 9 |
+
# --- Load model and artifacts ---
|
| 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 feature columns
|
| 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 |
+
# --- Define categorical features and map categories ---
|
| 22 |
categorical_features = ['Movement Activity', 'Location', 'day_of_week']
|
| 23 |
+
categories_map = {cat: encoder.categories_[i].tolist() for i, cat in enumerate(categorical_features)}
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# --- Identify numeric features ---
|
| 26 |
+
# All features except categorical one-hot columns and base categorical feature names
|
| 27 |
+
one_hot_cols = []
|
| 28 |
+
for cat_feat in categorical_features:
|
| 29 |
+
one_hot_cols.extend([f"{cat_feat}_{val}" for val in categories_map[cat_feat]])
|
| 30 |
+
numeric_features = [f for f in feature_names if f not in one_hot_cols and f not in categorical_features]
|
| 31 |
+
|
| 32 |
+
# --- Rolling window setup (optional, remove if not needed) ---
|
| 33 |
ROLLING_WINDOW = 3
|
| 34 |
feature_histories = {name: deque(maxlen=ROLLING_WINDOW) for name in feature_names if "rolling" in name}
|
| 35 |
|
| 36 |
+
# --- Prediction function accepting positional args ---
|
| 37 |
+
def predict_fall(movement_activity, location, day_of_week, *numeric_values):
|
| 38 |
try:
|
|
|
|
| 39 |
data = {name: 0 for name in feature_names}
|
| 40 |
|
| 41 |
+
# Set one-hot encoded categorical features
|
| 42 |
+
for cat_feat, selected_value in zip(categorical_features, [movement_activity, location, day_of_week]):
|
| 43 |
+
# Reset all to 0
|
| 44 |
+
for cat in categories_map[cat_feat]:
|
| 45 |
+
col = f"{cat_feat}_{cat}"
|
| 46 |
+
data[col] = 0
|
| 47 |
+
# Set selected category to 1 if exists
|
|
|
|
| 48 |
selected_col = f"{cat_feat}_{selected_value}"
|
| 49 |
if selected_col in data:
|
| 50 |
data[selected_col] = 1
|
| 51 |
|
| 52 |
+
# Map numeric inputs to numeric features in order
|
| 53 |
+
for name, val in zip(numeric_features, numeric_values):
|
| 54 |
+
data[name] = val
|
|
|
|
| 55 |
|
| 56 |
+
# Update rolling feature means if applicable
|
| 57 |
for fname in feature_histories.keys():
|
| 58 |
base_name = fname.replace("rolling_", "").replace("_mean", "")
|
| 59 |
+
if base_name in numeric_features:
|
| 60 |
+
feature_histories[fname].append(data[base_name])
|
| 61 |
data[fname] = np.mean(feature_histories[fname]) if len(feature_histories[fname]) > 0 else 0
|
| 62 |
|
| 63 |
+
# Create DataFrame with exact feature columns
|
| 64 |
df = pd.DataFrame([data])[feature_names]
|
| 65 |
|
| 66 |
# Scale numerical features
|
| 67 |
df_scaled = scaler.transform(df)
|
| 68 |
|
| 69 |
+
# Predict using the model
|
| 70 |
prediction_encoded = model.predict(df_scaled)
|
| 71 |
prediction_label = encoder.inverse_transform(prediction_encoded)
|
| 72 |
|
| 73 |
return f"Prediction: {prediction_label[0]}"
|
| 74 |
|
| 75 |
except Exception as e:
|
|
|
|
| 76 |
tb = traceback.format_exc()
|
| 77 |
+
print(f"Prediction error:\n{tb}") # Print full traceback to console
|
| 78 |
+
return f"Error: {str(e)}\nSee console/logs for full traceback."
|
| 79 |
|
| 80 |
+
# --- Build Gradio interface ---
|
|
|
|
| 81 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 82 |
gr.Markdown("# Fall Detection Model")
|
| 83 |
+
gr.Markdown("Provide sensor data to predict fall detection.")
|
| 84 |
|
| 85 |
inputs = []
|
| 86 |
|
| 87 |
+
# Add categorical dropdowns in order
|
| 88 |
for cat_feat in categorical_features:
|
| 89 |
inputs.append(
|
| 90 |
+
gr.Dropdown(label=cat_feat, choices=categories_map[cat_feat], value=categories_map[cat_feat][0])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
)
|
| 92 |
|
| 93 |
+
# Add numeric inputs in order
|
| 94 |
+
for num_feat in numeric_features:
|
| 95 |
+
# Use slider for hour/day if applicable, else number input
|
| 96 |
+
if "hour" in num_feat.lower():
|
| 97 |
+
inputs.append(gr.Slider(0, 23, step=1, label=num_feat))
|
| 98 |
+
elif "day" in num_feat.lower():
|
| 99 |
+
inputs.append(gr.Slider(0, 6, step=1, label=num_feat))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
else:
|
| 101 |
+
inputs.append(gr.Number(label=num_feat))
|
| 102 |
+
|
| 103 |
+
output = gr.Textbox(label="Prediction Result", lines=10)
|
| 104 |
|
|
|
|
| 105 |
gr.Button("Run Prediction").click(fn=predict_fall, inputs=inputs, outputs=output)
|
| 106 |
|
| 107 |
if __name__ == "__main__":
|