Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,35 +17,40 @@ import torch
|
|
| 17 |
# Disable GPU usage for TensorFlow
|
| 18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
| 19 |
|
| 20 |
-
# Suppress TensorFlow
|
| 21 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 22 |
|
| 23 |
-
# Download NLTK resources
|
| 24 |
nltk.download("punkt")
|
| 25 |
|
| 26 |
-
# Initialize
|
| 27 |
stemmer = LancasterStemmer()
|
| 28 |
|
| 29 |
-
# Load intents
|
| 30 |
with open("intents.json") as file:
|
| 31 |
intents_data = json.load(file)
|
| 32 |
|
| 33 |
-
# Load preprocessed data for Well-Being Chatbot
|
| 34 |
with open("data.pickle", "rb") as f:
|
| 35 |
words, labels, training, output = pickle.load(f)
|
| 36 |
|
| 37 |
-
# Build
|
| 38 |
net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32)
|
| 39 |
net = tflearn.fully_connected(net, 8)
|
| 40 |
net = tflearn.fully_connected(net, 8)
|
| 41 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
| 42 |
net = tflearn.regression(net)
|
| 43 |
-
|
| 44 |
-
# Load and initialize the trained model
|
| 45 |
chatbot_model = tflearn.DNN(net)
|
| 46 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
| 47 |
|
| 48 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def bag_of_words(s, words):
|
| 50 |
bag = [0 for _ in range(len(words))]
|
| 51 |
s_words = word_tokenize(s)
|
|
@@ -56,29 +61,26 @@ def bag_of_words(s, words):
|
|
| 56 |
bag[i] = 1
|
| 57 |
return np.array(bag)
|
| 58 |
|
| 59 |
-
# Chatbot
|
| 60 |
def chatbot(message, history):
|
| 61 |
history = history or []
|
| 62 |
-
message = message.lower()
|
| 63 |
try:
|
| 64 |
results = chatbot_model.predict([bag_of_words(message, words)])
|
| 65 |
tag = labels[np.argmax(results)]
|
| 66 |
-
|
| 67 |
-
response = "I'm not sure how to respond to 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: {str(e)} π₯"
|
|
|
|
| 74 |
history.append({"role": "user", "content": message})
|
| 75 |
history.append({"role": "assistant", "content": response})
|
| 76 |
return history, response
|
| 77 |
|
| 78 |
-
# Sentiment
|
| 79 |
-
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 80 |
-
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 81 |
-
|
| 82 |
def analyze_sentiment(user_input):
|
| 83 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 84 |
with torch.no_grad():
|
|
@@ -87,10 +89,7 @@ def analyze_sentiment(user_input):
|
|
| 87 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
| 88 |
return sentiment_map[sentiment_class]
|
| 89 |
|
| 90 |
-
# Emotion
|
| 91 |
-
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 92 |
-
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 93 |
-
|
| 94 |
def detect_emotion(user_input):
|
| 95 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 96 |
result = pipe(user_input)
|
|
@@ -105,63 +104,44 @@ def detect_emotion(user_input):
|
|
| 105 |
}
|
| 106 |
return emotion_map.get(emotion, "Unknown Emotion π€")
|
| 107 |
|
| 108 |
-
#
|
| 109 |
-
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
| 110 |
-
|
| 111 |
-
def get_health_professionals_and_map(location, query):
|
| 112 |
-
"""Search for health professionals and generate a map."""
|
| 113 |
-
try:
|
| 114 |
-
geo_location = gmaps.geocode(location)
|
| 115 |
-
if geo_location:
|
| 116 |
-
lat, lng = geo_location[0]["geometry"]["location"].values()
|
| 117 |
-
places_result = gmaps.places_nearby(
|
| 118 |
-
location=(lat, lng), radius=10000, type="doctor", keyword=query
|
| 119 |
-
).get("results", [])
|
| 120 |
-
|
| 121 |
-
# Create map
|
| 122 |
-
m = folium.Map(location=(lat, lng), zoom_start=13)
|
| 123 |
-
for place in places_result:
|
| 124 |
-
folium.Marker(
|
| 125 |
-
location=[
|
| 126 |
-
place["geometry"]["location"]["lat"],
|
| 127 |
-
place["geometry"]["location"]["lng"],
|
| 128 |
-
],
|
| 129 |
-
popup=place["name"],
|
| 130 |
-
).add_to(m)
|
| 131 |
-
map_html = m._repr_html_()
|
| 132 |
-
professionals_info = [
|
| 133 |
-
f"{place['name']} - {place.get('vicinity', 'No address available')}"
|
| 134 |
-
for place in places_result
|
| 135 |
-
]
|
| 136 |
-
return "\n".join(professionals_info), map_html
|
| 137 |
-
return "Unable to find location", ""
|
| 138 |
-
except Exception as e:
|
| 139 |
-
return f"Error: {e}", ""
|
| 140 |
-
|
| 141 |
-
# Suggestions Based on Emotion
|
| 142 |
def generate_suggestions(emotion):
|
| 143 |
suggestions = {
|
| 144 |
"π Joy": [
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
],
|
| 148 |
"π’ Sadness": [
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
],
|
| 152 |
}
|
| 153 |
-
return suggestions.get(emotion.split(" ")[1]
|
| 154 |
|
| 155 |
-
# Main
|
| 156 |
def app_function(message, location, query, history):
|
| 157 |
chatbot_history, _ = chatbot(message, history)
|
| 158 |
sentiment = analyze_sentiment(message)
|
| 159 |
emotion = detect_emotion(message)
|
| 160 |
suggestions = generate_suggestions(emotion)
|
| 161 |
-
|
| 162 |
-
return chatbot_history, sentiment, emotion, suggestions, map_html, places_info
|
| 163 |
|
| 164 |
-
# Gradio
|
| 165 |
with gr.Blocks() as demo:
|
| 166 |
gr.Markdown("# π Well-being Companion")
|
| 167 |
gr.Markdown("Empowering your mental health journey π")
|
|
@@ -172,29 +152,15 @@ with gr.Blocks() as demo:
|
|
| 172 |
query_input = gr.Textbox(label="Search Query", placeholder="Enter query (e.g., therapist)...", lines=1)
|
| 173 |
submit_btn = gr.Button("Submit")
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
emotion_output = gr.Textbox(label="Emotion Detected")
|
| 180 |
-
with gr.Row():
|
| 181 |
-
suggestions_output = gr.DataFrame(label="Suggestions", headers=["Title", "Subject", "Link"])
|
| 182 |
-
with gr.Row():
|
| 183 |
-
map_display = gr.HTML(label="Map of Nearby Professionals")
|
| 184 |
-
health_info_output = gr.Textbox(label="Health Professionals Info", lines=5)
|
| 185 |
|
| 186 |
-
# Button interaction
|
| 187 |
submit_btn.click(
|
| 188 |
app_function,
|
| 189 |
inputs=[user_input, location_input, query_input, chatbot_output],
|
| 190 |
-
outputs=[
|
| 191 |
-
chatbot_output,
|
| 192 |
-
sentiment_output,
|
| 193 |
-
emotion_output,
|
| 194 |
-
suggestions_output,
|
| 195 |
-
map_display,
|
| 196 |
-
health_info_output,
|
| 197 |
-
],
|
| 198 |
)
|
| 199 |
|
| 200 |
demo.launch()
|
|
|
|
| 17 |
# Disable GPU usage for TensorFlow
|
| 18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
| 19 |
|
| 20 |
+
# Suppress TensorFlow warnings
|
| 21 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 22 |
|
| 23 |
+
# Download necessary NLTK resources
|
| 24 |
nltk.download("punkt")
|
| 25 |
|
| 26 |
+
# Initialize a stemmer for NLP
|
| 27 |
stemmer = LancasterStemmer()
|
| 28 |
|
| 29 |
+
# Load chatbot intents and training data
|
| 30 |
with open("intents.json") as file:
|
| 31 |
intents_data = json.load(file)
|
| 32 |
|
|
|
|
| 33 |
with open("data.pickle", "rb") as f:
|
| 34 |
words, labels, training, output = pickle.load(f)
|
| 35 |
|
| 36 |
+
# Build the chatbot's neural network model
|
| 37 |
net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32)
|
| 38 |
net = tflearn.fully_connected(net, 8)
|
| 39 |
net = tflearn.fully_connected(net, 8)
|
| 40 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
| 41 |
net = tflearn.regression(net)
|
|
|
|
|
|
|
| 42 |
chatbot_model = tflearn.DNN(net)
|
| 43 |
chatbot_model.load("MentalHealthChatBotmodel.tflearn")
|
| 44 |
|
| 45 |
+
# Tokenizer and model for sentiment analysis (Hugging Face)
|
| 46 |
+
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 47 |
+
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 48 |
+
|
| 49 |
+
# Tokenizer and model for emotion detection (Hugging Face)
|
| 50 |
+
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 51 |
+
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 52 |
+
|
| 53 |
+
# Function to process input for TensorFlow model
|
| 54 |
def bag_of_words(s, words):
|
| 55 |
bag = [0 for _ in range(len(words))]
|
| 56 |
s_words = word_tokenize(s)
|
|
|
|
| 61 |
bag[i] = 1
|
| 62 |
return np.array(bag)
|
| 63 |
|
| 64 |
+
# Chatbot response function
|
| 65 |
def chatbot(message, history):
|
| 66 |
history = history or []
|
|
|
|
| 67 |
try:
|
| 68 |
results = chatbot_model.predict([bag_of_words(message, words)])
|
| 69 |
tag = labels[np.argmax(results)]
|
|
|
|
|
|
|
| 70 |
for intent in intents_data["intents"]:
|
| 71 |
if intent["tag"] == tag:
|
| 72 |
response = random.choice(intent["responses"])
|
| 73 |
break
|
| 74 |
+
else:
|
| 75 |
+
response = "I'm not sure how to respond to that. π€"
|
| 76 |
except Exception as e:
|
| 77 |
response = f"Error: {str(e)} π₯"
|
| 78 |
+
|
| 79 |
history.append({"role": "user", "content": message})
|
| 80 |
history.append({"role": "assistant", "content": response})
|
| 81 |
return history, response
|
| 82 |
|
| 83 |
+
# Sentiment analysis
|
|
|
|
|
|
|
|
|
|
| 84 |
def analyze_sentiment(user_input):
|
| 85 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
| 86 |
with torch.no_grad():
|
|
|
|
| 89 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
| 90 |
return sentiment_map[sentiment_class]
|
| 91 |
|
| 92 |
+
# Emotion detection
|
|
|
|
|
|
|
|
|
|
| 93 |
def detect_emotion(user_input):
|
| 94 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
| 95 |
result = pipe(user_input)
|
|
|
|
| 104 |
}
|
| 105 |
return emotion_map.get(emotion, "Unknown Emotion π€")
|
| 106 |
|
| 107 |
+
# Generate emotion-based suggestions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
def generate_suggestions(emotion):
|
| 109 |
suggestions = {
|
| 110 |
"π Joy": [
|
| 111 |
+
["Relaxation Techniques", "Relaxation", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 112 |
+
["Dealing with Stress", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 113 |
+
["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 114 |
+
["Relaxation Videos", "Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
|
| 115 |
+
],
|
| 116 |
+
"π Anger": [
|
| 117 |
+
["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 118 |
+
["Stress Management Tips", "Stress Management", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
|
| 119 |
+
["Dealing with Anger", "Anger Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 120 |
+
["Relaxation Videos", "Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
|
| 121 |
],
|
| 122 |
"π’ Sadness": [
|
| 123 |
+
["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 124 |
+
["Dealing with Anxiety", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 125 |
+
["Relaxation Videos", "Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
|
| 126 |
+
],
|
| 127 |
+
"π¨ Fear": [
|
| 128 |
+
["Mindfulness Practices", "Mindfulness", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
|
| 129 |
+
["Coping with Anxiety", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
|
| 130 |
+
["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
|
| 131 |
+
["Relaxation Videos", "Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
|
| 132 |
],
|
| 133 |
}
|
| 134 |
+
return suggestions.get(emotion.split(" ")[1], [["No specific suggestions available", "", ""]])
|
| 135 |
|
| 136 |
+
# Main app function
|
| 137 |
def app_function(message, location, query, history):
|
| 138 |
chatbot_history, _ = chatbot(message, history)
|
| 139 |
sentiment = analyze_sentiment(message)
|
| 140 |
emotion = detect_emotion(message)
|
| 141 |
suggestions = generate_suggestions(emotion)
|
| 142 |
+
return chatbot_history, sentiment, emotion, suggestions
|
|
|
|
| 143 |
|
| 144 |
+
# Gradio UI
|
| 145 |
with gr.Blocks() as demo:
|
| 146 |
gr.Markdown("# π Well-being Companion")
|
| 147 |
gr.Markdown("Empowering your mental health journey π")
|
|
|
|
| 152 |
query_input = gr.Textbox(label="Search Query", placeholder="Enter query (e.g., therapist)...", lines=1)
|
| 153 |
submit_btn = gr.Button("Submit")
|
| 154 |
|
| 155 |
+
chatbot_output = gr.Chatbot(label="Chat History", type="messages")
|
| 156 |
+
sentiment_output = gr.Textbox(label="Sentiment Analysis")
|
| 157 |
+
emotion_output = gr.Textbox(label="Emotion Detected")
|
| 158 |
+
suggestions_output = gr.DataFrame(label="Suggestions", headers=["Title", "Subject", "Link"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
|
|
|
| 160 |
submit_btn.click(
|
| 161 |
app_function,
|
| 162 |
inputs=[user_input, location_input, query_input, chatbot_output],
|
| 163 |
+
outputs=[chatbot_output, sentiment_output, emotion_output, suggestions_output],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
)
|
| 165 |
|
| 166 |
demo.launch()
|