DreamStream-1 commited on
Commit
e2fe7f3
·
verified ·
1 Parent(s): 88f558f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -44
app.py CHANGED
@@ -12,6 +12,11 @@ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipe
12
  import googlemaps
13
  import folium
14
  import torch
 
 
 
 
 
15
 
16
  # Suppress TensorFlow warnings
17
  os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
@@ -47,7 +52,7 @@ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/e
47
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
48
 
49
  # Disease dictionary to map disease names to numerical values
50
- disease_dict = {
51
  'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
52
  'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
53
  'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
@@ -60,7 +65,7 @@ disease_dict = {
60
  'Psoriasis': 39, 'Impetigo': 40
61
  }
62
 
63
- # Helper Functions
64
  def bag_of_words(s, words):
65
  """Convert user input to bag-of-words vector."""
66
  bag = [0] * len(words)
@@ -112,17 +117,6 @@ def detect_emotion(user_input):
112
  }
113
  return emotion_map.get(emotion, "Unknown 🤔"), emotion
114
 
115
- def disease_prediction(user_input):
116
- """Predict disease based on input symptoms."""
117
- # Here, we simulate disease prediction logic
118
- symptoms = user_input.lower().split()
119
- disease_probabilities = [random.random() for _ in disease_dict] # Placeholder for prediction model
120
-
121
- # Select the highest probability (for demonstration)
122
- disease_index = np.argmax(disease_probabilities)
123
- disease_name = list(disease_dict.keys())[disease_index]
124
- return disease_name
125
-
126
  def generate_suggestions(emotion):
127
  """Return relevant suggestions based on detected emotions."""
128
  emotion_key = emotion.lower()
@@ -177,7 +171,6 @@ def get_health_professionals_and_map(location, query):
177
  professionals = []
178
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
179
  for place in places_result:
180
- # Use a list of values to append each professional
181
  professionals.append([place['name'], place.get('vicinity', 'No address provided')])
