Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,6 @@
|
|
1 |
import gradio as gr
|
2 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
3 |
-
import
|
4 |
-
import nltk
|
5 |
-
import numpy as np
|
6 |
-
import tflearn
|
7 |
-
import tensorflow as tf
|
8 |
-
import random
|
9 |
-
import json
|
10 |
-
import pickle
|
11 |
-
from nltk.tokenize import word_tokenize
|
12 |
-
from nltk.stem.lancaster import LancasterStemmer
|
13 |
import requests
|
14 |
import csv
|
15 |
import time
|
@@ -48,14 +39,12 @@ net = tflearn.fully_connected(net, 8)
|
|
48 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
49 |
net = tflearn.regression(net)
|
50 |
|
51 |
-
#
|
52 |
model = tflearn.DNN(net)
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
# Load the model weights
|
58 |
-
checkpoint.restore("MentalHealthChatBotmodel.tflearn.meta")
|
59 |
|
60 |
# Function to process user input into a bag-of-words format
|
61 |
def bag_of_words(s, words):
|
@@ -72,7 +61,7 @@ def bag_of_words(s, words):
|
|
72 |
def chat(message, history):
|
73 |
history = history or []
|
74 |
message = message.lower()
|
75 |
-
|
76 |
try:
|
77 |
# Predict the tag
|
78 |
results = model.predict([bag_of_words(message, words)])
|
@@ -90,10 +79,43 @@ def chat(message, history):
|
|
90 |
|
91 |
except Exception as e:
|
92 |
response = f"An error occurred: {str(e)}"
|
93 |
-
|
94 |
history.append((message, response))
|
95 |
return history, history
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
# Function to send a request to Google Places API and fetch places data
|
98 |
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
99 |
params = {
|
@@ -229,7 +251,11 @@ def get_all_places(query, location, radius, api_key):
|
|
229 |
def save_to_csv(data, filename):
|
230 |
with open(filename, mode='w', newline='', encoding='utf-8') as file:
|
231 |
writer = csv.writer(file)
|
232 |
-
writer.writerow([
|
|
|
|
|
|
|
|
|
233 |
writer.writerows(data)
|
234 |
print(f"Data saved to {filename}")
|
235 |
|
@@ -243,30 +269,44 @@ def main():
|
|
243 |
|
244 |
# Gradio UI setup
|
245 |
with gr.Blocks() as demo:
|
246 |
-
# Load pre-trained model and tokenizer
|
247 |
-
@gr.cache_resource
|
248 |
-
def load_model():
|
249 |
-
tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
250 |
-
model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
251 |
-
return tokenizer, model
|
252 |
-
|
253 |
-
tokenizer, model = load_model()
|
254 |
-
|
255 |
# Display header
|
256 |
gr.Markdown("# Emotion Detection and Well-Being Suggestions")
|
257 |
|
258 |
# User input for text (emotion detection)
|
259 |
-
|
260 |
-
emotion_output = gr.Textbox(label="Emotion Detected")
|
261 |
|
262 |
-
# Model prediction
|
263 |
def predict_emotion(text):
|
264 |
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
265 |
result = pipe(text)
|
266 |
emotion = result[0]['label']
|
267 |
return emotion
|
268 |
|
269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
270 |
|
271 |
# Chatbot functionality
|
272 |
chatbot = gr.Chatbot(label="Chat")
|
@@ -276,14 +316,12 @@ with gr.Blocks() as demo:
|
|
276 |
def chat(message, history):
|
277 |
history = history or []
|
278 |
message = message.lower()
|
279 |
-
|
280 |
try:
|
281 |
-
# Predict the tag
|
282 |
results = model.predict([bag_of_words(message, words)])
|
283 |
results_index = np.argmax(results)
|
284 |
tag = labels[results_index]
|
285 |
|
286 |
-
# Match tag with intent and choose a random response
|
287 |
for tg in data["intents"]:
|
288 |
if tg['tag'] == tag:
|
289 |
responses = tg['responses']
|
@@ -294,22 +332,35 @@ with gr.Blocks() as demo:
|
|
294 |
|
295 |
except Exception as e:
|
296 |
response = f"An error occurred: {str(e)}"
|
297 |
-
|
298 |
history.append((message, response))
|
299 |
return history, history
|
300 |
|
301 |
message_input.submit(chat, inputs=[message_input, history_state], outputs=[chatbot, history_state])
|
302 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
303 |
# Button to fetch wellness professionals data
|
304 |
fetch_button = gr.Button("Fetch Wellness Professionals Data")
|
305 |
-
data_output = gr.
|
306 |
|
307 |
def fetch_data():
|
308 |
all_results = get_all_places(query, location, radius, api_key)
|
309 |
if all_results:
|
310 |
-
|
311 |
-
csv_file = df.to_csv(index=False)
|
312 |
-
return csv_file
|
313 |
else:
|
314 |
return "No data found."
|
315 |
|
|
|
1 |
import gradio as gr
|
2 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
3 |
+
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
import requests
|
5 |
import csv
|
6 |
import time
|
|
|
39 |
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
|
40 |
net = tflearn.regression(net)
|
41 |
|
42 |
+
# Load the trained model
|
43 |
model = tflearn.DNN(net)
|
44 |
+
try:
|
45 |
+
model.load("MentalHealthChatBotmodel.tflearn")
|
46 |
+
except FileNotFoundError:
|
47 |
+
raise FileNotFoundError("Error: Trained model file 'MentalHealthChatBotmodel.tflearn' not found.")
|
|
|
|
|
48 |
|
49 |
# Function to process user input into a bag-of-words format
|
50 |
def bag_of_words(s, words):
|
|
|
61 |
def chat(message, history):
|
62 |
history = history or []
|
63 |
message = message.lower()
|
64 |
+
|
65 |
try:
|
66 |
# Predict the tag
|
67 |
results = model.predict([bag_of_words(message, words)])
|
|
|
79 |
|
80 |
except Exception as e:
|
81 |
response = f"An error occurred: {str(e)}"
|
82 |
+
|
83 |
history.append((message, response))
|
84 |
return history, history
|
85 |
|
86 |
+
# Load tokenizer and model for sentiment analysis
|
87 |
+
tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
88 |
+
model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
89 |
+
|
90 |
+
# Google Places API endpoint
|
91 |
+
url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
|
92 |
+
places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
|
93 |
+
|
94 |
+
# Your actual Google API Key (replace with your key)
|
95 |
+
api_key = "AIzaSyCcfJzMFfuv_1LN7JPTJJYw_aS0A_SLeW0" # Replace with your own Google API key
|
96 |
+
|
97 |
+
# Search query for wellness professionals in Hawaii
|
98 |
+
query = "therapist OR counselor OR mental health professional OR marriage and family therapist OR psychotherapist OR psychiatrist OR psychologist OR nutritionist OR wellness doctor OR holistic practitioner OR integrative medicine OR chiropractor OR naturopath in Hawaii"
|
99 |
+
|
100 |
+
# Approximate latitude and longitude for Hawaii (e.g., Oahu)
|
101 |
+
location = "21.3,-157.8" # Center of Hawaii (Oahu)
|
102 |
+
radius = 50000 # 50 km radius
|
103 |
+
|
104 |
+
# Install Chrome and Chromedriver
|
105 |
+
def install_chrome_and_driver():
|
106 |
+
# Install Chrome (if not already installed)
|
107 |
+
os.system("apt-get update")
|
108 |
+
os.system("apt-get install -y wget curl")
|
109 |
+
os.system("wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb")
|
110 |
+
os.system("dpkg -i google-chrome-stable_current_amd64.deb")
|
111 |
+
os.system("apt-get install -y -f")
|
112 |
+
os.system("google-chrome-stable --version")
|
113 |
+
|
114 |
+
# Install Chromedriver (if not already installed)
|
115 |
+
chromedriver_autoinstaller.install()
|
116 |
+
|
117 |
+
install_chrome_and_driver()
|
118 |
+
|
119 |
# Function to send a request to Google Places API and fetch places data
|
120 |
def get_places_data(query, location, radius, api_key, next_page_token=None):
|
121 |
params = {
|
|
|
251 |
def save_to_csv(data, filename):
|
252 |
with open(filename, mode='w', newline='', encoding='utf-8') as file:
|
253 |
writer = csv.writer(file)
|
254 |
+
writer.writerow([
|
255 |
+
"Name", "Address", "Phone", "Rating", "Business Status",
|
256 |
+
"User Ratings Total", "Website", "Types", "Latitude", "Longitude",
|
257 |
+
"Opening Hours", "Reviews", "Email"
|
258 |
+
])
|
259 |
writer.writerows(data)
|
260 |
print(f"Data saved to {filename}")
|
261 |
|
|
|
269 |
|
270 |
# Gradio UI setup
|
271 |
with gr.Blocks() as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
# Display header
|
273 |
gr.Markdown("# Emotion Detection and Well-Being Suggestions")
|
274 |
|
275 |
# User input for text (emotion detection)
|
276 |
+
user_input_emotion = gr.Textbox(lines=1, label="How are you feeling today?")
|
|
|
277 |
|
278 |
+
# Model prediction for emotion detection
|
279 |
def predict_emotion(text):
|
280 |
pipe = pipeline("text-classification", model=model, tokenizer=tokenizer)
|
281 |
result = pipe(text)
|
282 |
emotion = result[0]['label']
|
283 |
return emotion
|
284 |
|
285 |
+
user_input_emotion.change(predict_emotion, inputs=user_input_emotion, outputs=gr.Textbox(label="Emotion Detected"))
|
286 |
+
|
287 |
+
# Provide suggestions based on the detected emotion
|
288 |
+
def show_suggestions(emotion):
|
289 |
+
if emotion == 'joy':
|
290 |
+
return "You're feeling happy! Keep up the great mood!\nUseful Resources:\n[Relaxation Techniques](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)\n[Dealing with Stress](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)"
|
291 |
+
elif emotion == 'anger':
|
292 |
+
return "You're feeling angry. It's okay to feel this way. Let's try to calm down.\nUseful Resources:\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n[Stress Management Tips](https://www.health.harvard.edu/health-a-to-z)\n[Dealing with Anger](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/MIc299Flibs)"
|
293 |
+
elif emotion == 'fear':
|
294 |
+
return "You're feeling fearful. Take a moment to breathe and relax.\nUseful Resources:\n[Mindfulness Practices](https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation)\n[Coping with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/yGKKz185M5o)"
|
295 |
+
elif emotion == 'sadness':
|
296 |
+
return "You're feeling sad. It's okay to take a break.\nUseful Resources:\n[Emotional Wellness Toolkit](https://www.nih.gov/health-information/emotional-wellness-toolkit)\n[Dealing with Anxiety](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/-e-4Kx5px_I)"
|
297 |
+
elif emotion == 'surprise':
|
298 |
+
return "You're feeling surprised. It's okay to feel neutral!\nUseful Resources:\n[Managing Stress](https://www.health.harvard.edu/health-a-to-z)\n[Coping Strategies](https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety)\n\nRelaxation Videos:\n[Watch on YouTube](https://youtu.be/m1vaUGtyo-A)"
|
299 |
+
|
300 |
+
emotion_output = gr.Textbox(label="Emotion Detected")
|
301 |
+
emotion_output.change(show_suggestions, inputs=emotion_output, outputs=gr.Textbox(label="Suggestions"))
|
302 |
+
|
303 |
+
# Button for summary
|
304 |
+
def show_summary(emotion):
|
305 |
+
return f"Emotion Detected: {emotion}\nUseful Resources based on your mood:\n{show_suggestions(emotion)}"
|
306 |
+
|
307 |
+
summary_button = gr.Button("Show Summary")
|
308 |
+
summary_output = gr.Textbox(label="Summary")
|
309 |
+
summary_button.click(show_summary, inputs=emotion_output, outputs=summary_output)
|
310 |
|
311 |
# Chatbot functionality
|
312 |
chatbot = gr.Chatbot(label="Chat")
|
|
|
316 |
def chat(message, history):
|
317 |
history = history or []
|
318 |
message = message.lower()
|
319 |
+
|
320 |
try:
|
|
|
321 |
results = model.predict([bag_of_words(message, words)])
|
322 |
results_index = np.argmax(results)
|
323 |
tag = labels[results_index]
|
324 |
|
|
|
325 |
for tg in data["intents"]:
|
326 |
if tg['tag'] == tag:
|
327 |
responses = tg['responses']
|
|
|
332 |
|
333 |
except Exception as e:
|
334 |
response = f"An error occurred: {str(e)}"
|
335 |
+
|
336 |
history.append((message, response))
|
337 |
return history, history
|
338 |
|
339 |
message_input.submit(chat, inputs=[message_input, history_state], outputs=[chatbot, history_state])
|
340 |
|
341 |
+
# User input for text (sentiment analysis)
|
342 |
+
user_input_sentiment = gr.Textbox(lines=1, label="Enter text to analyze sentiment:")
|
343 |
+
|
344 |
+
# Prediction button for sentiment analysis
|
345 |
+
def predict_sentiment(text):
|
346 |
+
inputs = tokenizer_sentiment(text, return_tensors="pt")
|
347 |
+
with torch.no_grad():
|
348 |
+
outputs = model_sentiment(**inputs)
|
349 |
+
predicted_class = torch.argmax(outputs.logits, dim=1).item()
|
350 |
+
sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
|
351 |
+
return sentiment
|
352 |
+
|
353 |
+
sentiment_output = gr.Textbox(label="Predicted Sentiment")
|
354 |
+
user_input_sentiment.change(predict_sentiment, inputs=user_input_sentiment, outputs=sentiment_output)
|
355 |
+
|
356 |
# Button to fetch wellness professionals data
|
357 |
fetch_button = gr.Button("Fetch Wellness Professionals Data")
|
358 |
+
data_output = gr.Dataframe(headers=["Name", "Address", "Phone", "Rating", "Business Status", "User Ratings Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
|
359 |
|
360 |
def fetch_data():
|
361 |
all_results = get_all_places(query, location, radius, api_key)
|
362 |
if all_results:
|
363 |
+
return pd.DataFrame(all_results, columns=["Name", "Address", "Phone", "Rating", "Business Status", "User Ratings Total", "Website", "Types", "Latitude", "Longitude", "Opening Hours", "Reviews", "Email"])
|
|
|
|
|
364 |
else:
|
365 |
return "No data found."
|
366 |
|