DreamStream-1 commited on
Commit
3631cca
Β·
verified Β·
1 Parent(s): 8b34069

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -59
app.py CHANGED
@@ -13,15 +13,15 @@ import googlemaps
13
  import folium
14
  import torch
15
 
16
- # Disable GPU usage for TensorFlow and logs
17
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
18
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
19
- nltk.download("punkt")
20
 
21
- # Initialize Stemmer
 
22
  stemmer = LancasterStemmer()
23
 
24
- # Load Chatbot Training Data
25
  with open("intents.json") as file:
26
  intents_data = json.load(file)
27
 
@@ -37,17 +37,16 @@ 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 for Nearby Professionals
48
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
49
 
50
- # Chatbot Helper
51
  def bag_of_words(s, words):
52
  bag = [0] * len(words)
53
  s_words = word_tokenize(s)
@@ -58,8 +57,9 @@ def bag_of_words(s, words):
58
  bag[i] = 1
59
  return np.array(bag)
60
 
 
61
  def chatbot(message, history):
62
- """Generate a chatbot response and update history."""
63
  history = history or []
64
  try:
65
  result = chatbot_model.predict([bag_of_words(message, words)])
@@ -74,8 +74,9 @@ def chatbot(message, history):
74
  history.append((message, response))
75
  return history, response
76
 
 
77
  def analyze_sentiment(user_input):
78
- """Detect sentiment and return sentiment emoji."""
79
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
80
  with torch.no_grad():
81
  outputs = model_sentiment(**inputs)
@@ -83,8 +84,9 @@ def analyze_sentiment(user_input):
83
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
84
  return sentiment_map[sentiment_class]
85
 
 
86
  def detect_emotion(user_input):
87
- """Detect user emotion 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()
@@ -96,82 +98,130 @@ def detect_emotion(user_input):
96
  "surprise": "😲 Surprise",
97
  "neutral": "😐 Neutral"
98
  }
99
- return emotion_map.get(emotion, "Unknown πŸ€”")
100
 
 
101
  def generate_suggestions(emotion):
102
- """Provide clickable suggestions for each emotion."""
103
  suggestions = {
104
  "joy": [
105
- ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
106
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov" target="_blank">Visit</a>'],
107
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
 
108
  ],
109
  "anger": [
110
- ["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
111
- ["Dealing with Anger", '<a href="https://www.helpguide.org" target="_blank">Visit</a>']
112
  ],
113
  "fear": [
114
- ["Coping with Anxiety", '<a href="https://www.helpguide.org" target="_blank">Visit</a>'],
115
- ["Mindfulness Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
116
  ],
117
  "sadness": [
118
- ["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
119
  ],
120
  "surprise": [
121
- ["Stress Tips", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
 
122
  ]
123
  }
124
- return suggestions.get(emotion.lower(), [["No suggestions available", ""]])
125
 
 
126
  def get_health_professionals_and_map(location, query):
127
- """Show nearby professionals and interactive map."""
128
- geo_location = gmaps.geocode(location)
129
- if geo_location:
130
- lat, lng = geo_location[0]["geometry"]["location"].values()
131
- map_ = folium.Map(location=(lat, lng), zoom_start=13)
132
- professionals = []
133
- places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
134
- for place in places_result:
135
- professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
136
- folium.Marker(
137
- location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
138
- popup=place["name"]
139
- ).add_to(map_)
140
- return professionals, map_._repr_html_()
141
- return ["No professionals found nearby."], ""
142
-
143
- # Main Function
 
 
 
 
 
 
 
 
 
 
 
144
  def app_function(user_input, location, query, history):
145
- chatbot_history, _ = chatbot(user_input, history)
146
  sentiment = analyze_sentiment(user_input)
147
  emotion = detect_emotion(user_input)
148
  suggestions = generate_suggestions(emotion)
149
  professionals, map_html = get_health_professionals_and_map(location, query)
150
  return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
151
 
152
- # CSS for Orange Themed Submit Button
153
  custom_css = """
