Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,154 +1,193 @@
|
|
1 |
-
import
|
|
|
2 |
import random
|
|
|
|
|
|
|
|
|
3 |
import requests
|
|
|
|
|
|
|
|
|
4 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
#
|
7 |
-
|
8 |
-
|
9 |
-
# Load pre-trained models for sentiment and emotion detection
|
10 |
-
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
11 |
-
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
12 |
-
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
13 |
-
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
14 |
-
|
15 |
-
# Function to get latitude and longitude from city using Google Maps Geocoding API
|
16 |
-
def get_lat_lng_from_city(city):
|
17 |
-
geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?address={city}&key={GOOGLE_API_KEY}"
|
18 |
-
response = requests.get(geocode_url)
|
19 |
-
data = response.json()
|
20 |
-
if data["status"] == "OK":
|
21 |
-
lat_lng = data["results"][0]["geometry"]["location"]
|
22 |
-
return lat_lng["lat"], lat_lng["lng"]
|
23 |
-
else:
|
24 |
-
return None, None
|
25 |
|
26 |
-
#
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
data =
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
}
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
#
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
# Function for emotion detection and suggestions
|
68 |
-
def detect_emotion(text, state):
|
69 |
-
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
|
70 |
-
result = pipe(text)
|
71 |
-
emotion = result[0]['label']
|
72 |
|
73 |
-
#
|
74 |
-
|
|
|
|
|
75 |
|
76 |
-
#
|
77 |
-
|
78 |
-
return emotion, suggestions, state
|
79 |
-
|
80 |
-
# Suggestions based on detected emotion
|
81 |
-
def provide_suggestions(emotion):
|
82 |
-
resources = {
|
83 |
-
'joy': {
|
84 |
-
'message': "You're feeling happy! Keep up the great mood! 😊",
|
85 |
-
'articles': [
|
86 |
-
"[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)",
|
87 |
-
"[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
|
88 |
-
],
|
89 |
-
'videos': "[Watch Relaxation Video](https://youtu.be/m1vaUGtyo-A)"
|
90 |
-
},
|
91 |
-
'anger': {
|
92 |
-
'message': "You're feeling angry. It's okay to feel this way. Let's try to calm down. 😡",
|
93 |
-
'articles': [
|
94 |
-
"[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)",
|
95 |
-
"[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)"
|
96 |
-
],
|
97 |
-
'videos': "[Watch Anger Management Video](https://youtu.be/MIc299Flibs)"
|
98 |
-
},
|
99 |
-
'fear': {
|
100 |
-
'message': "You're feeling fearful. Take a moment to breathe and relax. 😨",
|
101 |
-
'articles': [
|
102 |
-
"[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)",
|
103 |
-
"[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
|
104 |
-
],
|
105 |
-
'videos': "[Watch Coping Video](https://youtu.be/yGKKz185M5o)"
|
106 |
-
},
|
107 |
-
'sadness': {
|
108 |
-
'message': "You're feeling sad. It's okay to take a break. 😔",
|
109 |
-
'articles': [
|
110 |
-
"[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)",
|
111 |
-
"[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
|
112 |
-
],
|
113 |
-
'videos': "[Watch Sadness Relief Video](https://youtu.be/-e-4Kx5px_I)"
|
114 |
-
},
|
115 |
-
'surprise': {
|
116 |
-
'message': "You're feeling surprised. It's okay to feel neutral! 😲",
|
117 |
-
'articles': [
|
118 |
-
"[Managing Stress](https://www.health.harvard.edu/health-a-to-z)",
|
119 |
-
"[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)"
|
120 |
-
],
|
121 |
-
'videos': "[Watch Stress Relief Video](https://youtu.be/m1vaUGtyo-A)"
|
122 |
-
}
|
123 |
-
}
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
message_input = gr.Textbox(placeholder="Ask me something...", label="Enter your message")
|
140 |
-
sentiment_output = gr.Textbox(placeholder="Sentiment result", label="Sentiment")
|
141 |
-
emotion_output = gr.Textbox(placeholder="Detected emotion", label="Emotion")
|
142 |
-
wellness_output = gr.Textbox(placeholder="Wellness professionals nearby", label="Wellness Professionals")
|
143 |
-
location_input = gr.Textbox(placeholder="Enter your city for wellness professionals", label="Location")
|
144 |
-
|
145 |
-
message_input.submit(chat, [message_input, chatbot, state], [chatbot, chatbot, state])
|
146 |
-
message_input.submit(analyze_sentiment, [message_input, state], [sentiment_output, state])
|
147 |
-
sentiment_output.submit(detect_emotion, [sentiment_output, state], [emotion_output, wellness_output, state])
|
148 |
-
location_input.submit(search_wellness_professionals, [location_input, state], [wellness_output, state])
|
149 |
-
|
150 |
-
return demo
|
151 |
|
152 |
# Launch Gradio interface
|
153 |
-
|
154 |
-
demo.launch(
|
|
|
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 time
|
10 |
+
from bs4 import BeautifulSoup
|
11 |
+
from selenium import webdriver
|
12 |
+
from selenium.webdriver.chrome.options import Options
|
13 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
14 |
+
import torch
|
15 |
+
import pandas as pd
|
16 |
+
import os
|
17 |
+
import chromedriver_autoinstaller
|
18 |
+
from nltk.tokenize import word_tokenize
|
19 |
+
from nltk.stem.lancaster import LancasterStemmer
|
20 |
|
21 |
+
# Ensure necessary NLTK resources are downloaded
|
22 |
+
nltk.download('punkt')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
# Initialize the stemmer
|
25 |
+
stemmer = LancasterStemmer()
|
26 |
+
|
27 |
+
# Load intents.json
|
28 |
+
try:
|
29 |
+
with open("intents.json") as file:
|
30 |
+
data = json.load(file)
|
31 |
+
except FileNotFoundError:
|
32 |
+
raise FileNotFoundError("Error: 'intents.json' file not found. Ensure it exists in the current directory.")
|
33 |
+
|
34 |
+
# Load preprocessed data from pickle
|
35 |
+
try:
|
36 |
+
with open("data.pickle", "rb") as f:
|
37 |
+
words, labels, training, output = pickle.load(f)
|
38 |
+
except FileNotFoundError:
|
39 |
+
raise FileNotFoundError("Error: 'data.pickle' file not found. Ensure it exists and matches the model.")
|
40 |
+
|
41 |
+
# Build the model structure
|
42 |
+
net = tflearn.input_data(shape=[None, len(training[0])])
|
43 |
+
net = tflearn.fully_connected(net, 8)
|
44 |
+
net = tflearn.fully_connected(net, 8)
|
45 |
+
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
46 |
+
net = tflearn.regression(net)
|
47 |
+
|
48 |
+
# Load the trained model
|
49 |
+
model = tflearn.DNN(net)
|
50 |
+
try:
|
51 |
+
model.load("MentalHealthChatBotmodel.tflearn")
|
52 |
+
except FileNotFoundError:
|
53 |
+
raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
|
54 |
+
|
55 |
+
# Function to process user input into a bag-of-words format
|
56 |
+
def bag_of_words(s, words):
|
57 |
+
bag = [0 for _ in range(len(words))]
|
58 |
+
s_words = word_tokenize(s)
|
59 |
+
s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
|
60 |
+
for se in s_words:
|
61 |
+
for i, w in enumerate(words):
|
62 |
+
if w == se:
|
63 |
+
bag[i] = 1
|
64 |
+
return np.array(bag)
|
65 |
+
|
66 |
+
# Chat function
|
67 |
+
def chat(message, history):
|
68 |
+
history = history or []
|
69 |
+
message = message.lower()
|
70 |
+
|
71 |
+
try:
|
72 |
+
# Predict the tag
|
73 |
+
results = model.predict([bag_of_words(message, words)])
|
74 |
+
results_index = np.argmax(results)
|
75 |
+
tag = labels[results_index]
|
76 |
+
|
77 |
+
# Match tag with intent and choose a random response
|
78 |
+
for tg in data["intents"]:
|
79 |
+
if tg['tag'] == tag:
|
80 |
+
responses = tg['responses']
|
81 |
+
response = random.choice(responses)
|
82 |
+
break
|
83 |
+
else:
|
84 |
+
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
85 |
+
|
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 |
+
|
93 |
+
# Sentiment analysis setup
|
94 |
+
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
95 |
+
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
96 |
+
|
97 |
+
# Emotion detection setup
|
98 |
+
@st.cache_resource
|
99 |
+
def load_emotion_model():
|
100 |
+
tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
101 |
+
model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
102 |
+
return tokenizer, model
|
103 |
+
|
104 |
+
tokenizer_emotion, model_emotion = load_emotion_model()
|
105 |
+
|
106 |
+
# Google Places API setup for wellness professionals
|
107 |
+
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
108 |
+
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
109 |
+
api_key = "GOOGLE_API_KEY"
|
110 |
+
|
111 |
+
# Install Chrome and Chromedriver for web scraping
|
112 |
+
def install_chrome_and_driver():
|
113 |
+
os.system("apt-get update")
|
114 |
+
os.system("apt-get install -y wget curl")
|
115 |
+
os.system("wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")
|
116 |
+
os.system("dpkg -i google-chrome-stable_current_amd64.deb")
|
117 |
+
os.system("apt-get install -y -f")
|
118 |
+
os.system("google-chrome-stable --version")
|
119 |
+
chromedriver_autoinstaller.install()
|
120 |
+
|
121 |
+
install_chrome_and_driver()
|
122 |
+
|
123 |
+
# Function to get places data using Google Places API
|
124 |
+
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
125 |
+
params = {
|
126 |
+
"query": query,
|
127 |
+
"location": location,
|
128 |
+
"radius": radius,
|
129 |
+
"key": api_key
|
130 |
}
|
131 |
+
|
132 |
+
if next_page_token:
|
133 |
+
params["pagetoken"] = next_page_token
|
134 |
+
|
135 |
+
response = requests.get(url, params=params)
|
136 |
+
if response.status_code == 200:
|
137 |
+
return response.json()
|
138 |
+
else:
|
139 |
+
return None
|
140 |
+
|
141 |
+
# Main function to fetch wellness professional data and display on map
|
142 |
+
def get_wellness_professionals(location):
|
143 |
+
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"
|
144 |
+
radius = 50000 # 50 km radius
|
145 |
+
data = get_places_data(query, location, radius, api_key)
|
146 |
+
|
147 |
+
if data:
|
148 |
+
results = data.get('results', [])
|
149 |
+
wellness_data = []
|
150 |
+
for place in results:
|
151 |
+
name = place.get("name")
|
152 |
+
address = place.get("formatted_address")
|
153 |
+
latitude = place.get("geometry", {}).get("location", {}).get("lat")
|
154 |
+
longitude = place.get("geometry", {}).get("location", {}).get("lng")
|
155 |
+
wellness_data.append([name, address, latitude, longitude])
|
156 |
+
return wellness_data
|
157 |
+
return []
|
158 |
+
|
159 |
+
# Gradio interface setup for user interaction
|
160 |
+
def user_interface(message, location, history):
|
161 |
+
history, history = chat(message, history)
|
162 |
|
163 |
+
# Sentiment analysis
|
164 |
+
inputs = tokenizer_sentiment(message, return_tensors="pt")
|
165 |
+
outputs = model_sentiment(**inputs)
|
166 |
+
sentiment = ["Negative", "Neutral", "Positive"][torch.argmax(outputs.logits, dim=1).item()]
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
+
# Emotion detection
|
169 |
+
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
170 |
+
emotion_result = pipe(message)
|
171 |
+
emotion = emotion_result[0]['label']
|
172 |
|
173 |
+
# Get wellness professionals
|
174 |
+
wellness_data = get_wellness_professionals(location)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
|
176 |
+
return history, history, sentiment, emotion, wellness_data
|
177 |
+
|
178 |
+
# Gradio chatbot interface
|
179 |
+
chatbot = gr.Chatbot(label="Mental Health Chatbot")
|
180 |
+
location_input = gr.Textbox(label="Enter your location (latitude,longitude)", placeholder="e.g., 21.3,-157.8")
|
181 |
+
|
182 |
+
# Gradio interface definition
|
183 |
+
demo = gr.Interface(
|
184 |
+
user_interface,
|
185 |
+
[gr.Textbox(label="Message"), location_input, "state"],
|
186 |
+
[chatbot, "state", "text", "text", "json"],
|
187 |
+
allow_flagging="never",
|
188 |
+
title="Mental Health & Well-being Assistant"
|
189 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
190 |
|
191 |
# Launch Gradio interface
|
192 |
+
if __name__ == "__main__":
|
193 |
+
demo.launch()
|