DreamStream-1 commited on
Commit
d0463a0
·
verified ·
1 Parent(s): 902333f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -74
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"
@@ -46,9 +51,67 @@ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/e
46
  # Google Maps API Client
47
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
48
 
49
- # Helper Functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def bag_of_words(s, words):
51
- """Convert user input to bag-of-words vector."""
52
  bag = [0] * len(words)
53
  s_words = word_tokenize(s)
54
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
@@ -59,7 +122,6 @@ def bag_of_words(s, words):
59
  return np.array(bag)
60
 
61
  def generate_chatbot_response(message, history):
62
- """Generate chatbot response and maintain conversation history."""
63
  history = history or []
64
  try:
65
  result = chatbot_model.predict([bag_of_words(message, words)])
@@ -75,7 +137,6 @@ def generate_chatbot_response(message, history):
75
  return history, response
76
 
77
  def analyze_sentiment(user_input):
78
- """Analyze sentiment and map to emojis."""
79
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
80
  with torch.no_grad():
81
  outputs = model_sentiment(**inputs)
@@ -84,7 +145,6 @@ def analyze_sentiment(user_input):
84
  return f"Sentiment: {sentiment_map[sentiment_class]}"
85
 
86
  def detect_emotion(user_input):
87
- """Detect emotions based on input."""
88
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
89
  result = pipe(user_input)
90
  emotion = result[0]["label"].lower().strip()
@@ -99,52 +159,20 @@ def detect_emotion(user_input):
99
  return emotion_map.get(emotion, "Unknown 🤔"), emotion
100
 
101
  def generate_suggestions(emotion):
102
- """Return relevant suggestions based on detected emotions."""
103
  emotion_key = emotion.lower()
