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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -55
app.py CHANGED
@@ -21,14 +21,15 @@ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
21
  nltk.download("punkt")
22
  stemmer = LancasterStemmer()
23
 
24
- # Load chatbot 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
 
31
- # Build the Chatbot Model
32
  net = tflearn.input_data(shape=[None, len(training[0])])
33
  net = tflearn.fully_connected(net, 8)
34
  net = tflearn.fully_connected(net, 8)
@@ -37,19 +38,18 @@ net = tflearn.regression(net)
37
  chatbot_model = tflearn.DNN(net)
38
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
39
 
40
- # Sentiment and Emotion 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
-
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
- # Helper Functions
51
  def bag_of_words(s, words):
52
- """Convert user input to bag-of-words vector."""
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,6 +59,7 @@ def bag_of_words(s, words):
59
  bag[i] = 1
60
  return np.array(bag)
61
 
 
62
  def chatbot(message, history):
63
  """Generate chatbot response and append to chat history."""
64
  history = history or []
@@ -72,11 +73,12 @@ def chatbot(message, history):
72
  break
73
  except Exception as e:
74
  response = f"Error: {e}"
75
- history.append((message, response))
76
  return history, response
77
 
 
78
  def analyze_sentiment(user_input):
79
- """Analyze sentiment from user input."""
80
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
81
  with torch.no_grad():
82
  outputs = model_sentiment(**inputs)
@@ -84,61 +86,66 @@ def analyze_sentiment(user_input):
84
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
85
  return sentiment_map[sentiment_class]
86
 
 
87
  def detect_emotion(user_input):
88
- """Detect user emotion with emoji representation."""
89
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
90
  result = pipe(user_input)
91
- emotion = result[0]["label"].lower()
92
  emotion_map = {
93
  "joy": "😊 Joy",
94
  "anger": "😠 Anger",
95
  "sadness": "😒 Sadness",
96
  "fear": "😨 Fear",
97
  "surprise": "😲 Surprise",
98
- "neutral": "😐 Neutral",
99
  }
100
  return emotion_map.get(emotion, "Unknown πŸ€”")
101
 
 
102
  def generate_suggestions(emotion):
103
- """Provide suggestions for the detected emotion."""
 
104
  suggestions = {
105
  "joy": [
106
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
107
- ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
108
  ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
109
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
110
  ],
111
  "anger": [
112
  ["Stress Management Tips", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
113
- ["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
114
  ],
115
  "fear": [
116
  ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
117
- ["Mindfulness Practices", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
118
  ],
119
  "sadness": [
120
  ["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
121
  ],
122
  "surprise": [
123
  ["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
124
- ["Calm Relaxation", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
 
 
 
125
  ],
126
  }
127
- return suggestions.get(emotion.lower(), [["No suggestions are available.", ""]])
128
 
 
129
  def get_health_professionals_and_map(location, query):
130
- """Search for nearby healthcare professionals and generate a map."""
131
  try:
132
  if not location or not query:
133
- return ["Please provide a valid location and query."], ""
134
-
135
  geo_location = gmaps.geocode(location)
136
  if geo_location:
137
  lat, lng = geo_location[0]["geometry"]["location"].values()
138
  places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
139
-
140
- professionals = []
141
  map_ = folium.Map(location=(lat, lng), zoom_start=13)
 
142
  for place in places_result:
143
  professionals.append(f"{place['name']} - {place.get('vicinity', 'No address available')}")
144
  folium.Marker(
@@ -146,24 +153,23 @@ def get_health_professionals_and_map(location, query):
146
  popup=f"{place['name']}"
147
  ).add_to(map_)
148
  return professionals, map_._repr_html_()
149
-
150
  return ["No professionals found for the given location."], ""
151
  except Exception as e:
152
  return [f"An error occurred: {str(e)}"], ""
153
 
154
- # Application Logic
155
- def app_function(user_message, location, query, history):
156
- chatbot_history, _ = chatbot(user_message, history)
157
- sentiment = analyze_sentiment(user_message)
158
- emotion = detect_emotion(user_message)
159
  suggestions = generate_suggestions(emotion)
160
  professionals, map_html = get_health_professionals_and_map(location, query)
161
  return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
162
 
163
- # CSS Styling for Centered and Bigger Titles
164
  custom_css = """
165
  body {
166
- background: linear-gradient(135deg, #000000, #ff5722);
167
  font-family: 'Roboto', sans-serif;
168
  color: white;
169
  }
@@ -171,57 +177,49 @@ h1 {
171
  font-size: 4rem;
172
  font-weight: bold;
173
  text-align: center;
174
- margin-bottom: 10px;
175
- text-shadow: 3px 3px 8px rgba(0, 0, 0, 0.7);
176
  }
177
- h3 {
178
  font-size: 2rem;
179
- text-align: center;
180
- margin-bottom: 40px;
181
  font-weight: lighter;
 
 
182
  color: white;
183
  }
184
  button {
185
  background: linear-gradient(45deg, #ff5722, #ff9800) !important;
186
  border: none;
187
- padding: 12px 20px;
188
- font-size: 16px;
189
  border-radius: 8px;
190
- color: white;
191
  cursor: pointer;
192
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
193
- }
194
- textarea, input {
195
- background: black !important;
196
- color: white !important;
197
- border: 1px solid #ff5722;
198
- border-radius: 8px;
199
  }
200
  """
201
 
202
  # Gradio Application
203
  with gr.Blocks(css=custom_css) as app:
204
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
205
- gr.HTML("<h3>Empowering Your Mental Health Journey πŸ’š</h3>")
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 your location...")
210
- query = gr.Textbox(label="Health Query", placeholder="Search for professionals like therapists...")
211
 
212
  chatbot_history = gr.Chatbot(label="Chat History")
213
  sentiment_output = gr.Textbox(label="Detected Sentiment")
214
  emotion_output = gr.Textbox(label="Detected Emotion")
215
- suggestions_table = gr.DataFrame(headers=["Title", "Link"], label="Suggestions")
216
- professionals_output = gr.Textbox(label="Nearby Health Professionals", lines=5)
217
- map_output = gr.HTML(label="Map of Nearby Professionals")
218
 
219
  submit_button = gr.Button("Submit")
220
-
221
  submit_button.click(
222
  app_function,
223
  inputs=[user_message, location, query, chatbot_history],
224
- outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_table, professionals_output, map_output]
225
  )
226
 
227
  app.launch()
 
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
 
32
+ # Build chatbot model
33
  net = tflearn.input_data(shape=[None, len(training[0])])
34
  net = tflearn.fully_connected(net, 8)
35
  net = tflearn.fully_connected(net, 8)
 
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
  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 []
 
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
  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
  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
170
  custom_css = """
171
  body {
172
+ background: linear-gradient(135deg, #000, #ff5722);
173
  font-family: 'Roboto', sans-serif;
174
  color: white;
175
  }
 
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
 
201
  # Gradio Application
202
  with gr.Blocks(css=custom_css) as app:
203
  gr.HTML("<h1>🌟 Well-Being Companion</h1>")
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")
213
  emotion_output = gr.Textbox(label="Detected Emotion")
214
+ suggestions_output = gr.DataFrame(headers=["Title", "Link"], label="Suggestions")
215
+ professionals_output = gr.Textbox(label="Nearby Professionals", lines=5)
216
+ map_output = gr.HTML(label="Interactive Map")
217
 
218
  submit_button = gr.Button("Submit")
 
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()