Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,47 +1,13 @@
|
|
| 1 |
-
# Import required libraries
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
-
from ucimlrepo import fetch_ucirepo
|
| 6 |
from sklearn.model_selection import train_test_split
|
| 7 |
from sklearn.preprocessing import StandardScaler
|
| 8 |
import torch
|
| 9 |
import torch.nn as nn
|
| 10 |
import torch.optim as optim
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
cdc_diabetes_health_indicators = fetch_ucirepo(id=891)
|
| 14 |
-
|
| 15 |
-
# Extract features and targets
|
| 16 |
-
X_raw = cdc_diabetes_health_indicators.data.features
|
| 17 |
-
y = cdc_diabetes_health_indicators.data.targets
|
| 18 |
-
|
| 19 |
-
# Combine features and targets into a single DataFrame
|
| 20 |
-
df = pd.concat([X_raw, y], axis=1)
|
| 21 |
-
|
| 22 |
-
# Drop duplicates if there are any
|
| 23 |
-
df.drop_duplicates(inplace=True)
|
| 24 |
-
|
| 25 |
-
# Features and target selection
|
| 26 |
-
X_raw = df[['AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke',
|
| 27 |
-
'PhysHlth', 'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk',
|
| 28 |
-
'BMI', 'HighBP', 'GenHlth']]
|
| 29 |
-
y = df['Diabetes_binary']
|
| 30 |
-
|
| 31 |
-
# Data Preprocessing
|
| 32 |
-
scaler = StandardScaler()
|
| 33 |
-
X = scaler.fit_transform(X_raw)
|
| 34 |
-
|
| 35 |
-
# Train-test split
|
| 36 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=123)
|
| 37 |
-
|
| 38 |
-
# Convert to PyTorch tensors
|
| 39 |
-
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
|
| 40 |
-
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
|
| 41 |
-
y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32).view(-1, 1)
|
| 42 |
-
y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32).view(-1, 1)
|
| 43 |
-
|
| 44 |
-
# Define the PyTorch model
|
| 45 |
class NeuralNet(nn.Module):
|
| 46 |
def __init__(self, input_size, hidden_size, output_size):
|
| 47 |
super(NeuralNet, self).__init__()
|
|
@@ -57,97 +23,123 @@ class NeuralNet(nn.Module):
|
|
| 57 |
x = self.sigmoid(self.fc3(x))
|
| 58 |
return x
|
| 59 |
|
| 60 |
-
# Instantiate
|
| 61 |
-
input_size =
|
| 62 |
hidden_size = 64
|
| 63 |
output_size = 1
|
| 64 |
deep_model = NeuralNet(input_size, hidden_size, output_size)
|
|
|
|
| 65 |
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
st.
|
| 73 |
-
|
| 74 |
-
Berto
|
| 75 |
-
This
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
""
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
st.
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
else:
|
| 141 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
|
| 144 |
-
st.subheader("Tips to Maintain Low Diabetes Risk")
|
| 145 |
-
st.markdown("""
|
| 146 |
-
- **Keep a healthy weight**
|
| 147 |
-
- **Exercise often**
|
| 148 |
-
- **Eat well-balanced meals**
|
| 149 |
-
- **Cut down on sugar and unhealthy fats**
|
| 150 |
-
- **Check your blood sugar**
|
| 151 |
-
- **Manage stress**
|
| 152 |
-
- **Get regular check-ups**
|
| 153 |
""")
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from sklearn.model_selection import train_test_split
|
| 5 |
from sklearn.preprocessing import StandardScaler
|
| 6 |
import torch
|
| 7 |
import torch.nn as nn
|
| 8 |
import torch.optim as optim
|
| 9 |
|
| 10 |
+
# Neural network definition (same as before)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
class NeuralNet(nn.Module):
|
| 12 |
def __init__(self, input_size, hidden_size, output_size):
|
| 13 |
super(NeuralNet, self).__init__()
|
|
|
|
| 23 |
x = self.sigmoid(self.fc3(x))
|
| 24 |
return x
|
| 25 |
|
| 26 |
+
# Instantiate the model
|
| 27 |
+
input_size = 13
|
| 28 |
hidden_size = 64
|
| 29 |
output_size = 1
|
| 30 |
deep_model = NeuralNet(input_size, hidden_size, output_size)
|
| 31 |
+
scaler = StandardScaler()
|
| 32 |
|
| 33 |
+
# Sidebar for navigation
|
| 34 |
+
st.sidebar.title("Navigation")
|
| 35 |
+
app_mode = st.sidebar.selectbox("Choose the app mode", ["Diabetes Predictor", "Chronotherapy Scheduler"])
|
| 36 |
+
|
| 37 |
+
# Diabetes Predictor Section
|
| 38 |
+
if app_mode == "Diabetes Predictor":
|
| 39 |
+
st.title("BERTO AI😊 : Personalized Diabetes Treatment Predictor")
|
| 40 |
+
st.write("""
|
| 41 |
+
Berto AI is a personalized diabetes prediction tool built to assist users in better understanding their health risks.
|
| 42 |
+
This tool uses a deep learning model powered by PyTorch to predict whether you may have diabetes based on various health indicators.
|
| 43 |
+
""")
|
| 44 |
+
|
| 45 |
+
# Input form for user health information
|
| 46 |
+
st.subheader("Enter Your Health Information")
|
| 47 |
+
|
| 48 |
+
AnyHealthcare = st.selectbox("Any Healthcare (1: Yes, 0: No)", [0, 1])
|
| 49 |
+
Sex = st.selectbox("Sex (1: Male, 0: Female)", [0, 1])
|
| 50 |
+
Smoker = st.selectbox("Smoker (1: Yes, 0: No)", [0, 1])
|
| 51 |
+
MentHlth = st.slider("Mental Health (Bad days in last 30 days)", 0, 30, 0)
|
| 52 |
+
CholCheck = st.selectbox("Cholesterol Check in Last 5 Years (1: Yes, 0: No)", [0, 1])
|
| 53 |
+
Stroke = st.selectbox("History of Stroke (1: Yes, 0: No)", [0, 1])
|
| 54 |
+
PhysHlth = st.slider("Physical Health (Bad days in last 30 days)", 0, 30, 0)
|
| 55 |
+
HeartDiseaseorAttack = st.selectbox("History of Heart Disease or Attack (1: Yes, 0: No)", [0, 1])
|
| 56 |
+
Age = st.slider("Age", 18, 100, 30)
|
| 57 |
+
HighChol = st.selectbox("High Cholesterol (1: Yes, 0: No)", [0, 1])
|
| 58 |
+
DiffWalk = st.selectbox("Difficulty Walking (1: Yes, 0: No)", [0, 1])
|
| 59 |
+
HighBP = st.selectbox("High Blood Pressure (1: Yes, 0: No)", [0, 1])
|
| 60 |
+
GenHlth = st.slider("General Health (1=Excellent, 5=Poor)", 1, 5, 3)
|
| 61 |
+
|
| 62 |
+
# Create a feature array from the inputs
|
| 63 |
+
user_input = np.array([[AnyHealthcare, Sex, Smoker, MentHlth, CholCheck, Stroke,
|
| 64 |
+
PhysHlth, HeartDiseaseorAttack, Age, HighChol, DiffWalk,
|
| 65 |
+
HighBP, GenHlth]])
|
| 66 |
+
|
| 67 |
+
# Convert the NumPy array to a DataFrame
|
| 68 |
+
user_input_df = pd.DataFrame(user_input, columns=[
|
| 69 |
+
'AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke', 'PhysHlth',
|
| 70 |
+
'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk', 'HighBP', 'GenHlth'])
|
| 71 |
+
|
| 72 |
+
# Standardize the user input
|
| 73 |
+
user_input_scaled = scaler.fit_transform(user_input_df) # Use pre-trained scaler in practice
|
| 74 |
+
user_input_tensor = torch.tensor(user_input_scaled, dtype=torch.float32)
|
| 75 |
+
|
| 76 |
+
# Perform prediction
|
| 77 |
+
if st.button("Predict"):
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
deep_model.eval() # Set model to evaluation mode
|
| 80 |
+
prediction = deep_model(user_input_tensor).round().numpy()
|
| 81 |
+
|
| 82 |
+
if prediction == 1:
|
| 83 |
+
st.success("The model predicts that you likely **have diabetes**.")
|
| 84 |
+
st.warning("Tips to Manage Diabetes:\n\n- Manage blood sugar\n- Eat healthy meals\n- Exercise regularly\n- Monitor your blood pressure\n- Get enough sleep.")
|
| 85 |
+
else:
|
| 86 |
+
st.success("✅ Lower risk detected. Keep up the good work!")
|
| 87 |
+
st.info("""
|
| 88 |
+
Tips to Maintain Low Diabetes Risk:
|
| 89 |
+
- Keep a healthy weight
|
| 90 |
+
- Exercise often
|
| 91 |
+
- Eat well-balanced meals
|
| 92 |
+
- Cut down on sugar and unhealthy fats
|
| 93 |
+
- Check your blood sugar
|
| 94 |
+
- Manage stress
|
| 95 |
+
- Get regular check-ups
|
| 96 |
+
""")
|
| 97 |
+
|
| 98 |
+
# Chronotherapy Scheduler Section
|
| 99 |
+
elif app_mode == "Chronotherapy Scheduler":
|
| 100 |
+
st.title("Chronotherapy Scheduler for Type 2 Diabetes")
|
| 101 |
+
st.write("""
|
| 102 |
+
This scheduler generates a personalized routine for Type 2 Diabetes management based on your inputs.
|
| 103 |
+
Chronotherapy involves timing medical treatment and lifestyle interventions to better align with your body's natural rhythms.
|
| 104 |
+
""")
|
| 105 |
+
|
| 106 |
+
# Input fields
|
| 107 |
+
city = st.text_input("Enter your city name:")
|
| 108 |
+
a1c_level = st.slider("A1C level (%)", 4.0, 14.0, 7.0)
|
| 109 |
+
|
| 110 |
+
weight_unit = st.radio("Weight unit", ["kg", "lbs"])
|
| 111 |
+
if weight_unit == "kg":
|
| 112 |
+
weight = st.number_input("Weight (kg)", min_value=30.0, max_value=200.0, value=70.0)
|
| 113 |
else:
|
| 114 |
+
weight = st.number_input("Weight (lbs)", min_value=66.0, max_value=440.0, value=154.0)
|
| 115 |
+
|
| 116 |
+
height_unit = st.radio("Height unit", ["cm", "feet & inches"])
|
| 117 |
+
if height_unit == "cm":
|
| 118 |
+
height_cm = st.number_input("Height (cm)", min_value=100.0, max_value=250.0, value=170.0)
|
| 119 |
+
else:
|
| 120 |
+
height_ft = st.number_input("Height (feet)", min_value=3, max_value=8, value=5)
|
| 121 |
+
height_in = st.number_input("Height (inches)", min_value=0, max_value=11, value=7)
|
| 122 |
+
height_cm = height_ft * 30.48 + height_in * 2.54
|
| 123 |
+
|
| 124 |
+
glucose_level = st.number_input("Glucose level (mg/dL)", min_value=50.0, max_value=600.0, value=70.0)
|
| 125 |
+
age = st.slider("Age", min_value=18, max_value=100, value=45)
|
| 126 |
+
sex = st.radio("Sex", ["M", "F"])
|
| 127 |
+
smoking_status = st.radio("Do you smoke?", ["No", "Yes"])
|
| 128 |
+
diabetes_status = st.radio("Diabetes Status", ["Prediabetic", "Type 2 Diabetic"])
|
| 129 |
+
|
| 130 |
+
# Generate routine based on input
|
| 131 |
+
if st.button("Generate Schedule"):
|
| 132 |
+
st.subheader(f"Chronotherapy Routine for {city}")
|
| 133 |
+
st.write(f"""
|
| 134 |
+
Based on your inputs, here's a suggested routine for managing Type 2 Diabetes:
|
| 135 |
+
|
| 136 |
+
- **Morning (7:00 AM)**: Wake up and take your morning medication (if prescribed).
|
| 137 |
+
- **Breakfast (7:30 AM)**: A balanced meal with low sugar and carbs.
|
| 138 |
+
- **Mid-morning (10:00 AM)**: Light physical activity or a short walk.
|
| 139 |
+
- **Lunch (12:30 PM)**: A well-balanced meal with lean protein and fiber.
|
| 140 |
+
- **Afternoon (3:00 PM)**: Check glucose levels if needed, and have a light snack.
|
| 141 |
+
- **Evening (6:00 PM)**: Dinner with a focus on vegetables and healthy fats.
|
| 142 |
+
- **Before bed (10:00 PM)**: Wind down and manage stress with relaxation techniques.
|
| 143 |
|
| 144 |
+
Adjust this routine as needed based on medical advice.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
""")
|