DreamStream-1 commited on
Commit
dacc7c0
·
verified ·
1 Parent(s): 23d656c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -130
app.py CHANGED
@@ -1,101 +1,59 @@
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
- import pandas as pd
10
  from nltk.tokenize import word_tokenize
11
  from nltk.stem.lancaster import LancasterStemmer
12
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
13
  import torch
14
- import tensorflow as tf
15
- import tflearn
16
- from geopy.geocoders import Nominatim
17
  from bs4 import BeautifulSoup
18
- import re # Added for regex operations
 
 
 
19
 
20
- # Google Places API endpoint
21
- url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
22
- places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
23
-
24
- # Initialize necessary libraries for chatbot and NLP
25
  nltk.download('punkt')
 
 
26
  stemmer = LancasterStemmer()
27
 
28
- # Load the chatbot intents file
29
- with open("intents.json") as file:
30
- data = json.load(file)
 
 
 
31
 
32
  # Load preprocessed data from pickle
33
- with open("data.pickle", "rb") as f:
34
- words, labels, training, output = pickle.load(f)
 
 
 
35
 
36
- # Build the chatbot model
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
- model = tflearn.DNN(net)
43
- model.load("MentalHealthChatBotmodel.tflearn")
44
-
45
- # Emotion and sentiment analysis model
46
- def load_model():
47
- tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
48
- model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
49
- return tokenizer, model
50
-
51
- tokenizer, emotion_model = load_model()
52
-
53
- # Google Places API query function
54
- def get_places_data(query, location, radius=5000, api_key="GOOGLE_API_KEY"):
55
- # Use geopy to convert location name to coordinates
56
- geolocator = Nominatim(user_agent="place_search")
57
- location_obj = geolocator.geocode(location)
58
- if location_obj is None:
59
- return []
60
 
61
- latitude, longitude = location_obj.latitude, location_obj.longitude
62
- params = {
63
- "query": query,
64
- "location": f"{latitude},{longitude}",
65
- "radius": radius,
66
- "key": api_key
67
- }
68
- try:
69
- response = requests.get(url, params=params)
70
- response.raise_for_status()
71
- data = response.json()
72
- return data.get('results', [])
73
- except requests.exceptions.RequestException as e:
74
- print(f"Error fetching places data: {e}")
75
- return []
76
-
77
- # Map generation function
78
- def create_map(locations):
79
- m = folium.Map(location=[21.3, -157.8], zoom_start=12)
80
- for loc in locations:
81
- name = loc.get("name", "No Name")
82
- lat = loc['geometry']['location']['lat']
83
- lng = loc['geometry']['location']['lng']
84
- folium.Marker([lat, lng], popup=name).add_to(m)
85
- return m._repr_html_() # Return HTML representation
86
-
87
- # Sentiment Analysis function
88
- def analyze_sentiment(user_input):
89
- tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
90
- model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
91
- inputs = tokenizer(user_input, return_tensors="pt")
92
- with torch.no_grad():
93
- outputs = model(**inputs)
94
- predicted_class = torch.argmax(outputs.logits, dim=1).item()
95
- sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
96
- return sentiment
97
 
98
- # Chatbot function for user interaction
99
  def bag_of_words(s, words):
100
  bag = [0 for _ in range(len(words))]
101
  s_words = word_tokenize(s)
@@ -106,13 +64,18 @@ def bag_of_words(s, words):
106
  bag[i] = 1
107
  return np.array(bag)
108
 
109
- def chatbot(message, history):
 
110
  history = history or []
111
  message = message.lower()
 
112
  try:
 
113
  results = model.predict([bag_of_words(message, words)])
114
  results_index = np.argmax(results)
115
  tag = labels[results_index]
 
 
116
  for tg in data["intents"]:
117
  if tg['tag'] == tag:
118
  responses = tg['responses']
@@ -122,80 +85,130 @@ def chatbot(message, history):
122
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
123
  except Exception as e:
124
  response = f"An error occurred: {str(e)}"
 
125
  history.append((message, response))
126
  return history, history
127
 
128
- # Emotion Detection function
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def detect_emotion(user_input):
130
- pipe = pipeline("text-classification", model=emotion_model, tokenizer=tokenizer)
131
  result = pipe(user_input)
132
  emotion = result[0]['label']
133
  return emotion
134
 
