DreamStream-1 commited on
Commit
d0842d1
Β·
verified Β·
1 Parent(s): c7bfddf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -29
app.py CHANGED
@@ -1,5 +1,5 @@
1
- import os
2
  import gradio as gr
 
3
  import nltk
4
  import numpy as np
5
  import tflearn
@@ -11,8 +11,8 @@ from nltk.stem.lancaster import LancasterStemmer
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import googlemaps
13
  import folium
14
- import pandas as pd
15
- import torch
16
 
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
@@ -62,7 +62,6 @@ def chatbot(message, history):
62
  results = model.predict([bag_of_words(message, words)])
63
  results_index = np.argmax(results)
64
  tag = labels[results_index]
65
-
66
  # Match tag with intent and choose a random response
67
  for tg in data["intents"]:
68
  if tg['tag'] == tag:
@@ -73,11 +72,9 @@ def chatbot(message, history):
73
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
74
  except Exception as e:
75
  response = f"An error occurred: {str(e)}"
76
-
77
  # Convert the new message and response to the 'messages' format
78
  history.append({"role": "user", "content": message})
79
  history.append({"role": "assistant", "content": response})
80
-
81
  return history, history
82
 
83
  # Sentiment Analysis using Hugging Face model
@@ -88,9 +85,9 @@ def analyze_sentiment(user_input):
88
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
89
  with torch.no_grad():
90
  outputs = model_sentiment(**inputs)
91
- predicted_class = torch.argmax(outputs.logits, dim=1).item()
92
- sentiment = ["Negative", "Neutral", "Positive"][predicted_class] # Assuming 3 classes
93
- return f"Predicted Sentiment: {sentiment}"
94
 
95
  # Emotion Detection using Hugging Face model
96
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
@@ -173,10 +170,9 @@ def generate_suggestions(emotion):
173
  {"Title": "Relaxation Video", "Subject": "Video", "Link": '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch Video</a>'}
174
  ]
175
  }
176
-
177
  return suggestions.get(emotion, [])
178
 
179
- # Gradio interface
180
  def gradio_app(message, location, health_query, submit_button, history, state):
181
  if submit_button:
182
  # Chatbot interaction
@@ -197,14 +193,49 @@ def gradio_app(message, location, health_query, submit_button, history, state):
197
  # Create a DataFrame for displaying suggestions
198
  suggestions_df = pd.DataFrame(suggestions)
199
 
200
- return history, sentiment_response, emotion_response, route_info, map_html, gr.DataFrame(suggestions_df, headers=["Title", "Subject", "Link"]), state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  else:
202
- return history, "", "", "", "", gr.DataFrame([], headers=["Title", "Subject", "Link"]), state
203
 
204
  # Gradio UI components
205
  message_input = gr.Textbox(lines=1, label="Message", placeholder="Type your message here...")
206
  location_input = gr.Textbox(value="Honolulu, HI", label="Current Location", placeholder="Enter your current location...")
207
- health_query_input = gr.Textbox(value="doctor", label="Health Professional Query (e.g., doctor, health professional, well-being professional", placeholder="Search for health professionals...")
208
  submit_button = gr.Button("Submit")
209
 
210
  # Updated chat history component with 'messages' type
@@ -216,6 +247,7 @@ emotion_output = gr.Textbox(label="Emotion Detection Result")
216
  route_info_output = gr.Textbox(label="Health Professionals Information")
217
  map_output = gr.HTML(label="Map with Health Professionals")
218
  suggestions_output = gr.DataFrame(label="Well-Being Suggestions", headers=["Title", "Subject", "Link"])
 
219
 
220
  # Custom CSS for styling
