Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,7 +3,6 @@ import gradio as gr
|
|
3 |
import nltk
|
4 |
import numpy as np
|
5 |
import tflearn
|
6 |
-
import tensorflow
|
7 |
import random
|
8 |
import json
|
9 |
import pickle
|
@@ -25,12 +24,18 @@ nltk.download('punkt')
|
|
25 |
stemmer = LancasterStemmer()
|
26 |
|
27 |
# Load intents.json for Well-Being Chatbot
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
30 |
|
31 |
# Load preprocessed data for Well-Being Chatbot
|
32 |
-
|
33 |
-
|
|
|
|
|
|
|
34 |
|
35 |
# Build the model structure for Well-Being Chatbot
|
36 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
@@ -41,7 +46,10 @@ net = tflearn.regression(net)
|
|
41 |
|
42 |
# Load the trained model
|
43 |
model = tflearn.DNN(net)
|
44 |
-
|
|
|
|
|
|
|
45 |
|
46 |
# Function to process user input into a bag-of-words format for Chatbot
|
47 |
def bag_of_words(s, words):
|
@@ -86,121 +94,104 @@ tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-senti
|
|
86 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
87 |
|
88 |
def analyze_sentiment(user_input):
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
95 |
|
96 |
# Emotion Detection using Hugging Face model
|
97 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
98 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
99 |
|
100 |
def detect_emotion(user_input):
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
105 |
|
106 |
# Initialize Google Maps API client securely
|
107 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
108 |
|
109 |
# Function to search for health professionals
|
110 |
def search_health_professionals(query, location, radius=10000):
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
# Function to get directions and display on Gradio UI
|
115 |
def get_health_professionals_and_map(current_location, health_professional_query):
|
116 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
# Function to generate suggestions based on the detected emotion
|
119 |
def generate_suggestions(emotion):
|
120 |
-
|
121 |
-
|
122 |
{"Title": "Relaxation Techniques", "Subject": "Relaxation", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
|
123 |
{"Title": "Dealing with Stress", "Subject": "Stress Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
124 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
125 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
|
126 |
-
]
|
127 |
-
|
128 |
-
return [
|
129 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
130 |
{"Title": "Stress Management Tips", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
|
131 |
{"Title": "Dealing with Anger", "Subject": "Anger Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
132 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/MIc299Flibs"}
|
133 |
-
]
|
134 |
-
|
135 |
-
return [
|
136 |
{"Title": "Mindfulness Practices", "Subject": "Mindfulness", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
|
137 |
{"Title": "Coping with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
138 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
139 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/yGKKz185M5o"}
|
140 |
-
]
|
141 |
-
|
142 |
-
return [
|
143 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
144 |
{"Title": "Dealing with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
145 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/-e-4Kx5px_I"}
|
146 |
-
]
|
147 |
-
|
148 |
-
return [
|
149 |
{"Title": "Managing Stress", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
|
150 |
{"Title": "Coping Strategies", "Subject": "Coping", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
151 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
|
152 |
]
|
153 |
-
|
154 |
-
return []
|
155 |
-
|
156 |
-
# Gradio interface
|
157 |
-
def gradio_app(message, location, health_query, submit_button, history, state):
|
158 |
-
# Chatbot interaction
|
159 |
-
history, _ = chatbot(message, history)
|
160 |
-
|
161 |
-
# Sentiment analysis
|
162 |
-
sentiment_response = analyze_sentiment(message)
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
# Create a DataFrame for displaying suggestions
|
174 |
-
suggestions_df = pd.DataFrame(suggestions)
|
175 |
-
|
176 |
-
return history, sentiment_response, emotion_response, route_info, map_html, gr.DataFrame(suggestions_df, headers=["Title", "Subject", "Link"]), state
|
177 |
-
|
178 |
-
# Gradio UI components
|
179 |
-
message_input = gr.Textbox(lines=1, label="Message")
|
180 |
-
location_input = gr.Textbox(value="Honolulu, HI", label="Current Location")
|
181 |
-
health_query_input = gr.Textbox(value="doctor", label="Health Professional Query (e.g., doctor, psychiatrist, psychologist)")
|
182 |
-
submit_button = gr.Button("Submit") # Submit button
|
183 |
-
|
184 |
-
# Updated chat history component with 'messages' type
|
185 |
-
chat_history = gr.Chatbot(label="Well-Being Chat History", type='messages')
|
186 |
-
|
187 |
-
# Outputs
|
188 |
-
sentiment_output = gr.Textbox(label="Sentiment Analysis Result")
|
189 |
-
emotion_output = gr.Textbox(label="Emotion Detection Result")
|
190 |
-
route_info_output = gr.Textbox(label="Health Professionals Information")
|
191 |
-
map_output = gr.HTML(label="Map with Health Professionals")
|
192 |
-
suggestions_output = gr.DataFrame(label="Well-Being Suggestions", headers=["Title", "Subject", "Link"])
|
193 |
-
|
194 |
-
# Create Gradio interface
|
195 |
-
# Ensure there is exactly one state input and one state output
|
196 |
-
iface = gr.Interface(
|
197 |
-
fn=gradio_app,
|
198 |
-
inputs=[message_input, location_input, health_query_input, submit_button, gr.State()], # Updated to include only one state input
|
199 |
-
outputs=[chat_history, sentiment_output, emotion_output, route_info_output, map_output, suggestions_output, gr.State()], # Updated to include only one state output
|
200 |
-
allow_flagging="never",
|
201 |
-
live=True,
|
202 |
-
title="Well-Being App: Support, Sentiment, Emotion Detection & Health Professional Search"
|
203 |
-
)
|
204 |
-
|
205 |
-
# Launch the Gradio interface
|
206 |
iface.launch()
|
|
|
3 |
import nltk
|
4 |
import numpy as np
|
5 |
import tflearn
|
|
|
6 |
import random
|
7 |
import json
|
8 |
import pickle
|
|
|
24 |
stemmer = LancasterStemmer()
|
25 |
|
26 |
# Load intents.json for Well-Being Chatbot
|
27 |
+
try:
|
28 |
+
with open("intents.json") as file:
|
29 |
+
data = json.load(file)
|
30 |
+
except FileNotFoundError:
|
31 |
+
print("Error: 'intents.json' file not found.")
|
32 |
|
33 |
# Load preprocessed data for Well-Being Chatbot
|
34 |
+
try:
|
35 |
+
with open("data.pickle", "rb") as f:
|
36 |
+
words, labels, training, output = pickle.load(f)
|
37 |
+
except FileNotFoundError:
|
38 |
+
print("Error: 'data.pickle' file not found.")
|
39 |
|
40 |
# Build the model structure for Well-Being Chatbot
|
41 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
|
|
46 |
|
47 |
# Load the trained model
|
48 |
model = tflearn.DNN(net)
|
49 |
+
try:
|
50 |
+
model.load("MentalHealthChatBotmodel.tflearn")
|
51 |
+
except IOError:
|
52 |
+
print("Error: Model file not found or corrupted.")
|
53 |
|
54 |
# Function to process user input into a bag-of-words format for Chatbot
|
55 |
def bag_of_words(s, words):
|
|
|
94 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
95 |
|
96 |
def analyze_sentiment(user_input):
|
97 |
+
try:
|
98 |
+
inputs = tokenizer(user_input, return_tensors="pt")
|
99 |
+
with torch.no_grad():
|
100 |
+
outputs = model_sentiment(**inputs)
|
101 |
+
predicted_class = torch.argmax(outputs.logits, dim=1).item()
|
102 |
+
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
|
103 |
+
return f"Predicted Sentiment: {sentiment}"
|
104 |
+
except Exception as e:
|
105 |
+
return f"Sentiment analysis error: {str(e)}"
|
106 |
|
107 |
# Emotion Detection using Hugging Face model
|
108 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
109 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
110 |
|
111 |
def detect_emotion(user_input):
|
112 |
+
try:
|
113 |
+
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
114 |
+
result = pipe(user_input)
|
115 |
+
emotion = result[0]['label']
|
116 |
+
return f"Emotion Detected: {emotion}"
|
117 |
+
except Exception as e:
|
118 |
+
return f"Emotion detection error: {str(e)}"
|
119 |
|
120 |
# Initialize Google Maps API client securely
|
121 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
122 |
|
123 |
# Function to search for health professionals
|
124 |
def search_health_professionals(query, location, radius=10000):
|
125 |
+
try:
|
126 |
+
places_result = gmaps.places_nearby(location, radius=radius, type='doctor', keyword=query)
|
127 |
+
if 'results' in places_result:
|
128 |
+
return places_result['results']
|
129 |
+
else:
|
130 |
+
return []
|
131 |
+
except Exception as e:
|
132 |
+
print(f"Error fetching health professionals: {str(e)}")
|
133 |
+
return []
|
134 |
|
135 |
# Function to get directions and display on Gradio UI
|
136 |
def get_health_professionals_and_map(current_location, health_professional_query):
|
137 |
+
# Get health professionals using the search function
|
138 |
+
health_professionals = search_health_professionals(health_professional_query, current_location)
|
139 |
+
|
140 |
+
# Generate the map with the professionals' locations
|
141 |
+
map_obj = folium.Map(location=current_location, zoom_start=13)
|
142 |
+
for professional in health_professionals:
|
143 |
+
location = professional['geometry']['location']
|
144 |
+
folium.Marker([location['lat'], location['lng']], popup=professional['name']).add_to(map_obj)
|
145 |
+
|
146 |
+
# Save the map to an HTML file
|
147 |
+
map_html = "health_professionals_map.html"
|
148 |
+
map_obj.save(map_html)
|
149 |
+
|
150 |
+
# Generate route information (basic for now)
|
151 |
+
route_info = [f"{hp['name']} - {hp['vicinity']}" for hp in health_professionals]
|
152 |
+
|
153 |
+
return route_info, map_html
|
154 |
|
155 |
# Function to generate suggestions based on the detected emotion
|
156 |
def generate_suggestions(emotion):
|
157 |
+
suggestions = {
|
158 |
+
'joy': [
|
159 |
{"Title": "Relaxation Techniques", "Subject": "Relaxation", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
|
160 |
{"Title": "Dealing with Stress", "Subject": "Stress Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
161 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
162 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
|
163 |
+
],
|
164 |
+
'anger': [
|
|
|
165 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
166 |
{"Title": "Stress Management Tips", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
|
167 |
{"Title": "Dealing with Anger", "Subject": "Anger Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
168 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/MIc299Flibs"}
|
169 |
+
],
|
170 |
+
'fear': [
|
|
|
171 |
{"Title": "Mindfulness Practices", "Subject": "Mindfulness", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
|
172 |
{"Title": "Coping with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
173 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
174 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/yGKKz185M5o"}
|
175 |
+
],
|
176 |
+
'sadness': [
|
|
|
177 |
{"Title": "Emotional Wellness Toolkit", "Subject": "Wellness", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
|
178 |
{"Title": "Dealing with Anxiety", "Subject": "Anxiety Management", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
179 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/-e-4Kx5px_I"}
|
180 |
+
],
|
181 |
+
'surprise': [
|
|
|
182 |
{"Title": "Managing Stress", "Subject": "Stress Management", "Link": "https://www.health.harvard.edu/health-a-to-z"},
|
183 |
{"Title": "Coping Strategies", "Subject": "Coping", "Link": "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"},
|
184 |
{"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
|
185 |
]
|
186 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
|
188 |
+
return suggestions.get(emotion.lower(), [])
|
189 |
+
|
190 |
+
# Define the Gradio interface
|
191 |
+
iface = gr.Interface(fn=chatbot,
|
192 |
+
inputs=[gr.Textbox(label="Message"),
|
193 |
+
gr.State()],
|
194 |
+
outputs=[gr.Chatbot(), gr.State()],
|
195 |
+
allow_flagging="never", theme="compact")
|
196 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
197 |
iface.launch()
|