Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,24 +13,24 @@ import googlemaps
|
|
| 13 |
import folium
|
| 14 |
import torch
|
| 15 |
|
| 16 |
-
# Disable GPU usage for TensorFlow
|
| 17 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
| 18 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 19 |
|
| 20 |
-
#
|
| 21 |
nltk.download("punkt")
|
| 22 |
|
| 23 |
# Initialize Lancaster Stemmer
|
| 24 |
stemmer = LancasterStemmer()
|
| 25 |
|
| 26 |
-
# Load chatbot 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
|
| 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,18 +39,19 @@ net = tflearn.regression(net)
|
|
| 39 |
chatbot_model = tflearn.DNN(net)
|
| 40 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
| 41 |
|
| 42 |
-
# Hugging Face
|
| 43 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 44 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 45 |
|
| 46 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 47 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 48 |
|
| 49 |
-
# Google Maps API
|
| 50 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
| 51 |
|
| 52 |
-
#
|
| 53 |
def bag_of_words(s, words):
|
|
|
|
| 54 |
bag = [0] * len(words)
|
| 55 |
s_words = word_tokenize(s)
|
| 56 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
@@ -60,7 +61,6 @@ def bag_of_words(s, words):
|
|
| 60 |
bag[i] = 1
|
| 61 |
return np.array(bag)
|
| 62 |
|
| 63 |
-
# Chatbot Logic
|
| 64 |
def chatbot(message, history):
|
| 65 |
"""Generate chatbot response and append to history."""
|
| 66 |
history = history or []
|
|
@@ -77,8 +77,8 @@ def chatbot(message, history):
|
|
| 77 |
history.append((message, response))
|
| 78 |
return history, response
|
| 79 |
|
| 80 |
-
# Sentiment Analysis
|
| 81 |
def analyze_sentiment(user_input):
|
|
|
|
| 82 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 83 |
with torch.no_grad():
|
| 84 |
outputs = model_sentiment(**inputs)
|
|
@@ -86,125 +86,143 @@ def analyze_sentiment(user_input):
|
|
| 86 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
| 87 |
return sentiment_map[sentiment_class]
|
| 88 |
|
| 89 |
-
# Emotion Detection
|
| 90 |
def detect_emotion(user_input):
|
|
|
|
| 91 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 92 |
result = pipe(user_input)
|
| 93 |
emotion = result[0]['label']
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
# Generate Suggestions
|
| 97 |
def generate_suggestions(emotion):
|
| 98 |
-
"""Return suggestions
|
| 99 |
suggestions = {
|
| 100 |
"joy": [
|
| 101 |
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 102 |
["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 103 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 104 |
-
["Relaxation
|
| 105 |
],
|
| 106 |
"anger": [
|
| 107 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 108 |
-
["Stress Management Tips", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
| 109 |
-
["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anger-management" target="_blank">Visit</a>'],
|
| 110 |
-
["Relaxation
|
| 111 |
],
|
| 112 |
"fear": [
|
| 113 |
["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 114 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 115 |
-
["
|
|
|
|
| 116 |
],
|
| 117 |
"sadness": [
|
| 118 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 119 |
["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 120 |
-
["Relaxation
|
| 121 |
],
|
| 122 |
"surprise": [
|
| 123 |
-
["Managing Stress", '<a href="https://www.health.harvard.edu" target="_blank">Visit</a>'],
|
| 124 |
["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 125 |
-
["Relaxation
|
| 126 |
],
|
| 127 |
}
|
| 128 |
return suggestions.get(emotion.lower(), [["No suggestions available", ""]])
|
| 129 |
|
| 130 |
-
# Get Health Professionals and Generate Map
|
| 131 |
def get_health_professionals_and_map(location, query):
|
| 132 |
-
"""Search professionals and
|
| 133 |
try:
|
| 134 |
geo_location = gmaps.geocode(location)
|
| 135 |
if geo_location:
|
| 136 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
|
|
|
| 137 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 138 |
|
| 139 |
-
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 140 |
professionals = []
|
| 141 |
for place in places_result:
|
| 142 |
professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
|
| 143 |
-
folium.Marker(
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
return professionals, map_._repr_html_()
|
| 146 |
-
return ["No professionals found"], ""
|
| 147 |
except Exception as e:
|
| 148 |
-
return [f"Error: {e}"], ""
|
| 149 |
|
| 150 |
-
#
|
| 151 |
def app_function(user_input, location, query, history):
|
| 152 |
-
chatbot_history,
|
|
|
|
| 153 |
emotion = detect_emotion(user_input)
|
| 154 |
suggestions = generate_suggestions(emotion)
|
| 155 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 156 |
-
return chatbot_history, emotion, suggestions, professionals, map_html
|
| 157 |
|
| 158 |
-
#
|
| 159 |
custom_css = """
|
| 160 |
-
body {
|
| 161 |
-
background: linear-gradient(135deg, #000000, #ff5722);
|
| 162 |
-
color: white;
|
| 163 |
-
font-family: 'Roboto', sans-serif;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
}
|
| 165 |
-
|
| 166 |
-
background: #
|
| 167 |
-
color: white !important;
|
| 168 |
-
border: 2px solid #ff5722 !important;
|
| 169 |
-
border-radius: 5px;
|
| 170 |
-
padding: 12px !important;
|
| 171 |
}
|
| 172 |
-
|
| 173 |
-
background: #000000 !important;
|
| 174 |
-
color: white !important;
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
| 178 |
}
|
| 179 |
-
|
| 180 |
-
color:
|
| 181 |
-
|
| 182 |
-
|
| 183 |
}
|
| 184 |
"""
|
| 185 |
|
| 186 |
# Gradio Application
|
| 187 |
with gr.Blocks(css=custom_css) as app:
|
| 188 |
-
gr.Markdown("<h1>π Well-Being Companion</h1>")
|
| 189 |
-
gr.Markdown("<
|
| 190 |
|
| 191 |
with gr.Row():
|
| 192 |
-
|
| 193 |
location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
|
| 194 |
-
query = gr.Textbox(label="Query
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
|
| 204 |
-
|
| 205 |
app_function,
|
| 206 |
-
inputs=[
|
| 207 |
-
outputs=[
|
| 208 |
)
|
| 209 |
|
| 210 |
app.launch()
|
|
|
|
| 13 |
import folium
|
| 14 |
import torch
|
| 15 |
|
| 16 |
+
# Disable GPU usage for TensorFlow and suppress logs
|
| 17 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
| 18 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 19 |
|
| 20 |
+
# Ensure necessary NLTK resources are downloaded
|
| 21 |
nltk.download("punkt")
|
| 22 |
|
| 23 |
# Initialize Lancaster Stemmer
|
| 24 |
stemmer = LancasterStemmer()
|
| 25 |
|
| 26 |
+
# Load intents.json and chatbot 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 Chatbot 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 sentiment and emotion detection models
|
| 43 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 44 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 45 |
|
| 46 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 47 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 48 |
|
| 49 |
+
# Google Maps API client
|
| 50 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
| 51 |
|
| 52 |
+
# Helper Functions
|
| 53 |
def bag_of_words(s, words):
|
| 54 |
+
"""Convert user input into bag-of-words vector for use in chatbot model."""
|
| 55 |
bag = [0] * len(words)
|
| 56 |
s_words = word_tokenize(s)
|
| 57 |
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
|
|
|
| 61 |
bag[i] = 1
|
| 62 |
return np.array(bag)
|
| 63 |
|
|
|
|
| 64 |
def chatbot(message, history):
|
| 65 |
"""Generate chatbot response and append to history."""
|
| 66 |
history = history or []
|
|
|
|
| 77 |
history.append((message, response))
|
| 78 |
return history, response
|
| 79 |
|
|
|
|
| 80 |
def analyze_sentiment(user_input):
|
| 81 |
+
"""Analyze sentiment with emojis."""
|
| 82 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 83 |
with torch.no_grad():
|
| 84 |
outputs = model_sentiment(**inputs)
|
|
|
|
| 86 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
| 87 |
return sentiment_map[sentiment_class]
|
| 88 |
|
|
|
|
| 89 |
def detect_emotion(user_input):
|
| 90 |
+
"""Detect user emotion with emojis."""
|
| 91 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 92 |
result = pipe(user_input)
|
| 93 |
emotion = result[0]['label']
|
| 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 Emotion π€")
|
| 103 |
|
|
|
|
| 104 |
def generate_suggestions(emotion):
|
| 105 |
+
"""Return suggestions based on detected emotion."""
|
| 106 |
suggestions = {
|
| 107 |
"joy": [
|
| 108 |
["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 109 |
["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-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 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 115 |
+
["Stress Management Tips", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
|
| 116 |
+
["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">Visit</a>'],
|
| 117 |
+
["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
|
| 118 |
],
|
| 119 |
"fear": [
|
| 120 |
["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 121 |
["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 122 |
+
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 123 |
+
["Relaxation Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
|
| 124 |
],
|
| 125 |
"sadness": [
|
| 126 |
["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 127 |
["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 128 |
+
["Relaxation Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
|
| 129 |
],
|
| 130 |
"surprise": [
|
| 131 |
+
["Managing Stress", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
|
| 132 |
["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 133 |
+
["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
|
| 134 |
],
|
| 135 |
}
|
| 136 |
return suggestions.get(emotion.lower(), [["No suggestions available", ""]])
|
| 137 |
|
|
|
|
| 138 |
def get_health_professionals_and_map(location, query):
|
| 139 |
+
"""Search for nearby professionals and generate interactive map."""
|
| 140 |
try:
|
| 141 |
geo_location = gmaps.geocode(location)
|
| 142 |
if geo_location:
|
| 143 |
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 144 |
+
map_ = folium.Map(location=(lat, lng), zoom_start=13)
|
| 145 |
places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
|
| 146 |
|
|
|
|
| 147 |
professionals = []
|
| 148 |
for place in places_result:
|
| 149 |
professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
|
| 150 |
+
folium.Marker(
|
| 151 |
+
location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
|
| 152 |
+
popup=place["name"]
|
| 153 |
+
).add_to(map_)
|
| 154 |
return professionals, map_._repr_html_()
|
| 155 |
+
return ["No professionals found nearby."], ""
|
| 156 |
except Exception as e:
|
| 157 |
+
return [f"Error: {str(e)}"], ""
|
| 158 |
|
| 159 |
+
# Application Logic
|
| 160 |
def app_function(user_input, location, query, history):
|
| 161 |
+
chatbot_history, _ = chatbot(user_input, history)
|
| 162 |
+
sentiment = analyze_sentiment(user_input)
|
| 163 |
emotion = detect_emotion(user_input)
|
| 164 |
suggestions = generate_suggestions(emotion)
|
| 165 |
professionals, map_html = get_health_professionals_and_map(location, query)
|
| 166 |
+
return chatbot_history, sentiment, emotion, suggestions, professionals, map_html
|
| 167 |
|
| 168 |
+
# Custom CSS for Styling Submit Button and UI
|
| 169 |
custom_css = """
|
| 170 |
+
body {
|
| 171 |
+
background: linear-gradient(135deg, #000000, #ff5722);
|
| 172 |
+
color: white;
|
| 173 |
+
font-family: 'Roboto', sans-serif;
|
| 174 |
+
}
|
| 175 |
+
button {
|
| 176 |
+
background: linear-gradient(45deg, #ff5722, #ff9800) !important;
|
| 177 |
+
color: white !important;
|
| 178 |
+
border: none;
|
| 179 |
+
border-radius: 8px;
|
| 180 |
+
padding: 12px 20px;
|
| 181 |
+
cursor: pointer;
|
| 182 |
+
font-size: 16px;
|
| 183 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
|
| 184 |
}
|
| 185 |
+
button:hover {
|
| 186 |
+
background: linear-gradient(45deg, #ff9800, #ff5722) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
}
|
| 188 |
+
textarea, input {
|
| 189 |
+
background: #000000 !important;
|
| 190 |
+
color: white !important;
|
| 191 |
+
border: 1px solid #ff5722 !important;
|
| 192 |
+
padding: 12px;
|
| 193 |
+
font-size: 14px;
|
| 194 |
+
border-radius: 8px;
|
| 195 |
}
|
| 196 |
+
.gr-chatbot, .gr-textbox, .gr-html, .gr-dataframe {
|
| 197 |
+
background-color: #000 !important;
|
| 198 |
+
border: 1px solid #ff5722 !important;
|
| 199 |
+
color: white !important;
|
| 200 |
}
|
| 201 |
"""
|
| 202 |
|
| 203 |
# Gradio Application
|
| 204 |
with gr.Blocks(css=custom_css) as app:
|
| 205 |
+
gr.Markdown("<h1 style='text-align: center;'>π Well-Being Companion</h1>")
|
| 206 |
+
gr.Markdown("<h3 style='text-align: center;'>Empowering Your Well-Being Journey π</h3>")
|
| 207 |
|
| 208 |
with gr.Row():
|
| 209 |
+
user_message = gr.Textbox(label="Your Message", placeholder="Type your message...")
|
| 210 |
location = gr.Textbox(label="Your Location", placeholder="Enter your location...")
|
| 211 |
+
query = gr.Textbox(label="Search Query", placeholder="e.g., therapist, doctor")
|
| 212 |
|
| 213 |
+
chatbot_output = gr.Chatbot(label="Chat History")
|
| 214 |
+
sentiment_output = gr.Textbox(label="Detected Sentiment")
|
| 215 |
+
emotion_output = gr.Textbox(label="Detected Emotion")
|
| 216 |
+
suggestion_table = gr.DataFrame(headers=["Suggestion Title", "Link"], label="Well-Being Suggestions")
|
| 217 |
+
professionals_output = gr.Textbox(label="Health Professionals Nearby", lines=5)
|
| 218 |
+
map_html = gr.HTML(label="Interactive Map")
|
| 219 |
|
| 220 |
+
submit_btn = gr.Button("Submit")
|
| 221 |
|
| 222 |
+
submit_btn.click(
|
| 223 |
app_function,
|
| 224 |
+
inputs=[user_message, location, query, chatbot_output],
|
| 225 |
+
outputs=[chatbot_output, sentiment_output, emotion_output, suggestion_table, professionals_output, map_html]
|
| 226 |
)
|
| 227 |
|
| 228 |
app.launch()
|