221
  custom_css = """
@@ -225,11 +257,9 @@ body {
225
  color: #333;
226
  font-family: Arial, sans-serif;
227
  }
228
-
229
  h1, h2, h3, h4, h5, h6 {
230
  color: #0056b3;
231
  }
232
-
233
  .gradio-app {
234
  max-width: 800px;
235
  margin: 0 auto;
@@ -238,11 +268,9 @@ h1, h2, h3, h4, h5, h6 {
238
  border-radius: 10px;
239
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
240
  }
241
-
242
  .gradio-input, .gradio-output {
243
  margin-bottom: 15px;
244
  }
245
-
246
  .gradio-button {
247
  background-color: #0056b3;
248
  color: #fff;
@@ -251,43 +279,41 @@ h1, h2, h3, h4, h5, h6 {
251
  border-radius: 5px;
252
  cursor: pointer;
253
  }
254
-
255
  .gradio-button:hover {
256
  background-color: #004080;
257
  }
258
-
259
  .gradio-dataframe {
260
  border: 1px solid #ddd;
261
  border-radius: 5px;
262
  overflow: hidden;
263
  }
264
-
265
  .gradio-dataframe th, .gradio-dataframe td {
266
  padding: 10px;
267
  text-align: left;
268
  }
269
-
270
  .gradio-dataframe th {
271
  background-color: #0056b3;
272
  color: #fff;
273
  }
274
-
275
  .gradio-dataframe a {
276
  color: #0056b3;
277
  text-decoration: none;
278
  }
279
-
280
  .gradio-dataframe a:hover {
281
  text-decoration: underline;
282
  }
 
 
 
 
283
  </style>
284
  """
285
 
286
  # Create Gradio interface
287
- iface = gr.Interface(
288
- fn=gradio_app,
289
- inputs=[message_input, location_input, health_query_input, submit_button, gr.State()],
290
- outputs=[chat_history, sentiment_output, emotion_output, route_info_output, map_output, suggestions_output, gr.State()],
291
  allow_flagging="never",
292
  live=False,
293
  title="Well-Being App: Support, Sentiment, Emotion Detection & Health Professional Search",
@@ -295,4 +321,5 @@ iface = gr.Interface(
295
  )
296
 
297
  # Launch the Gradio interface
298
- iface.launch()
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
  import nltk
4
  import numpy as np
5
  import tflearn
 
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import googlemaps
13
  import folium
14
+ import os
15
+ import base64
16
 
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
 
62
  results = model.predict([bag_of_words(message, words)])
63
  results_index = np.argmax(results)
64
  tag = labels[results_index]
 
65
  # Match tag with intent and choose a random response
66
  for tg in data["intents"]:
67
  if tg['tag'] == tag:
 
72
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
73
  except Exception as e:
74
  response = f"An error occurred: {str(e)}"
 
75
  # Convert the new message and response to the 'messages' format
76
  history.append({"role": "user", "content": message})
77
  history.append({"role": "assistant", "content": response})
 
78
  return history, history
79
 
80
  # Sentiment Analysis using Hugging Face model
 
85
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
86
  with torch.no_grad():
87
  outputs = model_sentiment(**inputs)
88
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
89
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
90
+ return f"Predicted Sentiment: {sentiment}"
91
 
92
  # Emotion Detection using Hugging Face model
93
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
 
170
  {"Title": "Relaxation Video", "Subject": "Video", "Link": '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch Video</a>'}
171
  ]
172
  }
 
173
  return suggestions.get(emotion, [])
174
 
175
+ # Define the Gradio interface
176
  def gradio_app(message, location, health_query, submit_button, history, state):
177
  if submit_button:
178
  # Chatbot interaction
 
193
  # Create a DataFrame for displaying suggestions
194
  suggestions_df = pd.DataFrame(suggestions)
195
 