104
  suggestions = {
105
- "joy": [
106
- ["Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
107
- ["Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
108
- ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
109
- ["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
110
- ],
111
- "anger": [
112
- ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
113
- ["Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"],
114
- ["Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
115
- ["Relaxation Video", "https://youtu.be/MIc299Flibs"],
116
- ],
117
- "fear": [
118
- ["Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
119
- ["Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
120
- ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
121
- ["Relaxation Video", "https://youtu.be/yGKKz185M5o"],
122
- ],
123
- "sadness": [
124
- ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
125
- ["Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
126
- ["Relaxation Video", "https://youtu.be/-e-4Kx5px_I"],
127
- ],
128
- "surprise": [
129
- ["Managing Stress", "https://www.health.harvard.edu/health-a-to-z"],
130
- ["Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
131
- ["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
132
- ],
133
  }
134
 
135
- # Format the output to include HTML anchor tags
136
  formatted_suggestions = [
137
  [title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
138
  ]
139
-
140
  return formatted_suggestions
141
 
142
  def get_health_professionals_and_map(location, query):
143
- """Search nearby healthcare professionals using Google Maps API."""
144
  try:
145
  if not location or not query:
146
- return [], "" # Return empty list if inputs are missing
147
-
148
  geo_location = gmaps.geocode(location)
149
  if geo_location:
150
  lat, lng = geo_location[0]["geometry"]["location"].values()
@@ -152,35 +180,42 @@ def get_health_professionals_and_map(location, query):
152
  professionals = []
153
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
154
  for place in places_result:
155
- # Use a list of values to append each professional
156
  professionals.append([place['name'], place.get('vicinity', 'No address provided')])
157
  folium.Marker(
158
  location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
159
  popup=f"{place['name']}"
160
  ).add_to(map_)
161
  return professionals, map_._repr_html_()
162
-
163
- return [], "" # Return empty list if no professionals found
164
  except Exception as e:
165
- return [], "" # Return empty list on exception
166
 
167
  # Main Application Logic
168
- def app_function(user_input, location, query, history):
169
  chatbot_history, _ = generate_chatbot_response(user_input, history)
170
  sentiment_result = analyze_sentiment(user_input)
171
  emotion_result, cleaned_emotion = detect_emotion(user_input)
172
  suggestions = generate_suggestions(cleaned_emotion)
173
  professionals, map_html = get_health_professionals_and_map(location, query)
174
- return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
 
 
 
 
 
 
 
 
 
 
175
 
176
  # CSS Styling
177
  custom_css = """
178
  body {
179
  font-family: 'Roboto', sans-serif;
180
- background-color: #3c6487; /* Set the background color */
181
  color: white;
182
  }
183
-
184
  h1 {
185
  background: #ffffff;
186
  color: #000000;
@@ -190,7 +225,6 @@ h1 {
190
  text-align: center;
191
  font-size: 2.5rem;
192
  }
193
-
194
  textarea, input {
195
  background: transparent;
196
  color: black;
@@ -201,20 +235,12 @@ textarea, input {
201
  outline: none;
202
  border-radius: 8px;
203
  }
204
-
205
  textarea:focus, input:focus {
206
  background: transparent;
207
  color: black;
208
  border: 2px solid orange;
209
  outline: none;
210
  }
211
-
212
- textarea:hover, input:hover {
213
- background: transparent;
214
- color: black;
215
- border: 2px solid orange;
216
- }
217
-
218
  .df-container {
219
  background: white;
220
  color: black;
@@ -226,26 +252,21 @@ textarea:hover, input:hover {
226
  height: auto;
227
  overflow-y: auto;
228
  }
229
-
230
  #suggestions-title {
231
- text-align: center !important; /* Ensure the centering is applied */
232
- font-weight: bold !important; /* Ensure bold is applied */
233
- color: white !important; /* Ensure color is applied */
234
- font-size: 4.2rem !important; /* Ensure font size is applied */
235
- margin-bottom: 20px !important; /* Ensure margin is applied */
236
  }
237
-
238
- /* Style for the submit button */
239
  .gr-button {
240
- background-color: #ae1c93; /* Set the background color to #ae1c93 */
241
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
242
  transition: background-color 0.3s ease;
243
  }
244
-
245
  .gr-button:hover {
246
  background-color: #8f167b;
247
  }
248
-
249
  .gr-button:active {
250
  background-color: #7f156b;
251
  }
@@ -256,26 +277,35 @@ with gr.Blocks(css=custom_css) as app:
256
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
257
  with gr.Row():
258
  user_input = gr.Textbox(label="Please Enter Your Message Here")
259
- location = gr.Textbox(label="Please Enter Your Current Location Here")
260
- query = gr.Textbox(label="Please Enter Which Health Professional You Want To Search Nearby")
261
 
 
 
 
 
 
 
 
 
262
  submit = gr.Button(value="Submit", variant="primary")
263
 
264
  chatbot = gr.Chatbot(label="Chat History")
265
  sentiment = gr.Textbox(label="Detected Sentiment")
266
  emotion = gr.Textbox(label="Detected Emotion")
267
 
268
- # Adding Suggestions Title with Styled Markdown (Centered and Bold)
269
  gr.Markdown("Suggestions", elem_id="suggestions-title")
270
 
271
- suggestions = gr.DataFrame(headers=["Title", "Link"]) # Table for suggestions
272
- professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Changed to DataFrame
273
  map_html = gr.HTML(label="Interactive Map")
 
274
 
275
  submit.click(
276
  app_function,
277
- inputs=[user_input, location, query, chatbot],
278
- outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html],
279
  )
280
 
281
  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"
 
51
  # Google Maps API Client
52
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
53
 
54
+ # Disease Prediction Code
55
+ def load_data():
56
+ df = pd.read_csv("Training.csv")
57
+ tr = pd.read_csv("Testing.csv")
58
+
59
+ disease_dict = {
60
+ # Disease encoding dictionary...
61
+ }
62
+ df.replace({'prognosis': disease_dict}, inplace=True)
63
+ df = df.infer_objects(copy=False)
64
+
65
+ tr.replace({'prognosis': disease_dict}, inplace=True)
66
+ tr = tr.infer_objects(copy=False)
67
+
68
+ return df, tr, disease_dict
69
+
70
+ df, tr, disease_dict = load_data()
71
+ l1 = list(df.columns[:-1])
72
+ X = df[l1]
73
+ y = df['prognosis']
74
+ X_test = tr[l1]
75
+ y_test = tr['prognosis']
76
+
77
+ def train_models():
78
+ models = {
79
+ "Decision Tree": DecisionTreeClassifier(),
80
+ "Random Forest": RandomForestClassifier(),
81
+ "Naive Bayes": GaussianNB()
82
+ }
83
+ trained_models = {}
84
+ for model_name, model_obj in models.items():
85
+ model_obj.fit(X, y)
86
+ acc = accuracy_score(y_test, model_obj.predict(X_test))
87
+ trained_models[model_name] = (model_obj, acc)
88
+ return trained_models
89
+
90
+ trained_models = train_models()
91
+
92
+ def predict_disease(model, symptoms):
93
+ input_test = np.zeros(len(l1))
94
+ for symptom in symptoms:
95
+ if symptom in l1:
96
+ input_test[l1.index(symptom)] = 1
97
+ prediction = model.predict([input_test])[0]
98
+ return list(disease_dict.keys())[list(disease_dict.values()).index(prediction)]
99
+
100
+ def disease_prediction_interface(symptoms):
101
+ symptoms_selected = [s for s in symptoms if s != "None"]
102
+
103
+ if len(symptoms_selected) < 3:
104
+ return "Please select at least 3 symptoms for accurate prediction."
105
+
106
+ results = []
107
+ for model_name, (model, acc) in trained_models.items():
108
+ prediction = predict_disease(model, symptoms_selected)
109
+ results.append(f"{model_name} Prediction: Predicted Disease: **{prediction}** (Accuracy: **{acc * 100:.2f}%**)")
110
+
111
+ return results
112
+
113
+ # Helper Functions (for chatbot)
114
  def bag_of_words(s, words):
 
115
  bag = [0] * len(words)
116
  s_words = word_tokenize(s)
117
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
 
122
  return np.array(bag)
123
 
124
  def generate_chatbot_response(message, history):
 
125
  history = history or []
126
  try:
127
  result = chatbot_model.predict([bag_of_words(message, words)])
 
137
  return history, response
138
 
139
  def analyze_sentiment(user_input):
 
140
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
141
  with torch.no_grad():
142
  outputs = model_sentiment(**inputs)
 
145
  return f"Sentiment: {sentiment_map[sentiment_class]}"
146
 
147
  def detect_emotion(user_input):
 
148
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
149
  result = pipe(user_input)
150
  emotion = result[0]["label"].lower().strip()
 
159
  return emotion_map.get(emotion, "Unknown 🤔"), emotion
160
 
161
  def generate_suggestions(emotion):
 
162
  emotion_key = emotion.lower()
163
  suggestions = {
164
+ # Suggestions based on emotion...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  }
166
 
 
167
  formatted_suggestions = [
168
  [title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
169
  ]
 
170
  return formatted_suggestions
171
 
172
  def get_health_professionals_and_map(location, query):
 
173
  try:
174
  if not location or not query:
175
+ return [], ""
 
176
  geo_location = gmaps.geocode(location)
177
  if geo_location:
178
  lat, lng = geo_location[0]["geometry"]["location"].values()
 
180
  professionals = []
181
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
182
  for place in places_result:
 
183
  professionals.append([place['name'], place.get('vicinity', 'No address provided')])
184
  folium.Marker(
185
  location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
186
  popup=f"{place['name']}"
187
  ).add_to(map_)
188
  return professionals, map_._repr_html_()
189
+ return [], ""
 
190
  except Exception as e:
191
+ return [], ""
192
 
193
  # Main Application Logic
194
+ def app_function(user_input, location, query, symptoms, history):
195
  chatbot_history, _ = generate_chatbot_response(user_input, history)
196
  sentiment_result = analyze_sentiment(user_input)
197
  emotion_result, cleaned_emotion = detect_emotion(user_input)
198
  suggestions = generate_suggestions(cleaned_emotion)
199
  professionals, map_html = get_health_professionals_and_map(location, query)
200
+ disease_results = disease_prediction_interface(symptoms)
201
+
202
+ return (
203
+ chatbot_history,
204
+ sentiment_result,
205
+ emotion_result,
206
+ suggestions,
207
+ professionals,
208
+ map_html,
209
+ disease_results
210
+ )
211
 
212
  # CSS Styling
213
  custom_css = """
214
  body {
215
  font-family: 'Roboto', sans-serif;
216
+ background-color: #3c6487;
217
  color: white;
218
  }
 
219
  h1 {
220
  background: #ffffff;
221
  color: #000000;
 
225
  text-align: center;
226
  font-size: 2.5rem;
227
  }
 
228
  textarea, input {
229
  background: transparent;
230
  color: black;
 
235
  outline: none;
236
  border-radius: 8px;
237
  }
 
238
  textarea:focus, input:focus {
239
  background: transparent;
240
  color: black;
241
  border: 2px solid orange;
242
  outline: none;
243
  }
 
 
 
 
 
 
 
244
  .df-container {
245
  background: white;
246
  color: black;
 
252
  height: auto;
253
  overflow-y: auto;
254
  }
 
255
  #suggestions-title {
256
+ text-align: center !important;
257
+ font-weight: bold !important;
258
+ color: white !important;
259
+ font-size: 4.2rem !important;
260
+ margin-bottom: 20px !important;
261
  }
 
 
262
  .gr-button {
263
+ background-color: #ae1c93;
264
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 2px 4px rgba(0, 0, 0, 0.06);
265
  transition: background-color 0.3s ease;
266
  }
 
267
  .gr-button:hover {
268
  background-color: #8f167b;
269
  }
 
270
  .gr-button:active {
271
  background-color: #7f156b;
272
  }
 
277
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
278
  with gr.Row():
279
  user_input = gr.Textbox(label="Please Enter Your Message Here")
280
+ location = gr.Textbox(label="Your Current Location Here")
281
+ query = gr.Textbox(label="Search Health Professionals Nearby")
282
 
283
+ # New Row for Disease Prediction Symptoms
284
+ with gr.Row():
285
+ symptom1 = gr.Dropdown(choices=["None"] + l1, label="Symptom 1")
286
+ symptom2 = gr.Dropdown(choices=["None"] + l1, label="Symptom 2")
287
+ symptom3 = gr.Dropdown(choices=["None"] + l1, label="Symptom 3")
288
+ symptom4 = gr.Dropdown(choices=["None"] + l1, label="Symptom 4")
289
+ symptom5 = gr.Dropdown(choices=["None"] + l1, label="Symptom 5")
290
+
291
  submit = gr.Button(value="Submit", variant="primary")
292
 
293
  chatbot = gr.Chatbot(label="Chat History")
294
  sentiment = gr.Textbox(label="Detected Sentiment")
295
  emotion = gr.Textbox(label="Detected Emotion")
296
 
297
+ # Suggestions Title
298
  gr.Markdown("Suggestions", elem_id="suggestions-title")
299
 
300
+ suggestions = gr.DataFrame(headers=["Title", "Link"]) # Suggestions DataFrame
301
+ professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Professionals DataFrame
302
  map_html = gr.HTML(label="Interactive Map")
303
+ disease_predictions = gr.Textbox(label="Disease Predictions") # For Disease Prediction Results
304
 
305
  submit.click(
306
  app_function,
307
+ inputs=[user_input, location, query, [symptom1, symptom2, symptom3, symptom4, symptom5], chatbot],
308
+ outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html, disease_predictions],
309
  )
310
 
311
  app.launch()