DreamStream-1 commited on
Commit
0e313c1
·
verified ·
1 Parent(s): ece2285

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -188
app.py CHANGED
@@ -1,56 +1,96 @@
1
- import json
2
- import pickle
3
- import random
4
  import nltk
5
  import numpy as np
6
- import tflearn
 
 
7
  import gradio as gr
8
  import requests
9
- import torch
10
  import folium
11
- from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  from nltk.tokenize import word_tokenize
13
  from nltk.stem.lancaster import LancasterStemmer
14
- import os
15
- from functools import lru_cache
 
 
16
  import pandas as pd
17
- import tensorflow as tf # Added to enable resource variables
 
 
 
 
 
18
 
19
- # Enable resource variables in TensorFlow to avoid deprecated warnings
20
- tf.compat.v1.enable_resource_variables()
 
21
 
22
- # Ensure necessary NLTK resources are downloaded
23
  nltk.download('punkt')
24
-
25
- # Initialize the stemmer
26
  stemmer = LancasterStemmer()
27
 
28
- # Load intents.json
29
- def load_intents(file_path):
30
- with open(file_path) as file:
31
- return json.load(file)
32
 
33
  # Load preprocessed data from pickle
34
- def load_preprocessed_data(file_path):
35
- with open(file_path, "rb") as f:
36
- return pickle.load(f)
37
-
38
- # Build the model structure
39
- def build_model(words, labels, training, output):
40
- net = tflearn.input_data(shape=[None, len(training[0])])
41
- net = tflearn.fully_connected(net, 8)
42
- net = tflearn.fully_connected(net, 8)
43
- net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
44
- net = tflearn.regression(net)
45
- return tflearn.DNN(net)
46
-
47
- # Load the trained model
48
- def load_model(model_path, net):
49
- model = tflearn.DNN(net)
50
- model.load(model_path)
51
- return model
52
-
53
- # Function to process user input into a bag-of-words format
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  def bag_of_words(s, words):
55
  bag = [0 for _ in range(len(words))]
56
  s_words = word_tokenize(s)
@@ -61,18 +101,13 @@ def bag_of_words(s, words):
61
  bag[i] = 1
62
  return np.array(bag)
63
 
64
- # Chat function
65
- def chat(message, history, words, labels, model):
66
  history = history or []
67
  message = message.lower()
68
-
69
  try:
70
- # Predict the tag
71
  results = model.predict([bag_of_words(message, words)])
72
  results_index = np.argmax(results)
73
  tag = labels[results_index]
74
-
75
- # Match tag with intent and choose a random response
76
  for tg in data["intents"]:
77
  if tg['tag'] == tag:
78
  responses = tg['responses']
@@ -80,159 +115,81 @@ def chat(message, history, words, labels, model):
80
  break
81
  else:
82
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
83
-
84
  except Exception as e:
85
  response = f"An error occurred: {str(e)}"
86
-
87
  history.append((message, response))
88
  return history, history
89
 
90
- # Sentiment analysis setup
91
- tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
92
- model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
93
-
94
- # Emotion detection setup
95
- def load_emotion_model():
96
- tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
97
- model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
98
- return tokenizer, model
99
-
100
- tokenizer_emotion, model_emotion = load_emotion_model()
101
-
102
- # Emotion detection function with suggestions
103
  def detect_emotion(user_input):
104
- pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
105
  result = pipe(user_input)
106
  emotion = result[0]['label']