196
+ # Add emoticons based on emotion
197
+ emoticon = {
198
+ 'joy': '😊',
199
+ 'anger': '😑',
200
+ 'fear': '😨',
201
+ 'sadness': '😒',
202
+ 'surprise': '😲'
203
+ }
204
+
205
+ # Add info graphics based on emotion
206
+ info_graphics = {
207
+ 'joy': 'joy.png',
208
+ 'anger': 'anger.png',
209
+ 'fear': 'fear.png',
210
+ 'sadness': 'sadness.png',
211
+ 'surprise': 'surprise.png'
212
+ }
213
+
214
+ # Convert image to base64 for embedding in HTML
215
+ if info_graphics.get(emotion_response.split(': ')[1]):
216
+ with open(info_graphics[emotion_response.split(': ')[1]], "rb") as image_file:
217
+ encoded_string = base64.b64encode(image_file.read()).decode()
218
+ info_graphic_html = f'<img src="data:image/png;base64,{encoded_string}" alt="{emotion_response.split(": ")[1]}">'
219
+ else:
220
+ info_graphic_html = ''
221
+
222
+ return (
223
+ history,
224
+ sentiment_response,
225
+ f"{emotion_response} {emoticon.get(emotion_response.split(': ')[1], '')}",
226
+ route_info,
227
+ map_html,
228
+ gr.DataFrame(suggestions_df, headers=["Title", "Subject", "Link"]),
229
+ info_graphic_html,
230
+ state
231
+ )
232
  else:
233
+ return history, "", "", "", "", gr.DataFrame([], headers=["Title", "Subject", "Link"]), "", state
234
 
235
  # Gradio UI components
236
  message_input = gr.Textbox(lines=1, label="Message", placeholder="Type your message here...")
237
  location_input = gr.Textbox(value="Honolulu, HI", label="Current Location", placeholder="Enter your current location...")
238
+ health_query_input = gr.Textbox(value="doctor", label="Health Professional Query (e.g., doctor, health professional, well-being professional)", placeholder="Search for health professionals...")
239
  submit_button = gr.Button("Submit")
240
 
241
  # Updated chat history component with 'messages' type
 
247
  route_info_output = gr.Textbox(label="Health Professionals Information")
248
  map_output = gr.HTML(label="Map with Health Professionals")
249
  suggestions_output = gr.DataFrame(label="Well-Being Suggestions", headers=["Title", "Subject", "Link"])
250
+ info_graphic_output = gr.HTML(label="Info Graphic")
251
 
252
  # Custom CSS for styling
253
  custom_css = """
 
257
  color: #333;
258
  font-family: Arial, sans-serif;
259
  }
 
260
  h1, h2, h3, h4, h5, h6 {
261
  color: #0056b3;
262
  }
 
263
  .gradio-app {
264
  max-width: 800px;
265
  margin: 0 auto;
 
268
  border-radius: 10px;
269
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
270
  }
 
271
  .gradio-input, .gradio-output {
272
  margin-bottom: 15px;
273
  }
 
274
  .gradio-button {
275
  background-color: #0056b3;
276
  color: #fff;
 
279
  border-radius: 5px;
280
  cursor: pointer;
281
  }
 
282
  .gradio-button:hover {
283
  background-color: #004080;
284
  }
 
285
  .gradio-dataframe {
286
  border: 1px solid #ddd;
287
  border-radius: 5px;
288
  overflow: hidden;
289
  }
 
290
  .gradio-dataframe th, .gradio-dataframe td {
291
  padding: 10px;
292
  text-align: left;
293
  }
 
294
  .gradio-dataframe th {
295
  background-color: #0056b3;
296
  color: #fff;
297
  }
 
298
  .gradio-dataframe a {
299
  color: #0056b3;
300
  text-decoration: none;
301
  }
 
302
  .gradio-dataframe a:hover {
303
  text-decoration: underline;
304
  }
305
+ .info-graphic img {
306
+ max-width: 100%;
307
+ height: auto;
308
+ }
309
  </style>
310
  """
311
 
312
  # Create Gradio interface
313
+ demo = gr.Interface(
314
+ fn=gradio_app,
315
+ inputs=[message_input, location_input, health_query_input, submit_button, gr.State(), gr.State()],
316
+ outputs=[chat_history, sentiment_output, emotion_output, route_info_output, map_output, suggestions_output, info_graphic_output, gr.State()],
317
  allow_flagging="never",
318
  live=False,
319
  title="Well-Being App: Support, Sentiment, Emotion Detection & Health Professional Search",
 
321
  )
322
 
323
  # Launch the Gradio interface
324
+ if __name__ == "__main__":
325
+ demo.launch()