DreamStream-1 commited on
Commit
936af04
·
verified ·
1 Parent(s): a351676

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -248
app.py CHANGED
@@ -1,47 +1,29 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
- from transformers import pipeline
4
- import requests
5
- import csv
6
- import time
7
- import re
8
- from bs4 import BeautifulSoup
9
  import pandas as pd
10
- import chromedriver_autoinstaller
11
- import os
12
  import nltk
 
13
  import numpy as np
14
- import torch
15
- import torch.nn as nn
16
- import torch.optim as optim
17
- import tflearn
18
  import tensorflow as tf
19
- import json
20
- import pickle
21
- import random
22
 
23
- # Ensure necessary NLTK resources are downloaded
24
  nltk.download('punkt')
25
 
26
- # Import LancasterStemmer from nltk.stem
27
- from nltk.stem import LancasterStemmer
28
-
29
  # Initialize the stemmer
30
  stemmer = LancasterStemmer()
31
 
32
  # Load intents.json
33
- try:
34
- with open("intents.json") as file:
35
- data = json.load(file)
36
- except FileNotFoundError:
37
- raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
38
 
39
  # Load preprocessed data from pickle
40
- try:
41
- with open("data.pickle", "rb") as f:
42
- words, labels, training, output = pickle.load(f)
43
- except FileNotFoundError:
44
- raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
45
 
46
  # Build the model structure
47
  net = tflearn.input_data(shape=[None, len(training[0])])
@@ -52,247 +34,131 @@ net = tflearn.regression(net)
52
 
53
  # Load the trained model
54
  model = tflearn.DNN(net)
55
- try:
56
- model.load("MentalHealthChatBotmodel.tflearn")
57
- except FileNotFoundError:
58
- raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
59
-
60
- # Function to process user input into a bag-of-words format
61
- def bag_of_words(s, words):
62
- bag = [0 for _ in range(len(words))]
63
- s_words = nltk.word_tokenize(s)
64
- s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
65
- for se in s_words:
66
- for i, w in enumerate(words):
67
- if w == se:
68
- bag[i] = 1
69
- return np.array(bag)
70
-
71
- # Chat function
72
- def chat(message, history):
73
- history = history or []
74
- message = message.lower()
75
-
76
- try:
77
- # Predict the tag
78
- results = model.predict([bag_of_words(message, words)])
79
- results_index = np.argmax(results)
80
- tag = labels[results_index]
81
-
82
- # Match tag with intent and choose a random response
83
- for tg in data["intents"]:
84
- if tg['tag'] == tag:
85
- responses = tg['responses']
86
- response = random.choice(responses)
87
- break
88
- else:
89
- response = "I'm sorry, I didn't understand that. Could you please rephrase?"
90
-
91
- except Exception as e:
92
- response = f"An error occurred: {str(e)}"
93
-
94
- history.append((message, response))
95
- return history, history
96
 
97
  # Sentiment analysis
98
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
99
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
100
  sentiment_pipeline = pipeline("sentiment-analysis")
101
 
102
- def predict_sentiment(text):
103
- result = sentiment_pipeline(text)
104
- return result[0]['label']
105
-
106
  # Emotion detection
107
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
108
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
109
  emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
110
 
111
- def predict_emotion(text):
112
- result = emotion_pipeline(text)
113
- return result[0]['label']
114
-
115
- # Fetching nearby health professionals
116
- google_places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
117
- google_geocoding_url = "https://maps.googleapis.com/maps/api/geocode/json"
118
-
119
- def get_places_data(query, location, radius, api_key):
120
- params = {
121
- "query": query,
122
- "location": location,
123
- "radius": radius,
124
- "key": api_key
125
- }
126
- response = requests.get(google_places_url, params=params)
127
- return response.json()
128
-
129
- def get_place_details(place_id, api_key):
130
- details_url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&fields=name,rating,formatted_phone_number&key={api_key}"
131
- response = requests.get(details_url)
132
- return response.json()
133
-
134
- def fetch_nearby_health_professionals(location):
135
- api_key = "GOOGLE_API_KEY" # Replace with your actual Google API key
136
- query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist OR nutritionist OR wellness doctor OR holistic practitioner OR integrative medicine OR chiropractor OR naturopath"
137
- radius = 50000 # 50 km radius
138
-
139
- response = get_places_data(query, location, radius, api_key)
140
- results = response.get('results', [])
141
-
142
- data = []
143
- for place in results:
144
- place_id = place['place_id']
145
- place_details = get_place_details(place_id, api_key)
146
- name = place_details.get('result', {}).get('name', 'N/A')
147
- rating = place_details.get('result', {}).get('rating', 'N/A')
148
- phone_number = place_details.get('result', {}).get('formatted_phone_number', 'N/A')
149
-
150
- data.append([name, rating, phone_number])
151
-
152
- return pd.DataFrame(data, columns=['Name', 'Rating', 'Phone Number'])
153
 