135
- # Scraping the website to extract phone number or email
136
- def scrape_website_for_contact_info(website):
137
- phone_number = "Not available"
138
- email = "Not available"
139
- try:
140
- response = requests.get(website, timeout=5)
141
- soup = BeautifulSoup(response.content, 'html.parser')
142
- phone_match = re.search(r'$$?\+?[0-9]*$$?[0-9_\- $$$$]*', soup.get_text())
143
- if phone_match:
144
- phone_number = phone_match.group()
145
- email_match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', soup.get_text())
146
- if email_match:
147
- email = email_match.group()
148
- except Exception as e:
149
- print(f"Error scraping website {website}: {e}")
150
- return phone_number, email
151
-
152
- # Main Gradio interface for emotion detection and chatbot
153
- def emotion_and_chatbot(user_input, history, query, location, emotion_button, search_button):
154
- # Handle emotion detection
155
- if emotion_button:
156
- emotion = detect_emotion(user_input)
157
- sentiment = analyze_sentiment(user_input)
158
- emotion_response = f"Emotion Detected: {emotion}. Sentiment: {sentiment}"
159
- else:
160
- emotion_response = "Click on 'Detect Emotion' to analyze your input."
161
-
162
- # Handle place search (therapists or wellness centers)
163
- if search_button:
164
- places_data = get_places_data(query, location)
165
- places_df = pd.DataFrame(places_data)
166
- places_table = places_df[['name', 'vicinity', 'geometry']].head(10).to_html(classes='table table-bordered') if not places_df.empty else "No places found."
167
- places_map = create_map(places_data) if places_data else "No places found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  else:
169
- places_table = "Click on 'Search for Therapists' to search."
170
- places_map = ""
171
 
172
- # Handle chatbot conversation
173
- history, _ = chatbot(user_input, history)
 
 
 
 
 
 
 
 
 
174
 
175
- return emotion_response, places_map, places_table, history, history
 
 
 
176
 
177
  # Gradio interface setup
178
  iface = gr.Interface(
179
- fn=emotion_and_chatbot,
180
  inputs=[
181
- gr.Textbox(label="Enter your message", placeholder="How are you feeling?"),
182
- "state", # Chat history
183
- gr.Textbox(label="Search Query (e.g. wellness)", placeholder="e.g. therapist"),
184
- gr.Textbox(label="Location (e.g. Lahore, Hawaii, Allama Iqbal Town)", placeholder="e.g. Lahore, Allama Iqbal Town"),
185
- gr.Button("Detect Emotion"),
186
- gr.Button("Search for Therapists")
187
  ],
188
  outputs=[
189
- gr.Textbox(label="Emotion and Sentiment"),
190
- gr.HTML(label="Places Map"),
191
- gr.HTML(label="Places Table"),
192
- gr.Chatbot(label="Chatbot History"),
193
- "state"
194
  ],
195
- title="Wellbeing Chatbot with Emotion Detection & Location Search",
196
- description="A chatbot that provides mental health support, analyzes emotions, and helps find wellness professionals near you."
 
197
  )
198
 
199
- # Launch Gradio app
200
  if __name__ == "__main__":
201
- iface.launch(debug=True)
 
1
  import nltk
2
  import numpy as np
3
+ import tflearn
4
+ import tensorflow
5
  import random
6
  import json
7
  import pickle
8
  import gradio as gr
 
 
 
9
  from nltk.tokenize import word_tokenize
10
  from nltk.stem.lancaster import LancasterStemmer
11
  from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
  import torch
13
+ import requests
14
+ import pandas as pd
15
+ import time
16
  from bs4 import BeautifulSoup
17
+ from selenium import webdriver
18
+ from selenium.webdriver.chrome.options import Options
19
+ import chromedriver_autoinstaller
20
+ import os
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
+ try:
30
+ with open("intents.json") as file:
31
+ data = json.load(file)
32
+ except FileNotFoundError:
33
+ raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
34
 
35
  # Load preprocessed data from pickle
36
+ try:
37
+ with open("data.pickle", "rb") as f:
38
+ words, labels, training, output = pickle.load(f)
39
+ except FileNotFoundError:
40
+ raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
41
 
42
+ # Build the model structure
43
  net = tflearn.input_data(shape=[None, len(training[0])])
44
  net = tflearn.fully_connected(net, 8)
45
  net = tflearn.fully_connected(net, 8)
46
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
47
  net = tflearn.regression(net)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Load the trained model
50
+ model = tflearn.DNN(net)
51
+ try:
52
+ model.load("MentalHealthChatBotmodel.tflearn")
53
+ except FileNotFoundError:
54
+ raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ # Function to process user input into a bag-of-words format
57
  def bag_of_words(s, words):
58
  bag = [0 for _ in range(len(words))]
59
  s_words = word_tokenize(s)
 
64
  bag[i] = 1
65
  return np.array(bag)
66
 
67
+ # Chat function (Chatbot)
68
+ def chat(message, history):
69
  history = history or []
70
  message = message.lower()
71
+
72
  try:
73
+ # Predict the tag
74
  results = model.predict([bag_of_words(message, words)])
75
  results_index = np.argmax(results)
76
  tag = labels[results_index]
77
+
78
+ # Match tag with intent and choose a random response
79
  for tg in data["intents"]:
80
  if tg['tag'] == tag:
81
  responses = tg['responses']
 
85
  response = "I'm sorry, I didn't understand that. Could you please rephrase?"
86
  except Exception as e:
87
  response = f"An error occurred: {str(e)}"
