MahatirTusher commited on
Commit
eb2c6d9
·
verified ·
1 Parent(s): 07400cf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -206
app.py CHANGED
@@ -10,30 +10,41 @@ with open("stroke_clf.pkl", "rb") as f:
10
  with open("stroke_reg.pkl", "rb") as f:
11
  reg_model = pickle.load(f)
12
 
13
- def predict_stroke(age, chest_pain, shortness_breath, irregular_heartbeat, fatigue_weakness,
14
- dizziness, swelling, pain_neck_jaw, excessive_sweating, persistent_cough,
15
- nausea_vomiting, high_bp, chest_discomfort, cold_hands_feet, snoring, anxiety):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  """
17
- Prepares input features and returns stroke risk prediction using both models.
18
  """
19
- features = [
20
- 1 if chest_pain else 0,
21
- 1 if shortness_breath else 0,
22
- 1 if irregular_heartbeat else 0,
23
- 1 if fatigue_weakness else 0,
24
- 1 if dizziness else 0,
25
- 1 if swelling else 0,
26
- 1 if pain_neck_jaw else 0,
27
- 1 if excessive_sweating else 0,
28
- 1 if persistent_cough else 0,
29
- 1 if nausea_vomiting else 0,
30
- 1 if high_bp else 0,
31
- 1 if chest_discomfort else 0,
32
- 1 if cold_hands_feet else 0,
33
- 1 if snoring else 0,
34
- 1 if anxiety else 0,
35
- age
36
- ]
37
 
38
  sample_input = np.array([features])
39
 
@@ -42,224 +53,235 @@ def predict_stroke(age, chest_pain, shortness_breath, irregular_heartbeat, fatig
42
  regression_result = reg_model.predict(sample_input)[0]
43
  risk_percentage = round(regression_result, 2)
44
 
45
- # Simulate processing time for better UX
46
- time.sleep(1)
47
 
48
- # Format the response based on risk level
49
  if classification_result == 1:
 
 
50
  result = f"""
51
- ## 🚨 Risk Assessment Results
52
-
53
- **Status:** At Risk
54
- **Risk Level:** {risk_percentage}%
55
-
56
- ### Important Next Steps:
57
- 1. 👨‍⚕️ Schedule an immediate appointment with your healthcare provider
58
- 2. 📊 Monitor your blood pressure regularly
59
- 3. 💊 Take prescribed medications as directed
60
- 4. 📝 Maintain a log of any symptoms you experience
61
-
62
- ### Lifestyle Recommendations:
63
- - 🏃‍♂️ Start gentle exercise after consulting your doctor
64
- - 🥗 Follow a heart-healthy diet
65
- - 😴 Ensure 7-8 hours of quality sleep
66
- - 🚭 Quit smoking if applicable
67
- - 🧘‍♂️ Practice stress management techniques
68
 
69
- Remember: Early intervention is key to preventing stroke. Please consult a healthcare professional as soon as possible.
70
- """
 
 
 
 
 
 
 
71
  else:
72
  result = f"""
73
- ## Risk Assessment Results
74
-
75
- **Status:** Low Risk
76
- **Risk Level:** {risk_percentage}%
77
-
78
- ### Maintaining Your Health:
79
- 1. 🏃‍♂️ Continue regular exercise
80
- 2. 🥗 Maintain a balanced diet
81
- 3. 🩺 Schedule regular check-ups
82
- 4. 💧 Stay hydrated
83
- 5. 😌 Manage stress levels
84
-
85
- ### Preventive Measures:
86
- - 🌟 Regular physical activity (150 minutes/week)
87
- - 🍎 Five servings of fruits and vegetables daily
88
- - 💤 Consistent sleep schedule
89
- - 🧘‍♂️ Regular relaxation practices
90
- - 📊 Annual health screenings
91
 
92
- Keep up the good work in maintaining your health!
93
- """
 
 
 
 
 
 
 
94
 
95
  return result
96
 
97
- # Create the Gradio interface with a more interactive layout
98
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="purple")) as demo:
99
- # Header
100
- gr.Markdown(
101
- """
102
- # **Welcome to EarlyMed Stroke Risk Prediction Tool! 🏥🧠**
103
-
104
- Welcome to **EarlyMed**—an initiative by our team at **VIT-AP University**, dedicated to empowering you with early health insights.
105
- **Leveraging AI for early detection**, our mission is simple: ✨ **"Early Detection, Smarter Decision."**
106
 
107
- As part of our commitment to preventive healthcare, we have developed the **EarlyMed Stroke Risk Prediction Tool**
108
- to help you assess your stroke risk before consulting a doctor. This tool is designed to provide **timely insights**
109
- and encourage proactive health decisions.
 
 
 
 
 
110
  """)
