BERTO_AI / app.py
EdgarDataScientist's picture
Update app.py
6399bb4 verified
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.optim as optim
# Neural network definition (same as before)
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, output_size)
self.relu = nn.ReLU()
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.sigmoid(self.fc3(x))
return x
# Instantiate the model
input_size = 13
hidden_size = 64
output_size = 1
deep_model = NeuralNet(input_size, hidden_size, output_size)
scaler = StandardScaler()
# Sidebar for navigation
st.sidebar.title("Navigation")
app_mode = st.sidebar.selectbox("Choose the app mode", ["Diabetes Predictor", "Chronotherapy Scheduler"])
# Diabetes Predictor Section
if app_mode == "Diabetes Predictor":
st.title("BERTO AI: Personalized Diabetes Treatment Predictor")
st.write("""
Berto AI is a personalized diabetes prediction tool built to assist users in better understanding their health risks.
This tool uses a deep learning model powered by PyTorch to predict whether you may have diabetes based on various health indicators.
""")
# Input form for user health information
st.subheader("Enter Your Health Information")
AnyHealthcare = st.selectbox("Any Healthcare (1: Yes, 0: No)", [0, 1])
Sex = st.selectbox("Sex (1: Male, 0: Female)", [0, 1])
Smoker = st.selectbox("Smoker (1: Yes, 0: No)", [0, 1])
MentHlth = st.slider("Mental Health (Bad days in last 30 days)", 0, 30, 0)
CholCheck = st.selectbox("Cholesterol Check in Last 5 Years (1: Yes, 0: No)", [0, 1])
Stroke = st.selectbox("History of Stroke (1: Yes, 0: No)", [0, 1])
PhysHlth = st.slider("Physical Health (Bad days in last 30 days)", 0, 30, 0)
HeartDiseaseorAttack = st.selectbox("History of Heart Disease or Attack (1: Yes, 0: No)", [0, 1])
Age = st.slider("Age", 18, 100, 30)
HighChol = st.selectbox("High Cholesterol (1: Yes, 0: No)", [0, 1])
DiffWalk = st.selectbox("Difficulty Walking (1: Yes, 0: No)", [0, 1])
HighBP = st.selectbox("High Blood Pressure (1: Yes, 0: No)", [0, 1])
GenHlth = st.slider("General Health (1=Excellent, 5=Poor)", 1, 5, 3)
# Create a feature array from the inputs
user_input = np.array([[AnyHealthcare, Sex, Smoker, MentHlth, CholCheck, Stroke,
PhysHlth, HeartDiseaseorAttack, Age, HighChol, DiffWalk,
HighBP, GenHlth]])
# Convert the NumPy array to a DataFrame
user_input_df = pd.DataFrame(user_input, columns=[
'AnyHealthcare', 'Sex', 'Smoker', 'MentHlth', 'CholCheck', 'Stroke', 'PhysHlth',
'HeartDiseaseorAttack', 'Age', 'HighChol', 'DiffWalk', 'HighBP', 'GenHlth'])
# Standardize the user input
user_input_scaled = scaler.fit_transform(user_input_df) # Use pre-trained scaler in practice
user_input_tensor = torch.tensor(user_input_scaled, dtype=torch.float32)
# Perform prediction
if st.button("Predict"):
with torch.no_grad():
deep_model.eval() # Set model to evaluation mode
prediction = deep_model(user_input_tensor).round().numpy()
if prediction == 1:
st.success("The model predicts that you likely **have diabetes**.")
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.")
else:
st.success("✅ Lower risk detected. Keep up the good work!")
st.info("""
Tips to Maintain Low Diabetes Risk:
- Keep a healthy weight
- Exercise often
- Eat well-balanced meals
- Cut down on sugar and unhealthy fats
- Check your blood sugar
- Manage stress
- Get regular check-ups
""")
# Chronotherapy Scheduler Section
elif app_mode == "Chronotherapy Scheduler":
st.title("Chronotherapy Scheduler for Type 2 Diabetes")
st.write("""
This scheduler generates a personalized routine for Type 2 Diabetes management based on your inputs.
Chronotherapy involves timing medical treatment and lifestyle interventions to better align with your body's natural rhythms.
""")
# Input fields
city = st.text_input("Enter your city name:")
a1c_level = st.slider("A1C level (%)", 4.0, 14.0, 7.0)
weight_unit = st.radio("Weight unit", ["kg", "lbs"])
if weight_unit == "kg":
weight = st.number_input("Weight (kg)", min_value=30.0, max_value=200.0, value=70.0)
else:
weight = st.number_input("Weight (lbs)", min_value=66.0, max_value=440.0, value=154.0)
height_unit = st.radio("Height unit", ["cm", "feet & inches"])
if height_unit == "cm":
height_cm = st.number_input("Height (cm)", min_value=100.0, max_value=250.0, value=170.0)
else:
height_ft = st.number_input("Height (feet)", min_value=3, max_value=8, value=5)
height_in = st.number_input("Height (inches)", min_value=0, max_value=11, value=7)
height_cm = height_ft * 30.48 + height_in * 2.54
glucose_level = st.number_input("Glucose level (mg/dL)", min_value=50.0, max_value=600.0, value=70.0)
age = st.slider("Age", min_value=18, max_value=100, value=45)
sex = st.radio("Sex", ["M", "F"])
smoking_status = st.radio("Do you smoke?", ["No", "Yes"])
diabetes_status = st.radio("Diabetes Status", ["Prediabetic", "Type 2 Diabetic"])
# Generate routine based on input
if st.button("Generate Schedule"):
st.subheader(f"Chronotherapy Routine for {city}")
st.write(f"""
Based on your inputs, here's a suggested routine for managing Type 2 Diabetes:
- **Morning (7:00 AM)**: Wake up and take your morning medication (if prescribed).
- **Breakfast (7:30 AM)**: A balanced meal with low sugar and carbs.
- **Mid-morning (10:00 AM)**: Light physical activity or a short walk.
- **Lunch (12:30 PM)**: A well-balanced meal with lean protein and fiber.
- **Afternoon (3:00 PM)**: Check glucose levels if needed, and have a light snack.
- **Evening (6:00 PM)**: Dinner with a focus on vegetables and healthy fats.
- **Before bed (10:00 PM)**: Wind down and manage stress with relaxation techniques.
Adjust this routine as needed based on medical advice.
""")