import tensorflow as tf
import gradio as gr
import numpy as np
# Load the trained model
model = tf.keras.models.load_model('sleep_disorder_model.h5')
# Define the prediction function
def predict_sleep_disorder(gender, age, sleep_duration, quality_of_sleep, physical_activity_level, stress_level, heart_rate, daily_steps, systolic, diastolic, occupation, bmi_category):
# Gender encoding
gender_male = 1 if gender == "Male" else 0
# Occupation encoding
occupation_dict = {
"Doctor": 0, "Engineer": 1, "Lawyer": 2, "Manager": 3,
"Nurse": 4, "SalesRepresentative": 5, "Salesperson": 6,
"Scientist": 7, "SoftwareEngineer": 8, "Teacher": 9
}
occupation_encoded = [0] * 10 # Initialize a list of 10 zeros
if occupation in occupation_dict:
occupation_encoded[occupation_dict[occupation]] = 1 # Set the correct occupation to 1
# BMI Category encoding
bmi_dict = {
"NormalWeight": 0,
"Obese": 1,
"Overweight": 2
}
bmi_encoded = [0, 0, 0] # Initialize a list of 3 zeros
if bmi_category in bmi_dict:
bmi_encoded[bmi_dict[bmi_category]] = 1 # Set the correct BMI category to 1
# Combine all inputs into a single array
input_data = np.array([[
age, sleep_duration, quality_of_sleep, physical_activity_level,
stress_level, heart_rate, daily_steps, systolic, diastolic,
gender_male
] + occupation_encoded + bmi_encoded])
# Use the model to make a prediction
prediction = model.predict(input_data)
# Convert the prediction to a readable format
prediction_index = np.argmax(prediction, axis=1)[0] # Get the index of the highest probability
prediction_confidence = prediction[0][prediction_index] * 100
prediction_mapping = {
0: "No Sleep Disorder",
1: "Insomnia",
2: "Sleep Apnea"
}
result = prediction_mapping.get(prediction_index, "Unknown")
if result in ["Insomnia", "Sleep Apnea"]:
message = gr.Markdown("# Did you know?\n ## Here are some facts related to sleep disorders:")
image = "sleep_problems_table.png"
source_message = (
"Source: [AIHW - Sleep problems as a risk factor]"
"(https://www.aihw.gov.au/reports/risk-factors/sleep-problems-as-a-risk-factor/summary)"
)
else:
image = "starrysky.jpg"
message = gr.Markdown("# Have a good night's sleep!")
source_message = (""
)
confidence_message = f"**Model Confidence: {prediction_confidence:.2f}%**"
return result, confidence_message, message, image, source_message
def welcome(name):
if not name.strip():
return""
return f"Nice to meet you, {name}! Let's begin."
js = """
function createGradioAnimation() {
var container = document.createElement('div');
container.id = 'gradio-animation';
container.style.fontSize = '2em';
container.style.fontWeight = 'bold';
container.style.textAlign = 'left';
container.style.marginBottom = '20px';
var text = 'Welcome to the Sleep Disorder Prediction App';
for (var i = 0; i < text.length; i++) {
(function(i){
setTimeout(function(){
var letter = document.createElement('span');
letter.style.opacity = '0';
letter.style.transition = 'opacity 0.2s';
letter.innerText = text[i];
container.appendChild(letter);
setTimeout(function() {
letter.style.opacity = '1';
}, 30);
}, i * 30 );
})(i);
}
var gradioContainer = document.querySelector('.gradio-container');
gradioContainer.insertBefore(container, gradioContainer.firstChild);
return 'Animation created';
}
"""
# Build the Gradio interface
with gr.Blocks(js=js) as demo:
gr.Markdown("""
This app predicts the risk of developing sleep disorders based on your responses to a series of questions.
Please fill in the details below to get started.
*This project was built as an educational exercise during UWA's Data Analytics Bootcamp program. It was developed under a cooperative effort of Group 3
members: Daniel Usuga, Bradley Curthoys, Lisa Shimano, and Bailey Strauch.*
""")
# Welcome section
with gr.Row():
inp = gr.Textbox(placeholder="What is your name?", show_label=False, scale=0, min_width=300)
out = gr.Label(show_label=False, scale=1, min_width=500)
with gr.Row():
submit_btn = gr.Button("Submit", scale=0)
submit_btn.click(fn=welcome, inputs=inp, outputs=out)
with gr.Row():
gr.Markdown("""
"""
)
with gr.Row():
gr.Markdown("## User Questionnaire")
with gr.Row():
gr.Markdown("""
To make a prediction about your risk of developing a sleep disorder, please answer the questions below. All questions must be answered for the app to
process your data correctly. You can hover over the question heading to display the categorical values associated with each question.
***Disclaimer:*** This app is intended as interactive display of a machine learning model at work ONLY. It is not to be taken as medical advice. If you think you may have
or a be at risk of developing a sleep disorder, please consult your PCP or another licensed medical professional.
More information on Sleep Disorders
""")
with gr.Row():
gender = gr.Radio(choices=["Male", "Female"], label="Biological Gender")
age = gr.Number(label="Age", value=30)
with gr.Row():
gr.HTML("""