111
 
112
  with gr.Row():
113
  with gr.Column():
114
  # Basic Information
115
- gr.Markdown("### 👤 Basic Information")
116
- age = gr.Slider(label="What is your age?", minimum=18, maximum=100, step=1, value=50)
117
-
 
 
 
 
 
 
 
 
118
  # Primary Symptoms
119
- gr.Markdown("### 🫀 Primary Symptoms")
120
- chest_pain = gr.Radio(
121
- label="First of all, are you experiencing any chest pain?",
122
- choices=["No", "Yes"],
123
- value="No"
124
- )
125
- shortness_breath = gr.Radio(
126
- label="Do you feel short of breath during normal activities?",
127
- choices=["No", "Yes"],
128
- value="No"
129
- )
130
- irregular_heartbeat = gr.Radio(
131
- label="Have you noticed irregular heartbeats?",
132
- choices=["No", "Yes"],
133
- value="No"
134
- )
135
-
 
 
 
 
136
  with gr.Column():
137
- # Secondary Symptoms
138
- gr.Markdown("### 🤒 Additional Symptoms")
139
- fatigue_weakness = gr.Radio(
140
- label="Now I am gonna check some additional features. Do you feel unusual fatigue or weakness?",
141
- choices=["No", "Yes"],
142
- value="No"
143
- )
144
- dizziness = gr.Radio(
145
- label="Do you experience dizziness?",
146
- choices=["No", "Yes"],
147
- value="No"
148
- )
149
- swelling = gr.Radio(
150
- label="Have you noticed swelling in your extremities?",
151
- choices=["No", "Yes"],
152
- value="No"
153
- )
154
-
 
155
  with gr.Row():
156
  with gr.Column():
157
- # Additional Health Indicators
158
- gr.Markdown("### 🏥 Health Indicators")
159
- pain_neck_jaw = gr.Radio(
160
- label="Do you have pain in neck, jaw, or shoulders?",
161
- choices=["No", "Yes"],
162
- value="No"
163
- )
164
- excessive_sweating = gr.Radio(
165
- label="Do you experience excessive sweating?",
166
- choices=["No", "Yes"],
167
- value="No"
168
- )
169
- persistent_cough = gr.Radio(
170
- label="Do you have a persistent cough?",
171
- choices=["No", "Yes"],
172
- value="No"
173
- )
174
-
 
175
  with gr.Column():
176
- # Risk Factors
177
- gr.Markdown("### ⚠️ Risk Factors")
178
- nausea_vomiting = gr.Radio(
179
- label="Do you experience nausea or vomiting?",
180
- choices=["No", "Yes"],
181
- value="No"
182
- )
183
- high_bp = gr.Radio(
184
- label="Have you been diagnosed with high blood pressure?",
185
- choices=["No", "Yes"],
186
- value="No"
187
- )
188
- chest_discomfort = gr.Radio(
189
- label="Do you feel chest discomfort during activities?",
190
- choices=["No", "Yes"],
191
- value="No"
192
- )
193
-
 
194
  with gr.Row():
195
  with gr.Column():
196
  # Lifestyle Factors
197
- gr.Markdown("### 🌟 Lifestyle Factors")
198
- cold_hands_feet = gr.Radio(
199
- label="Do your hands or feet often feel cold?",
200
- choices=["No", "Yes"],
201
- value="No"
202
- )
203
- snoring = gr.Radio(
204
- label="Do you snore or have sleep apnea?",
205
- choices=["No", "Yes"],
206
- value="No"
207
- )
208
- anxiety = gr.Radio(
209
- label="Do you experience frequent anxiety?",
210
- choices=["No", "Yes"],
211
- value="No"
212
- )
213
-
 
214
  # Submit Button
215
- submit_btn = gr.Button("Analyze My Risk", variant="primary")
 
 
 
 
 
216
 
217
  # Output
218
- output = gr.Markdown(label="Risk Assessment Results")
219
-
220
- # Process inputs
221
- def process_inputs(*args):
222
- # Convert "Yes"/"No" to boolean
223
- bool_args = [arg == "Yes" for arg in args[1:]]
224
- return predict_stroke(args[0], *bool_args)
225
 
 
226
  submit_btn.click(
227
- process_inputs,
228
- inputs=[age, chest_pain, shortness_breath, irregular_heartbeat,
229
  fatigue_weakness, dizziness, swelling, pain_neck_jaw,
230
  excessive_sweating, persistent_cough, nausea_vomiting,
231
  high_bp, chest_discomfort, cold_hands_feet, snoring, anxiety],
232
  outputs=output
233
  )
