Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -57,17 +57,17 @@ def load_data():
|
|
57 |
try:
|
58 |
df = pd.read_csv("Training.csv")
|
59 |
tr = pd.read_csv("Testing.csv")
|
60 |
-
except FileNotFoundError:
|
61 |
-
raise RuntimeError("Data files not found. Please ensure `Training.csv` and `Testing.csv` are uploaded correctly.")
|
62 |
|
63 |
# Encode diseases
|
64 |
disease_dict = {
|
65 |
'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
|
66 |
-
'Peptic ulcer
|
67 |
-
'Hypertension
|
68 |
-
'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, '
|
69 |
'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
|
70 |
-
'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic
|
71 |
'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
|
72 |
'Hypoglycemia': 33, 'Osteoarthritis': 34, 'Arthritis': 35,
|
73 |
'(vertigo) Paroxysmal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
|
@@ -81,23 +81,21 @@ def load_data():
|
|
81 |
print("Unique values in prognosis after mapping:", df['prognosis'].unique())
|
82 |
|
83 |
# Ensure prognosis is purely numerical after mapping
|
84 |
-
if df['prognosis'].dtype == 'object':
|
85 |
raise ValueError(f"The prognosis contains unmapped values: {df['prognosis'].unique()}")
|
86 |
|
87 |
-
df['prognosis'] = df['prognosis'].astype(int)
|
88 |
-
df = df.infer_objects()
|
89 |
|
90 |
# Similar process for the testing data
|
91 |
tr.replace({'prognosis': disease_dict}, inplace=True)
|
92 |
-
|
93 |
-
# Check unique values in testing data
|
94 |
print("Unique values in prognosis for testing data after mapping:", tr['prognosis'].unique())
|
95 |
|
96 |
-
if tr['prognosis'].dtype == 'object':
|
97 |
raise ValueError(f"Testing data prognosis contains unmapped values: {tr['prognosis'].unique()}")
|
98 |
|
99 |
-
tr['prognosis'] = tr['prognosis'].astype(int)
|
100 |
-
tr = tr.infer_objects()
|
101 |
|
102 |
return df, tr, disease_dict
|
103 |
|
@@ -110,9 +108,9 @@ y_test = tr['prognosis']
|
|
110 |
|
111 |
# Encode the target variable with LabelEncoder if still in string format
|
112 |
le = LabelEncoder()
|
113 |
-
y_encoded = le.fit_transform(y)
|
114 |
|
115 |
-
def train_models():
|
116 |
models = {
|
117 |
"Decision Tree": DecisionTreeClassifier(),
|
118 |
"Random Forest": RandomForestClassifier(),
|
@@ -120,12 +118,15 @@ def train_models():
|
|
120 |
}
|
121 |
trained_models = {}
|
122 |
for model_name, model_obj in models.items():
|
123 |
-
|
124 |
-
|
125 |
-
|
|
|
|
|
|
|
126 |
return trained_models
|
127 |
|
128 |
-
trained_models = train_models()
|
129 |
|
130 |
def predict_disease(model, symptoms):
|
131 |
input_test = np.zeros(len(l1))
|
@@ -205,11 +206,39 @@ def detect_emotion(user_input):
|
|
205 |
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
206 |
|
207 |
def generate_suggestions(emotion):
|
|
|
208 |
emotion_key = emotion.lower()
|
209 |
suggestions = {
|
210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
211 |
}
|
212 |
-
|
213 |
formatted_suggestions = [
|
214 |
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
215 |
]
|
@@ -234,9 +263,10 @@ def get_health_professionals_and_map(location, query):
|
|
234 |
popup=f"{place['name']}"
|
235 |
).add_to(map_)
|
236 |
return professionals, map_._repr_html_()
|
237 |
-
return [], ""
|
238 |
except Exception as e:
|
239 |
-
|
|
|
240 |
|
241 |
# Main Application Logic
|
242 |
def app_function(user_input, location, query, symptoms, history):
|
@@ -261,10 +291,9 @@ def app_function(user_input, location, query, symptoms, history):
|
|
261 |
custom_css = """
|
262 |
body {
|
263 |
font-family: 'Roboto', sans-serif;
|
264 |
-
background-color: #3c6487;
|
265 |
color: white;
|
266 |
}
|
267 |
-
|
268 |
h1 {
|
269 |
background: #ffffff;
|
270 |
color: #000000;
|
@@ -274,7 +303,6 @@ h1 {
|
|
274 |
text-align: center;
|
275 |
font-size: 2.5rem;
|
276 |
}
|
277 |
-
|
278 |
textarea, input {
|
279 |
background: transparent;
|
280 |
color: black;
|
@@ -285,14 +313,12 @@ textarea, input {
|
|
285 |
outline: none;
|
286 |
border-radius: 8px;
|
287 |
}
|
288 |
-
|
289 |
textarea:focus, input:focus {
|
290 |
background: transparent;
|
291 |
color: black;
|
292 |
border: 2px solid orange;
|
293 |
outline: none;
|
294 |
}
|
295 |
-
|
296 |
.df-container {
|
297 |
background: white;
|
298 |
color: black;
|
@@ -304,26 +330,21 @@ textarea:focus, input:focus {
|
|
304 |
height: auto;
|
305 |
overflow-y: auto;
|
306 |
}
|
307 |
-
|
308 |
#suggestions-title {
|
309 |
-
text-align: center !important;
|
310 |
-
font-weight: bold !important;
|
311 |
-
color: white !important;
|
312 |
-
font-size: 4.2rem !important;
|
313 |
-
margin-bottom: 20px !important;
|
314 |
}
|
315 |
-
|
316 |
-
/* Style for the submit button */
|
317 |
.gr-button {
|
318 |
-
background-color: #ae1c93;
|
319 |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
320 |
transition: background-color 0.3s ease;
|
321 |
}
|
322 |
-
|
323 |
.gr-button:hover {
|
324 |
background-color: #8f167b;
|
325 |
}
|
326 |
-
|
327 |
.gr-button:active {
|
328 |
background-color: #7f156b;
|
329 |
}
|
@@ -334,9 +355,9 @@ with gr.Blocks(css=custom_css) as app:
|
|
334 |
gr.HTML("<h1>🌟 Well-Being Companion</h1>")
|
335 |
|
336 |
with gr.Row():
|
337 |
-
user_input = gr.Textbox(label="Please Enter Your Message Here")
|
338 |
-
location = gr.Textbox(label="Your Current Location Here")
|
339 |
-
query = gr.Textbox(label="Search Health Professionals Nearby")
|
340 |
|
341 |
with gr.Row():
|
342 |
symptom1 = gr.Dropdown(choices=["None"] + l1, label="Symptom 1")
|
@@ -353,10 +374,10 @@ with gr.Blocks(css=custom_css) as app:
|
|
353 |
|
354 |
gr.Markdown("Suggestions", elem_id="suggestions-title")
|
355 |
|
356 |
-
suggestions = gr.DataFrame(headers=["Title", "Link"])
|
357 |
-
professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"])
|
358 |
map_html = gr.HTML(label="Interactive Map")
|
359 |
-
disease_predictions = gr.Textbox(label="Disease Predictions")
|
360 |
|
361 |
submit.click(
|
362 |
app_function,
|
|
|
57 |
try:
|
58 |
df = pd.read_csv("Training.csv")
|
59 |
tr = pd.read_csv("Testing.csv")
|
60 |
+
except FileNotFoundError as e:
|
61 |
+
raise RuntimeError("Data files not found. Please ensure `Training.csv` and `Testing.csv` are uploaded correctly.") from e
|
62 |
|
63 |
# Encode diseases
|
64 |
disease_dict = {
|
65 |
'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
|
66 |
+
'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
|
67 |
+
'Hypertension': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
|
68 |
+
'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, 'Hepatitis A': 19,
|
69 |
'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
|
70 |
+
'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic hemorrhoids(piles)': 28,
|
71 |
'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
|
72 |
'Hypoglycemia': 33, 'Osteoarthritis': 34, 'Arthritis': 35,
|
73 |
'(vertigo) Paroxysmal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
|
|
|
81 |
print("Unique values in prognosis after mapping:", df['prognosis'].unique())
|
82 |
|
83 |
# Ensure prognosis is purely numerical after mapping
|
84 |
+
if df['prognosis'].dtype == 'object':
|
85 |
raise ValueError(f"The prognosis contains unmapped values: {df['prognosis'].unique()}")
|
86 |
|
87 |
+
df['prognosis'] = df['prognosis'].astype(int)
|
88 |
+
df = df.infer_objects()
|
89 |
|
90 |
# Similar process for the testing data
|
91 |
tr.replace({'prognosis': disease_dict}, inplace=True)
|
|
|
|
|
92 |
print("Unique values in prognosis for testing data after mapping:", tr['prognosis'].unique())
|
93 |
|
94 |
+
if tr['prognosis'].dtype == 'object':
|
95 |
raise ValueError(f"Testing data prognosis contains unmapped values: {tr['prognosis'].unique()}")
|
96 |
|
97 |
+
tr['prognosis'] = tr['prognosis'].astype(int)
|
98 |
+
tr = tr.infer_objects()
|
99 |
|
100 |
return df, tr, disease_dict
|
101 |
|
|
|
108 |
|
109 |
# Encode the target variable with LabelEncoder if still in string format
|
110 |
le = LabelEncoder()
|
111 |
+
y_encoded = le.fit_transform(y)
|
112 |
|
113 |
+
def train_models(X, y_encoded, X_test, y_test):
|
114 |
models = {
|
115 |
"Decision Tree": DecisionTreeClassifier(),
|
116 |
"Random Forest": RandomForestClassifier(),
|
|
|
118 |
}
|
119 |
trained_models = {}
|
120 |
for model_name, model_obj in models.items():
|
121 |
+
try:
|
122 |
+
model_obj.fit(X, y_encoded) # Fit the model
|
123 |
+
acc = accuracy_score(y_test, model_obj.predict(X_test))
|
124 |
+
trained_models[model_name] = (model_obj, acc)
|
125 |
+
except Exception as e:
|
126 |
+
print(f"Failed to train {model_name}: {e}")
|
127 |
return trained_models
|
128 |
|
129 |
+
trained_models = train_models(X, y_encoded, X_test, y_test)
|
130 |
|
131 |
def predict_disease(model, symptoms):
|
132 |
input_test = np.zeros(len(l1))
|
|
|
206 |
return emotion_map.get(emotion, "Unknown 🤔"), emotion
|
207 |
|
208 |
def generate_suggestions(emotion):
|
209 |
+
"""Return relevant suggestions based on detected emotions."""
|
210 |
emotion_key = emotion.lower()
|
211 |
suggestions = {
|
212 |
+
"joy": [
|
213 |
+
["Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
214 |
+
["Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
215 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
216 |
+
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
217 |
+
],
|
218 |
+
"anger": [
|
219 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
220 |
+
["Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"],
|
221 |
+
["Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
222 |
+
["Relaxation Video", "https://youtu.be/MIc299Flibs"],
|
223 |
+
],
|
224 |
+
"fear": [
|
225 |
+
["Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
|
226 |
+
["Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
227 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
228 |
+
["Relaxation Video", "https://youtu.be/yGKKz185M5o"],
|
229 |
+
],
|
230 |
+
"sadness": [
|
231 |
+
["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
|
232 |
+
["Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
233 |
+
["Relaxation Video", "https://youtu.be/-e-4Kx5px_I"],
|
234 |
+
],
|
235 |
+
"surprise": [
|
236 |
+
["Managing Stress", "https://www.health.harvard.edu/health-a-to-z"],
|
237 |
+
["Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
|
238 |
+
["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
|
239 |
+
],
|
240 |
}
|
241 |
+
|
242 |
formatted_suggestions = [
|
243 |
[title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
|
244 |
]
|
|
|
263 |
popup=f"{place['name']}"
|
264 |
).add_to(map_)
|
265 |
return professionals, map_._repr_html_()
|
266 |
+
return [], ""
|
267 |
except Exception as e:
|
268 |
+
print(f"Failed to fetch healthcare professionals: {e}")
|
269 |
+
return [], ""
|
270 |
|
271 |
# Main Application Logic
|
272 |
def app_function(user_input, location, query, symptoms, history):
|
|
|
291 |
custom_css = """
|
292 |
body {
|
293 |
font-family: 'Roboto', sans-serif;
|
294 |
+
background-color: #3c6487;
|
295 |
color: white;
|
296 |
}
|
|
|
297 |
h1 {
|
298 |
background: #ffffff;
|
299 |
color: #000000;
|
|
|
303 |
text-align: center;
|
304 |
font-size: 2.5rem;
|
305 |
}
|
|
|
306 |
textarea, input {
|
307 |
background: transparent;
|
308 |
color: black;
|
|
|
313 |
outline: none;
|
314 |
border-radius: 8px;
|
315 |
}
|
|
|
316 |
textarea:focus, input:focus {
|
317 |
background: transparent;
|
318 |
color: black;
|
319 |
border: 2px solid orange;
|
320 |
outline: none;
|
321 |
}
|
|
|
322 |
.df-container {
|
323 |
background: white;
|
324 |
color: black;
|
|
|
330 |
height: auto;
|
331 |
overflow-y: auto;
|
332 |
}
|
|
|
333 |
#suggestions-title {
|
334 |
+
text-align: center !important;
|
335 |
+
font-weight: bold !important;
|
336 |
+
color: white !important;
|
337 |
+
font-size: 4.2rem !important;
|
338 |
+
margin-bottom: 20px !important;
|
339 |
}
|
|
|
|
|
340 |
.gr-button {
|
341 |
+
background-color: #ae1c93;
|
342 |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
|
343 |
transition: background-color 0.3s ease;
|
344 |
}
|
|
|
345 |
.gr-button:hover {
|
346 |
background-color: #8f167b;
|
347 |
}
|
|
|
348 |
.gr-button:active {
|
349 |
background-color: #7f156b;
|
350 |
}
|
|
|
355 |
gr.HTML("<h1>🌟 Well-Being Companion</h1>")
|
356 |
|
357 |
with gr.Row():
|
358 |
+
user_input = gr.Textbox(label="Please Enter Your Message Here", placeholder="Type your message...")
|
359 |
+
location = gr.Textbox(label="Your Current Location Here", placeholder="Enter location...")
|
360 |
+
query = gr.Textbox(label="Search Health Professionals Nearby", placeholder="What are you looking for...")
|
361 |
|
362 |
with gr.Row():
|
363 |
symptom1 = gr.Dropdown(choices=["None"] + l1, label="Symptom 1")
|
|
|
374 |
|
375 |
gr.Markdown("Suggestions", elem_id="suggestions-title")
|
376 |
|
377 |
+
suggestions = gr.DataFrame(headers=["Title", "Link"])
|
378 |
+
professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"])
|
379 |
map_html = gr.HTML(label="Interactive Map")
|
380 |
+
disease_predictions = gr.Textbox(label="Disease Predictions")
|
381 |
|
382 |
submit.click(
|
383 |
app_function,
|