154
- button { background: linear-gradient(45deg, #ff5722, #ff9800); color: white; }
155
- .gr-dataframe, .gr-html, .gr-chatbot { background: black; color: white; border: 1px solid #ff5722; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  """
157
 
158
- # Gradio Application
159
  with gr.Blocks(css=custom_css) as app:
160
- gr.Markdown("### 🌟 Well-Being Companion")
161
- user_input = gr.Textbox(label="Enter Your Message")
162
- location_input = gr.Textbox(label="Your Location")
163
- query_input = gr.Textbox(label="Search Query (e.g., therapist)")
164
- chatbot_history = gr.Chatbot(label="Chatbot History")
165
- sentiment_box = gr.Textbox(label="Sentiment Detected")
166
- emotion_box = gr.Textbox(label="Emotion Detected")
167
- suggestions_table = gr.DataFrame(headers=["Title", "Link"], label="Suggestion Based On Emotion")
168
- map_output_box = gr.HTML(label="Interactive Map of Professionals")
169
- professional_list_box = gr.Textbox(label="Professionals Nearby", lines=5)
170
- submit_button = gr.Button("Submit")
 
 
 
171
 
 
172
  submit_button.click(
173
- app_function,
174
- inputs=[user_input, location_input, query_input, chatbot_history],
175
- outputs=[chatbot_history, sentiment_box, emotion_box, suggestions_table, professional_list_box, map_output_box]
176
  )
 
177
  app.launch()
 
13
  import folium
14
  import torch
15
 
16
+ # Suppress TensorFlow GPU usage and warnings
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
  stemmer = LancasterStemmer()
23
 
24
+ # Load chatbot training data
25
  with open("intents.json") as file:
26
  intents_data = json.load(file)
27
 
 
37
  chatbot_model = tflearn.DNN(net)
38
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
39
 
40
+ # Hugging Face sentiment and emotion 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
+ # Google Maps API Client
47
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
48
 
49
+ # Bag of Words Helper Function for Chatbot
50
  def bag_of_words(s, words):
51
  bag = [0] * len(words)
52
  s_words = word_tokenize(s)
 
57
  bag[i] = 1
58
  return np.array(bag)
59
 
60
+ # Chatbot Function
61
  def chatbot(message, history):
62
+ """Generate a chatbot response and append to the chat history."""
63
  history = history or []
64
  try:
65
  result = chatbot_model.predict([bag_of_words(message, words)])
 
74
  history.append((message, response))
75
  return history, response
76
 
77
+ # Sentiment Analysis
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
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
85
  return sentiment_map[sentiment_class]
86
 
87
+ # Emotion Detection
88
  def detect_emotion(user_input):
89
+ """Detect user emotion with an emoji."""
90
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
91
  result = pipe(user_input)
92
  emotion = result[0]['label'].lower()
 
98
  "surprise": "😲 Surprise",
99
  "neutral": "😐 Neutral"
100
  }
101
+ return emotion_map.get(emotion, "Unknown Emotion πŸ€”")
102
 
103
+ # Generate Suggestions for Emotion
104
  def generate_suggestions(emotion):
105
+ """Return suggestions for the detected emotion."""
106
  suggestions = {
107
  "joy": [
108
+ ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
109
+ ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
110
+ ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
111
+ ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
112
  ],
113
  "anger": [
114
+ ["Emotional Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
115
+ ["Calming Activities", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
116
  ],
117
  "fear": [
118
+ ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
119
+ ["Mindfulness Practices", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
120
  ],
121
  "sadness": [
122
+ ["Stress Management", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
123
  ],
124
  "surprise": [
125
+ ["Managing Stress", '<a href="https://www.health.harvard.edu/" target="_blank">Visit</a>'],
126
+ ["Relaxation Help", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
127
  ]
128
  }
129
+ return suggestions.get(emotion.lower(), [["No suggestions are available.", ""]])
130
 
131
+ # Search for Nearby Professionals and Generate Map
132
  def get_health_professionals_and_map(location, query):
133
+ """Search nearby healthcare professionals and display a map."""
134
+ try:
135
+ if not location or not query:
136
+ return ["Please provide a valid location and query."], ""
137
+
138
+ geo_location = gmaps.geocode(location)
139
+ if geo_location:
140
+ lat, lng = geo_location[0]["geometry"]["location"].values()
141
+
142
+ places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
143
+
144
+ professionals = []
145
+ map_ = folium.Map(location=(lat, lng), zoom_start=13)
146
+ for place in places_result:
147
+ professionals.append(f"{place['name']} - {place.get('vicinity', 'No address available')}")
148
+ folium.Marker(
149
+ location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
150
+ popup=f"{place['name']}"
151
+ ).add_to(map_)
152
+ return professionals, map_._repr_html_()
153
+
154
+ return ["No professionals found for the given location."], ""
155
+ except googlemaps.exceptions.HTTPError as e:
156
+ return [f"Google Maps API Error: {str(e)}"], ""
157
+ except Exception as e:
158
+ return [f"An error occurred: {str(e)}"], ""
159
+
160
+ # Main App Logic
161
  def app_function(user_input, location, query, history):
162
+ chatbot_history, response = 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 for Dark Theme and Gradient Buttons
170
  custom_css = """
171
+ body {
172
+ background: linear-gradient(135deg, #000, #ff5722);
173
+ font-family: 'Roboto', sans-serif;
174
+ color: white;
175
+ }
176
+ button {
177
+ background: linear-gradient(45deg, #ff5722, #ff9800) !important;
178
+ border: 0;
179
+ border-radius: 8px;
180
+ padding: 12px 20px;
181
+ cursor: pointer;
182
+ color: white;
183
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
184
+ }
185
+ button:hover {
186
+ background: linear-gradient(45deg, #ff9800, #ff5722) !important;
187
+ }
188
+ textarea, input {
189
+ background: black !important;
190
+ color: white !important;
191
+ padding: 12px;
192
+ border: 1px solid #ff5722 !important;
193
+ border-radius: 8px;
194
+ }
195
+ .gr-dataframe {
196
+ background-color: black !important;
197
+ color: white !important;
198
+ overflow-y: scroll;
199
+ height: 300px;
200
+ }
201
  """
202
 
203
+ # Gradio Interface
204
  with gr.Blocks(css=custom_css) as app:
205
+ gr.HTML("<h1 style='text-align: center;'>🌟 Well-Being Companion</h1>")
206
+ gr.HTML("<h3 style='text-align: center;'>Empowering Your Mental Health Journey πŸ’š</h3>")
207
+
208
+ with gr.Row():
209
+ user_message = gr.Textbox(label="Your Message", placeholder="Type your message...")
210
+ location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
211
+ query = gr.Textbox(label="Search Query", placeholder="e.g., therapist, doctor")
212
+
213
+ chatbot_history = gr.Chatbot(label="Chat History")
214
+ sentiment_output = gr.Textbox(label="Detected Sentiment")
215
+ emotion_output = gr.Textbox(label="Detected Emotion")
216
+ suggestions_output = gr.DataFrame(headers=["Title", "Link"], label="Suggestions")
217
+ map_html_output = gr.HTML(label="Map of Nearby Health Professionals")
218
+ professionals_output = gr.Textbox(label="Nearby Professionals", lines=5)
219
 
220
+ submit_button = gr.Button("Submit")
221
  submit_button.click(
222
+ app_function,
223
+ inputs=[user_message, location, query, chatbot_history],
224
+ outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_output, professionals_output, map_html_output]
225
  )
226
+
227
  app.launch()