Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -9,29 +9,27 @@ import pickle
|
|
9 |
from nltk.tokenize import word_tokenize
|
10 |
from nltk.stem.lancaster import LancasterStemmer
|
11 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
12 |
-
import googlemaps
|
13 |
-
import folium
|
14 |
import pandas as pd
|
15 |
import torch
|
16 |
|
17 |
-
# Disable GPU usage for TensorFlow
|
18 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
19 |
|
20 |
-
# Download
|
21 |
nltk.download('punkt')
|
22 |
|
23 |
# Initialize Lancaster Stemmer
|
24 |
stemmer = LancasterStemmer()
|
25 |
|
26 |
-
# Load intents.json for
|
27 |
with open("intents.json") as file:
|
28 |
intents_data = json.load(file)
|
29 |
|
30 |
-
# Load tokenized data
|
31 |
with open("data.pickle", "rb") as f:
|
32 |
words, labels, training, output = pickle.load(f)
|
33 |
|
34 |
-
# Build
|
35 |
def build_chatbot_model():
|
36 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
37 |
net = tflearn.fully_connected(net, 8)
|
@@ -44,7 +42,7 @@ def build_chatbot_model():
|
|
44 |
|
45 |
chatbot_model = build_chatbot_model()
|
46 |
|
47 |
-
# Bag of
|
48 |
def bag_of_words(s, words):
|
49 |
bag = [0 for _ in range(len(words))]
|
50 |
s_words = word_tokenize(s)
|
@@ -55,33 +53,31 @@ def bag_of_words(s, words):
|
|
55 |
bag[i] = 1
|
56 |
return np.array(bag)
|
57 |
|
58 |
-
# Chatbot
|
59 |
def chatbot_response(message, history):
|
60 |
-
"""Respond to user input and update chat history."""
|
61 |
history = history or []
|
62 |
try:
|
63 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
64 |
-
|
65 |
-
tag = labels[
|
66 |
-
|
67 |
-
response = "I didn't understand that. π€ Try rephrasing your question."
|
68 |
for intent in intents_data["intents"]:
|
69 |
if intent["tag"] == tag:
|
70 |
-
response =
|
71 |
break
|
72 |
except Exception as e:
|
73 |
response = f"Error generating response: {str(e)} π₯"
|
74 |
|
75 |
history.append({"role": "user", "content": f"π¬ {message}"})
|
76 |
-
history.append({"role": "assistant", "content": response})
|
77 |
return history, response
|
78 |
|
79 |
-
#
|
80 |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
81 |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
82 |
|
|
|
83 |
def detect_emotion(user_input):
|
84 |
-
"""Detect emotion using a pre-trained model and return label with an emoji."""
|
85 |
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
|
86 |
try:
|
87 |
result = pipe(user_input)
|
@@ -98,7 +94,7 @@ def detect_emotion(user_input):
|
|
98 |
except Exception as e:
|
99 |
return f"Error detecting emotion: {str(e)} π₯"
|
100 |
|
101 |
-
# Sentiment
|
102 |
sentiment_tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
103 |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
104 |
|
@@ -108,82 +104,99 @@ def analyze_sentiment(user_input):
|
|
108 |
try:
|
109 |
with torch.no_grad():
|
110 |
outputs = sentiment_model(**inputs)
|
111 |
-
|
112 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
113 |
-
return
|
114 |
except Exception as e:
|
115 |
return f"Error in sentiment analysis: {str(e)} π₯"
|
116 |
|
117 |
-
#
|
118 |
def generate_suggestions(emotion):
|
119 |
suggestions = {
|
120 |
"π Joy": [
|
121 |
-
{"Title": "Meditation
|
122 |
-
{"Title": "
|
123 |
],
|
124 |
"π’ Sadness": [
|
125 |
-
{"Title": "
|
126 |
-
{"Title": "
|
127 |
],
|
128 |
"π Anger": [
|
129 |
-
{"Title": "
|
130 |
-
{"Title": "
|
131 |
],
|
132 |
}
|
133 |
-
return suggestions.get(emotion, [{"Title": "General
|
134 |
|
135 |
-
#
|
136 |
-
def well_being_app(user_input,
|
137 |
-
"""Main
|
138 |
-
# Chatbot
|
139 |
history, chatbot_reply = chatbot_response(user_input, history)
|
140 |
|
141 |
-
# Emotion
|
142 |
emotion = detect_emotion(user_input)
|
143 |
|
144 |
-
# Sentiment
|
145 |
sentiment = analyze_sentiment(user_input)
|
146 |
|
147 |
-
#
|
148 |
-
|
149 |
-
suggestions = generate_suggestions(
|
150 |
suggestions_df = pd.DataFrame(suggestions)
|
151 |
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
-
# Gradio Interface UI
|
161 |
-
with gr.Blocks() as app:
|
162 |
with gr.Row():
|
163 |
-
gr.
|
164 |
-
|
165 |
with gr.Row():
|
166 |
-
|
167 |
-
location = gr.Textbox(value="Honolulu, HI", label="Your Location")
|
168 |
-
query = gr.Textbox(value="Counselor", label="Health Professional (Doctor, Therapist, etc.)")
|
169 |
|
170 |
with gr.Row():
|
171 |
-
|
172 |
-
|
|
|
|
|
173 |
with gr.Row():
|
174 |
-
|
175 |
-
sentiment_output = gr.Textbox(label="Sentiment Analysis")
|
176 |
-
emotion_output = gr.Textbox(label="Emotion Detected")
|
177 |
|
178 |
-
with gr.Row():
|
179 |
-
suggestions_output = gr.DataFrame(label="Suggestions Based on Mood")
|
180 |
-
|
181 |
-
# Connect inputs and outputs
|
182 |
submit_button.click(
|
183 |
well_being_app,
|
184 |
-
inputs=[user_input,
|
185 |
-
outputs=[
|
186 |
)
|
187 |
|
188 |
-
# Launch
|
189 |
-
|
|
|
9 |
from nltk.tokenize import word_tokenize
|
10 |
from nltk.stem.lancaster import LancasterStemmer
|
11 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
|
|
|
|
12 |
import pandas as pd
|
13 |
import torch
|
14 |
|
15 |
+
# Disable GPU usage for TensorFlow
|
16 |
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
17 |
|
18 |
+
# Download required NLTK resources
|
19 |
nltk.download('punkt')
|
20 |
|
21 |
# Initialize Lancaster Stemmer
|
22 |
stemmer = LancasterStemmer()
|
23 |
|
24 |
+
# Load intents.json for the chatbot
|
25 |
with open("intents.json") as file:
|
26 |
intents_data = json.load(file)
|
27 |
|
28 |
+
# Load tokenized training data
|
29 |
with open("data.pickle", "rb") as f:
|
30 |
words, labels, training, output = pickle.load(f)
|
31 |
|
32 |
+
# Build the TFlearn model
|
33 |
def build_chatbot_model():
|
34 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
35 |
net = tflearn.fully_connected(net, 8)
|
|
|
42 |
|
43 |
chatbot_model = build_chatbot_model()
|
44 |
|
45 |
+
# Function: Bag of words
|
46 |
def bag_of_words(s, words):
|
47 |
bag = [0 for _ in range(len(words))]
|
48 |
s_words = word_tokenize(s)
|
|
|
53 |
bag[i] = 1
|
54 |
return np.array(bag)
|
55 |
|
56 |
+
# Chatbot response generator
|
57 |
def chatbot_response(message, history):
|
|
|
58 |
history = history or []
|
59 |
try:
|
60 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
61 |
+
idx = np.argmax(result)
|
62 |
+
tag = labels[idx]
|
63 |
+
response = "I'm not sure how to respond to that π€"
|
|
|
64 |
for intent in intents_data["intents"]:
|
65 |
if intent["tag"] == tag:
|
66 |
+
response = random.choice(intent["responses"])
|
67 |
break
|
68 |
except Exception as e:
|
69 |
response = f"Error generating response: {str(e)} π₯"
|
70 |
|
71 |
history.append({"role": "user", "content": f"π¬ {message}"})
|
72 |
+
history.append({"role": "assistant", "content": f"π€ {response}"})
|
73 |
return history, response
|
74 |
|
75 |
+
# Hugging Face transformers model for emotion detection
|
76 |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
77 |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
78 |
|
79 |
+
# Detect emotion
|
80 |
def detect_emotion(user_input):
|
|
|
81 |
pipe = pipeline("text-classification", model=emotion_model, tokenizer=emotion_tokenizer)
|
82 |
try:
|
83 |
result = pipe(user_input)
|
|
|
94 |
except Exception as e:
|
95 |
return f"Error detecting emotion: {str(e)} π₯"
|
96 |
|
97 |
+
# Sentiment analysis using Hugging Face
|
98 |
sentiment_tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
99 |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
100 |
|
|
|
104 |
try:
|
105 |
with torch.no_grad():
|
106 |
outputs = sentiment_model(**inputs)
|
107 |
+
sentiment = torch.argmax(outputs.logits, dim=1).item()
|
108 |
sentiment_map = ["Negative π", "Neutral π", "Positive π"]
|
109 |
+
return sentiment_map[sentiment]
|
110 |
except Exception as e:
|
111 |
return f"Error in sentiment analysis: {str(e)} π₯"
|
112 |
|
113 |
+
# Suggestions based on emotion
|
114 |
def generate_suggestions(emotion):
|
115 |
suggestions = {
|
116 |
"π Joy": [
|
117 |
+
{"Title": "Mindful Meditation π§ββοΈ", "Link": "https://www.helpguide.org/meditation"},
|
118 |
+
{"Title": "Explore a new skill π", "Link": "https://www.skillshare.com/"},
|
119 |
],
|
120 |
"π’ Sadness": [
|
121 |
+
{"Title": "Improve mental resilience β¨", "Link": "https://www.psychologytoday.com/"},
|
122 |
+
{"Title": "Reach out to a therapist π¬", "Link": "https://www.betterhelp.com/"},
|
123 |
],
|
124 |
"π Anger": [
|
125 |
+
{"Title": "Anger Management Guide π₯", "Link": "https://www.mentalhealth.org.uk/"},
|
126 |
+
{"Title": "Calming Exercises πΏ", "Link": "https://www.calm.com/"},
|
127 |
],
|
128 |
}
|
129 |
+
return suggestions.get(emotion, [{"Title": "General Wellness Resources π", "Link": "https://www.wellness.com/"}])
|
130 |
|
131 |
+
# Main App Function
|
132 |
+
def well_being_app(user_input, history):
|
133 |
+
"""Main function for chatbot, emotion detection, sentiment analysis, and suggestions."""
|
134 |
+
# Chatbot response
|
135 |
history, chatbot_reply = chatbot_response(user_input, history)
|
136 |
|
137 |
+
# Emotion detection
|
138 |
emotion = detect_emotion(user_input)
|
139 |
|
140 |
+
# Sentiment analysis
|
141 |
sentiment = analyze_sentiment(user_input)
|
142 |
|
143 |
+
# Generating suggestions
|
144 |
+
detected_emotion = emotion.split(": ")[-1]
|
145 |
+
suggestions = generate_suggestions(detected_emotion)
|
146 |
suggestions_df = pd.DataFrame(suggestions)
|
147 |
|
148 |
+
return history, sentiment, emotion, suggestions_df
|
149 |
+
|
150 |
+
# Custom CSS for Beautification
|
151 |
+
custom_css = """
|
152 |
+
body {
|
153 |
+
background: linear-gradient(135deg, #8e44ad, #3498db);
|
154 |
+
font-family: 'Arial', sans-serif;
|
155 |
+
color: white;
|
156 |
+
text-align: center;
|
157 |
+
}
|
158 |
+
#component-0 span {
|
159 |
+
color: #ffcccc;
|
160 |
+
}
|
161 |
+
button {
|
162 |
+
background-color: #1abc9c;
|
163 |
+
border: none;
|
164 |
+
color: white;
|
165 |
+
padding: 12px 24px;
|
166 |
+
text-align: center;
|
167 |
+
font-size: 16px;
|
168 |
+
border-radius: 8px;
|
169 |
+
cursor: pointer;
|
170 |
+
}
|
171 |
+
button:hover {
|
172 |
+
background-color: #16a085;
|
173 |
+
}
|
174 |
+
"""
|
175 |
+
|
176 |
+
# Gradio UI
|
177 |
+
with gr.Blocks(css=custom_css) as interface:
|
178 |
+
gr.Markdown("# πΈ **Mental Health & Well-Being Assistant**")
|
179 |
+
gr.Markdown("### Powered by NLP & AI")
|
180 |
|
|
|
|
|
181 |
with gr.Row():
|
182 |
+
user_input = gr.Textbox(lines=2, placeholder="How can I support you today?", label="Your Input")
|
183 |
+
|
184 |
with gr.Row():
|
185 |
+
submit_button = gr.Button("Submit", elem_id="submit")
|
|
|
|
|
186 |
|
187 |
with gr.Row():
|
188 |
+
chatbot_out = gr.Chatbot(label="Chat History")
|
189 |
+
sentiment_out = gr.Textbox(label="Sentiment")
|
190 |
+
emotion_out = gr.Textbox(label="Detected Emotion")
|
191 |
+
|
192 |
with gr.Row():
|
193 |
+
suggestions_out = gr.DataFrame(label="Suggestions", headers=["Title", "Link"])
|
|
|
|
|
194 |
|
|
|
|
|
|
|
|
|
195 |
submit_button.click(
|
196 |
well_being_app,
|
197 |
+
inputs=[user_input, chatbot_out],
|
198 |
+
outputs=[chatbot_out, sentiment_out, emotion_out, suggestions_out],
|
199 |
)
|
200 |
|
201 |
+
# Launch App
|
202 |
+
interface.launch()
|