DreamStream-1 commited on
Commit
4a3e857
·
verified ·
1 Parent(s): 6a45be5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -130
app.py CHANGED
@@ -12,16 +12,10 @@ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipe
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
- from sklearn.preprocessing import LabelEncoder
21
 
22
  # Suppress TensorFlow warnings
23
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # No GPU available, use CPU only
24
- os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # Suppress TensorFlow logging
25
 
26
  # Download necessary NLTK resources
27
  nltk.download("punkt")
@@ -52,77 +46,9 @@ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/e
52
  # Google Maps API Client
53
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
54
 
55
- # Disease Prediction Code
56
- 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 in a dictionary
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,
69
- 'Hepatitis A': 19, 'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23,
70
- 'Alcoholic hepatitis': 24, 'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27,
71
- 'Heart attack': 28, 'Varicose veins': 29, 'Hypothyroidism': 30, 'Hyperthyroidism': 31,
72
- 'Hypoglycemia': 32, 'Osteoarthritis': 33, 'Arthritis': 34,
73
- '(vertigo) Paroxysmal Positional Vertigo': 35, 'Acne': 36, 'Urinary tract infection': 37,
74
- 'Psoriasis': 38, 'Impetigo': 39
75
- }
76
-
77
- # Replace prognosis values with numerical categories
78
- df.replace({'prognosis': disease_dict}, inplace=True)
79
- df['prognosis'] = df['prognosis'].astype(int)
80
-
81
- tr.replace({'prognosis': disease_dict}, inplace=True)
82
- tr['prognosis'] = tr['prognosis'].astype(int)
83
-
84
- return df, tr, disease_dict
85
-
86
- df, tr, disease_dict = load_data()
87
- l1 = list(df.columns[:-1]) # All columns except prognosis
88
- X = df[l1]
89
- y = df['prognosis']
90
- X_test = tr[l1]
91
- y_test = tr['prognosis']
92
-
93
- # Encode the target variable with LabelEncoder if still in string format
94
- le = LabelEncoder()
95
- y_encoded = le.fit_transform(y)
96
-
97
- def train_models():
98
- models = {
99
- "Decision Tree": DecisionTreeClassifier(),
100
- "Random Forest": RandomForestClassifier(),
101
- "Naive Bayes": GaussianNB()
102
- }
103
- trained_models = {}
104
- for model_name, model_obj in models.items():
105
- model_obj.fit(X, y_encoded)
106
- acc = accuracy_score(y_test, model_obj.predict(X_test))
107
- trained_models[model_name] = (model_obj, acc)
108
- return trained_models
109
-
110
- trained_models = train_models()
111
-
112
- def predict_disease(model, symptoms):
113
- input_test = np.zeros(len(l1))
114
- for symptom in symptoms:
115
- if symptom in l1:
116
- input_test[l1.index(symptom)] = 1
117
- prediction = model.predict([input_test])[0]
118
- confidence = model.predict_proba([input_test])[0][prediction] if hasattr(model, 'predict_proba') else None
119
- return {
120
- "disease": list(disease_dict.keys())[list(disease_dict.values()).index(prediction)],
121
- "confidence": confidence
122
- }
123
-
124
- # Helper Functions (for chatbot)
125
  def bag_of_words(s, words):
 
126
  bag = [0] * len(words)
127
  s_words = word_tokenize(s)
128
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
@@ -133,17 +59,23 @@ def bag_of_words(s, words):
133
  return np.array(bag)
134
 
135
  def generate_chatbot_response(message, history):
 
136
  history = history or []
137
  try:
138
  result = chatbot_model.predict([bag_of_words(message, words)])
139
  tag = labels[np.argmax(result)]
140
- response = next((random.choice(intent["responses"]) for intent in intents_data["intents"] if intent["tag"] == tag), "I'm sorry, I didn't understand that. 🤔")
 
 
 
 
141
  except Exception as e:
142
  response = f"Error: {e}"
143
  history.append((message, response))
144
  return history, response
145
 
146
  def analyze_sentiment(user_input):
 
147
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
148
  with torch.no_grad():
149
  outputs = model_sentiment(**inputs)
@@ -152,6 +84,7 @@ def analyze_sentiment(user_input):
152
  return f"Sentiment: {sentiment_map[sentiment_class]}"
153
 
154
  def detect_emotion(user_input):
 
155
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
156
  result = pipe(user_input)
157
  emotion = result[0]["label"].lower().strip()
@@ -166,20 +99,52 @@ def detect_emotion(user_input):
166
  return emotion_map.get(emotion, "Unknown 🤔"), emotion
167
 
168
  def generate_suggestions(emotion):
 
169
  emotion_key = emotion.lower()
