jialitan23 commited on
Commit
1c5e834
·
verified ·
1 Parent(s): a95d0db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -25
app.py CHANGED
@@ -2,66 +2,66 @@ import gradio as gr
2
  import joblib
3
  import pandas as pd
4
 
5
- # Load saved objects
6
  model = joblib.load('fall_detection_model.joblib')
7
  scaler = joblib.load('scaler.joblib')
8
  encoder = joblib.load('encoder.joblib')
9
- feature_names = joblib.load('feature_names.joblib') # make sure this has hour_of_day and minute_of_day
 
 
 
 
 
10
 
11
  def predict_fall(movement_activity, location, day_of_week, hour_of_day, minute_of_day, time_since_last_event):
12
  try:
13
- # Initialize all features with zero
14
- data = {f: 0 for f in feature_names}
15
 
16
  # One-hot encode categoricals
17
  data[f'Movement Activity_{movement_activity}'] = 1
18
  data[f'Location_{location}'] = 1
19
  data[f'day_of_week_{day_of_week}'] = 1
20
 
21
- # Set numerical features
22
  data['hour_of_day'] = hour_of_day
23
  data['minute_of_day'] = minute_of_day
24
  data['time_since_last_event'] = time_since_last_event
25
 
26
- # Build DataFrame with columns ordered as feature_names
27
  input_df = pd.DataFrame([data], columns=feature_names)
28
 
29
- # Scale numeric features
30
  scaled_array = scaler.transform(input_df)
31
  input_df.loc[:, feature_names] = scaled_array
32
 
33
- # Predict probability
34
- pred_proba = model.predict_proba(input_df)[0, 1]
 
35
  threshold = 0.4
36
- pred_label = "Fall Detected" if pred_proba >= threshold else "No Fall"
37
 
38
- return f"Prediction: {pred_label}\nFall Probability: {pred_proba:.2f}"
39
 
40
  except Exception as e:
41
  import traceback
42
- tb = traceback.format_exc()
43
- print("Error in prediction:\n", tb)
44
- return f"Error: {str(e)}\nCheck server logs for details."
45
-
46
- # Prepare dropdown choices from encoder categories
47
- movement_choices = encoder.categories_[0].tolist()
48
- location_choices = encoder.categories_[1].tolist()
49
- day_choices = [col.replace('day_of_week_', '') for col in feature_names if col.startswith('day_of_week_')]
50
 
51
- # Gradio Interface
52
  iface = gr.Interface(
53
  fn=predict_fall,
54
  inputs=[
55
- gr.Dropdown(choices=movement_choices, label="Movement Activity"),
56
- gr.Dropdown(choices=location_choices, label="Location"),
57
- gr.Dropdown(choices=day_choices, label="Day of Week"),
58
  gr.Slider(0, 23, step=1, label="Hour of Day"),
59
  gr.Slider(0, 59, step=1, label="Minute of Day"),
60
- gr.Number(label="Time Since Last Event (seconds)", value=60)
61
  ],
62
  outputs="text",
63
  title="Fall Detection Model",
64
- description="Predicts fall based on sensor data."
65
  )
66
 
67
  if __name__ == "__main__":
 
2
  import joblib
3
  import pandas as pd
4
 
5
+ # Load model artifacts
6
  model = joblib.load('fall_detection_model.joblib')
7
  scaler = joblib.load('scaler.joblib')
8
  encoder = joblib.load('encoder.joblib')
9
+ feature_names = joblib.load('feature_names.joblib') # your full feature list
10
+
11
+ # Extract categories for dropdown menus
12
+ movement_choices = encoder.categories_[0].tolist()
13
+ location_choices = encoder.categories_[1].tolist()
14
+ day_choices = [col.replace('day_of_week_', '') for col in feature_names if col.startswith('day_of_week_')]
15
 
16
  def predict_fall(movement_activity, location, day_of_week, hour_of_day, minute_of_day, time_since_last_event):
17
  try:
18
+ # Initialize all features to 0
19
+ data = {feat: 0 for feat in feature_names}
20
 
21
  # One-hot encode categoricals
22
  data[f'Movement Activity_{movement_activity}'] = 1
23
  data[f'Location_{location}'] = 1
24
  data[f'day_of_week_{day_of_week}'] = 1
25
 
26
+ # Set numeric features
27
  data['hour_of_day'] = hour_of_day
28
  data['minute_of_day'] = minute_of_day
29
  data['time_since_last_event'] = time_since_last_event
30
 
31
+ # Build DataFrame with columns in correct order
32
  input_df = pd.DataFrame([data], columns=feature_names)
33
 
34
+ # Scale all features (must match scaler's expected input columns)
35
  scaled_array = scaler.transform(input_df)
36
  input_df.loc[:, feature_names] = scaled_array
37
 
38
+ # Predict probability of fall
39
+ prob_fall = model.predict_proba(input_df)[:, 1][0]
40
+
41
  threshold = 0.4
42
+ prediction = "Fall Detected" if prob_fall >= threshold else "No Fall"
43
 
44
+ return f"Prediction: {prediction}\nFall Probability: {prob_fall:.2f}"
45
 
46
  except Exception as e:
47
  import traceback
48
+ traceback.print_exc()
49
+ return f"Error: {str(e)}. Check logs for details."
 
 
 
 
 
 
50
 
51
+ # Gradio interface setup
52
  iface = gr.Interface(
53
  fn=predict_fall,
54
  inputs=[
55
+ gr.Dropdown(movement_choices, label="Movement Activity"),
56
+ gr.Dropdown(location_choices, label="Location"),
57
+ gr.Dropdown(day_choices, label="Day of Week"),
58
  gr.Slider(0, 23, step=1, label="Hour of Day"),
59
  gr.Slider(0, 59, step=1, label="Minute of Day"),
60
+ gr.Number(label="Time Since Last Event (seconds)", value=60),
61
  ],
62
  outputs="text",
63
  title="Fall Detection Model",
64
+ description="Predicts if a fall is detected based on sensor input."
65
  )
66
 
67
  if __name__ == "__main__":