Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -13,22 +13,22 @@ import googlemaps
|
|
13 |
import folium
|
14 |
import torch
|
15 |
|
16 |
-
# Suppress TensorFlow GPU usage and warnings
|
17 |
-
os.environ[
|
18 |
-
os.environ[
|
19 |
|
20 |
-
# Download NLTK resources
|
21 |
nltk.download("punkt")
|
22 |
stemmer = LancasterStemmer()
|
23 |
|
24 |
-
# Load chatbot training data
|
25 |
with open("intents.json") as file:
|
26 |
intents_data = json.load(file)
|
27 |
|
28 |
with open("data.pickle", "rb") as f:
|
29 |
words, labels, training, output = pickle.load(f)
|
30 |
|
31 |
-
# Build Chatbot Model
|
32 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
33 |
net = tflearn.fully_connected(net, 8)
|
34 |
net = tflearn.fully_connected(net, 8)
|
@@ -37,17 +37,19 @@ net = tflearn.regression(net)
|
|
37 |
chatbot_model = tflearn.DNN(net)
|
38 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
39 |
|
40 |
-
#
|
41 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
42 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
|
43 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
44 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
45 |
|
46 |
# Google Maps API Client
|
47 |
-
gmaps = googlemaps.Client(key=os.getenv(
|
48 |
|
49 |
-
#
|
50 |
def bag_of_words(s, words):
|
|
|
51 |
bag = [0] * len(words)
|
52 |
s_words = word_tokenize(s)
|
53 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
@@ -57,9 +59,8 @@ def bag_of_words(s, words):
|
|
57 |
bag[i] = 1
|
58 |
return np.array(bag)
|
59 |
|
60 |
-
# Chatbot Function
|
61 |
def chatbot(message, history):
|
62 |
-
"""Generate
|
63 |
history = history or []
|
64 |
try:
|
65 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
@@ -70,11 +71,10 @@ def chatbot(message, history):
|
|
70 |
response = random.choice(intent["responses"])
|
71 |
break
|
72 |
except Exception as e:
|
73 |
-
response = f"Error: {
|
74 |
history.append((message, response))
|
75 |
return history, response
|
76 |
|
77 |
-
# Sentiment Analysis
|
78 |
def analyze_sentiment(user_input):
|
79 |
"""Analyze sentiment from user input."""
|
80 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
@@ -84,53 +84,50 @@ def analyze_sentiment(user_input):
|
|
84 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
85 |
return sentiment_map[sentiment_class]
|
86 |
|
87 |
-
# Emotion Detection
|
88 |
def detect_emotion(user_input):
|
89 |
-
"""Detect user emotion with
|
90 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
91 |
result = pipe(user_input)
|
92 |
-
emotion = result[0][
|
93 |
emotion_map = {
|
94 |
"joy": "π Joy",
|
95 |
"anger": "π Anger",
|
96 |
"sadness": "π’ Sadness",
|
97 |
"fear": "π¨ Fear",
|
98 |
"surprise": "π² Surprise",
|
99 |
-
"neutral": "π Neutral"
|
100 |
}
|
101 |
-
return emotion_map.get(emotion, "Unknown
|
102 |
|
103 |
-
# Generate Suggestions for Emotion
|
104 |
def generate_suggestions(emotion):
|
105 |
-
"""
|
106 |
suggestions = {
|
107 |
"joy": [
|
108 |
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
|
109 |
["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
110 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
111 |
-
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
|
112 |
],
|
113 |
"anger": [
|
114 |
-
["
|
115 |
-
["
|
116 |
],
|
117 |
"fear": [
|
118 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
119 |
-
["Mindfulness
|
120 |
],
|
121 |
"sadness": [
|
122 |
-
["
|
123 |
],
|
124 |
"surprise": [
|
125 |
-
["Managing
|
126 |
-
["Relaxation
|
127 |
-
]
|
128 |
}
|
129 |
return suggestions.get(emotion.lower(), [["No suggestions are available.", ""]])
|
130 |
|
131 |
-
# Search for Nearby Professionals and Generate Map
|
132 |
def get_health_professionals_and_map(location, query):
|
133 |
-
"""Search nearby healthcare professionals and
|
134 |
try:
|
135 |
if not location or not query:
|
136 |
return ["Please provide a valid location and query."], ""
|
@@ -138,7 +135,6 @@ def get_health_professionals_and_map(location, query):
|
|
138 |
geo_location = gmaps.geocode(location)
|
139 |
if geo_location:
|
140 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
141 |
-
|
142 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
143 |
|
144 |
professionals = []
|
@@ -152,16 +148,14 @@ def get_health_professionals_and_map(location, query):
|
|
152 |
return professionals, map_._repr_html_()
|
153 |
|
154 |
return ["No professionals found for the given location."], ""
|
155 |
-
except googlemaps.exceptions.HTTPError as e:
|
156 |
-
return [f"Google Maps API Error: {str(e)}"], ""
|
157 |
except Exception as e:
|
158 |
return [f"An error occurred: {str(e)}"], ""
|
159 |
|
160 |
-
# Main
|
161 |
-
def app_function(
|
162 |
-
chatbot_history,
|
163 |
-
sentiment = analyze_sentiment(
|
164 |
-
emotion = detect_emotion(
|
165 |
suggestions = generate_suggestions(emotion)
|
166 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
167 |
return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
|
@@ -169,17 +163,18 @@ def app_function(user_input, location, query, history):
|
|
169 |
# Custom CSS for Dark Theme and Gradient Buttons
|
170 |
custom_css = """
|
171 |
body {
|
172 |
-
background: linear-gradient(135deg, #
|
173 |
font-family: 'Roboto', sans-serif;
|
174 |
color: white;
|
175 |
}
|
176 |
button {
|
177 |
background: linear-gradient(45deg, #ff5722, #ff9800) !important;
|
178 |
-
border:
|
179 |
border-radius: 8px;
|
180 |
padding: 12px 20px;
|
181 |
cursor: pointer;
|
182 |
color: white;
|
|
|
183 |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
|
184 |
}
|
185 |
button:hover {
|
@@ -197,31 +192,33 @@ textarea, input {
|
|
197 |
color: white !important;
|
198 |
overflow-y: scroll;
|
199 |
height: 300px;
|
|
|
200 |
}
|
201 |
"""
|
202 |
|
203 |
# Gradio Interface
|
204 |
with gr.Blocks(css=custom_css) as app:
|
205 |
-
gr.
|
206 |
-
gr.
|
207 |
|
208 |
with gr.Row():
|
209 |
-
user_message = gr.Textbox(label="Your Message", placeholder="
|
210 |
location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
|
211 |
-
query = gr.Textbox(label="
|
212 |
|
213 |
chatbot_history = gr.Chatbot(label="Chat History")
|
214 |
sentiment_output = gr.Textbox(label="Detected Sentiment")
|
215 |
emotion_output = gr.Textbox(label="Detected Emotion")
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
|
220 |
submit_button = gr.Button("Submit")
|
|
|
221 |
submit_button.click(
|
222 |
app_function,
|
223 |
inputs=[user_message, location, query, chatbot_history],
|
224 |
-
outputs=[chatbot_history, sentiment_output, emotion_output,
|
225 |
)
|
226 |
|
227 |
app.launch()
|
|
|
13 |
import folium
|
14 |
import torch
|
15 |
|
16 |
+
# Suppress TensorFlow's GPU usage and warnings
|
17 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
18 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
19 |
|
20 |
+
# Download necessary NLTK resources
|
21 |
nltk.download("punkt")
|
22 |
stemmer = LancasterStemmer()
|
23 |
|
24 |
+
# Load intents and chatbot training data
|
25 |
with open("intents.json") as file:
|
26 |
intents_data = json.load(file)
|
27 |
|
28 |
with open("data.pickle", "rb") as f:
|
29 |
words, labels, training, output = pickle.load(f)
|
30 |
|
31 |
+
# Build the Chatbot Model
|
32 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
33 |
net = tflearn.fully_connected(net, 8)
|
34 |
net = tflearn.fully_connected(net, 8)
|
|
|
37 |
chatbot_model = tflearn.DNN(net)
|
38 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
39 |
|
40 |
+
# Sentiment and Emotion Detection Models
|
41 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
42 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
43 |
+
|
44 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
45 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
46 |
|
47 |
# Google Maps API Client
|
48 |
+
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
49 |
|
50 |
+
# Helper Functions
|
51 |
def bag_of_words(s, words):
|
52 |
+
"""Convert user input to bag-of-words vector."""
|
53 |
bag = [0] * len(words)
|
54 |
s_words = word_tokenize(s)
|
55 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
|
59 |
bag[i] = 1
|
60 |
return np.array(bag)
|
61 |
|
|
|
62 |
def chatbot(message, history):
|
63 |
+
"""Generate chatbot response and append to chat history."""
|
64 |
history = history or []
|
65 |
try:
|
66 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
|
|
71 |
response = random.choice(intent["responses"])
|
72 |
break
|
73 |
except Exception as e:
|
74 |
+
response = f"Error: {e}"
|
75 |
history.append((message, response))
|
76 |
return history, response
|
77 |
|
|
|
78 |
def analyze_sentiment(user_input):
|
79 |
"""Analyze sentiment from user input."""
|
80 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
|
|
84 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
85 |
return sentiment_map[sentiment_class]
|
86 |
|
|
|
87 |
def detect_emotion(user_input):
|
88 |
+
"""Detect user emotion with emoji representation."""
|
89 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
90 |
result = pipe(user_input)
|
91 |
+
emotion = result[0]["label"].lower()
|
92 |
emotion_map = {
|
93 |
"joy": "π Joy",
|
94 |
"anger": "π Anger",
|
95 |
"sadness": "π’ Sadness",
|
96 |
"fear": "π¨ Fear",
|
97 |
"surprise": "π² Surprise",
|
98 |
+
"neutral": "π Neutral",
|
99 |
}
|
100 |
+
return emotion_map.get(emotion, "Unknown π€")
|
101 |
|
|
|
102 |
def generate_suggestions(emotion):
|
103 |
+
"""Provide suggestions based on the detected emotion."""
|
104 |
suggestions = {
|
105 |
"joy": [
|
106 |
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
|
107 |
["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
108 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
109 |
+
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
110 |
],
|
111 |
"anger": [
|
112 |
+
["Stress Management Tips", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
113 |
+
["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
|
114 |
],
|
115 |
"fear": [
|
116 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
117 |
+
["Mindfulness Techniques", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
|
118 |
],
|
119 |
"sadness": [
|
120 |
+
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
|
121 |
],
|
122 |
"surprise": [
|
123 |
+
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
124 |
+
["Calm Relaxation", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
125 |
+
],
|
126 |
}
|
127 |
return suggestions.get(emotion.lower(), [["No suggestions are available.", ""]])
|
128 |
|
|
|
129 |
def get_health_professionals_and_map(location, query):
|
130 |
+
"""Search for nearby healthcare professionals and generate a map."""
|
131 |
try:
|
132 |
if not location or not query:
|
133 |
return ["Please provide a valid location and query."], ""
|
|
|
135 |
geo_location = gmaps.geocode(location)
|
136 |
if geo_location:
|
137 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
|
|
138 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
139 |
|
140 |
professionals = []
|
|
|
148 |
return professionals, map_._repr_html_()
|
149 |
|
150 |
return ["No professionals found for the given location."], ""
|
|
|
|
|
151 |
except Exception as e:
|
152 |
return [f"An error occurred: {str(e)}"], ""
|
153 |
|
154 |
+
# Main Application Logic
|
155 |
+
def app_function(user_message, location, query, history):
|
156 |
+
chatbot_history, _ = chatbot(user_message, history)
|
157 |
+
sentiment = analyze_sentiment(user_message)
|
158 |
+
emotion = detect_emotion(user_message)
|
159 |
suggestions = generate_suggestions(emotion)
|
160 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
161 |
return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
|
|
|
163 |
# Custom CSS for Dark Theme and Gradient Buttons
|
164 |
custom_css = """
|
165 |
body {
|
166 |
+
background: linear-gradient(135deg, #000000, #ff5722);
|
167 |
font-family: 'Roboto', sans-serif;
|
168 |
color: white;
|
169 |
}
|
170 |
button {
|
171 |
background: linear-gradient(45deg, #ff5722, #ff9800) !important;
|
172 |
+
border: none;
|
173 |
border-radius: 8px;
|
174 |
padding: 12px 20px;
|
175 |
cursor: pointer;
|
176 |
color: white;
|
177 |
+
font-size: 16px;
|
178 |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
|
179 |
}
|
180 |
button:hover {
|
|
|
192 |
color: white !important;
|
193 |
overflow-y: scroll;
|
194 |
height: 300px;
|
195 |
+
border: 1px solid #ff5722;
|
196 |
}
|
197 |
"""
|
198 |
|
199 |
# Gradio Interface
|
200 |
with gr.Blocks(css=custom_css) as app:
|
201 |
+
gr.Markdown("<h1 style='text-align: center;'>π Well-Being Companion</h1>")
|
202 |
+
gr.Markdown("<h3 style='text-align: center;'>Empowering Your Mental Health Journey π</h3>")
|
203 |
|
204 |
with gr.Row():
|
205 |
+
user_message = gr.Textbox(label="Your Message", placeholder="Enter your message...")
|
206 |
location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
|
207 |
+
query = gr.Textbox(label="Health Query", placeholder="Search for health professionals...")
|
208 |
|
209 |
chatbot_history = gr.Chatbot(label="Chat History")
|
210 |
sentiment_output = gr.Textbox(label="Detected Sentiment")
|
211 |
emotion_output = gr.Textbox(label="Detected Emotion")
|
212 |
+
suggestions_table = gr.DataFrame(headers=["Suggestion", "Link"], label="Suggestions")
|
213 |
+
professionals_output = gr.Textbox(label="Nearby Health Professionals", lines=5)
|
214 |
+
map_output = gr.HTML(label="Map")
|
215 |
|
216 |
submit_button = gr.Button("Submit")
|
217 |
+
|
218 |
submit_button.click(
|
219 |
app_function,
|
220 |
inputs=[user_message, location, query, chatbot_history],
|
221 |
+
outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_table, professionals_output, map_output]
|
222 |
)
|
223 |
|
224 |
app.launch()
|