ML-Project / app.py
jialitan23's picture
Update app.py
0d61f16 verified
import gradio as gr
import pandas as pd
import joblib
import os
import warnings
import imblearn
# Suppress the FutureWarning from pandas
warnings.simplefilter(action='ignore', category=FutureWarning)
# --- Gradio App Components ---
# List of possible values for the dropdown menus
locations = ['Bathroom', 'Bedroom', 'Kitchen', 'Living Room']
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# Load the trained model pipeline from the joblib file
try:
# Load the complete pipeline, which includes the pre-processors and the model
model_pipeline = joblib.load('fall_detection_pipeline.joblib')
# Load the final prediction threshold
with open('prediction_threshold.txt', 'r') as f:
threshold = float(f.read())
print("Model and threshold loaded successfully.")
except FileNotFoundError as e:
model_pipeline = None
threshold = 0.4 # Default threshold in case of loading error
print(f"Error: {e}. Model files not found. The app will run in a placeholder mode.")
except Exception as e:
model_pipeline = None
threshold = 0.4
print(f"An unexpected error occurred while loading files: {e}. The app will run in a placeholder mode.")
def predict_fall(location, day_of_week, hour_of_day, minute_of_day, time_since_last_event):
"""
Makes a fall prediction based on user inputs using the pre-trained model.
The function expects raw inputs and the pipeline handles all transformations.
"""
# Check if the model was loaded successfully. If not, return an error message.
if model_pipeline is None:
return "Prediction model not available. Please ensure model files are correctly saved."
try:
# Create a dictionary to hold the feature values based on the original data columns.
# This is the format the pipeline expects.
# The 'Movement Activity' column is not used based on previous analysis, but
# we can include it if the model requires it. For now, let's stick to the features
# identified in the previous steps.
# The feature names from the notebook cells were:
# ['Location', 'day_of_week', 'hour_of_day', 'minute_of_day', 'time_since_last_event']
# Create a DataFrame from the inputs
input_data = pd.DataFrame([{
'Location': location,
'day_of_week': day_of_week,
'hour_of_day': hour_of_day,
'minute_of_day': minute_of_day,
'time_since_last_event': time_since_last_event
}])
# Use the trained pipeline to get the probability. The pipeline
# automatically handles the scaling and one-hot encoding.
pred_proba = model_pipeline.predict_proba(input_data)[0, 1]
# Get the final prediction label based on the threshold.
pred_label = "Fall Detected" if pred_proba >= threshold else "No Fall"
return f"Prediction: {pred_label}\nFall Probability: {pred_proba:.2f}"
except Exception as e:
import traceback
traceback.print_exc()
return f"An error occurred during prediction: {str(e)}"
# Define the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("## Elderly Fall Prediction System")
gr.Markdown("This system uses a trained machine learning model to predict the likelihood of a fall based on behavioral data. **Note:** This is a demonstration and should not be used for medical diagnosis.")
with gr.Row():
location_input = gr.Dropdown(choices=locations, label="Location", value='Living Room')
day_input = gr.Dropdown(choices=days_of_week, label="Day of Week", value='Monday')
with gr.Row():
hour_input = gr.Slider(minimum=0, maximum=23, step=1, label="Hour of Day", value=12)
minute_input = gr.Slider(minimum=0, maximum=59, step=1, label="Minute of Day", value=30)
time_since_input = gr.Number(label="Time Since Last Event (minutes)", value=60)
predict_button = gr.Button("Predict Fall")
output = gr.Textbox(label="Prediction Result")
predict_button.click(
predict_fall,
inputs=[location_input, day_input, hour_input, minute_input, time_since_input],
outputs=output
)
if __name__ == "__main__":
demo.launch()