GDM / app.py
RazT's picture
Update app.py
0c9c3f7 verified
raw
history blame
No virus
9.19 kB
import gradio as gr
import joblib
import numpy as np
# Load the models and scalers
model_initial = joblib.load('model_initial.pkl')
scaler_initial = joblib.load('scaler_initial.pkl')
model_detailed = joblib.load('model_detailed.pkl')
scaler_detailed = joblib.load('scaler_detailed.pkl')
# Define risk thresholds globally
very_high_risk_threshold = 0.75
high_risk_threshold = 0.50
moderate_risk_threshold = 0.15
def initial_risk_check(features, detailed):
if detailed:
# Use the detailed model
features_scaled = scaler_detailed.transform([features])
prediction = model_detailed.predict_proba(features_scaled)[:, 1][0]
else:
# Use the initial model
features_scaled = scaler_initial.transform([features[:3]]) # Only use the first three features
prediction = model_initial.predict_proba(features_scaled)[:, 1][0]
return prediction
def update_output(family_history, personal_history, pregnancies, age, bmi, detailed, ogtt, sys_bp, hdl):
if detailed:
features = [pregnancies, age, bmi, ogtt, sys_bp, hdl]
else:
features = [pregnancies, age, bmi]
prediction = initial_risk_check(features, detailed)
# Adjust prediction based on the user's history
if family_history:
prediction *= 1.5 # Risk increases 1.5 times with a family history of diabetes
if personal_history:
prediction *= 2 # Risk increases 2 times with a personal history of GDM
# Ensure prediction does not exceed 1
prediction = min(prediction, 1)
# Determine risk level and recommendation
if prediction >= very_high_risk_threshold:
return f"**<span style='color: #FF0000;'>Very High risk ({prediction:.2%}). Please consult a doctor immediately.</span>**"
elif prediction >= high_risk_threshold:
return f"**<span style='color: #FF4500;'>High risk ({prediction:.2%}). Please consult a doctor and follow a personalized training program.</span>**"
elif prediction >= moderate_risk_threshold:
return f"**<span style='color: #DAA520;'>Moderate risk ({prediction:.2%}). Consider lifestyle changes and monitor your health closely.</span>**"
else:
return f"**<span style='color: #008000;'>Low risk ({prediction:.2%}). Maintain a healthy lifestyle and schedule routine check-ups.</span>**"
def launch_interface():
with gr.Blocks(css="""
.gradio-container {
font-family: Arial, sans-serif;
background-color: #f9f9f9;
color: #333;
}
.gr-button {
background-color: #007bff;
color: white;
}
.gr-button:hover {
background-color: #0056b3;
}
.gr-textbox {
margin-bottom: 1em;
}
.gr-markdown h1 {
color: #007bff;
}
.gr-radio-group label {
color: #007bff;
}
.gr-number,
.gr-textbox,
.gr-checkbox,
.gr-radio-group {
margin: 0.5em 0;
}
""") as app:
gr.Markdown("""
# Gestational Diabetes Risk Calculator
Welcome to our Gestational Diabetes Risk Calculator, designed to empower you with valuable insights about your health based on the latest NICE (National Institute for Health and Care Excellence) medical guidelines. By providing some key information, you can receive a personalized assessment of your risk level. If the system identifies a moderate or high risk, you will be guided to provide more detailed information for an accurate evaluation.
## How to Use the System
1. **Step 1**: Answer the questions about your family and personal history of diabetes.
2. **Step 2**: Enter your **Number of Pregnancies**, **Age**, and **BMI**.
3. **Step 3**: If the initial assessment indicates moderate or high risk, you will be prompted to provide additional details such as **OGTT**, **Systolic Blood Pressure**, and **HDL** levels.
4. **Step 4**: Click "Submit" to receive your risk assessment and personalized recommendations.
## Important Information
- **Family History**: Women with a first-degree relative (parent or sibling) with diabetes have a higher risk of developing GDM. This can increase the risk by about 2 to 3 times.
- **Personal History**: Women who have had GDM in a previous pregnancy have a 30% to 70% chance of developing GDM in subsequent pregnancies.
## Detailed Parameter Explanations
- **Number of Pregnancies**: The number of times you have been pregnant. Multiple pregnancies can increase the risk of GDM.
- **Age**: Your age in years. Advanced maternal age (over 25) is a risk factor for GDM.
- **BMI**: Body Mass Index, a measure of body fat based on height and weight. A higher BMI is associated with an increased risk of GDM.
- **OGTT**: Oral Glucose Tolerance Test, a test that measures the body's ability to use glucose. Higher values indicate greater risk.
- **Systolic Blood Pressure**: The upper number in a blood pressure reading, indicating how much pressure your blood is exerting against your artery walls when the heart beats. Higher blood pressure can be a risk factor.
- **HDL**: High-Density Lipoprotein, also known as 'good' cholesterol. Lower levels of HDL can indicate higher risk.
""")
# Initial inputs
family_history = gr.Checkbox(label="Family history of diabetes", value=False)
personal_history = gr.Checkbox(label="Personal history of GDM", value=False)
pregnancies = gr.Number(label="Number of Pregnancies", info="The number of times you have been pregnant.")
age = gr.Number(label="Age", info="Your age in years.")
bmi = gr.Number(label="BMI", info="Body Mass Index, a measure of body fat based on height and weight.")
detailed = gr.Checkbox(label="Check if you are at or above moderate risk for detailed input", value=False)
# Detailed inputs
ogtt = gr.Number(label="OGTT", visible=False, info="Oral Glucose Tolerance Test, a test that measures the body's ability to use glucose.")
sys_bp = gr.Number(label="Systolic Blood Pressure", visible=False, info="The upper number in a blood pressure reading, indicating how much pressure your blood is exerting against your artery walls when the heart beats.")
hdl = gr.Number(label="HDL", visible=False, info="High-Density Lipoprotein, also known as 'good' cholesterol.")
# Output and button
submit_button = gr.Button("Submit")
output = gr.Markdown(label="Result")
# Update output based on user input
def update_output(family_history, personal_history, pregnancies, age, bmi, detailed, ogtt, sys_bp, hdl):
if detailed:
features = [pregnancies, age, bmi, ogtt, sys_bp, hdl]
else:
features = [pregnancies, age, bmi]
prediction = initial_risk_check(features, detailed)
# Adjust prediction based on the user's history
if family_history:
prediction *= 1.5 # Risk increases 1.5 times with a family history of diabetes
if personal_history:
prediction *= 2 # Risk increases 2 times with a personal history of GDM
# Ensure prediction does not exceed 1
prediction = min(prediction, 1)
# Determine risk level and recommendation
if prediction >= very_high_risk_threshold:
return f"**<span style='color: #FF0000;'>Very High risk ({prediction:.2%}). Please consult a doctor immediately.</span>**"
elif prediction >= high_risk_threshold:
return f"**<span style='color: #FF4500;'>High risk ({prediction:.2%}). Please consult a doctor and follow a personalized training program.</span>**"
elif prediction >= moderate_risk_threshold:
return f"**<span style='color: #DAA520;'>Moderate risk ({prediction:.2%}). Consider lifestyle changes and monitor your health closely.</span>**"
else:
return f"**<span style='color: #008000;'>Low risk ({prediction:.2%}). Maintain a healthy lifestyle and schedule routine check-ups.</span>**"
# Toggle visibility of detailed inputs
def toggle_visibility(detailed):
return {
ogtt: gr.update(visible=detailed),
sys_bp: gr.update(visible=detailed),
hdl: gr.update(visible=detailed)
}
# Change visibility of detailed inputs based on checkbox
detailed.change(
fn=toggle_visibility,
inputs=[detailed],
outputs=[ogtt, sys_bp, hdl]
)
# Submit button functionality
submit_button.click(
fn=update_output,
inputs=[family_history, personal_history, pregnancies, age, bmi, detailed, ogtt, sys_bp, hdl],
outputs=[output]
)
app.launch(share=True)
if __name__ == "__main__":
launch_interface()