DreamStream-1 commited on
Commit
a7c229b
Β·
verified Β·
1 Parent(s): f9158d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -55
app.py CHANGED
@@ -17,15 +17,14 @@ import torch
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
  stemmer = LancasterStemmer()
23
 
24
- # Load intents for chatbot
25
  with open("intents.json") as file:
26
  intents_data = json.load(file)
27
 
28
- # Load training data for chatbot
29
  with open("data.pickle", "rb") as f:
30
  words, labels, training, output = pickle.load(f)
31
 
@@ -38,18 +37,18 @@ net = tflearn.regression(net)
38
  chatbot_model = tflearn.DNN(net)
39
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
40
 
41
- # Hugging Face models for emotion and sentiment detection
42
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
43
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
44
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
45
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
46
 
47
- # Google Maps API Client
48
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
49
 
50
- # Function: Bag of Words for Chatbot
51
  def bag_of_words(s, words):
52
- """Convert user input to bag-of-words representation."""
53
  bag = [0] * len(words)
54
  s_words = word_tokenize(s)
55
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
@@ -59,26 +58,26 @@ def bag_of_words(s, words):
59
  bag[i] = 1
60
  return np.array(bag)
61
 
62
- # Chatbot Response
63
  def chatbot(message, history):
64
- """Generate chatbot response and append to chat history."""
65
  history = history or []
66
  try:
67
  result = chatbot_model.predict([bag_of_words(message, words)])
68
  tag = labels[np.argmax(result)]
69
- response = "I'm not sure how to respond to that. πŸ€”"
70
  for intent in intents_data["intents"]:
71
  if intent["tag"] == tag:
72
  response = random.choice(intent["responses"])
73
  break
74
  except Exception as e:
75
  response = f"Error: {e}"
76
- history.append((message, response)) # Append to history as a tuple
77
  return history, response
78
 
79
- # Sentiment Detection
80
  def analyze_sentiment(user_input):
81
- """Analyze sentiment using Hugging Face sentiment model."""
82
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
83
  with torch.no_grad():
84
  outputs = model_sentiment(**inputs)
@@ -86,66 +85,67 @@ 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
- """Detect user emotion using Hugging Face emotion model."""
92
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
93
  result = pipe(user_input)
94
- emotion = result[0]["label"].lower().strip() # Normalize and clean label
95
  emotion_map = {
96
  "joy": "😊 Joy",
97
  "anger": "😠 Anger",
98
  "sadness": "😒 Sadness",
99
  "fear": "😨 Fear",
100
  "surprise": "😲 Surprise",
101
- "neutral": "😐 Neutral"
102
  }
103
  return emotion_map.get(emotion, "Unknown πŸ€”")
104
 
105
- # Suggestion Generation
106
  def generate_suggestions(emotion):
