Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345679 unmodified lines17181920212223246 unmodified lines3132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111 unmodified lineimport joblibimport pandas as pdimport random# 1. Load the trained pipelinemodel = joblib.load('model_pipeline.joblib')9 unmodified lines"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],6 unmodified lines# 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__":1 unmodified line23456789 unmodified lines18192021222324256 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231 unmodified lineimport joblibimport pandas as pdimport randomimport plotly.graph_objects as go# 1. Load the trained pipelinemodel = joblib.load('model_pipeline.joblib')9 unmodified lines"Google Pixel 5", "iPhone 12", "OnePlus 9", "Samsung Galaxy S21", "Xiaomi Mi 11"]# 2. Define the prediction and visualization functiondef predict_and_plot(screen_time, app_time, apps_installed, data_usage, age, device_model):# Prepare datainput_data = pd.DataFrame({'Screen On Time (hours/day)': [screen_time],6 unmodified lines# Make predictionprediction = model.predict(input_data)[0]# --- Create Interactive Gauge Chart ---# The bar turns red if it crosses 2006, otherwise it's green.bar_color = "red" if prediction >= 2006 else "#00cc66"fig = go.Figure(go.Indicator(mode = "gauge+number",value = prediction,number = {"suffix": " mAh"},domain = {'x': [0, 1], 'y': [0, 1]},title = {'text': "Predicted Daily Drain", 'font': {'size': 20}},gauge = {'axis': {'range': [0, 4000], 'tickwidth': 1, 'tickcolor': "darkblue"},'bar': {'color': bar_color},'bgcolor': "white",'borderwidth': 2,'bordercolor': "#e5e7eb",'steps': [{'range': [0, 2006], 'color': '#e6ffe6'}, # Safe zone{'range': [2006, 4000], 'color': '#ffe6e6'} # Danger zone],'threshold': {'line': {'color': "red", 'width': 4},'thickness': 0.75,'value': 2006}}))fig.update_layout(height=350, margin=dict(l=20, r=20, t=50, b=20))# --- Generate Warnings ---warning_text = "β System Optimized.\nBattery usage is in a healthy range. No action required."if prediction >= 2006:# Pick random apps to stopapps_string = ", ".join(random.sample(APP_LIST, k=random.randint(3, 4)))# 1. Trigger Native Flash Warninggr.Warning("CRITICAL: Battery drain limit exceeded!")# 2. Update the text box with the specific appswarning_text = f"β οΈ CRITICAL DRAIN ALERT!\nYour usage is above the 2006 mAh safety limit.\n\nRECOMMENDATION: Force stop these background apps to save battery:\nπ {apps_string}"return fig, warning_text# 3. Build a Clean, Modern UI# Using the "Ocean" theme for a sleek tech aestheticwith gr.Blocks(theme=gr.themes.Ocean()) as app:gr.Markdown("# π Mobile Battery Drain Predictor Dashboard")gr.Markdown("Adjust the user metrics below. The dashboard will instantly update to show predicted battery drain.")with gr.Row():# LEFT COLUMN: Inputswith gr.Column(scale=1):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=4.5, step=0.5, label="πΊ Screen On Time (hours/day)")app_time_input = gr.Slider(minimum=0, maximum=1440, value=200, step=10, label="β³ App Usage Time (min/day)")apps_installed_input = gr.Slider(minimum=0, maximum=150, value=50, step=1, label="π¦ Number of Apps Installed")data_usage_input = gr.Slider(minimum=0, maximum=5000, value=1000, step=100, label="π Data Usage (MB/day)")age_input = gr.Number(label="π€ User Age", value=30)# RIGHT COLUMN: Gauge Chart & Warningswith gr.Column(scale=1):# Interactive Gauge Chartgauge_output = gr.Plot()# Text box for the warningswarning_output = gr.Textbox(label="System Status", lines=6)# --- Live Interactivity ---# Instead of a submit button, we link every input to update the output INSTANTLY when dragged!inputs_list = [screen_time_input, app_time_input, apps_installed_input, data_usage_input, age_input, device_input]for input_element in inputs_list:input_element.change(fn=predict_and_plot,inputs=inputs_list,outputs=[gauge_output, warning_output])# Run once on startup so the chart isn't empty when the app loadsapp.load(fn=predict_and_plot,inputs=inputs_list,outputs=[gauge_output, warning_output])if __name__ == "__main__":
app.py+76-64