DreamStream-1 commited on
Commit
d9bd34f
Β·
verified Β·
1 Parent(s): 5f4fda6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -96
app.py CHANGED
@@ -17,20 +17,20 @@ import torch
17
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
18
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
19
 
20
- # Download NLTK resources
21
  nltk.download("punkt")
22
 
23
  # Initialize Lancaster Stemmer
24
  stemmer = LancasterStemmer()
25
 
26
- # Load chatbot intents and training data
27
  with open("intents.json") as file:
28
  intents_data = json.load(file)
29
 
30
  with open("data.pickle", "rb") as f:
31
  words, labels, training, output = pickle.load(f)
32
 
33
- # Build Chatbot Model
34
  net = tflearn.input_data(shape=[None, len(training[0])])
35
  net = tflearn.fully_connected(net, 8)
36
  net = tflearn.fully_connected(net, 8)
@@ -39,18 +39,17 @@ net = tflearn.regression(net)
39
  chatbot_model = tflearn.DNN(net)
40
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
41
 
42
- # Model for sentiment detection
43
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
44
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
45
 
46
- # Model for emotion detection
47
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
48
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
49
 
50
- # Google Maps API client
51
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
52
 
53
- # Chatbot logic
54
  def bag_of_words(s, words):
55
  bag = [0] * len(words)
56
  s_words = word_tokenize(s)
@@ -61,23 +60,24 @@ def bag_of_words(s, words):
61
  bag[i] = 1
62
  return np.array(bag)
63
 
 
64
  def chatbot(message, history):
65
  """Generate chatbot response and append to history."""
66
  history = history or []
67
  try:
68
- results = chatbot_model.predict([bag_of_words(message, words)])
69
- tag = labels[np.argmax(results)]
70
  response = "I'm not sure how to respond to that. πŸ€”"
71
  for intent in intents_data["intents"]:
72
  if intent["tag"] == tag:
73
  response = random.choice(intent["responses"])
74
  break
75
  except Exception as e:
76
- response = f"Error: {str(e)} πŸ’₯"
77
  history.append((message, response))
78
  return history, response
79
 
80
- # Sentiment analysis
81
  def analyze_sentiment(user_input):
82
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
83
  with torch.no_grad():
@@ -86,33 +86,50 @@ def analyze_sentiment(user_input):
86
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
87
  return sentiment_map[sentiment_class]
88
 
89
- # Emotion detection
90
  def detect_emotion(user_input):
91
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
92
  result = pipe(user_input)
93
- emotion = result[0]["label"]
94
  return emotion
95
 
96
  # Generate Suggestions
97
  def generate_suggestions(emotion):
 