234
 
235
- # Information Section
236
- gr.Markdown(
237
- """
238
- ---
239
- ### **How Does This Work? 🤖**
240
- Our AI model analyzes key health factors—such as **age, blood pressure, lifestyle habits, and medical history**—to predict your stroke risk with high accuracy. The tool uses **two approaches**:
241
-
242
- 🔹 **Classification Model:** Determines whether you are at risk or not.
243
- 🔹 **Regression Model:** Estimates your stroke risk percentage.
244
-
245
- ### **What to Do If Your Stroke Risk is High? 🚨**
246
- If the tool predicts a high risk of stroke, don't panic! Here's what you should do:
247
-
248
- ✅ **Consult a Doctor:** Share your results with a healthcare professional for expert advice.
249
- ✅ **Monitor Your Health:** Keep track of your **blood pressure, cholesterol levels, and overall fitness.**
250
- ✅ **Adopt a Healthy Lifestyle:** Regular exercise, a balanced diet, and quitting smoking can significantly reduce stroke risks.
251
- ✅ **Manage Chronic Conditions:** If you have **diabetes or hypertension**, ensure they are well-controlled.
252
-
253
- 💡 **Important:** This tool is meant for **early awareness** and is **not a substitute for medical diagnosis**. Always consult a doctor for professional assessment and guidance.
254
-
255
- Stay informed, stay healthy, and take control of your well-being! 💙💪
256
-
257
- ---
258
-
259
- *© 2025 EarlyMed - VIT-AP University*
260
-
261
- **Disclaimer:** This tool is for informational purposes only and should not be used as a substitute for professional medical advice, diagnosis, or treatment.
262
- """
263
- )
264
 
 
265
  demo.launch()
 
10
  with open("stroke_reg.pkl", "rb") as f:
11
  reg_model = pickle.load(f)
12
 
13
+ # Custom CSS for enhanced styling
14
+ custom_css = """
15
+ .gradio-container {
16
+ max-width: 1200px !important;
17
+ margin-left: auto !important;
18
+ margin-right: auto !important;
19
+ }
20
+
21
+ .container {
22
+ margin: 0 auto !important;
23
+ padding: 2rem !important;
24
+ }
25
+
26
+ .question-group {
27
+ border: 1px solid #e5e7eb !important;
28
+ border-radius: 8px !important;
29
+ padding: 1.5rem !important;
30
+ margin-bottom: 1.5rem !important;
31
+ background: white !important;
32
+ }
33
+
34
+ .footer {
35
+ text-align: center !important;
36
+ padding: 2rem !important;
37
+ background: #f8fafc !important;
38
+ border-top: 1px solid #e5e7eb !important;
39
+ }
40
+ """
41
+
42
+ def predict_stroke(*inputs):
43
  """
44
+ Enhanced prediction function with detailed output formatting
45
  """
46
+ age = inputs[0]
47
+ features = [1 if x == "Yes" else 0 for x in inputs[1:]] + [age]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  sample_input = np.array([features])
50
 
 
53
  regression_result = reg_model.predict(sample_input)[0]
54
  risk_percentage = round(regression_result, 2)
55
 
56
+ # Simulate processing
57
+ time.sleep(1.5)
58
 
59
+ # Enhanced results formatting
60
  if classification_result == 1:
61
+ severity = "High" if risk_percentage > 70 else "Moderate"
62
+ color = "red" if risk_percentage > 70 else "orange"
63
  result = f"""
64
+ <div style='background-color: #FEF2F2; padding: 20px; border-radius: 10px; border: 1px solid {color}'>
65
+ <h2 style='color: {color}; margin-bottom: 15px'>🚨 Risk Assessment Results: {severity} Risk</h2>
66
+ <div style='background-color: white; padding: 15px; border-radius: 8px; margin-bottom: 15px'>
67
+ <p style='font-size: 18px; margin-bottom: 10px'><strong>Risk Level:</strong> {risk_percentage}%</p>
68
+ <p style='color: {color}'><strong>Status:</strong> Immediate Attention Recommended</p>
69
+ </div>
70
+
71
+ <h3 style='margin: 20px 0 10px 0'>📋 Recommended Actions:</h3>
72
+ <ol style='margin-left: 20px'>
73
+ <li>Schedule an urgent appointment with your healthcare provider</li>
74
+ <li>Begin daily blood pressure monitoring</li>
75
+ <li>Review and log all current medications</li>
76
+ <li>Start a symptom diary</li>
77
+ </ol>
 
 
 
78
 
79
+ <h3 style='margin: 20px 0 10px 0'>🌟 Immediate Lifestyle Changes:</h3>
80
+ <ul style='margin-left: 20px'>
81
+ <li>Reduce sodium intake</li>
82
+ <li>Increase water consumption</li>
83
+ <li>Practice stress-reduction techniques</li>
84
+ <li>Ensure 7-8 hours of quality sleep</li>
85
+ </ul>
86
+ </div>
87
+ """
88
  else:
