Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,15 +17,14 @@ 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 intents
|
| 25 |
with open("intents.json") as file:
|
| 26 |
intents_data = json.load(file)
|
| 27 |
|
| 28 |
-
# Load training data for chatbot
|
| 29 |
with open("data.pickle", "rb") as f:
|
| 30 |
words, labels, training, output = pickle.load(f)
|
| 31 |
|
|
@@ -38,18 +37,18 @@ net = tflearn.regression(net)
|
|
| 38 |
chatbot_model = tflearn.DNN(net)
|
| 39 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
| 40 |
|
| 41 |
-
# Hugging Face
|
| 42 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 43 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 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
|
| 48 |
gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
|
| 49 |
|
| 50 |
-
#
|
| 51 |
def bag_of_words(s, words):
|
| 52 |
-
"""Convert user input
|
| 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,26 +58,26 @@ def bag_of_words(s, words):
|
|
| 59 |
bag[i] = 1
|
| 60 |
return np.array(bag)
|
| 61 |
|
| 62 |
-
# Chatbot
|
| 63 |
def chatbot(message, history):
|
| 64 |
-
"""Generate chatbot response and
|
| 65 |
history = history or []
|
| 66 |
try:
|
| 67 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 68 |
tag = labels[np.argmax(result)]
|
| 69 |
-
response = "I'm not sure how to respond
|
| 70 |
for intent in intents_data["intents"]:
|
| 71 |
if intent["tag"] == tag:
|
| 72 |
response = random.choice(intent["responses"])
|
| 73 |
break
|
| 74 |
except Exception as e:
|
| 75 |
response = f"Error: {e}"
|
| 76 |
-
history.append((message, response)) # Append to
|
| 77 |
return history, response
|
| 78 |
|
| 79 |
-
# Sentiment
|
| 80 |
def analyze_sentiment(user_input):
|
| 81 |
-
"""Analyze sentiment
|
| 82 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 83 |
with torch.no_grad():
|
| 84 |
outputs = model_sentiment(**inputs)
|
|
@@ -86,66 +85,67 @@ def analyze_sentiment(user_input):
|
|
| 86 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
| 87 |
return sentiment_map[sentiment_class]
|
| 88 |
|
| 89 |
-
# Emotion
|
| 90 |
def detect_emotion(user_input):
|
| 91 |
-
"""Detect user
|
| 92 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 93 |
result = pipe(user_input)
|
| 94 |
-
emotion = result[0]["label"].lower().strip()
|
| 95 |
emotion_map = {
|
| 96 |
"joy": "π Joy",
|
| 97 |
"anger": "π Anger",
|
| 98 |
"sadness": "π’ Sadness",
|
| 99 |
"fear": "π¨ Fear",
|
| 100 |
"surprise": "π² Surprise",
|
| 101 |
-
"neutral": "π Neutral"
|
| 102 |
}
|
| 103 |
return emotion_map.get(emotion, "Unknown π€")
|
| 104 |
|
| 105 |
-
#
|
| 106 |
def generate_suggestions(emotion):
|
| 107 |
-
"""
|
| 108 |
-
emotion_key = emotion.lower()
|
| 109 |
suggestions = {
|
| 110 |
"joy": [
|
| 111 |
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation" target="_blank">Visit</a>'],
|
| 112 |
-
["
|
| 113 |
-
["
|
| 114 |
-
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
|
| 115 |
],
|
| 116 |
"anger": [
|
| 117 |
-
["
|
| 118 |
-
["
|
| 119 |
],
|
| 120 |
"fear": [
|
| 121 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
| 122 |
-
["Mindfulness
|
| 123 |
],
|
| 124 |
"sadness": [
|
| 125 |
["Overcoming Sadness", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
|
| 126 |
],
|
| 127 |
"surprise": [
|
| 128 |
["Managing Surprises", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
| 129 |
-
["
|
| 130 |
],
|
| 131 |
"neutral": [
|
| 132 |
-
["General
|
| 133 |
],
|
| 134 |
}
|
| 135 |
-
return suggestions.get(emotion_key, [["No suggestions available.", ""]])
|
| 136 |
|
| 137 |
-
# Google Maps
|
| 138 |
def get_health_professionals_and_map(location, query):
|
| 139 |
-
"""Search nearby professionals and
|
| 140 |
try:
|
| 141 |
if not location or not query:
|
| 142 |
-
return ["Please provide
|
|
|
|
| 143 |
geo_location = gmaps.geocode(location)
|
| 144 |
if geo_location:
|
| 145 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 146 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 147 |
-
|
| 148 |
professionals = []
|
|
|
|
| 149 |
for place in places_result:
|
| 150 |
professionals.append(f"{place['name']} - {place.get('vicinity', 'No address available')}")
|
| 151 |
folium.Marker(
|
|
@@ -153,17 +153,18 @@ def get_health_professionals_and_map(location, query):
|
|
| 153 |
popup=f"{place['name']}"
|
| 154 |
).add_to(map_)
|
| 155 |
return professionals, map_._repr_html_()
|
| 156 |
-
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
-
return [f"
|
| 159 |
-
|
| 160 |
-
# Main
|
| 161 |
-
def app_function(
|
| 162 |
-
chatbot_history, _ = chatbot(
|
| 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
|
| 168 |
|
| 169 |
# Custom CSS
|
|
@@ -174,27 +175,27 @@ body {
|
|
| 174 |
color: white;
|
| 175 |
}
|
| 176 |
h1 {
|
| 177 |
-
font-size:
|
| 178 |
font-weight: bold;
|
| 179 |
text-align: center;
|
| 180 |
-
|
|
|
|
| 181 |
}
|
| 182 |
h2 {
|
| 183 |
font-size: 2rem;
|
| 184 |
-
font-weight: lighter;
|
| 185 |
text-align: center;
|
| 186 |
-
|
| 187 |
color: white;
|
|
|
|
| 188 |
}
|
| 189 |
-
button {
|
| 190 |
background: linear-gradient(45deg, #ff5722, #ff9800) !important;
|
| 191 |
-
border: none;
|
| 192 |
-
border-radius: 8px;
|
| 193 |
padding: 12px 20px;
|
|
|
|
|
|
|
| 194 |
cursor: pointer;
|
| 195 |
-
color: white;
|
| 196 |
font-size: 16px;
|
| 197 |
-
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
| 198 |
}
|
| 199 |
"""
|
| 200 |
|
|
@@ -204,9 +205,9 @@ with gr.Blocks(css=custom_css) as app:
|
|
| 204 |
gr.HTML("<h2>Empowering Your Mental Health Journey π</h2>")
|
| 205 |
|
| 206 |
with gr.Row():
|
| 207 |
-
user_message = gr.Textbox(label="Your Message", placeholder="
|
| 208 |
location = gr.Textbox(label="Your Location", placeholder="Enter location...")
|
| 209 |
-
query = gr.Textbox(label="Query
|
| 210 |
|
| 211 |
chatbot_history = gr.Chatbot(label="Chat History")
|
| 212 |
sentiment_output = gr.Textbox(label="Detected Sentiment")
|
|
@@ -219,7 +220,7 @@ with gr.Blocks(css=custom_css) as app:
|
|
| 219 |
submit_button.click(
|
| 220 |
app_function,
|
| 221 |
inputs=[user_message, location, query, chatbot_history],
|
| 222 |
-
outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_output, professionals_output, map_output]
|
| 223 |
)
|
| 224 |
|
| 225 |
app.launch()
|
|
|
|
| 17 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 18 |
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
|
| 19 |
|
| 20 |
+
# Ensure necessary NLTK resources
|
| 21 |
nltk.download("punkt")
|
| 22 |
stemmer = LancasterStemmer()
|
| 23 |
|
| 24 |
+
# Load chatbot intents and 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 |
|
|
|
|
| 37 |
chatbot_model = tflearn.DNN(net)
|
| 38 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
| 39 |
|
| 40 |
+
# Hugging Face emotion and sentiment 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 |
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 |
+
# Initialize 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 into 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 |
+
# Chatbot response logic
|
| 62 |
def chatbot(message, history):
|
| 63 |
+
"""Generate chatbot response and update chat history."""
|
| 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'm not sure how to respond. π€"
|
| 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)) # Append to the chatbot history
|
| 76 |
return history, response
|
| 77 |
|
| 78 |
+
# Sentiment detection function
|
| 79 |
def analyze_sentiment(user_input):
|
| 80 |
+
"""Analyze sentiment and return emoji-mapped sentiment."""
|
| 81 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 82 |
with torch.no_grad():
|
| 83 |
outputs = model_sentiment(**inputs)
|
|
|
|
| 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 using Hugging Face emotion model."""
|
| 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": "π Joy",
|
| 96 |
"anger": "π Anger",
|
| 97 |
"sadness": "π’ Sadness",
|
| 98 |
"fear": "π¨ Fear",
|
| 99 |
"surprise": "π² Surprise",
|
| 100 |
+
"neutral": "π Neutral",
|
| 101 |
}
|
| 102 |
return emotion_map.get(emotion, "Unknown π€")
|
| 103 |
|
| 104 |
+
# Generate suggestions based on emotion
|
| 105 |
def generate_suggestions(emotion):
|
| 106 |
+
"""Generate resources and videos to help based on the emotion detected."""
|
| 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/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 112 |
+
["Stress Management", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
|
|
|
| 113 |
],
|
| 114 |
"anger": [
|
| 115 |
+
["Calming Techniques", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
|
| 116 |
+
["Manage Anger", '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">Visit</a>'],
|
| 117 |
],
|
| 118 |
"fear": [
|
| 119 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety" target="_blank">Visit</a>'],
|
| 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">Read More</a>']
|
| 131 |
],
|
| 132 |
}
|
| 133 |
+
return suggestions.get(emotion_key, [["No specific suggestions available.", ""]])
|
| 134 |
|
| 135 |
+
# Google Maps integration
|
| 136 |
def get_health_professionals_and_map(location, query):
|
| 137 |
+
"""Search nearby health professionals and generate map."""
|
| 138 |
try:
|
| 139 |
if not location or not query:
|
| 140 |
+
return ["Please provide a valid location and query."], ""
|
| 141 |
+
|
| 142 |
geo_location = gmaps.geocode(location)
|
| 143 |
if geo_location:
|
| 144 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 145 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 146 |
+
|
| 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 available')}")
|
| 151 |
folium.Marker(
|
|
|
|
| 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 application logic
|
| 162 |
+
def app_function(user_message, location, query, history):
|
| 163 |
+
chatbot_history, _ = chatbot(user_message, history)
|
| 164 |
+
sentiment = analyze_sentiment(user_message) # Sentiment detection
|
| 165 |
+
emotion = detect_emotion(user_message) # Emotion detection
|
| 166 |
+
suggestions = generate_suggestions(emotion) # Get emotion-based suggestions
|
| 167 |
+
professionals, map_html = get_health_professionals_and_map(location, query) # Google Maps integration
|
| 168 |
return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
|
| 169 |
|
| 170 |
# Custom CSS
|
|
|
|
| 175 |
color: white;
|
| 176 |
}
|
| 177 |
h1 {
|
| 178 |
+
font-size: 4.5rem;
|
| 179 |
font-weight: bold;
|
| 180 |
text-align: center;
|
| 181 |
+
color: white;
|
| 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 |
+
.button {
|
| 192 |
background: linear-gradient(45deg, #ff5722, #ff9800) !important;
|
| 193 |
+
border: none !important;
|
|
|
|
| 194 |
padding: 12px 20px;
|
| 195 |
+
border-radius: 8px;
|
| 196 |
+
color: white !important;
|
| 197 |
cursor: pointer;
|
|
|
|
| 198 |
font-size: 16px;
|
|
|
|
| 199 |
}
|
| 200 |
"""
|
| 201 |
|
|
|
|
| 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 location...")
|
| 210 |
+
query = gr.Textbox(label="Search Query", placeholder="e.g., therapist")
|
| 211 |
|
| 212 |
chatbot_history = gr.Chatbot(label="Chat History")
|
| 213 |
sentiment_output = gr.Textbox(label="Detected Sentiment")
|
|
|
|
| 220 |
submit_button.click(
|
| 221 |
app_function,
|
| 222 |
inputs=[user_message, location, query, chatbot_history],
|
| 223 |
+
outputs=[chatbot_history, sentiment_output, emotion_output, suggestions_output, professionals_output, map_output],
|
| 224 |
)
|
| 225 |
|
| 226 |
app.launch()
|