98
  suggestions = {
99
  "joy": [
100
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
101
  ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
102
  ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
103
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
104
  ],
105
  "anger": [
106
  ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
107
- ["Stress Management Tips", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
108
- ["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
109
- ["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  ],
111
  }
112
- return suggestions.get(emotion, [["No suggestions available", ""]])
113
 
114
- # Get Nearby Professionals and Generate Map
115
  def get_health_professionals_and_map(location, query):
 
116
  try:
117
  geo_location = gmaps.geocode(location)
118
  if geo_location:
@@ -130,112 +147,64 @@ def get_health_professionals_and_map(location, query):
130
  except Exception as e:
131
  return [f"Error: {e}"], ""
132
 
133
- # App Main Function
134
- def app_function(message, location, query, history):
135
- chatbot_history, _ = chatbot(message, history)
136
- sentiment = analyze_sentiment(message)
137
- emotion = detect_emotion(message.lower())
138
  suggestions = generate_suggestions(emotion)
139
  professionals, map_html = get_health_professionals_and_map(location, query)
140
- return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
141
 
142
- # Enhanced CSS for Custom Title and Styling
143
  custom_css = """
144
- @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
145
  body {
146
  background: linear-gradient(135deg, #000000, #ff5722);
147
  color: white;
148
  font-family: 'Roboto', sans-serif;
149
  }
150
- button {
151
- background-color: #ff5722 !important;
152
- border: none !important;
153
- color: white !important;
154
- padding: 12px 20px;
155
- font-size: 16px;
156
- border-radius: 8px;
157
- cursor: pointer;
158
- }
159
- button:hover {
160
- background-color: #e64a19 !important;
161
- }
162
  textarea, input[type="text"], .gr-chatbot {
163
  background: #000000 !important;
164
  color: white !important;
165
  border: 2px solid #ff5722 !important;
 
166
  padding: 12px !important;
167
- border-radius: 8px !important;
168
- font-size: 14px;
169
  }
170
- .gr-dataframe, .gr-textbox {
171
  background: #000000 !important;
172
  color: white !important;
 
173
  border: 2px solid #ff5722 !important;
174
- border-radius: 8px !important;
175
- font-size: 14px;
176
- }
177
- .suggestions-title {
178
- font-size: 1.5rem !important;
179
- font-weight: bold;
180
- color: white;
181
- margin-top: 20px;
182
  }
183
- h1 {
184
- font-size: 4rem;
185
- font-weight: bold;
186
- margin-bottom: 10px;
187
  color: white;
188
  text-align: center;
189
- text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.6);
190
- }
191
- h2 {
192
- font-weight: 400;
193
- font-size: 1.8rem;
194
- color: white;
195
- text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.4);
196
- }
197
- .input-title, .output-title {
198
- font-size: 1.5rem;
199
  font-weight: bold;
200
- color: black;
201
- margin-bottom: 10px;
202
  }
203
  """
204
 
205
- # Gradio Interface
206
  with gr.Blocks(css=custom_css) as app:
207
- gr.HTML("<h1>🌟 Well-Being Companion</h1>")
208
- gr.HTML("<h2>Empowering Your Well-Being Journey πŸ’š</h2>")
209
 
210
  with gr.Row():
211
- gr.Markdown("<div class='input-title'>Your Message</div>")
212
- user_message = gr.Textbox(label=None, placeholder="Enter your message...")
213
- gr.Markdown("<div class='input-title'>Your Location</div>")
214
- user_location = gr.Textbox(label=None, placeholder="Enter your location...")
215
- gr.Markdown("<div class='input-title'>Your Query</div>")
216
- search_query = gr.Textbox(label=None, placeholder="Search for professionals...")
217
-
218
- chatbot_box = gr.Chatbot(label="Chat History")
219
- gr.Markdown("<div class='output-title'>Detected Emotion</div>")
220
- emotion_output = gr.Textbox(label=None)
221
- gr.Markdown("<div class='output-title'>Detected Sentiment</div>")
222
- sentiment_output = gr.Textbox(label=None)
223
- gr.Markdown("<div class='suggestions-title'>Suggestions</div>")
224
- suggestions_output = gr.DataFrame(headers=["Title", "Links"], label=None)
225
-
226
- gr.Markdown("<h2 class='suggestions-title'>Health Professionals Nearby</h2>")
227
- map_output = gr.HTML(label=None)
228
- professional_display = gr.Textbox(label=None, lines=5)
229
-
230
- submit_btn = gr.Button("Submit")
231
-
232
- submit_btn.click(
233
  app_function,
234
- inputs=[user_message, user_location, search_query, chatbot_box],
235
- outputs=[
236
- chatbot_box, sentiment_output, emotion_output,
237
- suggestions_output, professional_display, map_output,
238
- ],
239
  )
240
 
241
  app.launch()
 
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")
22
 
23
  # Initialize Lancaster Stemmer
24
  stemmer = LancasterStemmer()
25
 
26
+ # Load chatbot training data and intents
27
  with open("intents.json") as file:
28
  intents_data = json.load(file)
29
 
30
  with open("data.pickle", "rb") as f:
31
  words, labels, training, output = pickle.load(f)
32
 
33
+ # Build the chatbot's neural network model
34
  net = tflearn.input_data(shape=[None, len(training[0])])
35
  net = tflearn.fully_connected(net, 8)
36
  net = tflearn.fully_connected(net, 8)
 
39
  chatbot_model = tflearn.DNN(net)
40
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
41
 
42
+ # Hugging Face models for sentiment and emotion detection
43
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
44
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
45
 
 
46
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
47
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
48
 
49
+ # Google Maps API Client
50
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
51
 
52
+ # Function to process text input into a bag-of-words format
53
  def bag_of_words(s, words):
54
  bag = [0] * len(words)
55
  s_words = word_tokenize(s)
 
60
  bag[i] = 1
61
  return np.array(bag)
62
 
63
+ # Chatbot Logic
64
  def chatbot(message, history):
65
  """Generate chatbot response and append to history."""
66
  history = history or []
67
  try:
68
+ result = chatbot_model.predict([bag_of_words(message, words)])
69
+ tag = labels[np.argmax(result)]
70
  response = "I'm not sure how to respond to that. πŸ€”"
71
  for intent in intents_data["intents"]:
72
  if intent["tag"] == tag:
73
  response = random.choice(intent["responses"])
74
  break
75
  except Exception as e:
76
+ response = f"Error: {str(e)}"
77
  history.append((message, response))
78
  return history, response
79
 
80
+ # Sentiment Analysis
81
  def analyze_sentiment(user_input):
82
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
83
  with torch.no_grad():
 
86
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
87
  return sentiment_map[sentiment_class]
88
 
89
+ # Emotion Detection
90
  def detect_emotion(user_input):
91
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
92
  result = pipe(user_input)
93
+ emotion = result[0]['label']
94
  return emotion
95
 
96
  # Generate Suggestions
97
  def generate_suggestions(emotion):
98
+ """Return suggestions aligned with the detected emotion."""
99
  suggestions = {
100
  "joy": [
101
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
102
  ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
103
  ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
104
+ ["Relaxation Videos", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
105
  ],
106
  "anger": [
107
  ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
108
+ ["Stress Management Tips", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
109
+ ["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anger-management" target="_blank">Visit</a>'],
110
+ ["Relaxation Videos", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
111
+ ],
112
+ "fear": [
113
+ ["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
114
+ ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
115
+ ["Relaxation Videos", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
116
+ ],
117
+ "sadness": [
118
+ ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
119
+ ["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
120
+ ["Relaxation Videos", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
121
+ ],
122
+ "surprise": [
123
+ ["Managing Stress", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
124
+ ["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
125
+ ["Relaxation Videos", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
126
  ],
127
  }
128
+ return suggestions.get(emotion.lower(), [["No suggestions available", ""]])
129
 
130
+ # Get Health Professionals and Generate Map
131
  def get_health_professionals_and_map(location, query):
132
+ """Search professionals and return details + map as HTML."""
133
  try:
134
  geo_location = gmaps.geocode(location)
135
  if geo_location:
 
147
  except Exception as e:
148
  return [f"Error: {e}"], ""
149
 
150
+ # Main Application Logic
151
+ def app_function(user_input, location, query, history):
152
+ chatbot_history, response = chatbot(user_input, history)
153
+ emotion = detect_emotion(user_input)
 
154
  suggestions = generate_suggestions(emotion)
155
  professionals, map_html = get_health_professionals_and_map(location, query)
156
+ return chatbot_history, emotion, suggestions, professionals, map_html
157
 
158
+ # Enhanced CSS for Custom UI
159
  custom_css = """
 
160
  body {
161
  background: linear-gradient(135deg, #000000, #ff5722);
162
  color: white;
163
  font-family: 'Roboto', sans-serif;
164
  }
 
 
 
 
 
 
 
 
 
 
 
 
165
  textarea, input[type="text"], .gr-chatbot {
166
  background: #000000 !important;
167
  color: white !important;
168
  border: 2px solid #ff5722 !important;
169
+ border-radius: 5px;
170
  padding: 12px !important;
 
 
171
  }
172
+ .gr-dataframe {
173
  background: #000000 !important;
174
  color: white !important;
175
+ height: 350px !important;
176
  border: 2px solid #ff5722 !important;
177
+ overflow-y: auto;
 
 
 
 
 
 
 
178
  }
179
+ h1, h2, h3 {
 
 
 
180
  color: white;
181
  text-align: center;
 
 
 
 
 
 
 
 
 
 
182
  font-weight: bold;
 
 
183
  }
184
  """
185
 
186
+ # Gradio Application
187
  with gr.Blocks(css=custom_css) as app:
188
+ gr.Markdown("<h1>🌟 Well-Being Companion</h1>")
189
+ gr.Markdown("<h2>Empowering Your Well-Being Journey πŸ’š</h2>")
190
 
191
  with gr.Row():
192
+ user_input = gr.Textbox(label="Your Message", placeholder="Enter your message...")
193
+ location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
194
+ query = gr.Textbox(label="Query (e.g., therapists)", placeholder="Search...")
195
+
196
+ chatbot_history = gr.Chatbot(label="Chat History")
197
+ emotion_box = gr.Textbox(label="Detected Emotion")
198
+ suggestions_table = gr.DataFrame(headers=["Suggestion", "Link"])
199
+ map_box = gr.HTML(label="Map of Health Professionals")
200
+ professionals_list = gr.Textbox(label="Health Professionals Nearby", lines=5)
201
+
202
+ submit_button = gr.Button("Submit")
203
+
204
+ submit_button.click(
 
 
 
 
 
 
 
 
 
205
  app_function,
206
+ inputs=[user_input, location, query, chatbot_history],
207
+ outputs=[chatbot_history, emotion_box, suggestions_table, professionals_list, map_box],
 
 
 
208
  )
209
 
210
  app.launch()