Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import gradio as grimport pandas as pdimport joblibimport os# --- 1. Define Constants and Load Assets ---# Define the paths for the model and the datasetMODEL_PATH = 'model_pipeline.joblib'DATASET_PATH = 'user_behavior_dataset.csv'# --- 2. Load the Pre-trained Model and Data ---# Load the trained model pipeline. If it doesn't exist, the app will show an error.try:if not os.path.exists(MODEL_PATH):raise FileNotFoundError(f"Model file not found at {MODEL_PATH}. Please run the main training script first to create it.")model_pipeline = joblib.load(MODEL_PATH)print("Model loaded successfully from model_pipeline.joblib")# Load the dataset just to get the list of unique device models for the dropdownif not os.path.exists(DATASET_PATH):raise FileNotFoundError(f"Dataset file not found at {DATASET_PATH}. It's needed for the device model list.")df = pd.read_csv(DATASET_PATH)device_models = sorted(df['Device Model'].unique())print("Device list loaded successfully.")except Exception as e:print(f"FATAL ERROR: {e}")# Set placeholders if loading fails, so the app can still launch and show an errormodel_pipeline = Nonedevice_models = ["Error: Model or data file not found."]# --- 3. Create the Prediction Function ---def predict_battery_drain(device_model, screen_on_time, app_usage, num_apps, data_usage, age):"""This function takes user inputs from the Gradio interface,processes them using the loaded model pipeline, and returns a prediction."""if model_pipeline is None:return "ERROR: Model is not loaded. Please check the application logs."# Create a pandas DataFrame from the user inputs.# The column names MUST EXACTLY MATCH the ones used for training the pipeline.input_data = pd.DataFrame({'Device Model': [device_model],'Screen On Time (hours/day)': [screen_on_time],'App Usage Time (min/day)': [app_usage],'Number of Apps Installed': [num_apps],'Data Usage (MB/day)': [data_usage],'Age': [age]})# Use the loaded pipeline to make a prediction. The pipeline handles all preprocessing.try:prediction = model_pipeline.predict(input_data)[0]# Format the output to be user-friendlyreturn f"{prediction:.2f} mAh/day"except Exception as e:return f"Prediction Error: {e}"# --- 4. Build the Gradio User Interface (Normal Version) ---with gr.Blocks(title="Battery Drain Predictor") as demo:# Headergr.Markdown("# Mobile Battery Drain Predictor")gr.Markdown("An intelligent tool to forecast your phone's daily battery consumption based on your usage habits.")with gr.Row():# Input Columnwith gr.Column(scale=3):gr.Markdown("## Your Usage Profile")device_model_input = gr.Dropdown(choices=device_models,label="Device Model",value=device_models[0] if device_models else None,interactive=True)screen_time_input = gr.Slider(minimum=0, maximum=24, value=5.5, step=0.5, label="Screen On Time (hours/day)")app_usage_input = gr.Slider(minimum=0, maximum=1440, value=180, step=10, label="Apps Usage (min/day)")apps_installed_input = gr.Slider(minimum=10, maximum=250, value=70, step=1, label="Number of Apps Installed")data_usage_input = gr.Slider(minimum=0, maximum=5000, value=500, step=50, label="Data Usage (MB/day)")age_input = gr.Slider(minimum=0, maximum=72, value=12, step=1, label="Age of Phone (months)")predict_button = gr.Button("Predict Drain")# Output Columnwith gr.Column(scale=2):gr.Markdown("## Predicted Consumption")output_text = gr.Textbox(label="Predicted Battery Drain",interactive=False,placeholder="Prediction will appear here...")gr.Markdown("""**Note:** This prediction is based on a machine learning model trained on a sample dataset.Actual results may vary.""")# Define the action for the button clickinputs_list = [device_model_input,screen_time_input,app_usage_input,apps_installed_input,data_usage_input,age_input]predict_button.click(fn=predict_battery_drain, inputs=inputs_list, outputs=output_text)# --- 5. Launch the App ---if __name__ == "__main__":demo.launch(debug=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import gradio as grimport joblibimport pandas as pd# 1. Load the trained pipeline# Make sure model_pipeline.joblib is in the same directorymodel = joblib.load('model_pipeline.joblib')# 2. Define the prediction functiondef predict_battery_drain(screen_time, app_time, apps_installed, data_usage, age, device_model):# Create a dataframe from the inputs# CRITICAL: Column names must perfectly match the ones used during traininginput_data = pd.DataFrame({'Screen On Time (hours/day)': [screen_time],'App Usage Time (min/day)': [app_time],'Number of Apps Installed': [apps_installed],'Data Usage (MB/day)': [data_usage],'Age': [age],'Device Model': [device_model]})# Make prediction using the pipelineprediction = model.predict(input_data)[0]return f"{prediction:.2f} mAh/day"# 3. Define the Gradio Interface# Update this list with the actual Device Models from your dataset!device_model_list = ["Device A", "Device B", "Device C", "Device D"]inputs = [gr.Number(label="Screen On Time (hours/day)", value=4.5),gr.Number(label="App Usage Time (min/day)", value=120),gr.Number(label="Number of Apps Installed", value=45),gr.Number(label="Data Usage (MB/day)", value=1024),gr.Number(label="Age", value=25),gr.Dropdown(choices=device_model_list, label="Device Model", allow_custom_value=True)]outputs = gr.Textbox(label="Predicted Battery Drain")# 4. Launch the appapp = gr.Interface(fn=predict_battery_drain,inputs=inputs,outputs=outputs,title="🔋 Mobile Battery Drain Predictor",description="Enter device usage metrics to predict daily battery drain (in mAh/day).")if __name__ == "__main__":app.launch()
app.py+43-110