jialitan23 commited on
Commit
a8152c2
·
verified ·
1 Parent(s): 187e243

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -58
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 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
30
  feature_histories = {name: deque(maxlen=ROLLING_WINDOW) for name in feature_names if "rolling" in name}
31
 
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
 
72
  return f"Prediction: {prediction_label[0]}"
73
 
74
  except Exception as e:
75
- import traceback
76
  tb = traceback.format_exc()
77
- return f"Error: {str(e)}\nTraceback:\n{tb}"
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("Enter sensor data to check for fall detection.")
85
 
86
  inputs = []
87
 
88
- # Add categorical dropdowns first
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 remaining numeric inputs (skip one-hot columns)
99
- one_hot_cols = []
100
- for cat_feat in categorical_features:
101
- one_hot_cols.extend([f"{cat_feat}_{cat}" for cat in categories_map[cat_feat]])
102
-
103
- for feature in feature_names:
104
- if feature in one_hot_cols:
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=feature))
 
 
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__":