107
-
108
- suggestions = []
109
- video_link = ""
110
-
111
- # Provide suggestions based on the detected emotion
112
- if emotion == 'joy':
113
- suggestions = [
114
- ("Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
115
- ("Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
116
- ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
117
- ]
118
- video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
119
- elif emotion == 'anger':
120
- suggestions = [
121
- ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
122
- ("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"),
123
- ("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
124
- ]
125
- video_link = "Watch on YouTube: https://youtu.be/MIc299Flibs"
126
- elif emotion == 'fear':
127
- suggestions = [
128
- ("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
129
- ("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
130
- ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit")
131
- ]
132
- video_link = "Watch on YouTube: https://youtu.be/yGKKz185M5o"
133
- elif emotion == 'sadness':
134
- suggestions = [
135
- ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
136
- ("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
137
- ]
138
- video_link = "Watch on YouTube: https://youtu.be/-e-4Kx5px_I"
139
- elif emotion == 'surprise':
140
- suggestions = [
141
- ("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"),
142
- ("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety")
143
- ]
144
- video_link = "Watch on YouTube: https://youtu.be/m1vaUGtyo-A"
145
-
146
- return emotion, suggestions, video_link
147
 
148
- # Google Geocoding API setup to convert city name to latitude/longitude
149
- geocode_url = "https://maps.googleapis.com/maps/api/geocode/json"
150
-
151
- @lru_cache(maxsize=128)
152
- def get_lat_lon(location, api_key):
153
- params = {
154
- "address": location,
155
- "key": api_key
156
- }
157
- try:
158
- response = requests.get(geocode_url, params=params)
159
- response.raise_for_status()
160
- result = response.json()
161
- if result['status'] == 'OK':
162
- location = result['results'][0]['geometry']['location']
163
- return location['lat'], location['lng']
164
- else:
165
- return None, None
166
- except requests.RequestException as e:
167
- print(f"Error fetching coordinates: {e}")
168
- return None, None
169
-
170
- # Function to fetch places data using Google Places API
171
- def get_places_data(query, location, radius, api_key):
172
- places_url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
173
- params = {
174
- "query": query,
175
- "location": location,
176
- "radius": radius,
177
- "key": api_key
178
- }
179
  try:
180
- response = requests.get(places_url, params=params)
181
- response.raise_for_status()
182
- return response.json()
183
- except requests.RequestException as e:
184
- print(f"Error fetching places data: {e}")
185
- return None
186
-
187
- # Get wellness professionals
188
- def get_wellness_professionals(location, api_key):
189
- 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"
190
- radius = 50000 # 50 km radius
191
-
192
- lat, lon = get_lat_lon(location, api_key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
- if lat is None or lon is None:
195
- return "Unable to find coordinates for the given location."
196
-
197
- # Using Google Places API to fetch wellness professionals
198
- data = get_places_data(query, f"{lat},{lon}", radius, api_key)
199
-
200
- if data:
201
- results = data.get('results', [])
202
- wellness_data = []
203
- for place in results:
204
- name = place.get("name")
205
- address = place.get("formatted_address")
206
- latitude = place.get("geometry", {}).get("location", {}).get("lat")
207
- longitude = place.get("geometry", {}).get("location", {}).get("lng")
208
- wellness_data.append([name, address, latitude, longitude])
209
- return wellness_data
210
-
211
- return []
212
-
213
- # Function to generate a map with wellness professionals
214
- def generate_map(wellness_data):
215
- map_center = [23.685, 90.3563] # Default center for Bangladesh (you can adjust this)
216
- m = folium.Map(location=map_center, zoom_start=12)
217
-
218
- for place in wellness_data:
219
- name, address, lat, lon = place
220
- folium.Marker([lat, lon], popup=f"{name}\n{address}").add_to(m)
221
-
222
- return m
223
-
224
- # Initialize the necessary files
225
- data = load_intents("intents.json")
226
- words, labels, training, output = load_preprocessed_data("data.pickle")
227
-
228
- # Build the model
229
- model = build_model(words, labels, training, output)
230
- model = load_model("model.tflearn", model)
231
-
232
- # Gradio interface
233
- def chatbot_interface(message, history):
234
- return chat(message, history, words, labels, model)
235
-
236
- # Example usage with Gradio UI
237
- gr.Interface(fn=chatbot_interface, inputs=["text", "state"], outputs=["chatbot", "state"]).launch()
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import nltk
2
  import numpy as np
3
+ import random
4
+ import json
5
+ import pickle
6
  import gradio as gr
7
  import requests
 
8
  import folium
 
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
+ import tensorflow as tf
13
+ import tflearn
14
+ import torch
15
  import pandas as pd
16
+ import time
17
+ from bs4 import BeautifulSoup
18
+ from selenium import webdriver
19
+ from selenium.webdriver.chrome.options import Options
20
+ import chromedriver_autoinstaller
21
+ import os
22
 
23
+ # Google Places API endpoint
24
+ url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
25
+ places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
26
 
27
+ # Initialize necessary libraries for chatbot and NLP
28
  nltk.download('punkt')
 
 
29
  stemmer = LancasterStemmer()
30
 
31
+ # Load the chatbot intents file
32
+ with open("intents.json") as file:
33
+ data = json.load(file)
 
34
 
35
  # Load preprocessed data from pickle
36
+ with open("data.pickle", "rb") as f:
37
+ words, labels, training, output = pickle.load(f)
38
+
39
+ # Build the chatbot model
40
+ net = tflearn.input_data(shape=[None, len(training[0])])
41
+ net = tflearn.fully_connected(net, 8)
42
+ net = tflearn.fully_connected(net, 8)
43
+ net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
44
+ net = tflearn.regression(net)
45
+ model = tflearn.DNN(net)
46
+ model.load("MentalHealthChatBotmodel.tflearn")
47
+
48
+ # Emotion and sentiment analysis model
49
+ @st.cache_resource
50
+ def load_model():
51
+ tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
52
+ model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
53
+ return tokenizer, model
54
+
55
+ tokenizer, emotion_model = load_model()
56
+
57
+ # Google Places API query function
58
+ def get_places_data(query, location, radius=5000, api_key="YOUR_GOOGLE_API_KEY"):
59
+ params = {
60
+ "query": query,
61
+ "location": location,
62
+ "radius": radius,
63
+ "key": api_key
64
+ }
65
+ response = requests.get(url, params=params)
66
+ if response.status_code == 200:
67
+ data = response.json()
68
+ return data['results']
69
+ else:
70
+ return []
71
+
72
+ # Map generation function
73
+ def create_map(locations):
74
+ m = folium.Map(location=[21.3, -157.8], zoom_start=12)
75
+ for loc in locations:
76
+ name = loc.get("name", "No Name")
77
+ lat = loc['geometry']['location']['lat']
78
+ lng = loc['geometry']['location']['lng']
79
+ folium.Marker([lat, lng], popup=name).add_to(m)
80
+ return m
81
+
82
+ # Sentiment Analysis function
83
+ def analyze_sentiment(user_input):
84
+ tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
85
+ model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
86
+ inputs = tokenizer(user_input, return_tensors="pt")
87
+ with torch.no_grad():
88
+ outputs = model(**inputs)
89
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
90
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
91
+ return sentiment
92
+
93
+ # Chatbot function for user interaction
94
  def bag_of_words(s, words):
95
  bag = [0 for _ in range(len(words))]
96
  s_words = word_tokenize(s)
 
101
  bag[i] = 1
102
  return np.array(bag)
103
 
104
+ def chatbot(message, history):
 
105
  history = history or []
106
  message = message.lower()
 
107
  try:
 
108
  results = model.predict([bag_of_words(message, words)])
109
  results_index = np.argmax(results)
110
  tag = labels[results_index]
 
 
111
  for tg in data["intents"]:
112
  if tg['tag'] == tag:
113
  responses = tg['responses']
 
115
  break
116
  else:
117
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
 
118
  except Exception as e:
119
  response = f"An error occurred: {str(e)}"
 
120
  history.append((message, response))
121
  return history, history
122
 
123
+ # Emotion Detection function
 
 
 
 
 
 
 
 
 
 
 
 
124
  def detect_emotion(user_input):
125
+ pipe = pipeline("text-classification", model=emotion_model, tokenizer=tokenizer)
126
  result = pipe(user_input)
127
  emotion = result[0]['label']
128
+ return emotion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
+ # Scraping the website to extract phone number or email
131
+ def scrape_website_for_contact_info(website):
132
+ phone_number = "Not available"
133
+ email = "Not available"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  try:
135
+ response = requests.get(website, timeout=5)
136
+ soup = BeautifulSoup(response.content, 'html.parser')
137
+ phone_match = re.search(r'\(?\+?[0-9]*\)?[0-9_\- \(\)]*', soup.get_text())
138
+ if phone_match:
139
+ phone_number = phone_match.group()
140
+ email_match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())
141
+ if email_match:
142
+ email = email_match.group()
143
+ except Exception as e:
144
+ print(f"Error scraping website {website}: {e}")
145
+ return phone_number, email
146
+
147
+ # Main Gradio interface for location search and map generation
148
+ def search_and_display_location(query, location):
149
+ query = query or "wellness"
150
+ location = location or "21.3,-157.8" # Default location (Hawaii)
151
+ places_data = get_places_data(query, location)
152
+ if places_data:
153
+ map_object = create_map(places_data)
154
+ return map_object
155
+ else:
156
+ return "No results found for the given location."
157
+
158
+ # Main Gradio interface for emotion detection and chatbot
159
+ def emotion_and_chatbot(user_input, history, query, location):
160
+ # Emotion Detection
161
+ emotion = detect_emotion(user_input)
162
+ sentiment = analyze_sentiment(user_input)
163
+ emotion_response = f"Emotion Detected: {emotion}. Sentiment: {sentiment}"
164
 
165
+ # Search Places (for wellness or other queries)
166
+ places_data = get_places_data(query, location)
167
+ places_map = create_map(places_data) if places_data else "No places found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
+ # Chatbot response
170
+ history, _ = chatbot(user_input, history)
171
+
172
+ return emotion_response, places_map, history, history
173
+
174
+ # Gradio interface setup
175
+ iface = gr.Interface(
176
+ fn=emotion_and_chatbot,
177
+ inputs=[
178
+ gr.Textbox(label="Enter your message", placeholder="How are you feeling?"),
179
+ "state", # Chat history
180
+ gr.Textbox(label="Search Query (e.g. wellness)", placeholder="e.g. therapist"),
181
+ gr.Textbox(label="Location (latitude,longitude)", placeholder="e.g. 21.3,-157.8")
182
+ ],
183
+ outputs=[
184
+ gr.Textbox(label="Emotion and Sentiment"),
185
+ gr.HTML(label="Places Map"),
186
+ gr.Chatbot(label="Chatbot History"),
187
+ "state"
188
+ ],
189
+ title="Wellbeing Chatbot with Emotion Detection & Location Search",
190
+ description="A chatbot that provides mental health support, analyzes emotions, and helps find wellness professionals near you."
191
+ )
192
+
193
+ # Launch Gradio app
194
+ if __name__ == "__main__":
195
+ iface.launch(debug=True)