Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,24 +12,24 @@ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipe
|
|
| 12 |
import pandas as pd
|
| 13 |
import torch
|
| 14 |
|
| 15 |
-
# Disable GPU
|
| 16 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 17 |
|
| 18 |
# Download necessary 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
|
| 33 |
def build_chatbot_model():
|
| 34 |
net = tflearn.input_data(shape=[None, len(training[0])])
|
| 35 |
net = tflearn.fully_connected(net, 8)
|
|
@@ -42,7 +42,7 @@ def build_chatbot_model():
|
|
| 42 |
|
| 43 |
chatbot_model = build_chatbot_model()
|
| 44 |
|
| 45 |
-
# Function: Bag of
|
| 46 |
def bag_of_words(s, words):
|
| 47 |
bag = [0 for _ in range(len(words))]
|
| 48 |
s_words = word_tokenize(s)
|
|
@@ -53,15 +53,15 @@ def bag_of_words(s, words):
|
|
| 53 |
bag[i] = 1
|
| 54 |
return np.array(bag)
|
| 55 |
|
| 56 |
-
# Chatbot
|
| 57 |
def chatbot_response(message, history):
|
| 58 |
-
"""Generates a
|
| 59 |
history = history or []
|
| 60 |
try:
|
| 61 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 62 |
idx = np.argmax(result)
|
| 63 |
tag = labels[idx]
|
| 64 |
-
response = "I'
|
| 65 |
for intent in intents_data["intents"]:
|
| 66 |
if intent["tag"] == tag:
|
| 67 |
response = random.choice(intent["responses"])
|
|
@@ -69,11 +69,11 @@ def chatbot_response(message, history):
|
|
| 69 |
except Exception as e:
|
| 70 |
response = f"Error generating response: {str(e)} π₯"
|
| 71 |
|
| 72 |
-
|
| 73 |
-
history.append(
|
| 74 |
return history, response
|
| 75 |
|
| 76 |
-
# Emotion
|
| 77 |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 78 |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 79 |
|
|
@@ -94,12 +94,12 @@ def detect_emotion(user_input):
|
|
| 94 |
except Exception as e:
|
| 95 |
return f"Error detecting emotion: {str(e)} π₯"
|
| 96 |
|
| 97 |
-
# Sentiment
|
| 98 |
sentiment_tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 99 |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 100 |
|
| 101 |
def analyze_sentiment(user_input):
|
| 102 |
-
"""Analyze sentiment
|
| 103 |
inputs = sentiment_tokenizer(user_input, return_tensors="pt")
|
| 104 |
try:
|
| 105 |
with torch.no_grad():
|
|
@@ -110,37 +110,40 @@ def analyze_sentiment(user_input):
|
|
| 110 |
except Exception as e:
|
| 111 |
return f"Error in sentiment analysis: {str(e)} π₯"
|
| 112 |
|
| 113 |
-
# Suggestions
|
| 114 |
def generate_suggestions(emotion):
|
| 115 |
-
|
| 116 |
"π Joy": [
|
| 117 |
{"Title": "Mindful Meditation π§", "Link": "https://www.helpguide.org/meditation"},
|
| 118 |
-
{"Title": "Learn a
|
| 119 |
],
|
| 120 |
"π’ Sadness": [
|
| 121 |
-
{"Title": "Talk to a
|
| 122 |
-
{"Title": "Mental
|
| 123 |
],
|
| 124 |
"π Anger": [
|
| 125 |
{"Title": "Anger Management Tips π₯", "Link": "https://www.mentalhealth.org.uk"},
|
| 126 |
{"Title": "Stress Relieving Exercises πΏ", "Link": "https://www.calm.com/"},
|
| 127 |
],
|
| 128 |
}
|
| 129 |
-
return
|
| 130 |
|
| 131 |
-
# Dummy
|
| 132 |
def search_nearby_professionals(location, query):
|
| 133 |
-
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
| 140 |
def well_being_app(user_input, location, query, history):
|
| 141 |
-
"""
|
| 142 |
-
# Chatbot
|
| 143 |
-
history,
|
| 144 |
|
| 145 |
# Emotion Detection
|
| 146 |
emotion = detect_emotion(user_input)
|
|
@@ -148,83 +151,52 @@ def well_being_app(user_input, location, query, history):
|
|
| 148 |
# Sentiment Analysis
|
| 149 |
sentiment = analyze_sentiment(user_input)
|
| 150 |
|
| 151 |
-
# Suggestions
|
| 152 |
-
|
| 153 |
-
suggestions = generate_suggestions(
|
| 154 |
suggestions_df = pd.DataFrame(suggestions)
|
| 155 |
|
| 156 |
-
# Nearby Professionals
|
| 157 |
professionals = search_nearby_professionals(location, query)
|
| 158 |
|
| 159 |
return history, sentiment, emotion, suggestions_df, professionals
|
| 160 |
|
| 161 |
-
#
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
color: black;
|
| 167 |
-
}
|
| 168 |
-
button {
|
| 169 |
-
background-color: #1abc9c;
|
| 170 |
-
color: white;
|
| 171 |
-
padding: 10px 20px;
|
| 172 |
-
font-size: 16px;
|
| 173 |
-
border-radius: 8px;
|
| 174 |
-
cursor: pointer;
|
| 175 |
-
}
|
| 176 |
-
button:hover {
|
| 177 |
-
background-color: #16a085;
|
| 178 |
-
}
|
| 179 |
-
textarea, input[type="text"] {
|
| 180 |
-
background: #ffffff;
|
| 181 |
-
color: #000000;
|
| 182 |
-
font-size: 14px;
|
| 183 |
-
border: 1px solid #ced4da;
|
| 184 |
-
padding: 10px;
|
| 185 |
-
border-radius: 5px;
|
| 186 |
-
}
|
| 187 |
-
"""
|
| 188 |
-
|
| 189 |
-
# Gradio UI
|
| 190 |
-
with gr.Blocks(css=custom_css) as interface:
|
| 191 |
-
gr.Markdown("# π± **Well-being Companion**")
|
| 192 |
-
gr.Markdown("### Empowering Your Mental Health Journey with AI π")
|
| 193 |
-
|
| 194 |
-
# Input Section
|
| 195 |
with gr.Row():
|
| 196 |
-
gr.Textbox(label="Your Message",
|
| 197 |
-
gr.Textbox(label="Location", placeholder="Enter your
|
| 198 |
-
gr.Textbox(label="Search Query", placeholder="
|
| 199 |
-
submit_button = gr.Button("Submit")
|
| 200 |
|
| 201 |
# Chatbot Section
|
| 202 |
-
|
| 203 |
-
chatbot_title = "### Chatbot Response"
|
| 204 |
-
chatbot_output = gr.Chatbot(label=None)
|
| 205 |
|
| 206 |
-
# Sentiment and Emotion
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
sentiment_output = gr.Textbox(label=None)
|
| 210 |
-
gr.Markdown("### Detected Emotion")
|
| 211 |
-
emotion_output = gr.Textbox(label=None)
|
| 212 |
|
| 213 |
-
# Suggestions
|
| 214 |
-
|
| 215 |
-
gr.Markdown("### Suggestions")
|
| 216 |
-
suggestions_output = gr.DataFrame(headers=["Title", "Link"], interactive=False, max_height=300)
|
| 217 |
|
| 218 |
-
#
|
| 219 |
-
|
| 220 |
-
gr.Markdown("### Nearby Professionals")
|
| 221 |
-
location_output = gr.DataFrame(headers=["Name", "Address"], interactive=False, max_height=300)
|
| 222 |
|
|
|
|
| 223 |
submit_button.click(
|
| 224 |
well_being_app,
|
| 225 |
-
inputs=[
|
| 226 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
)
|
| 228 |
|
| 229 |
-
#
|
| 230 |
interface.launch()
|
|
|
|
| 12 |
import pandas as pd
|
| 13 |
import torch
|
| 14 |
|
| 15 |
+
# Disable TensorFlow GPU warnings (safe since we are using CPU)
|
| 16 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 17 |
|
| 18 |
# Download necessary NLTK resources
|
| 19 |
nltk.download("punkt")
|
| 20 |
|
| 21 |
+
# Initialize Lancaster Stemmer for text preprocessing
|
| 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 for chatbot
|
| 29 |
with open("data.pickle", "rb") as f:
|
| 30 |
words, labels, training, output = pickle.load(f)
|
| 31 |
|
| 32 |
+
# Build TFlearn Chatbot 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 Function
|
| 57 |
def chatbot_response(message, history):
|
| 58 |
+
"""Generates a chatbot response."""
|
| 59 |
history = history or []
|
| 60 |
try:
|
| 61 |
result = chatbot_model.predict([bag_of_words(message, words)])
|
| 62 |
idx = np.argmax(result)
|
| 63 |
tag = labels[idx]
|
| 64 |
+
response = "I didn't understand that. π€"
|
| 65 |
for intent in intents_data["intents"]:
|
| 66 |
if intent["tag"] == tag:
|
| 67 |
response = random.choice(intent["responses"])
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
response = f"Error generating response: {str(e)} π₯"
|
| 71 |
|
| 72 |
+
history.append({"role": "user", "content": message})
|
| 73 |
+
history.append({"role": "assistant", "content": response})
|
| 74 |
return history, response
|
| 75 |
|
| 76 |
+
# Emotion Detection Function
|
| 77 |
emotion_tokenizer = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 78 |
emotion_model = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
|
| 79 |
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
return f"Error detecting emotion: {str(e)} π₯"
|
| 96 |
|
| 97 |
+
# Sentiment Analysis Function
|
| 98 |
sentiment_tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 99 |
sentiment_model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
| 100 |
|
| 101 |
def analyze_sentiment(user_input):
|
| 102 |
+
"""Analyze sentiment based on input."""
|
| 103 |
inputs = sentiment_tokenizer(user_input, return_tensors="pt")
|
| 104 |
try:
|
| 105 |
with torch.no_grad():
|
|
|
|
| 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_map = {
|
| 116 |
"π Joy": [
|
| 117 |
{"Title": "Mindful Meditation π§", "Link": "https://www.helpguide.org/meditation"},
|
| 118 |
+
{"Title": "Learn a New Skill β¨", "Link": "https://www.skillshare.com/"},
|
| 119 |
],
|
| 120 |
"π’ Sadness": [
|
| 121 |
+
{"Title": "Talk to a Professional π¬", "Link": "https://www.betterhelp.com/"},
|
| 122 |
+
{"Title": "Mental Health Toolkit π οΈ", "Link": "https://www.psychologytoday.com/"},
|
| 123 |
],
|
| 124 |
"π Anger": [
|
| 125 |
{"Title": "Anger Management Tips π₯", "Link": "https://www.mentalhealth.org.uk"},
|
| 126 |
{"Title": "Stress Relieving Exercises πΏ", "Link": "https://www.calm.com/"},
|
| 127 |
],
|
| 128 |
}
|
| 129 |
+
return suggestions_map.get(emotion, [{"Title": "General Wellness Resources π", "Link": "https://www.helpguide.org/wellness"}])
|
| 130 |
|
| 131 |
+
# Dummy Nearby Professionals Function
|
| 132 |
def search_nearby_professionals(location, query):
|
| 133 |
+
"""Simulates the search for nearby professionals."""
|
| 134 |
+
if location and query:
|
| 135 |
+
return [
|
| 136 |
+
{"Name": "Wellness Center", "Address": "123 Wellness Way"},
|
| 137 |
+
{"Name": "Mental Health Clinic", "Address": "456 Recovery Road"},
|
| 138 |
+
{"Name": "Therapy Hub", "Address": "789 Peace Avenue"},
|
| 139 |
+
]
|
| 140 |
+
return []
|
| 141 |
+
|
| 142 |
+
# Main App Logic
|
| 143 |
def well_being_app(user_input, location, query, history):
|
| 144 |
+
"""Handles chatbot interaction, emotion detection, sentiment analysis, and professional search results."""
|
| 145 |
+
# Chatbot Response
|
| 146 |
+
history, _ = chatbot_response(user_input, history)
|
| 147 |
|
| 148 |
# Emotion Detection
|
| 149 |
emotion = detect_emotion(user_input)
|
|
|
|
| 151 |
# Sentiment Analysis
|
| 152 |
sentiment = analyze_sentiment(user_input)
|
| 153 |
|
| 154 |
+
# Emotion-based Suggestions
|
| 155 |
+
emotion_name = emotion.split(": ")[-1]
|
| 156 |
+
suggestions = generate_suggestions(emotion_name)
|
| 157 |
suggestions_df = pd.DataFrame(suggestions)
|
| 158 |
|
| 159 |
+
# Nearby Professionals Lookup
|
| 160 |
professionals = search_nearby_professionals(location, query)
|
| 161 |
|
| 162 |
return history, sentiment, emotion, suggestions_df, professionals
|
| 163 |
|
| 164 |
+
# Gradio Interface
|
| 165 |
+
with gr.Blocks() as interface:
|
| 166 |
+
gr.Markdown("## π± Well-being Companion")
|
| 167 |
+
gr.Markdown("> Empowering Your Health! π")
|
| 168 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
with gr.Row():
|
| 170 |
+
user_input = gr.Textbox(label="Your Message", placeholder="How are you feeling today? (e.g. I feel happy)")
|
| 171 |
+
location_input = gr.Textbox(label="Location", placeholder="Enter your city (e.g., New York)")
|
| 172 |
+
query_input = gr.Textbox(label="Search Query", placeholder="What are you searching for? (e.g., therapists)")
|
| 173 |
+
submit_button = gr.Button("Submit", variant="primary")
|
| 174 |
|
| 175 |
# Chatbot Section
|
| 176 |
+
chatbot_output = gr.Chatbot(label="Chatbot Interaction", type="messages", value=[])
|
|
|
|
|
|
|
| 177 |
|
| 178 |
+
# Sentiment and Emotion Outputs
|
| 179 |
+
sentiment_output = gr.Textbox(label="Sentiment Analysis")
|
| 180 |
+
emotion_output = gr.Textbox(label="Emotion Detected")
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
# Suggestions Table
|
| 183 |
+
suggestions_output = gr.DataFrame(label="Suggestions", value=[], headers=["Title", "Link"])
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
# Professionals Table
|
| 186 |
+
nearby_professionals_output = gr.DataFrame(label="Nearby Professionals", value=[], headers=["Name", "Address"])
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
# Connect Inputs to Outputs
|
| 189 |
submit_button.click(
|
| 190 |
well_being_app,
|
| 191 |
+
inputs=[user_input, location_input, query_input, chatbot_output],
|
| 192 |
+
outputs=[
|
| 193 |
+
chatbot_output,
|
| 194 |
+
sentiment_output,
|
| 195 |
+
emotion_output,
|
| 196 |
+
suggestions_output,
|
| 197 |
+
nearby_professionals_output,
|
| 198 |
+
],
|
| 199 |
)
|
| 200 |
|
| 201 |
+
# Run Gradio Application
|
| 202 |
interface.launch()
|