jialitan23 commited on
Commit
f46ccbe
·
verified ·
1 Parent(s): 21674d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -59
app.py CHANGED
@@ -3,106 +3,124 @@ import joblib
3
  import pandas as pd
4
  import os
5
  import numpy as np
 
6
 
7
- # --- Load the Model and Preprocessing Tools ---
8
  model = None
9
  scaler = None
10
  encoder = None
11
- all_feature_columns = None
12
- PREDICTION_THRESHOLD = 0.4
13
 
14
- # List of categorical and numerical features used during training
 
15
  features_to_encode = ['Movement Activity', 'Location', 'day_of_week']
16
- numerical_features = ['time_since_last_event']
17
 
 
18
  try:
 
19
  app_dir = os.path.dirname(os.path.abspath(__file__))
 
 
 
 
 
 
20
 
21
- # Load the model and preprocessing objects
22
- model = joblib.load(os.path.join(app_dir, 'fall_detection_model.joblib'))
23
- scaler = joblib.load(os.path.join(app_dir, 'scaler.joblib'))
24
- encoder = joblib.load(os.path.join(app_dir, 'encoder.joblib'))
25
 
26
- # ----------------------------------------------------
27
- # NEW FIX: Build the full list of feature names directly from the loaded encoder.
28
- # This is the most reliable method to ensure consistency.
29
- # ----------------------------------------------------
30
- encoded_feature_names = encoder.get_feature_names_out(features_to_encode)
31
- all_feature_columns = encoded_feature_names.tolist() + numerical_features
32
 
33
- print("Model, preprocessing tools, and feature names loaded successfully!")
 
 
 
 
 
 
34
 
35
  except FileNotFoundError as e:
36
- print(f"Error: A required file was not found. Please ensure all model artifacts are in the same directory as the 'app.py' script. {e}")
 
 
37
  except Exception as e:
38
- print(f"An unexpected error occurred during model loading: {e}")
 
39
 
40
- # --- Prediction Function for Gradio ---
41
- def predict_fall(movement_activity, location, day_of_week, time_since_last_event):
42
- if model is None or all_feature_columns is None:
43
- return "Error: Model not loaded. Check server logs."
 
 
 
44
 
45
  try:
46
- # Create a dictionary to build the input DataFrame with all required columns
47
- input_data = {}
48
- for col in all_feature_columns:
49
- input_data[col] = 0.0 # Initialize all columns to 0.0
 
 
 
 
 
50
 
51
- # Populate the dictionary with the user's input, setting the one-hot encoded
52
- # columns to 1.0. This prevents the KeyError.
53
  input_data[f'Movement Activity_{movement_activity}'] = 1.0
54
  input_data[f'Location_{location}'] = 1.0
55
  input_data[f'day_of_week_{day_of_week}'] = 1.0
56
- input_data['time_since_last_event'] = float(time_since_last_event)
57
 
58
- # Create the DataFrame in the exact order the model expects
59
- processed_df = pd.DataFrame([input_data], columns=all_feature_columns)
60
 
61
- # Scale the numerical feature
62
- processed_df[numerical_features] = scaler.transform(processed_df[numerical_features])
63
 
64
- # --- Prediction ---
65
- fall_probability = model.predict_proba(processed_df)[:, 1][0]
66
- prediction = 'Fall Detected' if fall_probability >= PREDICTION_THRESHOLD else 'No Fall'
67
 
68
  return f"Prediction: {prediction}\nFall Probability: {fall_probability:.2f}"
69
 
70
  except Exception as e:
71
- return f"An error occurred during prediction: {e}"
 
 
 
 
 
 
 
72
 
73
- # --- Gradio Interface Setup ---
74
- if model is not None and encoder is not None and all_feature_columns is not None:
75
  inputs = [
76
- gr.Dropdown(
77
- choices=encoder.categories_[0].tolist(),
78
- label="Movement Activity",
79
- value=encoder.categories_[0].tolist()[0]
80
- ),
81
- gr.Dropdown(
82
- choices=encoder.categories_[1].tolist(),
83
- label="Location",
84
- value=encoder.categories_[1].tolist()[0]
85
- ),
86
- gr.Dropdown(
87
- choices=encoder.categories_[2].tolist(),
88
- label="Day of Week",
89
- value=encoder.categories_[2].tolist()[0]
90
- ),
91
- gr.Number(label="Time Since Last Event (in seconds)", value=60)
92
  ]
93
 
94
  outputs = gr.Textbox(label="Prediction Result")
95
 
96
- iface = gr.Interface(
97
  fn=predict_fall,
98
  inputs=inputs,
99
  outputs=outputs,
100
  title="Fall Detection Model",
101
- description="This model predicts the likelihood of a fall based on sensor data. A fall is detected if the probability is >= 0.4.",
102
  theme="huggingface"
103
  )
104
 
 
105
  if __name__ == "__main__":
106
- iface.launch()
107
  else:
108
- print("Failed to launch Gradio app due to missing model artifacts.")
 
 
3
  import pandas as pd
4
  import os
5
  import numpy as np
6
+ import traceback
7
 
8
+ # --- 1. Define Model and Preprocessing Components ---
9
  model = None
10
  scaler = None
11
  encoder = None
12
+ prediction_threshold = 0.5 # Default threshold, will be updated from file
 
13
 
14
+ # Lists of categorical and numerical features used during model training
15
+ # These lists are hardcoded to match the training process.
16
  features_to_encode = ['Movement Activity', 'Location', 'day_of_week']
