import gradio as gr import pandas as pd import joblib import numpy as np # Load model assets model = joblib.load("model.pkl") columns = joblib.load("columns.pkl") le = joblib.load("label_encoder.pkl") # ------------------------------- # Mapping functions # ------------------------------- def map_inputs(data): return { "Gender": data["Gender"], "Age": data["Age"], "Height": data["Height"], "Weight": data["Weight"], "family_history_with_overweight": data["Family History"], "FAVC": data["High Calorie Food"], "FCVC": {"Rarely": 1, "Sometimes": 2, "Frequently": 3}[data["Vegetables"]], "NCP": data["Meals"], "CAEC": data["Snacking"], "SMOKE": data["Smoking"], "CH2O": data["Water"], "SCC": data["Calorie Monitoring"], "FAF": {"None": 0, "Light": 1, "Moderate": 2, "High": 3}[data["Activity"]], "TUE": {"Low": 0, "Medium": 1, "High": 2}[data["Screen Time"]], "CALC": data["Alcohol"], "MTRANS": data["Transport"] } def clean_label(label): return label.replace("_", " ").replace("Type", "Type ") def calculate_bmi(height, weight): if height > 0: bmi = weight / (height ** 2) return round(bmi, 1) return 0 def get_bmi_color(bmi): if bmi < 18.5: return "#3B82F6" elif bmi < 25: return "#22C55E" elif bmi < 30: return "#F59E0B" else: return "#EF4444" # ------------------------------- # Chart Builder # ------------------------------- CATEGORY_COLORS = { "Insufficient Weight": "#3B82F6", "Normal Weight": "#22C55E", "Overweight Level I": "#F59E0B", "Overweight Level II": "#F97316", "Obesity Type I": "#EF4444", "Obesity Type II": "#DC2626", "Obesity Type III": "#991B1B", } def build_chart_html(prob_dict: dict) -> str: if not prob_dict: return "" bars_html = "" for label, prob in prob_dict.items(): color = CATEGORY_COLORS.get(label, "#6B7280") pct = prob * 100 pct_display = f"{pct:.1f}%" bars_html += f"""
{label}
{pct_display}
""" return f"""

How Confident Is the Model?

{bars_html}

Each bar shows the model's confidence for that category

""" # ------------------------------- # Prediction function # ------------------------------- def predict( Gender, Age, Height, Weight, Family_History, High_Calorie_Food, Vegetables, Meals, Snacking, Smoking, Water, Calorie_Monitoring, Activity, Screen_Time, Alcohol, Transport ): data = { "Gender": Gender, "Age": Age, "Height": Height, "Weight": Weight, "Family History": Family_History, "High Calorie Food": High_Calorie_Food, "Vegetables": Vegetables, "Meals": Meals, "Snacking": Snacking, "Smoking": Smoking, "Water": Water, "Calorie Monitoring": Calorie_Monitoring, "Activity": Activity, "Screen Time": Screen_Time, "Alcohol": Alcohol, "Transport": Transport } mapped = map_inputs(data) df = pd.DataFrame([mapped]) df = pd.get_dummies(df) df = df.reindex(columns=columns, fill_value=0) probs = model.predict_proba(df)[0] classes = le.inverse_transform(np.arange(len(probs))) classes = [clean_label(c) for c in classes] best_idx = np.argmax(probs) best_class = classes[best_idx] confidence = probs[best_idx] * 100 # BMI — color only, no category label bmi = calculate_bmi(Height, Weight) bmi_color = get_bmi_color(bmi) bmi_position = min(max((bmi - 10) / (45 - 10) * 100, 0), 100) severity_colors = { "Insufficient Weight": "#3B82F6", "Normal Weight": "#22C55E", "Overweight Level I": "#F59E0B", "Overweight Level II": "#F97316", "Obesity Type I": "#EF4444", "Obesity Type II": "#DC2626", "Obesity Type III": "#991B1B", } color = severity_colors.get(best_class, "#6B7280") result_text = f"""

Predicted Level

🩺 {best_class}

Confidence

{confidence:.1f}%

Your BMI

