Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345675 unmodified lines1314151617181920213 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import gradio as grimport joblibimport pandas as pdimport random # Added to pick random apps# 1. Load the trained pipelinemodel = joblib.load('model_pipeline.joblib')5 unmodified lines"Spotify", "Google Maps", "Netflix", "Twitter/X"]# 2. Define the prediction functiondef predict_battery_drain(screen_time, app_time, apps_installed, data_usage, age, device_model):# Create a dataframe from the inputsinput_data = pd.DataFrame({'Screen On Time (hours/day)': [screen_time],'App Usage Time (min/day)': [app_time],3 unmodified lines'Device Model': [device_model]})# Make prediction using the pipelineprediction = model.predict(input_data)[0]result_text = f"{prediction:.2f} mAh/day"# --- NEW: Check threshold and trigger warning ---if prediction >= 2006:# Pick either 3 or 4 random appsnum_apps_to_pick = random.randint(3, 4)random_apps = random.sample(APP_LIST, k=num_apps_to_pick)apps_string = ", ".join(random_apps)warning_msg = f"Stop using these background apps to save battery: {apps_string}"# This triggers a visual popup flash in the UIgr.Warning(warning_msg)# Also append it to the text output so it stays on screen after the flash fadesresult_text += f"\n\nβ οΈ HIGH DRAIN DETECTED:\n{warning_msg}"return result_text# 3. Define the Gradio Interfacedevice_model_list = ["Google Pixel 5","iPhone 12","OnePlus 9","Samsung Galaxy S21","Xiaomi Mi 11"]inputs = [gr.Number(label="Screen On Time (hours/day)", value=7.5), # Increased default to trigger warning easier for testinggr.Number(label="App Usage Time (min/day)", value=400),gr.Number(label="Number of Apps Installed", value=50),gr.Number(label="Data Usage (MB/day)", value=2500),gr.Number(label="Age", value=30),gr.Dropdown(choices=device_model_list, label="Device Model", value="Google Pixel 5")]# Increased lines so the warning text has room to show upoutputs = gr.Textbox(label="Predicted Battery Drain", lines=4)# 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. Warnings will flash if usage exceeds 2006 mAh/day.")if __name__ == "__main__":app.launch()12345675 unmodified lines131415161718192021222324253 unmodified lines2930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import gradio as grimport joblibimport pandas as pdimport random# 1. Load the trained pipelinemodel = joblib.load('model_pipeline.joblib')5 unmodified lines"Spotify", "Google Maps", "Netflix", "Twitter/X"]device_model_list = ["Google Pixel 5", "iPhone 12", "OnePlus 9", "Samsung Galaxy S21", "Xiaomi Mi 11"]# 2. Define the prediction and UI update functiondef process_prediction(screen_time, app_time, apps_installed, data_usage, age, device_model):# Prepare datainput_data = pd.DataFrame({'Screen On Time (hours/day)': [screen_time],'App Usage Time (min/day)': [app_time],3 unmodified lines'Device Model': [device_model]})# Make predictionprediction = model.predict(input_data)[0]result_text = f"π {prediction:.0f} mAh/day"# Check threshold for dynamic UI updatesif prediction >= 2006:# Generate random appsrandom_apps = random.sample(APP_LIST, k=random.randint(3, 4))apps_string = ", ".join(random_apps)# Trigger the native Gradio popup flashgr.Warning("CRITICAL: High battery drain detected!")# Generate a styled HTML warning box (Interviewers love custom HTML in ML apps)warning_html = f"""<div style="background-color: #ffe6e6; border-left: 6px solid #ff3333; padding: 20px; border-radius: 8px; font-family: sans-serif;"><h3 style="color: #cc0000; margin-top: 0; font-size: 1.2em;">β οΈ CRITICAL DRAIN ALERT</h3><p style="color: #333; font-size: 1.1em; margin-bottom: 5px;">Your daily usage exceeds the 2006 mAh safe limit.</p><p style="color: #333; margin-top: 0;"><strong>System Recommendation:</strong> Force stop the following background processes immediately:</p><p style="color: #cc0000; font-weight: bold; font-size: 1.2em; margin-top: 10px;">π {apps_string}</p></div>"""return result_text, warning_htmlelse:# Generate a styled HTML success boxsuccess_html = """<div style="background-color: #e6ffe6; border-left: 6px solid #00cc66; padding: 20px; border-radius: 8px; font-family: sans-serif;"><h3 style="color: #00994d; margin-top: 0; font-size: 1.2em;">β BATTERY OPTIMIZED</h3><p style="color: #333; font-size: 1.1em; margin-bottom: 0;">Your device usage is within normal, healthy limits. No action required.</p></div>"""return result_text, success_html# 3. Build the Custom UI using gr.Blocks (Professional Layout)# We use a soft theme to make it look like a modern dashboardwith gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate")) as app:# Header Sectiongr.Markdown("""# β‘ AI Battery Drain Predictor DashboardWelcome to the diagnostic panel. Adjust the device metrics below to simulate different user profiles and predict daily battery consumption.""")with gr.Row():# LEFT COLUMN: User Inputswith gr.Column(scale=1):gr.Markdown("### βοΈ User Behavior Metrics")device_input = gr.Dropdown(choices=device_model_list, label="Device Model", value="Google Pixel 5")screen_time_input = gr.Slider(minimum=0, maximum=24, value=7.5, step=0.1, label="Screen On Time (hours/day)")app_time_input = gr.Slider(minimum=0, maximum=1440, value=400, step=10, label="App Usage Time (min/day)")apps_installed_input = gr.Number(label="Number of Apps Installed", value=50)data_usage_input = gr.Number(label="Data Usage (MB/day)", value=2500)age_input = gr.Number(label="User Age", value=30)predict_btn = gr.Button("π Run Diagnostics", variant="primary")# RIGHT COLUMN: Results & Dynamic HTML Warningwith gr.Column(scale=1):gr.Markdown("### π Diagnostic Results")# Big, bold text for the final numberprediction_output = gr.Textbox(label="Predicted Daily Drain", text_align="center")# This HTML block will update dynamically based on the model's output!html_output = gr.HTML(value='<div style="padding: 20px; color: #666; text-align: center; border: 2px dashed #ccc; border-radius: 8px;">Run a diagnostic to see system alerts here.</div>')# 4. Connect the button to the functionpredict_btn.click(fn=process_prediction,inputs=[screen_time_input, app_time_input, apps_installed_input, data_usage_input, age_input, device_input],outputs=[prediction_output, html_output])if __name__ == "__main__":app.launch()
app.py+77-45