89
  result = f"""
90
+ <div style='background-color: #F0FDF4; padding: 20px; border-radius: 10px; border: 1px solid #22C55E'>
91
+ <h2 style='color: #22C55E; margin-bottom: 15px'>✅ Risk Assessment Results: Low Risk</h2>
92
+ <div style='background-color: white; padding: 15px; border-radius: 8px; margin-bottom: 15px'>
93
+ <p style='font-size: 18px; margin-bottom: 10px'><strong>Risk Level:</strong> {risk_percentage}%</p>
94
+ <p style='color: #22C55E'><strong>Status:</strong> Healthy Range</p>
95
+ </div>
96
+
97
+ <h3 style='margin: 20px 0 10px 0'>🌟 Maintaining Your Health:</h3>
98
+ <ul style='margin-left: 20px'>
99
+ <li>Continue regular exercise routine</li>
100
+ <li>Maintain balanced nutrition</li>
101
+ <li>Schedule regular check-ups</li>
102
+ <li>Practice stress management</li>
103
+ </ul>
 
 
 
 
104
 
105
+ <h3 style='margin: 20px 0 10px 0'>💪 Preventive Measures:</h3>
106
+ <ul style='margin-left: 20px'>
107
+ <li>Annual health screenings</li>
108
+ <li>Regular blood pressure checks</li>
109
+ <li>Adequate sleep and hydration</li>
110
+ <li>Active lifestyle maintenance</li>
111
+ </ul>
112
+ </div>
113
+ """
114
 
115
  return result
116
 
117
+ # Create the enhanced Gradio interface
118
+ with gr.Blocks(
119
+ theme=gr.themes.Soft(primary_hue="blue", secondary_hue="purple"),
120
+ title="EarlyMed: AI-Powered Stroke Risk Assessment",
121
+ css=custom_css
122
+ ) as demo:
 
 
 
123
 
124
+ # Header Section
125
+ gr.HTML("""
126
+ <div style="text-align: center; padding: 2rem; background: linear-gradient(to right, #E8F0FF, #F0F7FF);">
127
+ <h1 style="color: #1E40AF; margin-bottom: 1rem;">🌟 EarlyMed: AI-Powered Stroke Risk Assessment 🧠</h1>
128
+ <p style="color: #4B5563; font-size: 1.1rem; max-width: 800px; margin: 0 auto;">
129
+ Welcome to <strong>EarlyMed</strong>—a VIT-AP University initiative using advanced AI to help you understand your stroke risk factors.
130
+ </p>
131
+ </div>
132
  """)
133
 
134
  with gr.Row():
135
  with gr.Column():
136
  # Basic Information
137
+ with gr.Group(elem_classes="question-group"):
138
+ gr.Markdown("### 👤 Your Profile")
139
+ age = gr.Slider(
140
+ label="How old are you?",
141
+ minimum=18,
142
+ maximum=100,
143
+ step=1,
144
+ value=50,
145
+ info="Move the slider to your age"
146
+ )
147
+
148
  # Primary Symptoms
149
+ with gr.Group(elem_classes="question-group"):
150
+ gr.Markdown("### 💗 Heart & Chest Symptoms")
151
+ chest_pain = gr.Radio(
152
+ label="Do you experience any discomfort or pain in your chest?",
153
+ choices=["No", "Yes"],
154
+ value="No",
155
+ info="This might feel like pressure, squeezing, or general discomfort"
156
+ )
157
+ shortness_breath = gr.Radio(
158
+ label="Do you find yourself getting out of breath easily?",
159
+ choices=["No", "Yes"],
160
+ value="No",
161
+ info="For example, during light activities like climbing stairs"
162
+ )
163
+ irregular_heartbeat = gr.Radio(
164
+ label="Have you noticed your heart beating irregularly?",
165
+ choices=["No", "Yes"],
166
+ value="No",
167
+ info="This might feel like skipped beats or fluttering"
168
+ )
169
+
170
  with gr.Column():