154
- # Gradio interface for recommendations
155
  def generate_recommendations(emotion):
156
  if emotion == 'joy':
157
  return [
158
- {"title": "Mindful Breathing Meditation", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
159
- {"title": "Dealing with Stress", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
160
- {"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}
161
  ]
162
  elif emotion == 'anger':
163
  return [
164
- {"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
165
- {"title": "Stress Management Tips", "link": "https://www.health.harvard.edu/health-a-to-z"},
166
- {"title": "Dealing with Anger", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}
167
- ]
168
- elif emotion == 'fear':
169
- return [
170
- {"title": "Mindfulness Practices", "link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
171
- {"title": "Coping with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
172
- {"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"}
173
- ]
174
- elif emotion == 'sadness':
175
- return [
176
- {"title": "Emotional Wellness Toolkit", "link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
177
- {"title": "Dealing with Anxiety", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}
178
- ]
179
- elif emotion == 'surprise':
180
- return [
181
- {"title": "Managing Stress", "link": "https://www.health.harvard.edu/health-a-to-z"},
182
- {"title": "Coping Strategies", "link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"}
183
  ]
 
184
  else:
185
  return []
186
 
187
- def recommendations_interface(emotion):
188
- recs = generate_recommendations(emotion)
189
- html = "<ul>"
190
- for rec in recs:
191
- html += f"<li><a href='{rec['link']}'>{rec['title']}</a></li>"
192
- html += "</ul>"
193
- return html
194
-
195
- # Gradio interface
196
- with gr.Blocks() as demo:
197
- gr.Markdown("# Well-Being Assistant")
198
-
199
- # User input for text (emotion detection)
200
- user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?")
201
- submit_emotion = gr.Button("Submit")
202
-
203
- # Model prediction for emotion detection
204
- def predict_emotion(text):
205
- result = emotion_pipeline(text)
206
- return result[0]['label']
207
-
208
- # Show suggestions based on the detected emotion
209
- def show_suggestions(emotion):
210
- if emotion == 'joy':
211
- return "You're feeling happy! Keep up the great mood!"
212
- elif emotion == 'anger':
213
- return "You're feeling angry. It's okay to feel this way. Let's try to calm down."
214
- elif emotion == 'fear':
215
- return "You're feeling fearful. Take a moment to breathe and relax."
216
- elif emotion == 'sadness':
217
- return "You're feeling sad. It's okay to take a break."
218
- elif emotion == 'surprise':
219
- return "You're feeling surprised. It's okay to feel neutral!"
220
-
221
- emotion_output = gr.Textbox(label="Emotion Detected")
222
- submit_emotion.click(predict_emotion, inputs=user_input_emotion, outputs=emotion_output)
223
-
224
- # Button for summary
225
- def show_summary(emotion):
226
- return f"Emotion Detected: {emotion}"
227
-
228
- summary_button = gr.Button("Show Summary")
229
- summary_output = gr.Textbox(label="Summary")
230
- summary_button.click(show_summary, inputs=emotion_output, outputs=summary_output)
231
-
232
- # Chatbot functionality
233
- chatbot = gr.Chatbot(label="Chat")
234
- message_input = gr.Textbox(lines=1, label="Message")
235
- submit_chat = gr.Button("Send")
236
-
237
- def chat_with_sentiment_and_emotion(message, history):
238
- history = history or []
239
- message = message.lower()
240
-
241
- try:
242
- # Predict the tag
243
- results = model.predict([bag_of_words(message, words)])
244
- results_index = np.argmax(results)
245
- tag = labels[results_index]
246
-
247
- # Match tag with intent and choose a random response
248
- for tg in data["intents"]:
249
- if tg['tag'] == tag:
250
- responses = tg['responses']
251
- response = random.choice(responses)
252
- break
253
- else:
254
- response = "I'm sorry, I didn't understand that. Could you please rephrase?"
255
-
256
- except Exception as e:
257
- response = f"An error occurred: {str(e)}"
258
-
259
- history.append((message, response))
260
-
261
- # Sentiment analysis
262
- sentiment_result = predict_sentiment(message)
263
- emotion_result = predict_emotion(message)
264
-
265
- return history, history, sentiment_result, emotion_result
266
-
267
- submit_chat.click(chat_with_sentiment_and_emotion, inputs=[message_input, gr.State()], outputs=[chatbot, gr.State(), gr.Textbox(), gr.Textbox()])
268
-
269
- # Location input for fetching nearby health professionals
270
- location_input = gr.Textbox(lines=1, label="Enter your location (plain English):")
271
- submit_location = gr.Button("Find Nearby Health Professionals")
272
-
273
- # Fetch and display nearby health professionals
274
- def fetch_nearby_health_professionals(location):
275
- df = fetch_nearby_health_professionals(location)
276
- return df
277
-
278
- nearby_health_professionals_table = gr.Dataframe(headers=["Name", "Rating", "Phone Number"])
279
- submit_location.click(fetch_nearby_health_professionals, inputs=location_input, outputs=nearby_health_professionals_table)
280
 
281
- # Article and video recommendations
282
- article_video_recs = gr.HTML("<h2>Article and Video Recommendations</h2><p>No recommendations yet.</p>")
283
- recommendations_ui = gr.Interface(
284
- fn=recommendations_interface,
285
- inputs="text",
286
- outputs="html",
287
- title="Article and Video Recommendations",
288
- description="Get personalized recommendations based on your mood."
289
- )
290
 
291
- def update_recommendations(emotion):
292
- recs_html = recommendations_interface(emotion)
293
- article_video_recs.update(recs_html)
294
 
295
- emotion_output.change(update_recommendations, inputs=emotion_output, outputs=article_video_recs)
 
 
296
 
297
- # Launch Gradio interface
298
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
3
+ import json
4
+ import pickle
5
+ import random
 
 
 
6
  import pandas as pd
7
+ import requests
 
8
  import nltk
9
+ from nltk.stem import LancasterStemmer
10
  import numpy as np
 
 
 
 
11
  import tensorflow as tf
12
+ from bs4 import BeautifulSoup
 
 
13
 
14
+ # Download necessary NLTK resources
15
  nltk.download('punkt')
16
 
 
 
 
17
  # Initialize the stemmer
18
  stemmer = LancasterStemmer()
19
 
20
  # Load intents.json
21
+ with open("intents.json") as file:
22
+ data = json.load(file)
 
 
 
23
 
24
  # Load preprocessed data from pickle
25
+ with open("data.pickle", "rb") as f:
26
+ words, labels, training, output = pickle.load(f)
 
 
 
27
 
28
  # Build the model structure
29
  net = tflearn.input_data(shape=[None, len(training[0])])
 
34
 
35
  # Load the trained model
36
  model = tflearn.DNN(net)
37
+ model.load("MentalHealthChatBotmodel.tflearn")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  # Sentiment analysis
40
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
41
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
42
  sentiment_pipeline = pipeline("sentiment-analysis")
43
 
 
 
 
 
44
  # Emotion detection
45
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
46
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
47
  emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
48
 
49
+ # Function to process user input into a bag-of-words format
50
+ def bag_of_words(s, words):
51
+ bag = [0 for _ in range(len(words))]
52
+ s_words = nltk.word_tokenize(s)
53
+ s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
54
+ for se in s_words:
55
+ for i, w in enumerate(words):
56
+ if w == se:
57
+ bag[i] = 1
58
+ return np.array(bag)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ # Function to generate recommendations based on emotion
61
  def generate_recommendations(emotion):
62
  if emotion == 'joy':
63
  return [
64
+ {"title": "Mindful Breathing Meditation", "link": "https://www.example.com/joy"},
65
+ {"title": "Dealing with Stress", "link": "https://www.example.com/stress"},
66
+ {"title": "Emotional Wellness Toolkit", "link": "https://www.example.com/wellness"}
67
  ]
68
  elif emotion == 'anger':
69
  return [
70
+ {"title": "Anger Management Techniques", "link": "https://www.example.com/anger"},
71
+ {"title": "Stress Management Tips", "link": "https://www.example.com/stress"},
72
+ {"title": "Dealing with Anger", "link": "https://www.example.com/dealing_with_anger"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  ]
74
+ # Add more cases for other emotions
75
  else:
76
  return []
77
 
78
+ # Function to fetch nearby health professionals
79
+ def fetch_nearby_health_professionals(location):
80
+ # Placeholder for fetching nearby health professionals
81
+ # Actual implementation depends on the API used and should replace the placeholder data
82
+ return pd.DataFrame([
83
+ {'Name': 'Dr. Jane Smith', 'Address': '123 Wellness St.', 'Phone': '555-1234'},
84
+ {'Name': 'Dr. John Doe', 'Address': '456 Health Rd.', 'Phone': '555-5678'}
85
+ ])
86
+
87
+ # Function to detect emotion and provide suggestions
88
+ def detect_emotion_and_suggest(text):
89
+ pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
90
+ result = pipe(text)
91
+ emotion = result[0]['label']
92
+
93
+ # Prepare suggestions based on the detected emotion
94
+ suggestions = ""
95
+ relaxation_videos = ""
96
+ if emotion == 'joy':
97
+ suggestions = "You're feeling happy! Keep up the great mood!\n\nUseful Resources:\n- Relaxation Techniques: [Link](https://www.example.com/joy)\n- Dealing with Stress: [Link](https://www.example.com/stress)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
98
+ relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ elif emotion == 'anger':
101
+ suggestions = "You're feeling angry. It's okay to feel this way. Let's try to calm down.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/anger)\n- Stress Management Tips: [Link](https://www.example.com/stress)\n- Dealing with Anger: [Link](https://www.example.com/dealing_with_anger)"
102
+ relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/MIc299Flibs)"
 
 
 
 
 
 
103
 
104
+ elif emotion == 'fear':
105
+ suggestions = "You're feeling fearful. Take a moment to breathe and relax.\n\nUseful Resources:\n- Mindfulness Practices: [Link](https://www.example.com/fear)\n- Coping with Anxiety: [Link](https://www.example.com/anxiety)\n- Emotional Wellness Toolkit: [Link](https://www.example.com/wellness)"
106
+ relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/yGKKz185M5o)"
107
 
108
+ elif emotion == 'sadness':
109
+ suggestions = "You're feeling sad. It's okay to take a break.\n\nUseful Resources:\n- Emotional Wellness Toolkit: [Link](https://www.example.com/sadness)\n- Dealing with Anxiety: [Link](https://www.example.com/anxiety)"
110
+ relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/-e-4Kx5px_I)"
111
 
112
+ elif emotion == 'surprise':
113
+ suggestions = "You're feeling surprised. It's okay to feel neutral!\n\nUseful Resources:\n- Managing Stress: [Link](https://www.example.com/surprise)\n- Coping Strategies: [Link](https://www.example.com/coping)"
114
+ relaxation_videos = "Relaxation Videos:\n- Watch on YouTube: [Link](https://youtu.be/m1vaUGtyo-A)"
115
+
116
+ return emotion, suggestions, relaxation_videos
117
+
118
+ # Gradio interface for emotion detection and suggestions
119
+ iface = gr.Interface(
120
+ fn=detect_emotion_and_suggest,
121
+ inputs="text",
122
+ outputs=[
123
+ "text", # For displaying detected emotion
124
+ "markdown", # For displaying suggestions
125
+ "markdown", # For displaying relaxation videos
126
+ ],
127
+ title="Emotion Detection and Well-Being Suggestions",
128
+ description="Enter your thoughts below to detect your current emotion and receive personalized well-being suggestions.",
129
+ )
130
+
131
+ # Function to show a summary of the detected emotion and suggestions
132
+ def show_summary(emotion, suggestions):
133
+ return f"**Emotion Detected:** {emotion}\n{suggestions}"
134
+
135
+ # Gradio interface for showing summary
136
+ summary_iface = gr.Interface(
137
+ fn=show_summary,
138
+ inputs=[
139
+ "text", # For detected emotion
140
+ "text", # For suggestions
141
+ ],
142
+ outputs="markdown",
143
+ title="Summary of Emotion and Suggestions",
144
+ description="Click the button to see a summary of your detected emotion and the suggested well-being resources.",
145
+ )
146
+
147
+ # Function to fetch and display nearby health professionals
148
+ def fetch_and_display_health_professionals(location):
149
+ df = fetch_nearby_health_professionals(location)
150
+ return df
151
+
152
+ # Gradio interface for fetching nearby health professionals
153
+ health_professionals_iface = gr.Interface(
154
+ fn=fetch_and_display_health_professionals,
155
+ inputs="text",
156
+ outputs="dataframe",
157
+ title="Find Nearby Health Professionals",
158
+ description="Enter your location to find nearby health professionals.",
159
+ )
160
+
161
+ # Launch the Gradio interfaces
162
+ iface.launch()
163
+ summary_iface.launch()
164
+ health_professionals_iface.launch()