jialitan23 commited on
Commit
a5bd7b3
·
verified ·
1 Parent(s): 58d830e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -60
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
- model = joblib.load("fall_detection_model.joblib")
11
- scaler = joblib.load("scaler.joblib")
12
- encoder = joblib.load("encoder.joblib")
13
- feature_names = joblib.load("feature_names.joblib") # List of features in correct order
 
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
- # --- Prepare category mappings for dropdowns ---
20
- # This assumes encoder.categories_ order matches the features that have one-hot encoded columns
21
- # We'll infer categories from encoder to create dropdowns for each categorical feature
22
-
23
- # Extract base categorical feature names from feature_names
24
- # They usually look like "Movement Activity_Lying" => base "Movement Activity"
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
- # Fill numeric and categorical values from kwargs
 
 
 
 
 
 
 
 
 
 
 
 
49
  for key, value in kwargs.items():
50
- # For categorical base features, set the corresponding one-hot column to 1
51
- if key in categories_map:
52
- # Reset all one-hot columns for this base to 0
53
- for cat in categories_map[key]:
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 UI ---
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
- for feature in feature_names:
90
- # Check if feature is categorical base
91
- if feature in categorical_bases:
92
- inputs.append(
93
- gr.Dropdown(
94
- choices=categories_map[feature],
95
- label=feature,
96
- value=categories_map[feature][0]
97
- )
98
  )
99
- elif any(feature.startswith(f"{base}_") for base in categorical_bases):
100
- # Skip one-hot encoded columns, already handled by dropdown
101
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  else:
103
- # Numerical inputs
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)