17
+ numerical_features = ['hour_of_day', 'minute_of_day', 'time_since_last_event']
18
 
19
+ # --- 2. Load the Model and Preprocessing Tools with Error Handling ---
20
  try:
21
+ # Get the directory of the script to correctly locate model files
22
  app_dir = os.path.dirname(os.path.abspath(__file__))
23
+
24
+ # Load all the necessary model artifacts
25
+ model_path = os.path.join(app_dir, 'fall_detection_model.joblib')
26
+ scaler_path = os.path.join(app_dir, 'scaler.joblib')
27
+ encoder_path = os.path.join(app_dir, 'encoder.joblib')
28
+ threshold_path = os.path.join(app_dir, 'prediction_threshold.txt')
29
 
30
+ model = joblib.load(model_path)
31
+ scaler = joblib.load(scaler_path)
32
+ encoder = joblib.load(encoder_path)
 
33
 
34
+ # Read the prediction threshold from the text file
35
+ with open(threshold_path, 'r') as f:
36
+ prediction_threshold = float(f.read().strip())
 
 
 
37
 
38
+ print("All model and preprocessing files loaded successfully.")
39
+
40
+ # --- 3. Dynamically build the feature column list ---
41
+ # This is a crucial step to avoid errors and ensure consistency.
42
+ encoded_feature_names = encoder.get_feature_names_out(features_to_encode)
43
+ all_feature_columns = np.concatenate([encoded_feature_names, numerical_features])
44
+ print("Full list of feature names created.")
45
 
46
  except FileNotFoundError as e:
47
+ print(f"Error: A required file was not found. Please ensure all model artifacts "
48
+ f"are in the same directory as this script. Missing file: {e.filename}")
49
+ model = None # Set model to None to prevent app from launching
50
  except Exception as e:
51
+ print(f"An unexpected error occurred during file loading: {e}\n{traceback.format_exc()}")
52
+ model = None
53
 
54
+ # --- 4. Prediction Function for Gradio ---
55
+ def predict_fall(movement_activity, location, day_of_week, hour_of_day, minute_of_day, time_since_last_event):
56
+ """
57
+ Takes user inputs and uses the loaded model to predict the likelihood of a fall.
58
+ """
59
+ if model is None:
60
+ return "Error: Model not loaded. Check server logs for details."
61
 
62
  try:
63
+ # Create a dictionary to hold the input data.
64
+ # It is important to initialize with all features set to 0.0 to match the model's
65
+ # expected input shape, especially for one-hot encoded columns.
66
+ input_data = {col: 0.0 for col in all_feature_columns}
67
+
68
+ # Populate the numerical features
69
+ input_data['hour_of_day'] = float(hour_of_day)
70
+ input_data['minute_of_day'] = float(minute_of_day)
71
+ input_data['time_since_last_event'] = float(time_since_last_event)
72
 
73
+ # Populate the one-hot encoded features
74
+ # We need to construct the correct column name for the one-hot encoded features
75
  input_data[f'Movement Activity_{movement_activity}'] = 1.0
76
  input_data[f'Location_{location}'] = 1.0
77
  input_data[f'day_of_week_{day_of_week}'] = 1.0
 
78
 
79
+ # Create a DataFrame from the dictionary, ensuring the column order is correct
80
+ input_df = pd.DataFrame([input_data], columns=all_feature_columns)
81
 
82
+ # Scale the numerical features using the loaded scaler
83
+ input_df[numerical_features] = scaler.transform(input_df[numerical_features])
84
 
85
+ # Make the prediction
86
+ fall_probability = model.predict_proba(input_df)[:, 1][0]
87
+ prediction = 'Fall Detected' if fall_probability >= prediction_threshold else 'No Fall'
88
 
89
  return f"Prediction: {prediction}\nFall Probability: {fall_probability:.2f}"
90
 
91
  except Exception as e:
92
+ return f"An error occurred during prediction: {e}\n{traceback.format_exc()}"
93
+
94
+ # --- 5. Gradio Interface Setup ---
95
+ if model is not None:
96
+ # Use the encoder's categories to populate the dropdown choices for a consistent experience
97
+ movement_choices = encoder.categories_[0].tolist()
98
+ location_choices = encoder.categories_[1].tolist()
99
+ day_choices = encoder.categories_[2].tolist()
100
 
 
 
101
  inputs = [
102
+ gr.Dropdown(choices=movement_choices, label="Movement Activity"),
103
+ gr.Dropdown(choices=location_choices, label="Location"),
104
+ gr.Dropdown(choices=day_choices, label="Day of Week"),
105
+ gr.Number(label="Hour of Day (0-23)", value=12),
106
+ gr.Number(label="Minute of Day (0-59)", value=30),
107
+ gr.Number(label="Time Since Last Event (in seconds)", value=3600)
 
 
 
 
 
 
 
 
 
 
108
  ]
109
 
110
  outputs = gr.Textbox(label="Prediction Result")
111
 
112
+ demo = gr.Interface(
113
  fn=predict_fall,
114
  inputs=inputs,
115
  outputs=outputs,
116
  title="Fall Detection Model",
117
+ description=f"This model predicts the likelihood of a fall. A fall is detected if the probability is >= {prediction_threshold}.",
118
  theme="huggingface"
119
  )
120
 
121
+ # --- 6. Launch the Gradio App ---
122
  if __name__ == "__main__":
123
+ demo.launch()
124
  else:
125
+ print("Gradio app cannot be launched due to errors during model loading.")
126
+