{bmi} kg/m²
10 18.5 25 30 45

⚠️ For informational use only. Please consult a healthcare professional.

""" prob_dict = {classes[i]: float(probs[i]) for i in range(len(classes))} return result_text, prob_dict # ------------------------------- # Custom CSS # ------------------------------- custom_css = """ *, *::before, *::after { box-sizing: border-box !important; } body, .gradio-container { background: linear-gradient(160deg, #0f0f1a 0%, #1a1a2e 50%, #16213e 100%) !important; min-height: 100vh; font-family: 'Segoe UI', system-ui, sans-serif !important; overflow-x: hidden !important; } .gradio-container > * { max-width: 100% !important; } .app-header { text-align: center; padding: 36px 16px 28px; background: linear-gradient(135deg, #1e1e3f, #2d2d5e); border-radius: 16px; margin-bottom: 24px; border: 1px solid rgba(99,102,241,0.3); box-shadow: 0 16px 48px rgba(99,102,241,0.15); } .section-card { background: linear-gradient(145deg, #1e1e2e, #252535) !important; border-radius: 14px !important; padding: 18px !important; border: 1px solid rgba(255,255,255,0.07) !important; box-shadow: 0 4px 20px rgba(0,0,0,0.2) !important; margin-bottom: 16px !important; } label span, .gr-form label { color: #C4B5FD !important; font-weight: 500 !important; font-size: 0.85rem !important; } input[type="number"], .gr-dropdown select, textarea, .gr-input input { background: #2a2a3e !important; border: 1px solid rgba(139,92,246,0.3) !important; border-radius: 10px !important; color: #E5E7EB !important; padding: 10px 14px !important; width: 100% !important; } input[type="number"]:focus, .gr-dropdown select:focus { border-color: #8B5CF6 !important; box-shadow: 0 0 0 3px rgba(139,92,246,0.15) !important; outline: none !important; } .gr-radio label { background: #2a2a3e !important; border: 1px solid rgba(139,92,246,0.25) !important; border-radius: 8px !important; padding: 6px 12px !important; color: #D1D5DB !important; cursor: pointer !important; font-size: 0.85rem !important; } .gr-radio input:checked + label { background: linear-gradient(135deg, #7C3AED, #4F46E5) !important; border-color: #7C3AED !important; color: white !important; } .predict-btn button { background: linear-gradient(135deg, #7C3AED 0%, #4F46E5 50%, #2563EB 100%) !important; color: white !important; font-size: 1rem !important; font-weight: 700 !important; padding: 14px 32px !important; border-radius: 12px !important; border: none !important; cursor: pointer !important; box-shadow: 0 8px 28px rgba(124,58,237,0.4) !important; transition: all 0.3s ease !important; width: 100% !important; } .predict-btn button:hover { transform: translateY(-2px) !important; box-shadow: 0 12px 36px rgba(124,58,237,0.6) !important; } .section-title { color: #A78BFA !important; font-size: 0.8rem !important; font-weight: 700 !important; text-transform: uppercase !important; letter-spacing: 1.5px !important; margin-bottom: 14px !important; padding-bottom: 8px !important; border-bottom: 1px solid rgba(167,139,250,0.2) !important; } ::-webkit-scrollbar { width: 5px; } ::-webkit-scrollbar-track { background: #1e1e2e; } ::-webkit-scrollbar-thumb { background: #4C1D95; border-radius: 3px; } ::-webkit-scrollbar-thumb:hover { background: #7C3AED; } @media (max-width: 768px) { .app-header { padding: 22px 14px 18px; border-radius: 12px; margin-bottom: 14px; } .section-card { padding: 13px !important; } .main-row { flex-direction: column !important; } .main-row > div { width: 100% !important; min-width: 0 !important; } input[type="number"], select { font-size: 16px !important; } } @media (max-width: 480px) { .gradio-container { padding: 8px !important; } .section-card { padding: 11px !important; } } """ # ------------------------------- # UI Layout # ------------------------------- with gr.Blocks(css=custom_css, title="Obesity Level Predictor") as app: # ── Header ── gr.HTML("""

🏥 Obesity Level Predictor

Fill in your health and lifestyle details to get an AI-powered obesity level assessment.

ML-Powered ⚡ Instant Results 🔒 Privacy First
""") with gr.Row(equal_height=False, elem_classes="main-row"): # ── LEFT COLUMN ── with gr.Column(scale=5, min_width=280): with gr.Group(elem_classes="section-card"): gr.HTML('

Personal Information

') with gr.Row(): Gender = gr.Dropdown(["Male","Female"], label="Gender", value="Male") Age = gr.Number(label="Age (years)", value=25, minimum=1, maximum=120) with gr.Row(): Height = gr.Number(label="Height (m)", value=1.70, minimum=0.5, maximum=2.5) Weight = gr.Number(label="Weight (kg)", value=70, minimum=10, maximum=300) with gr.Group(elem_classes="section-card"): gr.HTML('

🍽️ Eating Habits

') with gr.Row(): Family_History = gr.Radio(["yes","no"], label="Family history of overweight?", value="no") High_Calorie_Food = gr.Radio(["yes","no"], label="Frequent high-calorie food?", value="no") with gr.Row(): Vegetables = gr.Dropdown(["Rarely","Sometimes","Frequently"], label="Vegetable consumption", value="Sometimes") Snacking = gr.Dropdown(["no","Sometimes","Frequently","Always"], label="Snacking between meals", value="Sometimes") with gr.Row(): Meals = gr.Number(label="Meals per day", value=3, minimum=1, maximum=10) Water = gr.Number(label="Water intake (L/day)", value=2.0, minimum=0, maximum=10) Calorie_Monitoring = gr.Radio(["yes","no"], label="Do you monitor calories?", value="no") with gr.Group(elem_classes="section-card"): gr.HTML('

🏃 Lifestyle & Habits

') with gr.Row(): Activity = gr.Dropdown(["None","Light","Moderate","High"], label="Physical activity level", value="Light") Screen_Time = gr.Dropdown(["Low","Medium","High"], label="Daily screen time", value="Medium") with gr.Row(): Smoking = gr.Radio(["yes","no"], label="Smoking", value="no") Alcohol = gr.Dropdown(["no","Sometimes","Frequently","Always"], label="Alcohol consumption", value="Sometimes") with gr.Group(elem_classes="section-card"): gr.HTML('

Transport

') Transport = gr.Dropdown( ["Walking","Bike","Public_Transportation","Automobile"], label="Primary mode of transport", value="Public_Transportation" ) with gr.Row(elem_classes="predict-btn"): btn = gr.Button("Predict My Obesity Level", variant="primary") # ── RIGHT COLUMN ── with gr.Column(scale=4, min_width=280): gr.HTML("""

How to use

  1. Fill in all fields on the left
  2. Click Predict
  3. Review your result and BMI
  4. Consult a doctor for medical advice
""") output_text = gr.HTML(value="""
🩺

Your prediction will appear here

Fill in the form and click Predict

""") output_chart = gr.HTML(value="") gr.HTML("""
⚠️

This tool is for informational purposes only and does not constitute medical advice. Always consult a qualified healthcare professional.

""") # ── Event Handler ── def predict_and_format( Gender, Age, Height, Weight, Family_History, High_Calorie_Food, Vegetables, Meals, Snacking, Smoking, Water, Calorie_Monitoring, Activity, Screen_Time, Alcohol, Transport ): result_html, prob_dict = predict( Gender, Age, Height, Weight, Family_History, High_Calorie_Food, Vegetables, Meals, Snacking, Smoking, Water, Calorie_Monitoring, Activity, Screen_Time, Alcohol, Transport ) chart_html = build_chart_html(prob_dict) return result_html, chart_html btn.click( fn=predict_and_format, inputs=[ Gender, Age, Height, Weight, Family_History, High_Calorie_Food, Vegetables, Meals, Snacking, Smoking, Water, Calorie_Monitoring, Activity, Screen_Time, Alcohol, Transport ], outputs=[output_text, output_chart] ) app.launch(server_name="0.0.0.0", server_port=7860)