107
- """Provide resources based on detected emotion."""
108
- emotion_key = emotion.lower() # Match key with normalized emotion
109
  suggestions = {
110
  "joy": [
111
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
112
- ["Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
113
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
114
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
115
  ],
116
  "anger": [
117
- ["Stress Management Tips", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
118
- ["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
119
  ],
120
  "fear": [
121
  ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
122
- ["Mindfulness Practices", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
123
  ],
124
  "sadness": [
125
  ["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
126
  ],
127
  "surprise": [
128
  ["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
129
- ["Calm Relaxation", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
130
  ],
131
  "neutral": [
132
- ["General Well-Being Tips", '<a href="https://www.psychologytoday.com" target="_blank">Visit</a>']
133
  ],
134
  }
135
- return suggestions.get(emotion_key, [["No suggestions available.", ""]])
136
 
137
- # Google Maps Integration
138
  def get_health_professionals_and_map(location, query):
139
- """Search nearby professionals and display on interactive map."""
140
  try:
141
  if not location or not query:
142
- return ["Please provide both location and search query."], ""
 
143
  geo_location = gmaps.geocode(location)
144
  if geo_location:
145
  lat, lng = geo_location[0]["geometry"]["location"].values()
146
  places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
147
- map_ = folium.Map(location=(lat, lng), zoom_start=13)
148
  professionals = []
 
149
  for place in places_result:
150
  professionals.append(f"{place['name']} - {place.get('vicinity', 'No address available')}")
151
  folium.Marker(
@@ -153,17 +153,18 @@ def get_health_professionals_and_map(location, query):
153
  popup=f"{place['name']}"
154
  ).add_to(map_)
155
  return professionals, map_._repr_html_()
156
- return ["No professionals found for the given location."], ""
 
157
  except Exception as e:
158
- return [f"An error occurred: {str(e)}"], ""
159
-
160
- # Main Application Logic
161
- def app_function(user_input, location, query, history):
162
- chatbot_history, _ = chatbot(user_input, history)
163
- sentiment = analyze_sentiment(user_input)
164
- emotion = detect_emotion(user_input)
165
- suggestions = generate_suggestions(emotion)
166
- professionals, map_html = get_health_professionals_and_map(location, query)
167
  return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
168
 
169
  # Custom CSS
@@ -174,27 +175,27 @@ body {
174
  color: white;
175
  }
176
  h1 {
177
- font-size: 4rem;
178
  font-weight: bold;
179
  text-align: center;
180
- margin-bottom: 20px;
 
181
  }
182
  h2 {
183
  font-size: 2rem;
184
- font-weight: lighter;
185
  text-align: center;
186
- margin-bottom: 30px;
187
  color: white;
 
188
  }
189
- button {
190
  background: linear-gradient(45deg, #ff5722, #ff9800) !important;
191
- border: none;
192
- border-radius: 8px;
193
  padding: 12px 20px;
 
 
194
  cursor: pointer;
195
- color: white;
196
  font-size: 16px;
197
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
198
  }
199
  """
200
 
@@ -204,9 +205,9 @@ with gr.Blocks(css=custom_css) as app:
204
  gr.HTML("<h2>Empowering Your Mental Health Journey πŸ’š</h2>")
205
 
206
  with gr.Row():
207
- user_message = gr.Textbox(label="Your Message", placeholder="Type your message...")
208
  location = gr.Textbox(label="Your Location", placeholder="Enter location...")
209
- query = gr.Textbox(label="Query (e.g., therapist, doctor)", placeholder="Search for professionals...")
210
 
211
  chatbot_history = gr.Chatbot(label="Chat History")
212
  sentiment_output = gr.Textbox(label="Detected Sentiment")
@@ -219,7 +220,7 @@ with gr.Blocks(css=custom_css) as app:
219
  submit_button.click(
220
  app_function,
221
  inputs=[user_message, location, query, chatbot_history],
222
- outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_output, professionals_output, map_output]
223
  )
224
 
225
  app.launch()
 
17
  os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
18
  os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
19
 
20
+ # Ensure necessary NLTK resources
21
  nltk.download("punkt")
22
  stemmer = LancasterStemmer()
23
 
24
+ # Load chatbot intents and training data
25
  with open("intents.json") as file:
26
  intents_data = json.load(file)
27
 
 
28
  with open("data.pickle", "rb") as f:
29
  words, labels, training, output = pickle.load(f)
30
 
 
37
  chatbot_model = tflearn.DNN(net)
38
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
39
 
40
+ # Hugging Face emotion and sentiment detection models
41
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
42
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
43
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
44
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
45
 
46
+ # Initialize 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 into 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()]
 
58
  bag[i] = 1
59
  return np.array(bag)
60
 
61
+ # Chatbot response logic
62
  def chatbot(message, history):
63
+ """Generate chatbot response and update chat history."""
64
  history = history or []
65
  try:
66
  result = chatbot_model.predict([bag_of_words(message, words)])
67
  tag = labels[np.argmax(result)]
68
+ response = "I'm sorry, I'm not sure how to respond. πŸ€”"
69
  for intent in intents_data["intents"]:
70
  if intent["tag"] == tag:
71
  response = random.choice(intent["responses"])
72
  break
73
  except Exception as e:
74
  response = f"Error: {e}"
75
+ history.append((message, response)) # Append to the chatbot history
76
  return history, response
77
 
78
+ # Sentiment detection function
79
  def analyze_sentiment(user_input):
80
+ """Analyze sentiment and return emoji-mapped sentiment."""
81
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
82
  with torch.no_grad():
83
  outputs = model_sentiment(**inputs)
 
85
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
86
  return sentiment_map[sentiment_class]
87
 
88
+ # Emotion detection function
89
  def detect_emotion(user_input):
90
+ """Detect emotion from user input using Hugging Face emotion model."""
91
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
92
  result = pipe(user_input)
93
+ emotion = result[0]["label"].lower().strip()
94
  emotion_map = {
95
  "joy": "😊 Joy",
96
  "anger": "😠 Anger",
97
  "sadness": "😒 Sadness",
98
  "fear": "😨 Fear",
99
  "surprise": "😲 Surprise",
100
+ "neutral": "😐 Neutral",
101
  }
102
  return emotion_map.get(emotion, "Unknown πŸ€”")
103
 
104
+ # Generate suggestions based on emotion
105
  def generate_suggestions(emotion):
106
+ """Generate resources and videos to help based on the emotion detected."""
107
+ emotion_key = emotion.lower()
108
  suggestions = {
109
  "joy": [
110
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
111
+ ["Emotional Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
112
+ ["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
 
113
  ],
114
  "anger": [
115
+ ["Calming Techniques", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
116
+ ["Manage Anger", '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">Visit</a>'],
117
  ],
118
  "fear": [
119
  ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
120
+ ["Mindfulness Meditation", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
121
  ],
122
  "sadness": [
123
  ["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
124
  ],
125
  "surprise": [
126
  ["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
127
+ ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
128
  ],
129
  "neutral": [
130
+ ["General Tips", '<a href="https://www.psychologytoday.com" target="_blank">Read More</a>']
131
  ],
132
  }
133
+ return suggestions.get(emotion_key, [["No specific suggestions available.", ""]])
134
 
135
+ # Google Maps integration
136
  def get_health_professionals_and_map(location, query):
137
+ """Search nearby health professionals and generate map."""
138
  try:
139
  if not location or not query:
140
+ return ["Please provide a valid location and query."], ""
141
+
142
  geo_location = gmaps.geocode(location)
143
  if geo_location:
144
  lat, lng = geo_location[0]["geometry"]["location"].values()
145
  places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
146
+
147
  professionals = []
148
+ map_ = folium.Map(location=(lat, lng), zoom_start=13)
149
  for place in places_result:
150
  professionals.append(f"{place['name']} - {place.get('vicinity', 'No address available')}")
151
  folium.Marker(
 
153
  popup=f"{place['name']}"
154
  ).add_to(map_)
155
  return professionals, map_._repr_html_()
156
+
157
+ return ["No professionals found."], ""
158
  except Exception as e:
159
+ return [f"Error: {e}"], ""
160
+
161
+ # Main application logic
162
+ def app_function(user_message, location, query, history):
163
+ chatbot_history, _ = chatbot(user_message, history)
164
+ sentiment = analyze_sentiment(user_message) # Sentiment detection
165
+ emotion = detect_emotion(user_message) # Emotion detection
166
+ suggestions = generate_suggestions(emotion) # Get emotion-based suggestions
167
+ professionals, map_html = get_health_professionals_and_map(location, query) # Google Maps integration
168
  return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
169
 
170
  # Custom CSS
 
175
  color: white;
176
  }
177
  h1 {
178
+ font-size: 4.5rem;
179
  font-weight: bold;
180
  text-align: center;
181
+ color: white;
182
+ text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.4);
183
  }
184
  h2 {
185
  font-size: 2rem;
 
186
  text-align: center;
187
+ font-weight: lighter;
188
  color: white;
189
+ margin-bottom: 30px;
190
  }
191
+ .button {
192
  background: linear-gradient(45deg, #ff5722, #ff9800) !important;
193
+ border: none !important;
 
194
  padding: 12px 20px;
195
+ border-radius: 8px;
196
+ color: white !important;
197
  cursor: pointer;
 
198
  font-size: 16px;
 
199
  }
200
  """
201
 
 
205
  gr.HTML("<h2>Empowering Your Mental Health Journey πŸ’š</h2>")
206
 
207
  with gr.Row():
208
+ user_message = gr.Textbox(label="Your Message", placeholder="Enter your message...")
209
  location = gr.Textbox(label="Your Location", placeholder="Enter location...")
210
+ query = gr.Textbox(label="Search Query", placeholder="e.g., therapist")
211
 
212
  chatbot_history = gr.Chatbot(label="Chat History")
213
  sentiment_output = gr.Textbox(label="Detected Sentiment")
 
220
  submit_button.click(
221
  app_function,
222
  inputs=[user_message, location, query, chatbot_history],
223
+ outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_output, professionals_output, map_output],
224
  )
225
 
226
  app.launch()