DreamStream-1 commited on
Commit
7479a23
Β·
verified Β·
1 Parent(s): f0734be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -65
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 for compatibility
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
19
 
20
- # Download necessary NLTK resources
21
  nltk.download('punkt')
22
 
23
  # Initialize Lancaster Stemmer
24
  stemmer = LancasterStemmer()
25
 
26
- # Load intents.json for Chatbot
27
  with open("intents.json") as file:
28
  intents_data = json.load(file)
29
 
30
- # Load tokenized data for Chatbot
31
  with open("data.pickle", "rb") as f:
32
  words, labels, training, output = pickle.load(f)
33
 
34
- # Build Chatbot Model
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 Words Function for Chatbot
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 Response Function
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
- result_index = np.argmax(result)
65
- tag = labels[result_index]
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 = f"πŸ€– {random.choice(intent['responses'])}"
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
- # Emotion Detection with Transformers
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 Analysis
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
- sentiment_class = torch.argmax(outputs.logits, dim=1).item()
112
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
113
- return f"Sentiment: {sentiment_map[sentiment_class]}"
114
  except Exception as e:
115
  return f"Error in sentiment analysis: {str(e)} πŸ’₯"
116
 
117
- # Generate Suggestions Based on Emotion
118
  def generate_suggestions(emotion):
119
  suggestions = {
120
  "😊 Joy": [
121
- {"Title": "Meditation Techniques", "Link": "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"},
122
- {"Title": "Learn Something New", "Link": "https://www.edx.org/"},
123
  ],
124
  "😒 Sadness": [
125
- {"Title": "Emotional Wellness Toolkit", "Link": "https://www.nih.gov/health-information/emotional-wellness-toolkit"},
126
- {"Title": "Relaxation Videos", "Link": "https://youtu.be/-e-4Kx5px_I"},
127
  ],
128
  "😠 Anger": [
129
- {"Title": "Dealing with Anger", "Link": "https://www.helpguide.org/articles/anger/anger-management.htm"},
130
- {"Title": "Stress Reducing Tips", "Link": "https://www.webmd.com/stress-management"},
131
  ],
132
  }
133
- return suggestions.get(emotion, [{"Title": "General Tips", "Link": "https://www.psychologytoday.com/"}])
134
 
135
- # Gradio Interface Main Function
136
- def well_being_app(user_input, location, query, history):
137
- """Main app combining chatbot, emotion detection, sentiment, suggestions, and map."""
138
- # Chatbot Interaction
139
  history, chatbot_reply = chatbot_response(user_input, history)
140
 
141
- # Emotion Detection
142
  emotion = detect_emotion(user_input)
143
 
144
- # Sentiment Analysis
145
  sentiment = analyze_sentiment(user_input)
146
 
147
- # Suggestions Based on Emotion
148
- emotion_label = emotion.split(": ")[-1]
149
- suggestions = generate_suggestions(emotion_label)
150
  suggestions_df = pd.DataFrame(suggestions)
151
 
152
- # Return Outputs
153
- return (
154
- history,
155
- sentiment,
156
- emotion,
157
- suggestions_df
158
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- # Gradio Interface UI
161
- with gr.Blocks() as app:
162
  with gr.Row():
163
- gr.Markdown("# 🌼 Well-Being Support Application")
164
-
165
  with gr.Row():
166
- user_input = gr.Textbox(lines=2, placeholder="Type your message here...", label="Your Message")
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
- submit_button = gr.Button(value="Submit", label="Submit")
172
-
 
 
173
  with gr.Row():
174
- chatbot = gr.Chatbot(label="Chat History")
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, location, query, chatbot],
185
- outputs=[chatbot, sentiment_output, emotion_output, suggestions_output],
186
  )
187
 
188
- # Launch the app
189
- app.launch()
 
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()