Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -17,18 +17,18 @@ import torch
|
|
17 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
18 |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
19 |
|
20 |
-
#
|
21 |
nltk.download("punkt")
|
22 |
stemmer = LancasterStemmer()
|
23 |
|
24 |
-
# Load
|
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
|
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,18 +37,18 @@ net = tflearn.regression(net)
|
|
37 |
chatbot_model = tflearn.DNN(net)
|
38 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
39 |
|
40 |
-
# Hugging Face
|
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 |
-
#
|
47 |
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
48 |
|
49 |
# Helper Functions
|
50 |
def bag_of_words(s, words):
|
51 |
-
"""Convert user input
|
52 |
bag = [0] * len(words)
|
53 |
s_words = word_tokenize(s)
|
54 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
@@ -58,87 +58,79 @@ def bag_of_words(s, words):
|
|
58 |
bag[i] = 1
|
59 |
return np.array(bag)
|
60 |
|
61 |
-
# Chatbot response logic
|
62 |
def chatbot(message, history):
|
63 |
-
"""Generate chatbot response and
|
64 |
history = history or []
|
65 |
try:
|
66 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
67 |
tag = labels[np.argmax(result)]
|
68 |
-
response = "I'm sorry, I'
|
69 |
for intent in intents_data["intents"]:
|
70 |
if intent["tag"] == tag:
|
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 |
-
# Sentiment detection function
|
79 |
def analyze_sentiment(user_input):
|
80 |
-
"""Analyze sentiment
|
81 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
82 |
with torch.no_grad():
|
83 |
outputs = model_sentiment(**inputs)
|
84 |
sentiment_class = torch.argmax(outputs.logits, dim=1).item()
|
85 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
86 |
-
return sentiment_map[sentiment_class]
|
87 |
|
88 |
-
# Emotion detection function
|
89 |
def detect_emotion(user_input):
|
90 |
-
"""Detect emotion from user input
|
91 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
92 |
result = pipe(user_input)
|
93 |
emotion = result[0]["label"].lower().strip()
|
94 |
emotion_map = {
|
95 |
-
"joy": "π
|
96 |
-
"anger": "π
|
97 |
-
"sadness": "π’
|
98 |
-
"fear": "π¨
|
99 |
-
"surprise": "π²
|
100 |
-
"neutral": "π
|
101 |
}
|
102 |
-
return emotion_map.get(emotion, "Unknown π€")
|
103 |
|
104 |
-
# Generate suggestions based on emotion
|
105 |
def generate_suggestions(emotion):
|
106 |
-
"""Generate resources
|
107 |
-
emotion_key = emotion.lower()
|
108 |
suggestions = {
|
109 |
"joy": [
|
110 |
-
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
|
111 |
-
["Emotional Toolkit", '<a href="https://www.nih.gov
|
112 |
["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
113 |
],
|
114 |
"anger": [
|
115 |
-
["
|
116 |
-
["
|
117 |
],
|
118 |
"fear": [
|
119 |
-
["
|
120 |
-
["Mindfulness Meditation", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
|
121 |
],
|
122 |
"sadness": [
|
123 |
-
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
|
124 |
],
|
125 |
"surprise": [
|
126 |
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
127 |
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
128 |
],
|
129 |
"neutral": [
|
130 |
-
["General Tips", '<a href="https://www.psychologytoday.com" target="_blank">
|
131 |
-
]
|
132 |
}
|
133 |
-
return suggestions.get(
|
134 |
|
135 |
-
# Google Maps integration
|
136 |
def get_health_professionals_and_map(location, query):
|
137 |
-
"""Search
|
138 |
try:
|
139 |
if not location or not query:
|
140 |
-
return ["Please provide a
|
141 |
-
|
142 |
geo_location = gmaps.geocode(location)
|
143 |
if geo_location:
|
144 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
@@ -147,30 +139,31 @@ def get_health_professionals_and_map(location, query):
|
|
147 |
professionals = []
|
148 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
149 |
for place in places_result:
|
150 |
-
professionals.append(f"{place['name']} - {place.get('vicinity', 'No address
|
151 |
folium.Marker(
|
152 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
153 |
popup=f"{place['name']}"
|
154 |
).add_to(map_)
|
|
|
155 |
return professionals, map_._repr_html_()
|
156 |
|
157 |
-
return ["No professionals found."], ""
|
158 |
except Exception as e:
|
159 |
return [f"Error: {e}"], ""
|
160 |
|
161 |
-
# Main
|
162 |
-
def app_function(
|
163 |
-
chatbot_history, _ = chatbot(
|
164 |
-
|
165 |
-
|
166 |
-
suggestions = generate_suggestions(
|
167 |
-
professionals, map_html = get_health_professionals_and_map(location, query) #
|
168 |
-
return chatbot_history,
|
169 |
|
170 |
-
# Custom CSS
|
171 |
custom_css = """
|
172 |
body {
|
173 |
-
background: linear-gradient(135deg, #
|
174 |
font-family: 'Roboto', sans-serif;
|
175 |
color: white;
|
176 |
}
|
@@ -178,49 +171,61 @@ h1 {
|
|
178 |
font-size: 4.5rem;
|
179 |
font-weight: bold;
|
180 |
text-align: center;
|
181 |
-
|
182 |
-
text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.4);
|
183 |
}
|
184 |
h2 {
|
185 |
font-size: 2rem;
|
186 |
text-align: center;
|
187 |
-
font-weight: lighter;
|
188 |
-
color: white;
|
189 |
margin-bottom: 30px;
|
|
|
|
|
190 |
}
|
191 |
-
|
192 |
-
background: linear-gradient(45deg, #ff5722, #ff9800)
|
193 |
-
border: none
|
|
|
194 |
padding: 12px 20px;
|
|
|
195 |
border-radius: 8px;
|
196 |
-
color: white !important;
|
197 |
cursor: pointer;
|
198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
}
|
200 |
"""
|
201 |
|
202 |
-
# Gradio
|
203 |
with gr.Blocks(css=custom_css) as app:
|
204 |
gr.HTML("<h1>π Well-Being Companion</h1>")
|
205 |
gr.HTML("<h2>Empowering Your Mental Health Journey π</h2>")
|
206 |
|
207 |
with gr.Row():
|
208 |
-
user_message = gr.Textbox(label="Your Message", placeholder="Enter your message...")
|
209 |
-
location = gr.Textbox(label="Your Location", placeholder="Enter
|
210 |
-
query = gr.Textbox(label="Search Query", placeholder="e.g., therapist")
|
211 |
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
|
219 |
submit_button = gr.Button("Submit")
|
220 |
submit_button.click(
|
221 |
app_function,
|
222 |
-
inputs=[user_message, location, query,
|
223 |
-
outputs=[
|
224 |
)
|
225 |
|
226 |
app.launch()
|
|
|
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.json 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 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 |
+
# Hugging Face Models for Sentiment and Emotion Detection
|
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("GOOGLE_API_KEY"))
|
48 |
|
49 |
# Helper Functions
|
50 |
def bag_of_words(s, words):
|
51 |
+
"""Convert user input to bag-of-words vector."""
|
52 |
bag = [0] * len(words)
|
53 |
s_words = word_tokenize(s)
|
54 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
|
58 |
bag[i] = 1
|
59 |
return np.array(bag)
|
60 |
|
|
|
61 |
def chatbot(message, history):
|
62 |
+
"""Generate chatbot response and maintain chat history."""
|
63 |
history = history or []
|
64 |
try:
|
65 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
66 |
tag = labels[np.argmax(result)]
|
67 |
+
response = "I'm sorry, I didn't understand that. π€"
|
68 |
for intent in intents_data["intents"]:
|
69 |
if intent["tag"] == tag:
|
70 |
response = random.choice(intent["responses"])
|
71 |
break
|
72 |
except Exception as e:
|
73 |
response = f"Error: {e}"
|
74 |
+
history.append((message, response))
|
75 |
return history, response
|
76 |
|
|
|
77 |
def analyze_sentiment(user_input):
|
78 |
+
"""Analyze sentiment of user input."""
|
79 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
80 |
with torch.no_grad():
|
81 |
outputs = model_sentiment(**inputs)
|
82 |
sentiment_class = torch.argmax(outputs.logits, dim=1).item()
|
83 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
84 |
+
return f"Sentiment: {sentiment_map[sentiment_class]}"
|
85 |
|
|
|
86 |
def detect_emotion(user_input):
|
87 |
+
"""Detect emotion from user input."""
|
88 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
89 |
result = pipe(user_input)
|
90 |
emotion = result[0]["label"].lower().strip()
|
91 |
emotion_map = {
|
92 |
+
"joy": "Joy π",
|
93 |
+
"anger": "Anger π ",
|
94 |
+
"sadness": "Sadness π’",
|
95 |
+
"fear": "Fear π¨",
|
96 |
+
"surprise": "Surprise π²",
|
97 |
+
"neutral": "Neutral π",
|
98 |
}
|
99 |
+
return emotion_map.get(emotion, "Unknown π€"), emotion # Text + clean emotion for matching keys
|
100 |
|
|
|
101 |
def generate_suggestions(emotion):
|
102 |
+
"""Generate helpful resources based on emotion."""
|
|
|
103 |
suggestions = {
|
104 |
"joy": [
|
105 |
+
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
106 |
+
["Emotional Toolkit", '<a href="https://www.nih.gov" target="_blank">Visit</a>'],
|
107 |
["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
108 |
],
|
109 |
"anger": [
|
110 |
+
["Calm Down Exercises", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
|
111 |
+
["Handle Anger", '<a href="https://www.helpguide.org" target="_blank">Visit</a>']
|
112 |
],
|
113 |
"fear": [
|
114 |
+
["Overcoming Fear", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
|
|
|
115 |
],
|
116 |
"sadness": [
|
117 |
+
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
|
118 |
],
|
119 |
"surprise": [
|
120 |
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
121 |
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
|
122 |
],
|
123 |
"neutral": [
|
124 |
+
["General Wellness Tips", '<a href="https://www.psychologytoday.com" target="_blank">Visit</a>'],
|
125 |
+
]
|
126 |
}
|
127 |
+
return suggestions.get(emotion, [["No specific suggestions available.", ""]])
|
128 |
|
|
|
129 |
def get_health_professionals_and_map(location, query):
|
130 |
+
"""Search for healthcare professionals and create an interactive map."""
|
131 |
try:
|
132 |
if not location or not query:
|
133 |
+
return ["Please provide both a location and search query."], ""
|
|
|
134 |
geo_location = gmaps.geocode(location)
|
135 |
if geo_location:
|
136 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
|
|
139 |
professionals = []
|
140 |
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
141 |
for place in places_result:
|
142 |
+
professionals.append(f"{place['name']} - {place.get('vicinity', 'No address provided')}")
|
143 |
folium.Marker(
|
144 |
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
145 |
popup=f"{place['name']}"
|
146 |
).add_to(map_)
|
147 |
+
|
148 |
return professionals, map_._repr_html_()
|
149 |
|
150 |
+
return ["No professionals found near this location."], ""
|
151 |
except Exception as e:
|
152 |
return [f"Error: {e}"], ""
|
153 |
|
154 |
+
# Main Application
|
155 |
+
def app_function(user_input, location, query, history):
|
156 |
+
chatbot_history, _ = chatbot(user_input, history) # Chatbot response
|
157 |
+
sentiment_output = analyze_sentiment(user_input) # Sentiment analysis
|
158 |
+
emotion_detected, clean_emotion = detect_emotion(user_input) # Emotion detection
|
159 |
+
suggestions = generate_suggestions(clean_emotion) # Emotion-matched suggestions
|
160 |
+
professionals, map_html = get_health_professionals_and_map(location, query) # Map of professionals
|
161 |
+
return chatbot_history, sentiment_output, emotion_detected, suggestions, professionals, map_html
|
162 |
|
163 |
+
# Custom CSS for Polished UI
|
164 |
custom_css = """
|
165 |
body {
|
166 |
+
background: linear-gradient(135deg, #000000, #ff5722);
|
167 |
font-family: 'Roboto', sans-serif;
|
168 |
color: white;
|
169 |
}
|
|
|
171 |
font-size: 4.5rem;
|
172 |
font-weight: bold;
|
173 |
text-align: center;
|
174 |
+
margin: 20px auto;
|
|
|
175 |
}
|
176 |
h2 {
|
177 |
font-size: 2rem;
|
178 |
text-align: center;
|
|
|
|
|
179 |
margin-bottom: 30px;
|
180 |
+
color: white;
|
181 |
+
font-weight: lighter;
|
182 |
}
|
183 |
+
button {
|
184 |
+
background: linear-gradient(45deg, #ff5722, #ff9800);
|
185 |
+
border: none;
|
186 |
+
color: white;
|
187 |
padding: 12px 20px;
|
188 |
+
font-size: 16px;
|
189 |
border-radius: 8px;
|
|
|
190 |
cursor: pointer;
|
191 |
+
}
|
192 |
+
textarea, input {
|
193 |
+
background: black;
|
194 |
+
color: white;
|
195 |
+
border: 1px solid #ff5722;
|
196 |
+
padding: 12px;
|
197 |
+
border-radius: 8px;
|
198 |
+
}
|
199 |
+
.gr-dataframe {
|
200 |
+
background-color: black !important;
|
201 |
+
color: white !important;
|
202 |
+
overflow: auto;
|
203 |
+
border: 1px solid orange;
|
204 |
}
|
205 |
"""
|
206 |
|
207 |
+
# Gradio UI Interface
|
208 |
with gr.Blocks(css=custom_css) as app:
|
209 |
gr.HTML("<h1>π Well-Being Companion</h1>")
|
210 |
gr.HTML("<h2>Empowering Your Mental Health Journey π</h2>")
|
211 |
|
212 |
with gr.Row():
|
213 |
+
user_message = gr.Textbox(label="Your Message", placeholder="Enter your message here...")
|
214 |
+
location = gr.Textbox(label="Your Location", placeholder="Enter a city...")
|
215 |
+
query = gr.Textbox(label="Search Query", placeholder="e.g., therapist, doctor")
|
216 |
|
217 |
+
chatbot = gr.Chatbot(label="Chat History")
|
218 |
+
sentiment = gr.Textbox(label="Detected Sentiment")
|
219 |
+
emotion = gr.Textbox(label="Detected Emotion")
|
220 |
+
suggestions = gr.DataFrame(headers=["Suggestion Title", "Link"], label="Suggestions")
|
221 |
+
professionals = gr.Textbox(label="Nearby Professionals", lines=6)
|
222 |
+
map_html = gr.HTML(label="Interactive Map")
|
223 |
|
224 |
submit_button = gr.Button("Submit")
|
225 |
submit_button.click(
|
226 |
app_function,
|
227 |
+
inputs=[user_message, location, query, chatbot],
|
228 |
+
outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html]
|
229 |
)
|
230 |
|
231 |
app.launch()
|