Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -17,76 +17,65 @@ import torch
|
|
17 |
# Disable GPU usage for TensorFlow
|
18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
19 |
|
20 |
-
# Suppress
|
21 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
22 |
|
23 |
-
#
|
24 |
-
|
25 |
-
nltk.download('punkt')
|
26 |
-
except Exception as e:
|
27 |
-
print(f"Error downloading NLTK data: {e}")
|
28 |
|
29 |
-
# Initialize
|
30 |
stemmer = LancasterStemmer()
|
31 |
|
32 |
-
# Load intents.json for
|
33 |
with open("intents.json") as file:
|
34 |
-
|
35 |
|
36 |
# Load preprocessed data for Well-Being Chatbot
|
37 |
with open("data.pickle", "rb") as f:
|
38 |
words, labels, training, output = pickle.load(f)
|
39 |
|
40 |
-
# Build
|
41 |
-
net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32)
|
42 |
net = tflearn.fully_connected(net, 8)
|
43 |
net = tflearn.fully_connected(net, 8)
|
44 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
45 |
net = tflearn.regression(net)
|
46 |
|
47 |
-
# Load the trained model
|
48 |
-
|
49 |
-
|
50 |
|
51 |
-
# Function to process user input into a bag-of-words format
|
52 |
def bag_of_words(s, words):
|
53 |
bag = [0 for _ in range(len(words))]
|
54 |
s_words = word_tokenize(s)
|
55 |
-
s_words = [stemmer.stem(word.lower()) for word in s_words if word.
|
56 |
for se in s_words:
|
57 |
for i, w in enumerate(words):
|
58 |
if w == se:
|
59 |
bag[i] = 1
|
60 |
return np.array(bag)
|
61 |
|
62 |
-
#
|
63 |
def chatbot(message, history):
|
64 |
history = history or []
|
65 |
message = message.lower()
|
66 |
try:
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
if tg['tag'] == tag:
|
75 |
-
responses = tg['responses']
|
76 |
-
response = random.choice(responses)
|
77 |
break
|
78 |
-
else:
|
79 |
-
response = "I'm sorry, I didn't understand that. Could you please rephrase?"
|
80 |
except Exception as e:
|
81 |
-
response = f"
|
82 |
-
|
83 |
-
# Convert the new message and response to the 'messages' format
|
84 |
history.append({"role": "user", "content": message})
|
85 |
history.append({"role": "assistant", "content": response})
|
86 |
-
|
87 |
-
return history, history
|
88 |
|
89 |
-
# Sentiment Analysis
|
90 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
91 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
92 |
|
@@ -94,103 +83,118 @@ def analyze_sentiment(user_input):
|
|
94 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
95 |
with torch.no_grad():
|
96 |
outputs = model_sentiment(**inputs)
|
97 |
-
|
98 |
-
|
99 |
-
return
|
100 |
|
101 |
-
# Emotion Detection
|
102 |
tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
103 |
model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
104 |
|
105 |
def detect_emotion(user_input):
|
106 |
pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
|
107 |
result = pipe(user_input)
|
108 |
-
emotion = result[0][
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
-
#
|
112 |
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
return route_info, map_html
|
147 |
-
else:
|
148 |
-
return "Unable to find location.", ""
|
149 |
-
|
150 |
-
# Function to generate suggestions based on the detected emotion
|
151 |
def generate_suggestions(emotion):
|
152 |
suggestions = {
|
153 |
-
|
154 |
-
{"Title": "
|
155 |
-
{"Title": "
|
156 |
-
{"Title": "Emotional Wellness Toolkit πͺ", "Subject": "Wellness", "Link": '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Emotional Wellness Toolkit</a>'},
|
157 |
-
{"Title": "Relaxation Video π₯", "Subject": "Video", "Link": '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch Video</a>'}
|
158 |
],
|
159 |
-
|
160 |
-
{"Title": "
|
161 |
-
{"Title": "
|
162 |
-
{"Title": "Relaxation Techniques π", "Subject": "Relaxation", "Link": '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Mindful Breathing Meditation</a>'},
|
163 |
-
{"Title": "Dealing with Stress π‘", "Subject": "Stress Management", "Link": '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Tips for Dealing with Anxiety</a>'}
|
164 |
],
|
165 |
-
'sadness': [
|
166 |
-
{"Title": "Overcoming Sadness π", "Subject": "Well-being", "Link": '<a href="https://www.helpguide.org/mental-health/depression.htm" target="_blank">Overcoming Sadness</a>'},
|
167 |
-
{"Title": "Building Self-Esteem πͺ", "Subject": "Confidence", "Link": '<a href="https://www.helpguide.org/mental-health/self-confidence.htm" target="_blank">Self-Confidence Guide</a>'},
|
168 |
-
{"Title": "Breathing Exercises π§ββοΈ", "Subject": "Breathing", "Link": '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Mindful Breathing Meditation</a>'},
|
169 |
-
{"Title": "Relaxation Tips πΏ", "Subject": "Relaxation", "Link": '<a href="https://www.helpguide.org/mental-health/stress-relief.htm" target="_blank">Stress Relief Tips</a>'}
|
170 |
-
]
|
171 |
}
|
172 |
-
|
173 |
-
|
174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
|
176 |
# Gradio Interface
|
177 |
with gr.Blocks() as demo:
|
|
|
|
|
|
|
178 |
with gr.Row():
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
# Disable GPU usage for TensorFlow
|
18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
19 |
|
20 |
+
# Suppress TensorFlow GPU warnings & logs
|
21 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
22 |
|
23 |
+
# Download NLTK resources
|
24 |
+
nltk.download("punkt")
|
|
|
|
|
|
|
25 |
|
26 |
+
# Initialize Lancaster Stemmer
|
27 |
stemmer = LancasterStemmer()
|
28 |
|
29 |
+
# Load intents.json for the chatbot
|
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 TFlearn Chatbot Model
|
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 |
+
# Function to process user input into a bag-of-words format
|
49 |
def bag_of_words(s, words):
|
50 |
bag = [0 for _ in range(len(words))]
|
51 |
s_words = word_tokenize(s)
|
52 |
+
s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
|
53 |
for se in s_words:
|
54 |
for i, w in enumerate(words):
|
55 |
if w == se:
|
56 |
bag[i] = 1
|
57 |
return np.array(bag)
|
58 |
|
59 |
+
# Chatbot Response Function
|
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 Analysis Function
|
79 |
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
80 |
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
81 |
|
|
|
83 |
inputs = tokenizer_sentiment(user_input, return_tensors="pt")
|
84 |
with torch.no_grad():
|
85 |
outputs = model_sentiment(**inputs)
|
86 |
+
sentiment_class = torch.argmax(outputs.logits, dim=1).item()
|
87 |
+
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
88 |
+
return sentiment_map[sentiment_class]
|
89 |
|
90 |
+
# Emotion Detection Function
|
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)
|
97 |
+
emotion = result[0]["label"]
|
98 |
+
emotion_map = {
|
99 |
+
"joy": "π Joy",
|
100 |
+
"anger": "π Anger",
|
101 |
+
"sadness": "π’ Sadness",
|
102 |
+
"fear": "π¨ Fear",
|
103 |
+
"surprise": "π² Surprise",
|
104 |
+
"neutral": "π Neutral",
|
105 |
+
}
|
106 |
+
return emotion_map.get(emotion, "Unknown Emotion π€")
|
107 |
|
108 |
+
# Health Professionals Search
|
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 |
+
{"Title": "Meditation π§", "Subject": "Relaxation", "Link": "https://example.com/meditation"},
|
146 |
+
{"Title": "Learn a skill π", "Subject": "Growth", "Link": "https://example.com/skills"},
|
|
|
|
|
147 |
],
|
148 |
+
"π’ Sadness": [
|
149 |
+
{"Title": "Therapist Help π¬", "Subject": "Support", "Link": "https://example.com/therapist"},
|
150 |
+
{"Title": "Stress Management πΏ", "Subject": "Wellness", "Link": "https://example.com/stress"},
|
|
|
|
|
151 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
}
|
153 |
+
return suggestions.get(emotion.split(" ")[1].lower(), [])
|
154 |
+
|
155 |
+
# Main Gradio App Function
|
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 |
+
places_info, map_html = get_health_professionals_and_map(location, query)
|
162 |
+
return chatbot_history, sentiment, emotion, suggestions, map_html, places_info
|
163 |
|
164 |
# Gradio Interface
|
165 |
with gr.Blocks() as demo:
|
166 |
+
gr.Markdown("# π Well-being Companion")
|
167 |
+
gr.Markdown("Empowering your mental health journey π")
|
168 |
+
|
169 |
with gr.Row():
|
170 |
+
user_input = gr.Textbox(label="Your Message", placeholder="Type your message...", lines=2)
|
171 |
+
location_input = gr.Textbox(label="Your Location", placeholder="Enter location...", lines=2)
|
172 |
+
query_input = gr.Textbox(label="Search Query", placeholder="Enter query (e.g., therapist)...", lines=1)
|
173 |
+
submit_btn = gr.Button("Submit")
|
174 |
+
|
175 |
+
with gr.Row():
|
176 |
+
chatbot_output = gr.Chatbot(label="Chat History", type="messages")
|
177 |
+
with gr.Row():
|
178 |
+
sentiment_output = gr.Textbox(label="Sentiment Analysis")
|
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()
|