88
+
89
  history.append((message, response))
90
  return history, history
91
 
92
+ # Sentiment Analysis (Code 2)
93
+ tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
94
+ model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
95
+
96
+ def analyze_sentiment(user_input):
97
+ inputs = tokenizer_sentiment(user_input, return_tensors="pt")
98
+ with torch.no_grad():
99
+ outputs = model_sentiment(**inputs)
100
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
101
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
102
+ return f"**Predicted Sentiment:** {sentiment}"
103
+
104
+ # Emotion Detection (Code 3)
105
+ tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
106
+ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
107
+ pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
108
+
109
  def detect_emotion(user_input):
 
110
  result = pipe(user_input)
111
  emotion = result[0]['label']
112
  return emotion
113
 
114
+ def provide_suggestions(emotion):
115
+ suggestions = ""
116
+ if emotion == 'joy':
117
+ suggestions += "You're feeling happy! Keep up the great mood!"
118
+ elif emotion == 'anger':
119
+ suggestions += "You're feeling angry. It's okay to feel this way."
120
+ elif emotion == 'fear':
121
+ suggestions += "You're feeling fearful. Take a moment to breathe."
122
+ elif emotion == 'sadness':
123
+ suggestions += "You're feeling sad. It's okay to take a break."
124
+ elif emotion == 'surprise':
125
+ suggestions += "You're feeling surprised. It's okay to feel neutral!"
126
+ return suggestions
127
+
128
+ # Google Places API (Code 4)
129
+ api_key = "YOUR_GOOGLE_API_KEY" # Replace with your API key
130
+
131
+ def get_places_data(query, location, radius, api_key, next_page_token=None):
132
+ url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
133
+ params = {
134
+ "query": query,
135
+ "location": location,
136
+ "radius": radius,
137
+ "key": api_key
138
+ }
139
+ if next_page_token:
140
+ params["pagetoken"] = next_page_token
141
+ response = requests.get(url, params=params)
142
+ return response.json() if response.status_code == 200 else None
143
+
144
+ def get_all_places(query, location, radius, api_key):
145
+ all_results = []
146
+ next_page_token = None
147
+ while True:
148
+ data = get_places_data(query, location, radius, api_key, next_page_token)
149
+ if data:
150
+ results = data.get('results', [])
151
+ for place in results:
152
+ place_id = place.get("place_id")
153
+ name = place.get("name")
154
+ address = place.get("formatted_address")
155
+ website = place.get("website", "Not available")
156
+ all_results.append([name, address, website])
157
+ next_page_token = data.get('next_page_token')
158
+ if not next_page_token:
159
+ break
160
+ else:
161
+ break
162
+ return all_results
163
+
164
+ # Search Wellness Professionals
165
+ def search_wellness_professionals(location):
166
+ query = "therapist OR counselor OR mental health professional"
167
+ radius = 50000
168
+ google_places_data = get_all_places(query, location, radius, api_key)
169
+ if google_places_data:
170
+ df = pd.DataFrame(google_places_data, columns=["Name", "Address", "Website"])
171
+ return df.to_csv(index=False)
172
  else:
173
+ return "No data found."
 
174
 
175
+ # Gradio Interface
176
+ def gradio_interface(message, location, history):
177
+ # Stage 1: Mental Health Chatbot
178
+ history, _ = chat(message, history)
179
+
180
+ # Stage 2: Sentiment Analysis
181
+ sentiment = analyze_sentiment(message)
182
+
183
+ # Stage 3: Emotion Detection and Suggestions
184
+ emotion = detect_emotion(message)
185
+ suggestions = provide_suggestions(emotion)
186
 
187
+ # Stage 4: Search for Wellness Professionals
188
+ wellness_results = search_wellness_professionals(location)
189
+
190
+ return history, sentiment, emotion, suggestions, wellness_results
191
 
192
  # Gradio interface setup
193
  iface = gr.Interface(
194
+ fn=gradio_interface,
195
  inputs=[
196
+ gr.Textbox(label="Enter your message", placeholder="How are you feeling today?"),
197
+ gr.Textbox(label="Enter your location (e.g., Hawaii, Oahu)", placeholder="Your location"),
198
+ "state"
 
 
 
199
  ],
200
  outputs=[
201
+ gr.Chatbot(label="Chat History"),
202
+ gr.Textbox(label="Sentiment Analysis"),
203
+ gr.Textbox(label="Detected Emotion"),
204
+ gr.Textbox(label="Suggestions"),
205
+ gr.File(label="Download Wellness Professionals CSV")
206
  ],
207
+ allow_flagging="never",
208
+ title="Mental Wellbeing App with AI Assistance",
209
+ description="This app provides a mental health chatbot, sentiment analysis, emotion detection, and wellness professional search functionality.",
210
  )
211
 
212
+ # Launch Gradio interface
213
  if __name__ == "__main__":
214
+ iface.launch(debug=True)