170
  suggestions = {
171
- # Define suggestions based on the detected emotion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  }
173
 
 
174
  formatted_suggestions = [
175
  [title, f'<a href="{link}" target="_blank">{link}</a>'] for title, link in suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
176
  ]
 
177
  return formatted_suggestions
178
 
179
  def get_health_professionals_and_map(location, query):
 
180
  try:
181
  if not location or not query:
182
- return [], ""
 
183
  geo_location = gmaps.geocode(location)
184
  if geo_location:
185
  lat, lng = geo_location[0]["geometry"]["location"].values()
@@ -187,92 +152,130 @@ def get_health_professionals_and_map(location, query):
187
  professionals = []
188
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
189
  for place in places_result:
 
190
  professionals.append([place['name'], place.get('vicinity', 'No address provided')])
191
  folium.Marker(
192
  location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
193
  popup=f"{place['name']}"
194
  ).add_to(map_)
195
  return professionals, map_._repr_html_()
196
- return [], ""
 
197
  except Exception as e:
198
- return [], ""
199
 
200
  # Main Application Logic
201
- def app_function(user_input, location, query, symptoms, history):
202
  chatbot_history, _ = generate_chatbot_response(user_input, history)
203
  sentiment_result = analyze_sentiment(user_input)
204
  emotion_result, cleaned_emotion = detect_emotion(user_input)
205
  suggestions = generate_suggestions(cleaned_emotion)
206
  professionals, map_html = get_health_professionals_and_map(location, query)
207
-
208
- # Disease prediction logic
209
- symptoms_selected = [s for s in symptoms if s != "None"]
210
- if len(symptoms_selected) < 3:
211
- disease_results = ["Please select at least 3 symptoms for accurate prediction."]
212
- else:
213
- results = []
214
- for model_name, (model, acc) in trained_models.items():
215
- prediction_info = predict_disease(model, symptoms_selected)
216
- predicted_disease = prediction_info["disease"]
217
- confidence_score = prediction_info["confidence"]
218
-
219
- result = f"{model_name} Prediction: Predicted Disease: **{predicted_disease}**"
220
- if confidence_score is not None:
221
- result += f" (Confidence: {confidence_score:.2f})"
222
- result += f" (Accuracy: {acc * 100:.2f}%)"
223
-
224
- results.append(result)
225
- disease_results = results
226
-
227
- return (
228
- chatbot_history,
229
- sentiment_result,
230
- emotion_result,
231
- suggestions,
232
- professionals,
233
- map_html,
234
- disease_results
235
- )
236
 
237
  # CSS Styling
238
  custom_css = """
239
- /* Your custom CSS styles go here */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  """
241
 
242
  # Gradio Application
243
  with gr.Blocks(css=custom_css) as app:
244
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
245
-
246
  with gr.Row():
247
  user_input = gr.Textbox(label="Please Enter Your Message Here")
248
- location = gr.Textbox(label="Your Current Location Here")
249
- query = gr.Textbox(label="Search Health Professionals Nearby")
250
 
251
- with gr.Row():
252
- symptom1 = gr.Dropdown(choices=["None"] + l1, label="Symptom 1")
253
- symptom2 = gr.Dropdown(choices=["None"] + l1, label="Symptom 2")
254
- symptom3 = gr.Dropdown(choices=["None"] + l1, label="Symptom 3")
255
- symptom4 = gr.Dropdown(choices=["None"] + l1, label="Symptom 4")
256
- symptom5 = gr.Dropdown(choices=["None"] + l1, label="Symptom 5")
257
-
258
  submit = gr.Button(value="Submit", variant="primary")
259
 
260
  chatbot = gr.Chatbot(label="Chat History")
261
  sentiment = gr.Textbox(label="Detected Sentiment")
262
  emotion = gr.Textbox(label="Detected Emotion")
263
 
 
264
  gr.Markdown("Suggestions", elem_id="suggestions-title")
265
 
266
- suggestions = gr.DataFrame(headers=["Title", "Link"]) # Suggestions DataFrame
267
- professionals = gr.DataFrame(label="Nearby Health Professionals", headers=["Name", "Address"]) # Professionals DataFrame
268
  map_html = gr.HTML(label="Interactive Map")
269
- disease_predictions = gr.Textbox(label="Disease Predictions") # For Disease Prediction Results
270
 
271
  submit.click(
272
  app_function,
273
- inputs=[user_input, location, query, [symptom1, symptom2, symptom3, symptom4, symptom5], chatbot],
274
- outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html, disease_predictions],
275
  )
276
 
277
- # Launch the Gradio application
278
  app.launch()
 
12
  import googlemaps
13
  import folium
14
  import torch
 
 
 
 
 
 
15
 
16
  # Suppress TensorFlow warnings
17
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
18
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
19
 
20
  # Download necessary NLTK resources
21
  nltk.download("punkt")
 
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
  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)])
66
  tag = labels[np.argmax(result)]
67
+ response = "I'm sorry, I didn't understand that. 🤔"
68
+ for intent in intents_data["intents"]:
69
+ if intent["tag"] == tag:
70
+ response = random.choice(intent["responses"])
71
+ break
72
  except Exception as e:
73
  response = f"Error: {e}"
74
  history.append((message, response))
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
  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
  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
  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;
187
+ border-radius: 8px;
188
+ padding: 10px;
189
+ font-weight: bold;
190
+ text-align: center;
191
+ font-size: 2.5rem;
192
+ }
193
+
194
+ textarea, input {
195
+ background: transparent;
196
+ color: black;
197
+ border: 2px solid orange;
198
+ padding: 8px;
199
+ font-size: 1rem;
200
+ caret-color: black;
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;
221
+ border: 2px solid orange;
222
+ border-radius: 10px;
223
+ padding: 10px;
224
+ font-size: 14px;
225
+ max-height: 400px;
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
+ }
252
  """
253
 
254
  # Gradio Application
255
  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()