171
+ # Daily Symptoms
172
+ with gr.Group(elem_classes="question-group"):
173
+ gr.Markdown("### 😮‍💨 Daily Experiences")
174
+ fatigue_weakness = gr.Radio(
175
+ label="Do you often feel unusually tired or weak?",
176
+ choices=["No", "Yes"],
177
+ value="No"
178
+ )
179
+ dizziness = gr.Radio(
180
+ label="Do you experience dizziness or light-headedness?",
181
+ choices=["No", "Yes"],
182
+ value="No"
183
+ )
184
+ swelling = gr.Radio(
185
+ label="Have you noticed swelling in your legs or ankles?",
186
+ choices=["No", "Yes"],
187
+ value="No"
188
+ )
189
+
190
  with gr.Row():
191
  with gr.Column():
192
+ # Additional Symptoms
193
+ with gr.Group(elem_classes="question-group"):
194
+ gr.Markdown("### 🤒 Additional Signs")
195
+ pain_neck_jaw = gr.Radio(
196
+ label="Do you experience pain in your neck, jaw, or shoulders?",
197
+ choices=["No", "Yes"],
198
+ value="No"
199
+ )
200
+ excessive_sweating = gr.Radio(
201
+ label="Do you sweat more than usual, even when not active?",
202
+ choices=["No", "Yes"],
203
+ value="No"
204
+ )
205
+ persistent_cough = gr.Radio(
206
+ label="Have you developed a cough that won't go away?",
207
+ choices=["No", "Yes"],
208
+ value="No"
209
+ )
210
+
211
  with gr.Column():
212
+ # Health Conditions
213
+ with gr.Group(elem_classes="question-group"):
214
+ gr.Markdown("### 🏥 Health Conditions")
215
+ nausea_vomiting = gr.Radio(
216
+ label="Do you feel nauseated or sick to your stomach?",
217
+ choices=["No", "Yes"],
218
+ value="No"
219
+ )
220
+ high_bp = gr.Radio(
221
+ label="Has a doctor ever told you that you have high blood pressure?",
222
+ choices=["No", "Yes"],
223
+ value="No"
224
+ )
225
+ chest_discomfort = gr.Radio(
226
+ label="Do you feel discomfort in your chest when you're active?",
227
+ choices=["No", "Yes"],
228
+ value="No"
229
+ )
230
+
231
  with gr.Row():
232
  with gr.Column():
233
  # Lifestyle Factors
234
+ with gr.Group(elem_classes="question-group"):
235
+ gr.Markdown("### 🌟 Lifestyle & Well-being")
236
+ cold_hands_feet = gr.Radio(
237
+ label="Do your hands or feet often feel unusually cold?",
238
+ choices=["No", "Yes"],
239
+ value="No"
240
+ )
241
+ snoring = gr.Radio(
242
+ label="Has anyone told you that you snore loudly or stop breathing during sleep?",
243
+ choices=["No", "Yes"],
244
+ value="No"
245
+ )
246
+ anxiety = gr.Radio(
247
+ label="Do you often feel anxious or experience a sense of doom?",
248
+ choices=["No", "Yes"],
249
+ value="No"
250
+ )
251
+
252
  # Submit Button
253
+ gr.Markdown("""<div style='text-align: center; margin: 2rem 0;'>""")
254
+ submit_btn = gr.Button(
255
+ "Analyze My Risk Factors",
256
+ variant="primary",
257
+ size="lg"
258
+ )
259
 
260
  # Output
261
+ output = gr.HTML(label="Assessment Results")
 
 
 
 
 
 
262
 
263
+ # Wire up the prediction
264
  submit_btn.click(
265
+ predict_stroke,
266
+ inputs=[age, chest_pain, shortness_breath, irregular_heartbeat,
267
  fatigue_weakness, dizziness, swelling, pain_neck_jaw,
268
  excessive_sweating, persistent_cough, nausea_vomiting,
269
  high_bp, chest_discomfort, cold_hands_feet, snoring, anxiety],
270
  outputs=output
271
  )
272
 
273
+ # Footer
274
+ gr.HTML("""
275
+ <div style="text-align: center; margin-top: 2rem; padding: 2rem; background: linear-gradient(to right, #F8FAFC, #F0F7FF);">
276
+ <h3 style="color: #1E40AF; margin-bottom: 1rem;">💡 Important Note</h3>
277
+ <p style="color: #4B5563; max-width: 800px; margin: 0 auto 1rem auto;">
278
+ This tool is designed for educational purposes and early awareness only. It is not a substitute for professional medical diagnosis or advice.
279
+ </p>
280
+ <p style="color: #6B7280; font-size: 0.9rem;">
281
+ © 2025 EarlyMed - VIT-AP University | All Rights Reserved
282
+ </p>
283
+ </div>
284
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
+ # Launch the interface
287
  demo.launch()