DreamStream-1 commited on
Commit
19503c4
·
verified ·
1 Parent(s): 23325a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -139
app.py CHANGED
@@ -8,46 +8,55 @@ import pickle
8
  import torch
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import requests
13
  import pandas as pd
14
  import os
 
 
 
 
15
 
16
  # Ensure necessary NLTK resources are downloaded
17
  nltk.download('punkt')
18
 
19
- # Initialize the stemmer
 
 
 
 
 
 
 
 
 
 
20
  stemmer = LancasterStemmer()
21
 
22
- # Load intents.json
23
  try:
24
  with open("intents.json") as file:
25
  data = json.load(file)
26
  except FileNotFoundError:
27
- raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
28
 
29
- # Load preprocessed data from pickle
30
  try:
31
  with open("data.pickle", "rb") as f:
32
  words, labels, training, output = pickle.load(f)
33
  except FileNotFoundError:
34
- raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
35
 
36
- # Build the model structure
37
  net = tflearn.input_data(shape=[None, len(training[0])])
38
  net = tflearn.fully_connected(net, 8)
39
  net = tflearn.fully_connected(net, 8)
40
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
41
  net = tflearn.regression(net)
42
 
43
- # Load the trained model
44
  model = tflearn.DNN(net)
45
  try:
46
  model.load("MentalHealthChatBotmodel.tflearn")
47
  except FileNotFoundError:
48
  raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
49
 
50
- # Function to process user input into a bag-of-words format
51
  def bag_of_words(s, words):
52
  bag = [0 for _ in range(len(words))]
53
  s_words = word_tokenize(s)
@@ -58,18 +67,13 @@ def bag_of_words(s, words):
58
  bag[i] = 1
59
  return np.array(bag)
60
 
61
- # Chat function (Chatbot)
62
  def chat(message, history):
63
  history = history or []
64
  message = message.lower()
65
-
66
  try:
67
- # Predict the tag
68
  results = model.predict([bag_of_words(message, words)])
69
  results_index = np.argmax(results)
70
  tag = labels[results_index]
71
-
72
- # Match tag with intent and choose a random response
73
  for tg in data["intents"]:
74
  if tg['tag'] == tag:
75
  responses = tg['responses']
@@ -79,83 +83,35 @@ def chat(message, history):
79
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
80
  except Exception as e:
81
  response = f"An error occurred: {str(e)}"
82
-
83
  history.append((message, response))
84
  return history, history
85
 
86
- # Sentiment Analysis
87
- tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
88
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
89
 
90
- def analyze_sentiment(user_input):
91
- inputs = tokenizer_sentiment(user_input, return_tensors="pt")
92
- with torch.no_grad():
93
- outputs = model_sentiment(**inputs)
94
- predicted_class = torch.argmax(outputs.logits, dim=1).item()
95
- sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
96
- return f"**Predicted Sentiment:** {sentiment}"
97
-
98
- # Emotion Detection
99
- tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
100
- model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
101
- pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
102
 
103
- def detect_emotion(user_input):
104
- result = pipe(user_input)
105
- emotion = result[0]['label']
106
- return emotion
107
 
 
108
  def provide_suggestions(emotion):
109
- suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
110
-
111
- if emotion == 'joy':
112
- suggestions = suggestions.append({
113
- "Subject": "Relaxation Techniques",
114
- "Article URL": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation",
115
- "Video URL": "https://youtu.be/m1vaUGtyo-A"
116
- }, ignore_index=True)
117
- suggestions = suggestions.append({
118
- "Subject": "Dealing with Stress",
119
- "Article URL": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
120
- "Video URL": "https://youtu.be/MIc299Flibs"
121
- }, ignore_index=True)
122
-
123
- elif emotion == 'anger':
124
- suggestions = suggestions.append({
125
- "Subject": "Managing Anger",
126
- "Article URL": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
127
- "Video URL": "https://youtu.be/MIc299Flibs"
128
- }, ignore_index=True)
129
-
130
- elif emotion == 'fear':
131
- suggestions = suggestions.append({
132
- "Subject": "Coping with Anxiety",
133
- "Article URL": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
134
- "Video URL": "https://youtu.be/yGKKz185M5o"
135
- }, ignore_index=True)
136
-
137
- elif emotion == 'sadness':
138
- suggestions = suggestions.append({
139
- "Subject": "Dealing with Sadness",
140
- "Article URL": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety",
141
- "Video URL": "https://youtu.be/-e-4Kx5px_I"
142
- }, ignore_index=True)
143
-
144
- elif emotion == 'surprise':
145
- suggestions = suggestions.append({
146
- "Subject": "Managing Stress",
147
- "Article URL": "https://www.health.harvard.edu/health-a-to-z",
148
- "Video URL": "https://youtu.be/m1vaUGtyo-A"
149
- }, ignore_index=True)
150
-
151
- return suggestions
152
-
153
- # Google Places API integration
154
- api_key = os.environ.get("GOOGLE_API_KEY") # Get API key from environment variable
155
-
156
- url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
157
- places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
158
 
 
159
  def get_places_data(query, location, radius, api_key, next_page_token=None):