182
  folium.Marker(
183
  location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
@@ -189,17 +182,79 @@ def get_health_professionals_and_map(location, query):
189
  except Exception as e:
190
  return [], "" # Return empty list on exception
191
 
192
- # Main Application Logic
193
- def app_function(user_input, location, query, history):
194
  chatbot_history, _ = generate_chatbot_response(user_input, history)
195
  sentiment_result = analyze_sentiment(user_input)
196
  emotion_result, cleaned_emotion = detect_emotion(user_input)
197
  suggestions = generate_suggestions(cleaned_emotion)
198
  professionals, map_html = get_health_professionals_and_map(location, query)
199
- disease_result = disease_prediction(user_input) # Get disease prediction
200
- return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html, disease_result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
- # CSS Styling
203
  custom_css = """
204
  body {
205
  font-family: 'Roboto', sans-serif;
@@ -280,30 +335,47 @@ textarea:hover, input:hover {
280
  # Gradio Application
281
  with gr.Blocks(css=custom_css) as app:
282
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
283
- with gr.Row():
284
- user_input = gr.Textbox(label="Please Enter Your Message Here")
285
- location = gr.Textbox(label="Please Enter Your Current Location Here")
286
- query = gr.Textbox(label="Please Enter Which Health Professional You Want To Search Nearby")
287
-
288
- submit = gr.Button(value="Submit", variant="primary")
289
-
290
- chatbot = gr.Chatbot(label="Chat History")
291
- sentiment = gr.Textbox(label="Detected Sentiment")
292
- emotion = gr.Textbox(label="Detected Emotion")
293
-
294
- # Adding Suggestions Title with Styled Markdown (Centered and Bold)
295
- gr.Markdown("Suggestions", elem_id="suggestions-title")
296
-
297
- suggestions = gr.DataFrame(headers=["Title", "Link"]) # Table for suggestions
298
- professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Changed to DataFrame
299
- map_html = gr.HTML(label="Interactive Map")
300
 
301
- disease = gr.Textbox(label="Predicted Disease") # Display disease prediction
302
-
303
- submit.click(
304
- app_function,
305
- inputs=[user_input, location, query, chatbot],
306
- outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html, disease],
307
- )
308
 
309
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  import googlemaps
13
  import folium
14
  import torch
15
+ import pandas as pd
16
+ from sklearn.tree import DecisionTreeClassifier
17
+ from sklearn.ensemble import RandomForestClassifier
18
+ from sklearn.naive_bayes import GaussianNB
19
+ from sklearn.metrics import accuracy_score
20
 
21
  # Suppress TensorFlow warnings
22
  os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
 
52
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
53
 
54
  # Disease dictionary to map disease names to numerical values
55
+ disease_dict = {
56
  'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
57
  'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
58
  'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
 
65
  'Psoriasis': 39, 'Impetigo': 40
66
  }
67
 
68
+ # Helper Functions for Chatbot
69
  def bag_of_words(s, words):
70
  """Convert user input to bag-of-words vector."""
71
  bag = [0] * len(words)
 
117
  }
118
  return emotion_map.get(emotion, "Unknown 🤔"), emotion
119
 
 
 
 
 
 
 
 
 
 
 
 
120
  def generate_suggestions(emotion):
121
  """Return relevant suggestions based on detected emotions."""
122
  emotion_key = emotion.lower()
 
171
  professionals = []
172
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
173
  for place in places_result:
 
174
  professionals.append([place['name'], place.get('vicinity', 'No address provided')])
175
  folium.Marker(
176
  location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
 
182
  except Exception as e:
183
  return [], "" # Return empty list on exception
184
 
185
+ # Main Application Logic for Chatbot
186
+ def app_function_chatbot(user_input, location, query, history):
187
  chatbot_history, _ = generate_chatbot_response(user_input, history)
188
  sentiment_result = analyze_sentiment(user_input)
189
  emotion_result, cleaned_emotion = detect_emotion(user_input)
190
  suggestions = generate_suggestions(cleaned_emotion)
191
  professionals, map_html = get_health_professionals_and_map(location, query)
192
+ return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
193
+
194
+ # Load datasets for Disease Prediction
195
+ def load_data():
196
+ df = pd.read_csv("Training.csv")
197
+ tr = pd.read_csv("Testing.csv")
198
+
199
+ # Encode diseases
200
+ df.replace({'prognosis': disease_dict}, inplace=True)
201
+ df = df.infer_objects(copy=False)
202
+ tr.replace({'prognosis': disease_dict}, inplace=True)
203
+ tr = tr.infer_objects(copy=False)
204
+
205
+ return df, tr
206
+
207
+ df, tr = load_data()
208
+ l1 = list(df.columns[:-1])
209
+ X = df[l1]
210
+ y = df['prognosis']
211
+ X_test = tr[l1]
212
+ y_test = tr['prognosis']
213
+
214
+ # Trained models
215
+ def train_models():
216
+ models = {
217
+ "Decision Tree": DecisionTreeClassifier(),
218
+ "Random Forest": RandomForestClassifier(),
219
+ "Naive Bayes": GaussianNB()
220
+ }
221
+ trained_models = {}
222
+ for model_name, model_obj in models.items():
223
+ model_obj.fit(X, y)
224
+ acc = accuracy_score(y_test, model_obj.predict(X_test))
225
+ trained_models[model_name] = (model_obj, acc)
226
+ return trained_models
227
+
228
+ trained_models = train_models()
229
+
230
+ def predict_disease(model, symptoms):
231
+ input_test = np.zeros(len(l1))
232
+ for symptom in symptoms:
233
+ if symptom in l1:
234
+ input_test[l1.index(symptom)] = 1
235
+ prediction = model.predict([input_test])[0]
236
+ return list(disease_dict.keys())[list(disease_dict.values()).index(prediction)]
237
+
238
+ # Disease Prediction Application Logic
239
+ def app_function_disease(name, symptom1, symptom2, symptom3, symptom4, symptom5):
240
+ if not name.strip():
241
+ return "Please enter the patient's name."
242
+
243
+ symptoms_selected = [s for s in [symptom1, symptom2, symptom3, symptom4, symptom5] if s != "None"]
244
+
245
+ if len(symptoms_selected) < 3:
246
+ return "Please select at least 3 symptoms for accurate prediction."
247
+
248
+ results = []
249
+ for model_name, (model, acc) in trained_models.items():
250
+ prediction = predict_disease(model, symptoms_selected)
251
+ result = f"{model_name} Prediction: Predicted Disease: **{prediction}**"
252
+ result += f" (Accuracy: {acc * 100:.2f}%)"
253
+ results.append(result)
254
+
255
+ return "\n\n".join(results)
256
 
257
+ # CSS Styling for the Gradio Interface
258
  custom_css = """
259
  body {
260
  font-family: 'Roboto', sans-serif;
 
335
  # Gradio Application
336
  with gr.Blocks(css=custom_css) as app:
337
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
 
339
+ with gr.Tab("Mental Health Chatbot"):
340
+ with gr.Row():
341
+ user_input = gr.Textbox(label="Please Enter Your Message Here")
342
+ location = gr.Textbox(label="Please Enter Your Current Location Here")
343
+ query = gr.Textbox(label="Please Enter Which Health Professional You Want To Search Nearby")
344
+
345
+ submit_chatbot = gr.Button(value="Submit Chatbot", variant="primary")
346
 
347
+ chatbot = gr.Chatbot(label="Chat History")
348
+ sentiment = gr.Textbox(label="Detected Sentiment")
349
+ emotion = gr.Textbox(label="Detected Emotion")
350
+
351
+ gr.Markdown("Suggestions", elem_id="suggestions-title")
352
+
353
+ suggestions = gr.DataFrame(headers=["Title", "Link"])
354
+ professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"])
355
+ map_html = gr.HTML(label="Interactive Map")
356
+
357
+ submit_chatbot.click(
358
+ app_function_chatbot,
359
+ inputs=[user_input, location, query, chatbot],
360
+ outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html],
361
+ )
362
+
363
+ with gr.Tab("Disease Prediction"):
364
+ patient_name = gr.Textbox(label="Name of Patient")
365
+ symptom1 = gr.Dropdown(["None"] + l1, label="Symptom 1")
366
+ symptom2 = gr.Dropdown(["None"] + l1, label="Symptom 2")
367
+ symptom3 = gr.Dropdown(["None"] + l1, label="Symptom 3")
368
+ symptom4 = gr.Dropdown(["None"] + l1, label="Symptom 4")
369
+ symptom5 = gr.Dropdown(["None"] + l1, label="Symptom 5")
370
+
371
+ submit_disease = gr.Button(value="Submit Disease Prediction", variant="primary")
372
+ disease_prediction_result = gr.Textbox(label="Prediction")
373
+
374
+ submit_disease.click(
375
+ app_function_disease,
376
+ inputs=[patient_name, symptom1, symptom2, symptom3, symptom4, symptom5],
377
+ outputs=disease_prediction_result,
378
+ )
379
+
380
+ # Launch the Gradio application
381
+ app.launch()