Spaces:
Running
Running
Download src/streamlit_app.py from EnYa32/DiabetesPrediction: direct link, hf CLI and curl.
- Browser
- Download file 7.2 kB
-
https://huggingface.co/spaces/EnYa32/DiabetesPrediction/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/EnYa32/DiabetesPrediction/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/EnYa32/DiabetesPrediction/resolve/main/src/streamlit_app.py
7.2 kB
| import numpy as np | |
| import pandas as pd | |
| import streamlit as st | |
| import joblib | |
| from pathlib import Path | |
| # ----------------------------- | |
| # Page config | |
| # ----------------------------- | |
| st.set_page_config( | |
| page_title='Diabetes Risk Predictor (LightGBM)', | |
| page_icon='🩺', | |
| layout='centered' | |
| ) | |
| st.title('🩺 Diabetes Risk Predictor') | |
| st.write('Predicts the probability of being diagnosed with diabetes using a trained LightGBM model.') | |
| # ----------------------------- | |
| # Paths (HF-friendly) | |
| # ----------------------------- | |
| BASE_DIR = Path(__file__).resolve().parent | |
| MODEL_PATH = BASE_DIR / 'lgbm_model.pkl' | |
| FEATURE_COLS_PATH = BASE_DIR / 'feature_cols.pkl' | |
| # ----------------------------- | |
| # Load artifacts | |
| # ----------------------------- | |
| def load_artifacts(): | |
| if not MODEL_PATH.exists(): | |
| raise FileNotFoundError( | |
| f'Model not found: {MODEL_PATH.name}. Put it in the repo root (same folder as app.py).' | |
| ) | |
| if not FEATURE_COLS_PATH.exists(): | |
| raise FileNotFoundError( | |
| f'Feature list not found: {FEATURE_COLS_PATH.name}. Put it in the repo root (same folder as app.py).' | |
| ) | |
| model = joblib.load(MODEL_PATH) | |
| feature_cols = joblib.load(FEATURE_COLS_PATH) | |
| return model, feature_cols | |
| model, feature_cols = load_artifacts() | |
| # ----------------------------- | |
| # Feature engineering (must match your notebook logic) | |
| # ----------------------------- | |
| def add_features(df: pd.DataFrame) -> pd.DataFrame: | |
| df = df.copy() | |
| eps = 1e-6 | |
| # Body / Age | |
| df['bmi_age_ratio'] = df['bmi'] / (df['age'] + eps) | |
| df['is_obese'] = (df['bmi'] >= 30).astype(int) | |
| # Activity | |
| df['activity_per_age'] = df['physical_activity_minutes_per_week'] / (df['age'] + eps) | |
| df['low_activity'] = (df['physical_activity_minutes_per_week'] < 150).astype(int) | |
| # Sleep | |
| df['sleep_deficit'] = 7 - df['sleep_hours_per_day'] | |
| df['poor_sleep'] = (df['sleep_hours_per_day'] < 6).astype(int) | |
| # Cholesterol | |
| if {'ldl_cholesterol', 'hdl_cholesterol'}.issubset(df.columns): | |
| df['chol_ratio'] = df['ldl_cholesterol'] / (df['hdl_cholesterol'] + eps) | |
| df['high_ldl'] = (df['ldl_cholesterol'] >= 130).astype(int) | |
| df['low_hdl'] = (df['hdl_cholesterol'] < 40).astype(int) | |
| return df | |
| # ----------------------------- | |
| # UI Inputs | |
| # ----------------------------- | |
| with st.form('input_form'): | |
| st.subheader('Patient Information') | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| age = st.number_input('Age', min_value=1, max_value=120, value=45, step=1) | |
| gender = st.selectbox('Gender', ['Female', 'Male', 'Other']) | |
| ethnicity = st.selectbox('Ethnicity', ['White', 'Hispanic', 'Black', 'Asian', 'Other']) | |
| education_level = st.selectbox('Education Level', ['Highschool', 'Graduate', 'Postgraduate', 'No formal']) | |
| employment_status = st.selectbox('Employment Status', ['Employed', 'Retired', 'Unemployed', 'Student']) | |
| with col2: | |
| income_level = st.selectbox('Income Level', ['Low', 'Lower-Middle', 'Middle', 'Upper-Middle', 'High']) | |
| smoking_status = st.selectbox('Smoking Status', ['Never', 'Former', 'Current']) | |
| family_history_diabetes = st.selectbox('Family History of Diabetes', [0, 1], index=0) | |
| hypertension_history = st.selectbox('Hypertension History', [0, 1], index=0) | |
| cardiovascular_history = st.selectbox('Cardiovascular History', [0, 1], index=0) | |
| st.subheader('Lifestyle & Health Metrics') | |
| col3, col4 = st.columns(2) | |
| with col3: | |
| alcohol_consumption_per_week = st.number_input('Alcohol Consumption per Week', min_value=0, max_value=50, value=2, step=1) | |
| physical_activity_minutes_per_week = st.number_input('Physical Activity (minutes/week)', min_value=0, max_value=2000, value=90, step=5) | |
| diet_score = st.number_input('Diet Score', min_value=0.0, max_value=10.0, value=6.0, step=0.1) | |
| sleep_hours_per_day = st.number_input('Sleep Hours per Day', min_value=0.0, max_value=24.0, value=7.0, step=0.1) | |
| screen_time_hours_per_day = st.number_input('Screen Time Hours per Day', min_value=0.0, max_value=24.0, value=6.0, step=0.1) | |
| with col4: | |
| bmi = st.number_input('BMI', min_value=10.0, max_value=60.0, value=26.0, step=0.1) | |
| waist_to_hip_ratio = st.number_input('Waist-to-Hip Ratio', min_value=0.50, max_value=1.50, value=0.86, step=0.01) | |
| systolic_bp = st.number_input('Systolic BP', min_value=50, max_value=250, value=116, step=1) | |
| diastolic_bp = st.number_input('Diastolic BP', min_value=30, max_value=160, value=75, step=1) | |
| heart_rate = st.number_input('Heart Rate', min_value=20, max_value=220, value=70, step=1) | |
| col5, col6 = st.columns(2) | |
| with col5: | |
| cholesterol_total = st.number_input('Total Cholesterol', min_value=50, max_value=400, value=187, step=1) | |
| hdl_cholesterol = st.number_input('HDL Cholesterol', min_value=5, max_value=150, value=54, step=1) | |
| with col6: | |
| ldl_cholesterol = st.number_input('LDL Cholesterol', min_value=5, max_value=300, value=103, step=1) | |
| triglycerides = st.number_input('Triglycerides', min_value=10, max_value=600, value=123, step=1) | |
| submitted = st.form_submit_button('Predict Risk') | |
| # ----------------------------- | |
| # Prediction | |
| # ----------------------------- | |
| if submitted: | |
| # Build one-row dataframe (must match your training columns BEFORE encoding) | |
| row = { | |
| 'age': int(age), | |
| 'alcohol_consumption_per_week': int(alcohol_consumption_per_week), | |
| 'physical_activity_minutes_per_week': int(physical_activity_minutes_per_week), | |
| 'diet_score': float(diet_score), | |
| 'sleep_hours_per_day': float(sleep_hours_per_day), | |
| 'screen_time_hours_per_day': float(screen_time_hours_per_day), | |
| 'bmi': float(bmi), | |
| 'waist_to_hip_ratio': float(waist_to_hip_ratio), | |
| 'systolic_bp': int(systolic_bp), | |
| 'diastolic_bp': int(diastolic_bp), | |
| 'heart_rate': int(heart_rate), | |
| 'cholesterol_total': int(cholesterol_total), | |
| 'hdl_cholesterol': int(hdl_cholesterol), | |
| 'ldl_cholesterol': int(ldl_cholesterol), | |
| 'triglycerides': int(triglycerides), | |
| 'gender': gender, | |
| 'ethnicity': ethnicity, | |
| 'education_level': education_level, | |
| 'income_level': income_level, | |
| 'smoking_status': smoking_status, | |
| 'employment_status': employment_status, | |
| 'family_history_diabetes': int(family_history_diabetes), | |
| 'hypertension_history': int(hypertension_history), | |
| 'cardiovascular_history': int(cardiovascular_history), | |
| } | |
| X_user = pd.DataFrame([row]) | |
| # Feature engineering | |
| X_user = add_features(X_user) | |
| # One-hot encode | |
| X_user_enc = pd.get_dummies(X_user, drop_first=True) | |
| # Align columns to training feature set | |
| X_user_enc = X_user_enc.reindex(columns=feature_cols, fill_value=0) | |
| # Predict probability | |
| proba = float(model.predict_proba(X_user_enc)[:, 1][0]) | |
| st.success(f'Predicted Diabetes Probability: {proba:.3f}') | |
| st.progress(min(max(proba, 0.0), 1.0)) | |
| st.caption('Note: This app outputs probability (0–1). It is not a medical diagnosis.') |