MahatirTusher commited on
Commit
07400cf
Β·
verified Β·
1 Parent(s): 0278f2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +265 -107
app.py CHANGED
@@ -1,107 +1,265 @@
1
- import gradio as gr
2
- import numpy as np
3
- import pickle
4
-
5
- # Load the trained models
6
- with open("stroke_clf.pkl", "rb") as f:
7
- clf_model = pickle.load(f)
8
-
9
- with open("stroke_reg.pkl", "rb") as f:
10
- reg_model = pickle.load(f)
11
-
12
- def predict_stroke(chest_pain, shortness_breath, irregular_heartbeat, fatigue_weakness,
13
- dizziness, swelling, pain_neck_jaw, excessive_sweating,
14
- persistent_cough, nausea_vomiting, high_bp, chest_discomfort,
15
- cold_hands_feet, snoring, anxiety, age):
16
- """
17
- Prepares the input features and returns stroke risk prediction using both the classification
18
- and regression models.
19
- """
20
- # Convert boolean inputs to 1 (True) or 0 (False), keeping age as numeric.
21
- features = [
22
- 1 if chest_pain else 0,
23
- 1 if shortness_breath else 0,
24
- 1 if irregular_heartbeat else 0,
25
- 1 if fatigue_weakness else 0,
26
- 1 if dizziness else 0,
27
- 1 if swelling else 0,
28
- 1 if pain_neck_jaw else 0,
29
- 1 if excessive_sweating else 0,
30
- 1 if persistent_cough else 0,
31
- 1 if nausea_vomiting else 0,
32
- 1 if high_bp else 0,
33
- 1 if chest_discomfort else 0,
34
- 1 if cold_hands_feet else 0,
35
- 1 if snoring else 0,
36
- 1 if anxiety else 0,
37
- age
38
- ]
39
-
40
- sample_input = np.array([features])
41
-
42
- # Get predictions
43
- classification_result = clf_model.predict(sample_input)[0]
44
- risk_class = "At Risk" if classification_result == 1 else "Not At Risk"
45
-
46
- regression_result = reg_model.predict(sample_input)[0]
47
- risk_percentage = round(regression_result, 2)
48
-
49
- return (f"**Classification Result:** {risk_class}\n"
50
- f"**Regression Result:** {risk_percentage}% stroke risk")
51
-
52
- # Build Gradio Interface using Blocks for a clean, organized UI
53
- with gr.Blocks(css=".output { white-space: pre-wrap; }") as demo:
54
- gr.Markdown(
55
- """
56
- # Stroke Risk Prediction
57
- This application uses two machine learning models to predict stroke risk:
58
-
59
- - **Classification Model:** Determines if an individual is at risk (Yes/No).
60
- - **Regression Model:** Estimates the stroke risk percentage.
61
-
62
- **Provide the following information based on your symptoms:**
63
- """
64
- )
65
-
66
- with gr.Row():
67
- with gr.Column():
68
- chest_pain = gr.Checkbox(label="Chest Pain")
69
- shortness_breath = gr.Checkbox(label="Shortness of Breath")
70
- irregular_heartbeat = gr.Checkbox(label="Irregular Heartbeat")
71
- fatigue_weakness = gr.Checkbox(label="Fatigue & Weakness")
72
- dizziness = gr.Checkbox(label="Dizziness")
73
- swelling = gr.Checkbox(label="Swelling (Edema)")
74
- pain_neck_jaw = gr.Checkbox(label="Pain in Neck/Jaw/Shoulder/Back")
75
- excessive_sweating = gr.Checkbox(label="Excessive Sweating")
76
- with gr.Column():
77
- persistent_cough = gr.Checkbox(label="Persistent Cough")
78
- nausea_vomiting = gr.Checkbox(label="Nausea/Vomiting")
79
- high_bp = gr.Checkbox(label="High Blood Pressure")
80
- chest_discomfort = gr.Checkbox(label="Chest Discomfort (During Activity)")
81
- cold_hands_feet = gr.Checkbox(label="Cold Hands/Feet")
82
- snoring = gr.Checkbox(label="Snoring/Sleep Apnea")
83
- anxiety = gr.Checkbox(label="Anxiety/Feeling of Doom")
84
- age = gr.Number(label="Age", value=50)
85
-
86
- predict_btn = gr.Button("Predict Stroke Risk", variant="primary")
87
- output = gr.Markdown(label="Prediction Results", elem_classes="output")
88
-
89
- predict_btn.click(
90
- predict_stroke,
91
- inputs=[
92
- chest_pain, shortness_breath, irregular_heartbeat, fatigue_weakness,
93
- dizziness, swelling, pain_neck_jaw, excessive_sweating,
94
- persistent_cough, nausea_vomiting, high_bp, chest_discomfort,
95
- cold_hands_feet, snoring, anxiety, age
96
- ],
97
- outputs=output
98
- )
99
-
100
- gr.Markdown(
101
- """
102
- ---
103
- **Disclaimer:** This tool is intended for informational purposes only and should not be used as a substitute for professional medical advice.
104
- """
105
- )
106
-
107
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import pickle
4
+ import time
5
+
6
+ # Load the trained models
7
+ with open("stroke_clf.pkl", "rb") as f:
8
+ clf_model = pickle.load(f)
9
+
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
+
40
+ # Get predictions
41
+ classification_result = clf_model.predict(sample_input)[0]
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()