updated app.py
Browse files
app.py
ADDED
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import xgboost as xgb
|
3 |
+
import pandas as pd
|
4 |
+
import numpy as np
|
5 |
+
from sklearn.model_selection import train_test_split
|
6 |
+
from sklearn.metrics import accuracy_score, confusion_matrix
|
7 |
+
import plotly.express as px
|
8 |
+
import plotly.graph_objects as go
|
9 |
+
import json
|
10 |
+
|
11 |
+
class DiabetesGame:
|
12 |
+
def __init__(self):
|
13 |
+
self.data = self.load_data()
|
14 |
+
self.model = self.train_model()
|
15 |
+
self.user_score = 0
|
16 |
+
self.total_attempts = 0
|
17 |
+
self.tips_database = {
|
18 |
+
"glucose": "Normal fasting blood glucose levels are less than 100 mg/dL. Levels between 100-125 mg/dL indicate prediabetes.",
|
19 |
+
"bmi": "A BMI between 18.5 and 24.9 is considered healthy. BMI over 30 indicates obesity, a risk factor for diabetes.",
|
20 |
+
"blood_pressure": "Normal blood pressure is usually below 120/80 mmHg. High blood pressure often co-occurs with diabetes.",
|
21 |
+
"age": "Type 2 diabetes risk increases with age, particularly after 45 years.",
|
22 |
+
"pregnancies": "Gestational diabetes during pregnancy increases future diabetes risk.",
|
23 |
+
"lifestyle": "Regular exercise and a balanced diet can significantly reduce diabetes risk.",
|
24 |
+
"family_history": "Having a parent or sibling with diabetes increases your risk.",
|
25 |
+
"general": "Early detection and lifestyle changes can prevent or delay type 2 diabetes."
|
26 |
+
}
|
27 |
+
|
28 |
+
def load_data(self):
|
29 |
+
return pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv')
|
30 |
+
|
31 |
+
def train_model(self):
|
32 |
+
X = self.data.drop(columns=['Outcome'])
|
33 |
+
y = self.data['Outcome']
|
34 |
+
X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=42)
|
35 |
+
|
36 |
+
model = xgb.XGBClassifier(
|
37 |
+
eval_metric='logloss',
|
38 |
+
max_depth=6,
|
39 |
+
learning_rate=0.1,
|
40 |
+
n_estimators=100,
|
41 |
+
random_state=42
|
42 |
+
)
|
43 |
+
model.fit(X_train, y_train)
|
44 |
+
return model
|
45 |
+
|
46 |
+
def create_radar_chart(self, values):
|
47 |
+
categories = ['Pregnancies', 'Glucose', 'Blood Pressure', 'Skin Thickness',
|
48 |
+
'Insulin', 'BMI', 'Diabetes Pedigree', 'Age']
|
49 |
+
|
50 |
+
# Normalize values for radar chart
|
51 |
+
max_values = [17, 200, 122, 99, 846, 67.1, 2.42, 81]
|
52 |
+
normalized_values = [v/m for v, m in zip(values, max_values)]
|
53 |
+
|
54 |
+
fig = go.Figure()
|
55 |
+
fig.add_trace(go.Scatterpolar(
|
56 |
+
r=normalized_values,
|
57 |
+
theta=categories,
|
58 |
+
fill='toself',
|
59 |
+
name='Patient Values'
|
60 |
+
))
|
61 |
+
|
62 |
+
fig.update_layout(
|
63 |
+
polar=dict(
|
64 |
+
radialaxis=dict(
|
65 |
+
visible=True,
|
66 |
+
range=[0, 1]
|
67 |
+
)),
|
68 |
+
showlegend=True,
|
69 |
+
title="Patient Risk Factors Radar Chart"
|
70 |
+
)
|
71 |
+
return fig
|
72 |
+
|
73 |
+
def create_feature_importance_plot(self):
|
74 |
+
importance_df = pd.DataFrame({
|
75 |
+
'Feature': ['Pregnancies', 'Glucose', 'Blood Pressure', 'Skin Thickness',
|
76 |
+
'Insulin', 'BMI', 'Diabetes Pedigree', 'Age'],
|
77 |
+
'Importance': self.model.feature_importances_
|
78 |
+
})
|
79 |
+
importance_df = importance_df.sort_values('Importance', ascending=True)
|
80 |
+
|
81 |
+
fig = px.bar(importance_df, x='Importance', y='Feature',
|
82 |
+
orientation='h',
|
83 |
+
title='Feature Importance in Diagnosis')
|
84 |
+
fig.update_layout(height=400)
|
85 |
+
return fig
|
86 |
+
|
87 |
+
def get_relevant_tips(self, values):
|
88 |
+
tips = []
|
89 |
+
|
90 |
+
# Add tips based on values
|
91 |
+
if values[1] > 140: # High glucose
|
92 |
+
tips.append(("⚠️ High Glucose", self.tips_database["glucose"]))
|
93 |
+
if values[5] > 30: # High BMI
|
94 |
+
tips.append(("⚠️ High BMI", self.tips_database["bmi"]))
|
95 |
+
if values[2] > 90: # High blood pressure
|
96 |
+
tips.append(("⚠️ High Blood Pressure", self.tips_database["blood_pressure"]))
|
97 |
+
|
98 |
+
# Always add a random general tip
|
99 |
+
general_tips = [self.tips_database["lifestyle"],
|
100 |
+
self.tips_database["family_history"],
|
101 |
+
self.tips_database["general"]]
|
102 |
+
tips.append(("💡 Health Tip", np.random.choice(general_tips)))
|
103 |
+
|
104 |
+
return "\n\n".join([f"{title}\n{content}" for title, content in tips])
|
105 |
+
|
106 |
+
def predict_and_play(self, pregnancies, glucose, blood_pressure, skin_thickness,
|
107 |
+
insulin, bmi, diabetes_pedigree, age, user_diagnosis):
|
108 |
+
|
109 |
+
values = [pregnancies, glucose, blood_pressure, skin_thickness,
|
110 |
+
insulin, bmi, diabetes_pedigree, age]
|
111 |
+
|
112 |
+
# Make prediction
|
113 |
+
user_input = np.array(values).reshape(1, -1)
|
114 |
+
prediction = self.model.predict(user_input)[0]
|
115 |
+
probability = self.model.predict_proba(user_input)[0][1] * 100
|
116 |
+
|
117 |
+
# Update score
|
118 |
+
self.total_attempts += 1
|
119 |
+
correct = (user_diagnosis == "Yes" and prediction == 1) or \
|
120 |
+
(user_diagnosis == "No" and prediction == 0)
|
121 |
+
if correct:
|
122 |
+
self.user_score += 1
|
123 |
+
|
124 |
+
# Create visualizations
|
125 |
+
radar_chart = self.create_radar_chart(values)
|
126 |
+
importance_plot = self.create_feature_importance_plot()
|
127 |
+
|
128 |
+
# Generate result message
|
129 |
+
accuracy = (self.user_score / self.total_attempts) * 100 if self.total_attempts > 0 else 0
|
130 |
+
|
131 |
+
result = f"""{'🎉 Correct!' if correct else '❌ Incorrect'}\n
|
132 |
+
Model Prediction: {'Diabetes Risk Detected' if prediction == 1 else 'No Significant Risk'}\n
|
133 |
+
Confidence: {probability:.1f}%\n
|
134 |
+
Your Score: {self.user_score}/{self.total_attempts} ({accuracy:.1f}% accuracy)
|
135 |
+
"""
|
136 |
+
|
137 |
+
# Get relevant tips
|
138 |
+
tips = self.get_relevant_tips(values)
|
139 |
+
|
140 |
+
return result, radar_chart, importance_plot, tips
|
141 |
+
|
142 |
+
# Initialize game
|
143 |
+
game = DiabetesGame()
|
144 |
+
|
145 |
+
# Create the interface
|
146 |
+
with gr.Blocks(theme=gr.themes.Soft()) as interface:
|
147 |
+
gr.Markdown("""
|
148 |
+
# 🏥 Interactive Diabetes Diagnosis Game
|
149 |
+
|
150 |
+
Test your medical diagnosis skills! Analyze patient data and try to predict diabetes risk.
|
151 |
+
Your score will be tracked as you play.
|
152 |
+
|
153 |
+
## How to Play:
|
154 |
+
1. Adjust the patient parameters using the sliders
|
155 |
+
2. Make your diagnosis (Yes/No for diabetes risk)
|
156 |
+
3. Submit to see if you matched the model's prediction
|
157 |
+
4. Learn from the visualizations and tips
|
158 |
+
""")
|
159 |
+
|
160 |
+
with gr.Row():
|
161 |
+
with gr.Column():
|
162 |
+
pregnancies = gr.Slider(0, 17, step=1, label="Pregnancies")
|
163 |
+
glucose = gr.Slider(0, 200, value=120, step=1, label="Glucose Level")
|
164 |
+
blood_pressure = gr.Slider(0, 122, value=70, step=1, label="Blood Pressure")
|
165 |
+
skin_thickness = gr.Slider(0, 99, value=20, step=1, label="Skin Thickness")
|
166 |
+
|
167 |
+
with gr.Column():
|
168 |
+
insulin = gr.Slider(0, 846, value=80, step=1, label="Insulin")
|
169 |
+
bmi = gr.Slider(0.0, 67.1, value=25.0, step=0.1, label="BMI")
|
170 |
+
diabetes_pedigree = gr.Slider(0.078, 2.42, value=0.5, step=0.001, label="Diabetes Pedigree")
|
171 |
+
age = gr.Slider(21, 81, value=30, step=1, label="Age")
|
172 |
+
|
173 |
+
diagnosis = gr.Radio(["Yes", "No"], label="Your Diagnosis", info="Do you think this patient has diabetes?")
|
174 |
+
submit_btn = gr.Button("Submit Diagnosis", variant="primary")
|
175 |
+
|
176 |
+
with gr.Row():
|
177 |
+
result_box = gr.Textbox(label="Game Result", lines=5)
|
178 |
+
tips_box = gr.Textbox(label="Health Tips & Information", lines=5)
|
179 |
+
|
180 |
+
with gr.Row():
|
181 |
+
radar_plot = gr.Plot(label="Patient Risk Factors")
|
182 |
+
importance_plot = gr.Plot(label="Feature Importance")
|
183 |
+
|
184 |
+
submit_btn.click(
|
185 |
+
fn=game.predict_and_play,
|
186 |
+
inputs=[pregnancies, glucose, blood_pressure, skin_thickness,
|
187 |
+
insulin, bmi, diabetes_pedigree, age, diagnosis],
|
188 |
+
outputs=[result_box, radar_plot, importance_plot, tips_box]
|
189 |
+
)
|
190 |
+
|
191 |
+
gr.Markdown("""
|
192 |
+
## 📚 About the Features
|
193 |
+
|
194 |
+
- **Pregnancies**: Number of times pregnant
|
195 |
+
- **Glucose**: Plasma glucose concentration (2 hours in an oral glucose tolerance test)
|
196 |
+
- **Blood Pressure**: Diastolic blood pressure (mm Hg)
|
197 |
+
- **Skin Thickness**: Triceps skin fold thickness (mm)
|
198 |
+
- **Insulin**: 2-Hour serum insulin (mu U/ml)
|
199 |
+
- **BMI**: Body mass index (weight in kg/(height in m)²)
|
200 |
+
- **Diabetes Pedigree**: A function scoring likelihood of diabetes based on family history
|
201 |
+
- **Age**: Age in years
|
202 |
+
""")
|
203 |
+
|
204 |
+
if __name__ == "__main__":
|
205 |
+
interface.launch()
|