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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -108
app.py CHANGED
@@ -13,17 +13,15 @@ import googlemaps
13
  import folium
14
  import torch
15
 
16
- # Disable GPU usage for TensorFlow and suppress logs
17
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
18
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
19
-
20
- # Ensure necessary NLTK resources are downloaded
21
  nltk.download("punkt")
22
 
23
- # Initialize Lancaster Stemmer
24
  stemmer = LancasterStemmer()
25
 
26
- # Load intents.json and chatbot training data
27
  with open("intents.json") as file:
28
  intents_data = json.load(file)
29
 
@@ -39,19 +37,18 @@ net = tflearn.regression(net)
39
  chatbot_model = tflearn.DNN(net)
40
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
41
 
42
- # Hugging Face sentiment and emotion detection models
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
- # Helper Functions
53
  def bag_of_words(s, words):
54
- """Convert user input into bag-of-words vector for use in chatbot model."""
55
  bag = [0] * len(words)
56
  s_words = word_tokenize(s)
57
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
@@ -62,7 +59,7 @@ def bag_of_words(s, words):
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
  result = chatbot_model.predict([bag_of_words(message, words)])
@@ -78,7 +75,7 @@ def chatbot(message, history):
78
  return history, response
79
 
80
  def analyze_sentiment(user_input):
81
- """Analyze sentiment with emojis."""
82
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
83
  with torch.no_grad():
84
  outputs = model_sentiment(**inputs)
@@ -87,10 +84,10 @@ def analyze_sentiment(user_input):
87
  return sentiment_map[sentiment_class]
88
 
89
  def detect_emotion(user_input):
90
- """Detect user emotion with emojis."""
91
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
92
  result = pipe(user_input)
93
- emotion = result[0]['label']
94
  emotion_map = {
95
  "joy": "😊 Joy",
96
  "anger": "😠 Anger",
@@ -99,64 +96,51 @@ def detect_emotion(user_input):
99
  "surprise": "😲 Surprise",
100
  "neutral": "😐 Neutral"
101
  }
102
- return emotion_map.get(emotion, "Unknown Emotion πŸ€”")
103
 
104
  def generate_suggestions(emotion):
105
- """Return suggestions based on detected emotion."""
106
  suggestions = {
107
  "joy": [
108
  ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
109
- ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-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 Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
115
- ["Stress Management Tips", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
116
- ["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">Visit</a>'],
117
- ["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
118
  ],
119
  "fear": [
120
- ["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
121
- ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
122
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
123
- ["Relaxation Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
124
  ],
125
  "sadness": [
126
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
127
- ["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
128
- ["Relaxation Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
129
  ],
130
  "surprise": [
131
- ["Managing Stress", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
132
- ["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
133
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
134
- ],
135
  }
136
  return suggestions.get(emotion.lower(), [["No suggestions available", ""]])
137
 
138
  def get_health_professionals_and_map(location, query):
139
- """Search for nearby professionals and generate interactive map."""
140
- try:
141
- geo_location = gmaps.geocode(location)
142
- if geo_location:
143
- lat, lng = geo_location[0]["geometry"]["location"].values()
144
- map_ = folium.Map(location=(lat, lng), zoom_start=13)
145
- places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
146
-
147
- professionals = []
148
- for place in places_result:
149
- professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
150
- folium.Marker(
151
- location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
152
- popup=place["name"]
153
- ).add_to(map_)
154
- return professionals, map_._repr_html_()
155
- return ["No professionals found nearby."], ""
156
- except Exception as e:
157
- return [f"Error: {str(e)}"], ""
158
-
159
- # Application Logic
160
  def app_function(user_input, location, query, history):
161
  chatbot_history, _ = chatbot(user_input, history)
162
  sentiment = analyze_sentiment(user_input)
@@ -165,64 +149,29 @@ def app_function(user_input, location, query, history):
165
  professionals, map_html = get_health_professionals_and_map(location, query)
166
  return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
167
 
168
- # Custom CSS for Styling Submit Button and UI
169
  custom_css = """
170
- body {
171
- background: linear-gradient(135deg, #000000, #ff5722);
172
- color: white;
173
- font-family: 'Roboto', sans-serif;
174
- }
175
- button {
176
- background: linear-gradient(45deg, #ff5722, #ff9800) !important;
177
- color: white !important;
178
- border: none;
179
- border-radius: 8px;
180
- padding: 12px 20px;
181
- cursor: pointer;
182
- font-size: 16px;
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: #000000 !important;
190
- color: white !important;
191
- border: 1px solid #ff5722 !important;
192
- padding: 12px;
193
- font-size: 14px;
194
- border-radius: 8px;
195
- }
196
- .gr-chatbot, .gr-textbox, .gr-html, .gr-dataframe {
197
- background-color: #000 !important;
198
- border: 1px solid #ff5722 !important;
199
- color: white !important;
200
- }
201
  """
202
 
203
  # Gradio Application
204
  with gr.Blocks(css=custom_css) as app:
205
- gr.Markdown("<h1 style='text-align: center;'>🌟 Well-Being Companion</h1>")
206
- gr.Markdown("<h3 style='text-align: center;'>Empowering Your Well-Being 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_output = gr.Chatbot(label="Chat History")
214
- sentiment_output = gr.Textbox(label="Detected Sentiment")
215
- emotion_output = gr.Textbox(label="Detected Emotion")
216
- suggestion_table = gr.DataFrame(headers=["Suggestion Title", "Link"], label="Well-Being Suggestions")
217
- professionals_output = gr.Textbox(label="Health Professionals Nearby", lines=5)
218
- map_html = gr.HTML(label="Interactive Map")
219
-
220
- submit_btn = gr.Button("Submit")
221
-
222
- submit_btn.click(
223
- app_function,
224
- inputs=[user_message, location, query, chatbot_output],
225
- outputs=[chatbot_output, sentiment_output, emotion_output, suggestion_table, professionals_output, map_html]
226
  )
227
-
228
  app.launch()
 
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
  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)
54
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
 
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)])
 
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)
 
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()
91
  emotion_map = {
92
  "joy": "😊 Joy",
93
  "anger": "😠 Anger",
 
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)
 
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()