160
  params = {
161
  "query": query,
@@ -166,39 +122,55 @@ def get_places_data(query, location, radius, api_key, next_page_token=None):
166
  if next_page_token:
167
  params["pagetoken"] = next_page_token
168
  response = requests.get(url, params=params)
169
- return response.json() if response.status_code == 200 else None
 
 
 
 
170
 
171
  def get_place_details(place_id, api_key):
172
- params = {
173
- "place_id": place_id,
174
- "key": api_key
175
- }
176
  response = requests.get(places_details_url, params=params)
177
  if response.status_code == 200:
178
  details_data = response.json().get("result", {})
179
  return {
180
- "opening_hours": details_data.get("opening_hours", {}).get("weekday_text", "Not available"),
181
- "reviews": details_data.get("reviews", "Not available"),
182
  "phone_number": details_data.get("formatted_phone_number", "Not available"),
183
  "website": details_data.get("website", "Not available")
184
  }
185
  else:
186
  return {}
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  def get_all_places(query, location, radius, api_key):
189
  all_results = []
190
  next_page_token = None
191
  while True:
192
- data = get_places_data(query, location, radius, api_key, next_page_token)
193
  if data:
194
  results = data.get('results', [])
195
  for place in results:
196
- place_id = place.get("place_id", "N/A") # Handle missing place_id
197
- name = place.get("name", "N/A") # Handle missing name
198
- address = place.get("formatted_address", "N/A") # Handle missing address
199
- website = place.get("website", "Not available")
200
- details = get_place_details(place_id, api_key) if place_id != "N/A" else {} #Avoid error if place_id is missing
201
  phone_number = details.get("phone_number", "Not available")
 
202
  all_results.append([name, address, phone_number, website])
203
  next_page_token = data.get('next_page_token')
204
  if not next_page_token:
@@ -207,50 +179,67 @@ def get_all_places(query, location, radius, api_key):
207
  break
208
  return all_results
209
 
210
- def search_wellness_professionals(location):
211
- query = "therapist OR counselor OR mental health professional"
212
- radius = 50000
213
- try:
214
- google_places_data = get_all_places(query, location, radius, api_key)
215
- if google_places_data:
216
- df = pd.DataFrame(google_places_data, columns=["Name", "Address", "Phone", "Website"])
217
- return df
 
 
 
 
 
 
 
 
218
  else:
219
- return pd.DataFrame([["No data found.", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
220
- except Exception as e:
221
- return pd.DataFrame([["Error fetching data: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
222
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- # Gradio Interface
225
- def gradio_interface(message, location, state):
226
- history = state or [] # If state is None, initialize it as an empty list
227
-
228
- # Stage 1: Mental Health Chatbot
229
- history, _ = chat(message, history)
230
-
231
- # Stage 2: Sentiment Analysis
232
- sentiment = analyze_sentiment(message)
233
-
234
- # Stage 3: Emotion Detection and Suggestions
235
- emotion = detect_emotion(message)
236
- suggestions = provide_suggestions(emotion)
237
-
238
- # Stage 4: Search for Wellness Professionals
239
- try:
240
- wellness_results = search_wellness_professionals(location)
241
- except Exception as e:
242
- wellness_results = pd.DataFrame([["Error: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
243
-
244
- # Return the results in a tabular form within the Gradio interface
245
- return history, sentiment, emotion, suggestions, wellness_results, history # Last 'history' is for state
246
 
247
- # Gradio interface setup
248
  iface = gr.Interface(
249
  fn=gradio_interface,
250
  inputs=[
251
  gr.Textbox(label="Enter your message", placeholder="How are you feeling today?"),
252
- gr.Textbox(label="Enter your location (e.g., 'Hawaii, USA')", placeholder="Enter your location"),
253
- gr.State() # To maintain state (chat history)
 
 
254
  ],
255
  outputs=[
256
  gr.Chatbot(label="Chatbot Responses"),
@@ -258,16 +247,11 @@ iface = gr.Interface(
258
  gr.Textbox(label="Emotion Detected"),
259
  gr.DataFrame(label="Suggested Articles & Videos"),
260
  gr.DataFrame(label="Nearby Wellness Professionals"),
261
- gr.State() # To maintain state (chat history)
262
  ],
263
  live=True,
264
  title="Mental Health Chatbot with Wellness Professional Search",
265
- description="This chatbot provides mental health support with sentiment analysis, emotion detection, suggestions, and a list of nearby wellness professionals."
266
  )
267
 
268
- # Check for API key; if not found, print an error message
269
- if api_key is None:
270
- print("Error: GOOGLE_MAPS_API_KEY environment variable not set. Please set this environment variable with your Google Maps API key.")
271
-
272
- # Launch the interface
273
  iface.launch(debug=True, share=True)
 
8
  import torch
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
12
  import requests
13
  import pandas as pd
14
  import os
15
+ from bs4 import BeautifulSoup
16
+ from selenium import webdriver
17
+ from selenium.webdriver.chrome.options import Options
18
+ import chromedriver_autoinstaller
19
 
20
  # Ensure necessary NLTK resources are downloaded
21
  nltk.download('punkt')
22
 
23
+ # --- Constants ---
24
+ GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY") # Get API key from environment variable
25
+ if not GOOGLE_MAPS_API_KEY:
26
+ raise ValueError("Error: GOOGLE_MAPS_API_KEY environment variable not set.")
27
+
28
+ url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
29
+ places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
30
+ 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"
31
+
32
+
33
+ # --- Chatbot Logic ---
34
  stemmer = LancasterStemmer()
35
 
 
36
  try:
37
  with open("intents.json") as file:
38
  data = json.load(file)
39
  except FileNotFoundError:
40
+ raise FileNotFoundError("Error: 'intents.json' file not found.")
41
 
 
42
  try:
43
  with open("data.pickle", "rb") as f:
44
  words, labels, training, output = pickle.load(f)
45
  except FileNotFoundError:
46
+ raise FileNotFoundError("Error: 'data.pickle' file not found.")
47
 
 
48
  net = tflearn.input_data(shape=[None, len(training[0])])
49
  net = tflearn.fully_connected(net, 8)
50
  net = tflearn.fully_connected(net, 8)
51
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
52
  net = tflearn.regression(net)
53
 
 
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
  def bag_of_words(s, words):
61
  bag = [0 for _ in range(len(words))]
62
  s_words = word_tokenize(s)
 
67
  bag[i] = 1
68
  return np.array(bag)
69
 
 
70
  def chat(message, history):
71
  history = history or []
72
  message = message.lower()
 
73
  try:
 
74
  results = model.predict([bag_of_words(message, words)])
75
  results_index = np.argmax(results)
76
  tag = labels[results_index]
 
 
77
  for tg in data["intents"]:
78
  if tg['tag'] == tag:
79
  responses = tg['responses']
 
83
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
84
  except Exception as e:
85
  response = f"An error occurred: {str(e)}"
 
86
  history.append((message, response))
87
  return history, history
88
 
89
+ # --- Sentiment Analysis ---
90
+ tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
91
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
92
 
93
+ def analyze_sentiment(text):
94
+ try:
95
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
96
+ with torch.no_grad():
97
+ outputs = model_sentiment(**inputs)
98
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
99
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
100
+ return f"**Predicted Sentiment:** {sentiment}"
101
+ except Exception as e:
102
+ return f"Error analyzing sentiment: {str(e)}"
 
 
103
 
104
+ # --- Emotion Detection (Placeholder) ---
105
+ def detect_emotion(text):
106
+ # Replace with your actual emotion detection logic
107
+ return "Emotion detection not implemented"
108
 
109
+ # --- Suggestion Generation (Placeholder) ---
110
  def provide_suggestions(emotion):
111
+ # Replace with your actual suggestion generation logic
112
+ return pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ # --- Google Places API Functions ---
115
  def get_places_data(query, location, radius, api_key, next_page_token=None):
116
  params = {
117
  "query": query,
 
122
  if next_page_token:
123
  params["pagetoken"] = next_page_token
124
  response = requests.get(url, params=params)
125
+ if response.status_code == 200:
126
+ return response.json()
127
+ else:
128
+ print(f"Error: {response.status_code} - {response.text}")
129
+ return None
130
 
131
  def get_place_details(place_id, api_key):
132
+ params = {"place_id": place_id, "key": api_key}
 
 
 
133
  response = requests.get(places_details_url, params=params)
134
  if response.status_code == 200:
135
  details_data = response.json().get("result", {})
136
  return {
 
 
137
  "phone_number": details_data.get("formatted_phone_number", "Not available"),
138
  "website": details_data.get("website", "Not available")
139
  }
140
  else:
141
  return {}
142
 
143
+ def scrape_website_from_google_maps(place_name):
144
+ chrome_options = Options()
145
+ chrome_options.add_argument("--headless")
146
+ chrome_options.add_argument("--no-sandbox")
147
+ chrome_options.add_argument("--disable-dev-shm-usage")
148
+ driver = webdriver.Chrome(options=chrome_options)
149
+ search_url = f"https://www.google.com/maps/search/{place_name.replace(' ', '+')}"
150
+ driver.get(search_url)
151
+ time.sleep(5)
152
+ try:
153
+ website_element = driver.find_element("xpath", '//a[contains(@aria-label, "Visit") and contains(@aria-label, "website")]')
154
+ website_url = website_element.get_attribute('href')
155
+ except:
156
+ website_url = "Not available"
157
+ driver.quit()
158
+ return website_url
159
+
160
  def get_all_places(query, location, radius, api_key):
161
  all_results = []
162
  next_page_token = None
163
  while True:
164
+ data = get_places_data(query + f" in {location}", location, radius, api_key, next_page_token)
165
  if data:
166
  results = data.get('results', [])
167
  for place in results:
168
+ place_id = place.get("place_id")
169
+ name = place.get("name")
170
+ address = place.get("formatted_address")
171
+ details = get_place_details(place_id, api_key)
 
172
  phone_number = details.get("phone_number", "Not available")
173
+ website = details.get("website", "Not available")
174
  all_results.append([name, address, phone_number, website])
175
  next_page_token = data.get('next_page_token')
176
  if not next_page_token:
 
179
  break
180
  return all_results
181
 
182
+ # --- Gradio Interface ---
183
+ def gradio_interface(message, location, state, btn_chat, btn_search):
184
+ history = state or []
185
+ if len(history) == 0:
186
+ if btn_chat:
187
+ history, _ = chat(message, history)
188
+ sentiment = analyze_sentiment(message)
189
+ emotion = detect_emotion(message)
190
+ suggestions = provide_suggestions(emotion)
191
+ if location:
192
+ try:
193
+ wellness_results = pd.DataFrame(get_all_places(query, location, 50000, GOOGLE_MAPS_API_KEY), columns=["Name", "Address", "Phone", "Website"])
194
+ except Exception as e:
195
+ wellness_results = pd.DataFrame([["Error fetching data: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
196
+ else:
197
+ wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
198
  else:
199
+ history = history
200
+ sentiment = ""
201
+ emotion = ""
202
+ suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
203
+ wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
204
+ elif len(history) > 0 and location == "":
205
+ if btn_chat:
206
+ history, _ = chat(message, history)
207
+ sentiment = analyze_sentiment(message)
208
+ emotion = detect_emotion(message)
209
+ suggestions = provide_suggestions(emotion)
210
+ wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
211
+ else:
212
+ history = history
213
+ sentiment = ""
214
+ emotion = ""
215
+ suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
216
+ wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
217
+ elif len(history) > 0 and location != "" and btn_search:
218
+ try:
219
+ wellness_results = pd.DataFrame(get_all_places(query, location, 50000, GOOGLE_MAPS_API_KEY), columns=["Name", "Address", "Phone", "Website"])
220
+ sentiment = analyze_sentiment(message)
221
+ emotion = detect_emotion(message)
222
+ suggestions = provide_suggestions(emotion)
223
+ history, _ = chat(message, history)
224
+ except Exception as e:
225
+ wellness_results = pd.DataFrame([["Error: " + str(e), "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
226
+ else:
227
+ history = history
228
+ sentiment = ""
229
+ emotion = ""
230
+ suggestions = pd.DataFrame(columns=["Subject", "Article URL", "Video URL"])
231
+ wellness_results = pd.DataFrame([["", "", "", ""]], columns=["Name", "Address", "Phone", "Website"])
232
 
233
+ return history, sentiment, emotion, suggestions, wellness_results, history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
 
235
  iface = gr.Interface(
236
  fn=gradio_interface,
237
  inputs=[
238
  gr.Textbox(label="Enter your message", placeholder="How are you feeling today?"),
239
+ gr.Textbox(label="Enter your location (e.g., 'Hawaii, USA')", placeholder="Enter your location (optional)"),
240
+ gr.State(),
241
+ gr.Button("Chat"),
242
+ gr.Button("Search")
243
  ],
244
  outputs=[
245
  gr.Chatbot(label="Chatbot Responses"),
 
247
  gr.Textbox(label="Emotion Detected"),
248
  gr.DataFrame(label="Suggested Articles & Videos"),
249
  gr.DataFrame(label="Nearby Wellness Professionals"),
250
+ gr.State()
251
  ],
252
  live=True,
253
  title="Mental Health Chatbot with Wellness Professional Search",
254
+ description="This chatbot provides mental health support with sentiment analysis, emotion detection, suggestions, and a list of nearby wellness professionals. Interact with the chatbot first, then enter a location to search."
255
  )
256
 
 
 
 
 
 
257
  iface.launch(debug=True, share=True)