Spaces:
Sleeping
Sleeping
| import joblib | |
| import pandas as pd | |
| import gradio as gr | |
| # Load model, scaler, feature names etc. | |
| model = joblib.load('fall_detection_model.joblib') # updated here | |
| scaler = joblib.load('scaler.joblib') | |
| feature_names = joblib.load('feature_names.joblib') # list of all features in correct order | |
| movement_activities = ['Lying', 'No Movement', 'Sitting', 'Walking'] | |
| locations = ['Bathroom', 'Bedroom', 'Kitchen', 'Living Room'] | |
| days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] | |
| def predict_fall(movement_activity, location, day_of_week, hour_of_day, minute_of_day, time_since_last_event): | |
| try: | |
| data = {f: 0 for f in feature_names} | |
| data[f'Movement Activity_{movement_activity}'] = 1 | |
| data[f'Location_{location}'] = 1 | |
| data[f'day_of_week_{day_of_week}'] = 1 | |
| data['hour_of_day'] = hour_of_day | |
| data['minute_of_day'] = minute_of_day | |
| data['time_since_last_event'] = time_since_last_event | |
| input_df = pd.DataFrame([data], columns=feature_names, dtype=float) | |
| scaler_cols = scaler.feature_names_in_ | |
| scaled_features = scaler.transform(input_df[scaler_cols]) | |
| input_df.loc[:, scaler_cols] = scaled_features | |
| input_df = input_df[model.feature_names_in_] | |
| pred_proba = model.predict_proba(input_df)[0, 1] | |
| threshold = 0.4 | |
| 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"Error: {str(e)}. Check server logs." | |
| print("User inputs:", movement_activity, location, day_of_week, hour_of_day, minute_of_day, time_since_last_event) | |
| print("Data dict:", data) | |
| print("Input dataframe:\n", input_df) | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## Fall Prediction") | |
| with gr.Row(): | |
| movement_input = gr.Dropdown(choices=movement_activities, label="Movement Activity") | |
| location_input = gr.Dropdown(choices=locations, label="Location") | |
| day_input = gr.Dropdown(choices=days_of_week, label="Day of Week") | |
| with gr.Row(): | |
| hour_input = gr.Slider(minimum=0, maximum=23, step=1, label="Hour of Day") | |
| minute_input = gr.Slider(minimum=0, maximum=59, step=1, label="Minute of Day") | |
| time_since_input = gr.Number(label="Time Since Last Event (minutes)") | |
| predict_button = gr.Button("Predict") | |
| output = gr.Textbox(label="Prediction Result") | |
| predict_button.click( | |
| predict_fall, | |
| inputs=[movement_input, location_input, day_input, hour_input, minute_input, time_since_input], | |
| outputs=output | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |