Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,6 @@ import os
|
|
2 |
import gradio as gr
|
3 |
import nltk
|
4 |
import numpy as np
|
5 |
-
import tensorflow as tf
|
6 |
import tflearn
|
7 |
import random
|
8 |
import json
|
@@ -16,7 +15,7 @@ import torch
|
|
16 |
|
17 |
# Disable GPU usage for TensorFlow
|
18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
19 |
-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
20 |
|
21 |
# Ensure necessary NLTK resources are downloaded
|
22 |
nltk.download("punkt")
|
@@ -24,14 +23,14 @@ nltk.download("punkt")
|
|
24 |
# Initialize stemmer
|
25 |
stemmer = LancasterStemmer()
|
26 |
|
27 |
-
# Load intents
|
28 |
with open("intents.json") as file:
|
29 |
intents_data = json.load(file)
|
30 |
|
31 |
with open("data.pickle", "rb") as f:
|
32 |
words, labels, training, output = pickle.load(f)
|
33 |
|
34 |
-
# Build
|
35 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
36 |
net = tflearn.fully_connected(net, 8)
|
37 |
net = tflearn.fully_connected(net, 8)
|
@@ -40,18 +39,16 @@ net = tflearn.regression(net)
|
|
40 |
chatbot_model = tflearn.DNN(net)
|
41 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
42 |
|
43 |
-
#
|
44 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
45 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
46 |
-
|
47 |
-
# Emotion Detection Model
|
48 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
49 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
50 |
|
51 |
-
# Google Maps API
|
52 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
53 |
|
54 |
-
#
|
55 |
def bag_of_words(s, words):
|
56 |
bag = [0] * len(words)
|
57 |
s_words = word_tokenize(s)
|
@@ -62,7 +59,6 @@ def bag_of_words(s, words):
|
|
62 |
bag[i] = 1
|
63 |
return np.array(bag)
|
64 |
|
65 |
-
# Chatbot Functionality
|
66 |
def chatbot(message, history):
|
67 |
history = history or []
|
68 |
try:
|
@@ -79,7 +75,7 @@ def chatbot(message, history):
|
|
79 |
history.append({"role": "assistant", "content": response})
|
80 |
return history, response
|
81 |
|
82 |
-
#
|
83 |
def analyze_sentiment(user_input):
|
84 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
85 |
with torch.no_grad():
|
@@ -88,98 +84,99 @@ def analyze_sentiment(user_input):
|
|
88 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
89 |
return sentiment_map[sentiment_class]
|
90 |
|
91 |
-
#
|
92 |
def detect_emotion(user_input):
|
93 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
94 |
result = pipe(user_input)
|
95 |
emotion = result[0]["label"]
|
96 |
-
|
97 |
-
"joy": "π Joy",
|
98 |
-
"anger": "π Anger",
|
99 |
-
"sadness": "π’ Sadness",
|
100 |
-
"fear": "π¨ Fear",
|
101 |
-
"surprise": "π² Surprise",
|
102 |
-
"neutral": "π Neutral",
|
103 |
-
}
|
104 |
-
return emotion_map.get(emotion, "Unknown Emotion π€")
|
105 |
|
106 |
-
# Generate
|
107 |
def generate_suggestions(emotion):
|
108 |
-
|
109 |
-
"
|
110 |
-
["Relaxation Techniques",
|
111 |
-
["Dealing with Stress",
|
112 |
-
["Emotional Wellness Toolkit",
|
113 |
-
["Relaxation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
],
|
115 |
-
"
|
116 |
-
["Emotional Wellness Toolkit",
|
117 |
-
["Dealing with Anxiety",
|
118 |
-
["Relaxation
|
|
|
|
|
|
|
|
|
|
|
119 |
],
|
120 |
-
"π¨ Fear": [
|
121 |
-
["Mindfulness Practices", "Mindfulness", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
122 |
-
["Coping with Anxiety", "Anxiety Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
123 |
-
["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
124 |
-
["Relaxation Videos", "Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
|
125 |
-
]
|
126 |
}
|
127 |
-
return
|
128 |
|
129 |
-
# Search
|
130 |
def get_health_professionals_and_map(location, query):
|
131 |
try:
|
132 |
geo_location = gmaps.geocode(location)
|
133 |
if geo_location:
|
134 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
135 |
-
places_result = gmaps.places_nearby(
|
136 |
-
|
137 |
-
)["results"]
|
138 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
139 |
professionals = []
|
140 |
for place in places_result:
|
141 |
professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
|
142 |
-
|
143 |
-
|
144 |
return professionals, map_._repr_html_()
|
145 |
-
return [
|
146 |
except Exception as e:
|
147 |
return [f"Error: {e}"], ""
|
148 |
|
149 |
-
#
|
150 |
def app_function(message, location, query, history):
|
151 |
chatbot_history, _ = chatbot(message, history)
|
152 |
sentiment = analyze_sentiment(message)
|
153 |
-
emotion = detect_emotion(message)
|
154 |
suggestions = generate_suggestions(emotion)
|
155 |
professionals_info, map_html = get_health_professionals_and_map(location, query)
|
156 |
return chatbot_history, sentiment, emotion, suggestions, professionals_info, map_html
|
157 |
|
158 |
-
# Gradio
|
159 |
-
with gr.Blocks() as
|
160 |
gr.Markdown("# π Well-Being Companion")
|
161 |
-
gr.Markdown("Empowering
|
162 |
-
|
163 |
with gr.Row():
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
app_function,
|
178 |
-
inputs=[
|
179 |
outputs=[
|
180 |
-
|
181 |
-
suggestions_output, professionals_output, map_output
|
182 |
],
|
183 |
)
|
184 |
|
185 |
-
|
|
|
2 |
import gradio as gr
|
3 |
import nltk
|
4 |
import numpy as np
|
|
|
5 |
import tflearn
|
6 |
import random
|
7 |
import json
|
|
|
15 |
|
16 |
# Disable GPU usage for TensorFlow
|
17 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
18 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Suppress TensorFlow warnings
|
19 |
|
20 |
# Ensure necessary NLTK resources are downloaded
|
21 |
nltk.download("punkt")
|
|
|
23 |
# Initialize stemmer
|
24 |
stemmer = LancasterStemmer()
|
25 |
|
26 |
+
# Load chatbot intents and training data
|
27 |
with open("intents.json") as file:
|
28 |
intents_data = json.load(file)
|
29 |
|
30 |
with open("data.pickle", "rb") as f:
|
31 |
words, labels, training, output = pickle.load(f)
|
32 |
|
33 |
+
# Build the chatbot's neural network model
|
34 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
35 |
net = tflearn.fully_connected(net, 8)
|
36 |
net = tflearn.fully_connected(net, 8)
|
|
|
39 |
chatbot_model = tflearn.DNN(net)
|
40 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
41 |
|
42 |
+
# Hugging Face models for sentiment and emotion detection
|
43 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
44 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
|
|
|
|
45 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
46 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
47 |
|
48 |
+
# Google Maps API client
|
49 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
50 |
|
51 |
+
# Chatbot logic
|
52 |
def bag_of_words(s, words):
|
53 |
bag = [0] * len(words)
|
54 |
s_words = word_tokenize(s)
|
|
|
59 |
bag[i] = 1
|
60 |
return np.array(bag)
|
61 |
|
|
|
62 |
def chatbot(message, history):
|
63 |
history = history or []
|
64 |
try:
|
|
|
75 |
history.append({"role": "assistant", "content": response})
|
76 |
return history, response
|
77 |
|
78 |
+
# Sentiment analysis
|
79 |
def analyze_sentiment(user_input):
|
80 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
81 |
with torch.no_grad():
|
|
|
84 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
85 |
return sentiment_map[sentiment_class]
|
86 |
|
87 |
+
# Emotion detection
|
88 |
def detect_emotion(user_input):
|
89 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
90 |
result = pipe(user_input)
|
91 |
emotion = result[0]["label"]
|
92 |
+
return emotion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
+
# Generate suggestions based on detected emotion
|
95 |
def generate_suggestions(emotion):
|
96 |
+
suggestions = {
|
97 |
+
"joy": [
|
98 |
+
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Read</a>'],
|
99 |
+
["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Read</a>'],
|
100 |
+
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Read</a>'],
|
101 |
+
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
102 |
+
],
|
103 |
+
"anger": [
|
104 |
+
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Read</a>'],
|
105 |
+
["Stress Management Tips", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Read</a>'],
|
106 |
+
["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Read</a>'],
|
107 |
+
["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
|
108 |
+
],
|
109 |
+
"fear": [
|
110 |
+
["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Read</a>'],
|
111 |
+
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Read</a>'],
|
112 |
+
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Read</a>'],
|
113 |
+
["Relaxation Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
|
114 |
],
|
115 |
+
"sadness": [
|
116 |
+
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Read</a>'],
|
117 |
+
["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Read</a>'],
|
118 |
+
["Relaxation Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
|
119 |
+
],
|
120 |
+
"surprise": [
|
121 |
+
["Managing Stress", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Read</a>'],
|
122 |
+
["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Read</a>'],
|
123 |
+
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
124 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
}
|
126 |
+
return suggestions.get(emotion)
|
127 |
|
128 |
+
# Search nearby professionals and generate map
|
129 |
def get_health_professionals_and_map(location, query):
|
130 |
try:
|
131 |
geo_location = gmaps.geocode(location)
|
132 |
if geo_location:
|
133 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
134 |
+
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
135 |
+
|
|
|
136 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
137 |
professionals = []
|
138 |
for place in places_result:
|
139 |
professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
|
140 |
+
folium.Marker([place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
141 |
+
popup=place["name"]).add_to(map_)
|
142 |
return professionals, map_._repr_html_()
|
143 |
+
return [], ""
|
144 |
except Exception as e:
|
145 |
return [f"Error: {e}"], ""
|
146 |
|
147 |
+
# Application logic integrated in one function
|
148 |
def app_function(message, location, query, history):
|
149 |
chatbot_history, _ = chatbot(message, history)
|
150 |
sentiment = analyze_sentiment(message)
|
151 |
+
emotion = detect_emotion(message.lower())
|
152 |
suggestions = generate_suggestions(emotion)
|
153 |
professionals_info, map_html = get_health_professionals_and_map(location, query)
|
154 |
return chatbot_history, sentiment, emotion, suggestions, professionals_info, map_html
|
155 |
|
156 |
+
# Gradio app interface
|
157 |
+
with gr.Blocks() as app:
|
158 |
gr.Markdown("# π Well-Being Companion")
|
159 |
+
gr.Markdown("Empowering Your Mental Health Journey π")
|
160 |
+
|
161 |
with gr.Row():
|
162 |
+
user_message = gr.Textbox(label="Your Message", placeholder="Enter your message...")
|
163 |
+
user_location = gr.Textbox(label="Your Location", placeholder="Enter location...")
|
164 |
+
search_query = gr.Textbox(label="Query (e.g., therapist)", placeholder="Search for professionals...")
|
165 |
+
submit_btn = gr.Button(value="Submit")
|
166 |
+
|
167 |
+
chatbot_box = gr.Chatbot(label="Chat History", type="messages")
|
168 |
+
emotion_display = gr.Textbox(label="Detected Emotion")
|
169 |
+
sentiment_display = gr.Textbox(label="Detected Sentiment")
|
170 |
+
suggestions_table = gr.DataFrame(headers=["Title", "Links"], label="Suggestions", height=250)
|
171 |
+
map_output = gr.HTML(label="Nearby Professionals Map")
|
172 |
+
professional_display = gr.Textbox(label="Nearby Professionals", lines=5)
|
173 |
+
|
174 |
+
submit_btn.click(
|
175 |
app_function,
|
176 |
+
inputs=[user_message, user_location, search_query, chatbot_box],
|
177 |
outputs=[
|
178 |
+
chatbot_box, sentiment_display, emotion_display, suggestions_table, professional_display, map_output,
|
|
|
179 |
],
|
180 |
)
|
181 |
|
182 |
+
app.launch()
|