DreamStream-1 commited on
Commit
9508310
Β·
verified Β·
1 Parent(s): 5d0e15d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -92
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 usage for TensorFlow compatibility
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 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,7 +42,7 @@ def build_chatbot_model():
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,15 +53,15 @@ def bag_of_words(s, words):
53
  bag[i] = 1
54
  return np.array(bag)
55
 
56
- # Chatbot response generator
57
  def chatbot_response(message, history):
58
- """Generates a response from the chatbot and appends it to the history."""
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'm not sure how to respond to that. πŸ€”"
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
- # Format output as tuples for Gradio Chatbot compatibility
73
- history.append((message, response))
74
  return history, response
75
 
76
- # Emotion detection transformer model
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 analysis model
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 of user input."""
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 based on emotion
114
  def generate_suggestions(emotion):
115
- suggestions = {
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.get(emotion, [{"Title": "Wellness Resources 🌈", "Link": "https://www.helpguide.org/wellness"}])
130
 
131
- # Dummy Function for Location Query Simulation (replace this with actual map/search integration)
132
  def search_nearby_professionals(location, query):
133
- """Simulate searching for nearby professionals and returning results."""
134
- return [
135
- {"Name": "Wellness Center One", "Address": "123 Wellness Way"},
136
- {"Name": "Mental Health Clinic", "Address": "456 Recovery Road"},
137
- {"Name": "Therapists Hub", "Address": "789 Peace Avenue"},
138
- ] if location and query else []
139
-
 
 
 
140
  def well_being_app(user_input, location, query, history):
141
- """Main function for chatbot, emotion detection, sentiment, suggestions, and location query."""
142
- # Chatbot response
143
- history, chatbot_reply = chatbot_response(user_input, 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
- detected_emotion = emotion.split(": ")[-1]
153
- suggestions = generate_suggestions(detected_emotion)
154
  suggestions_df = pd.DataFrame(suggestions)
155
 
156
- # Nearby Professionals (Location Query)
157
  professionals = search_nearby_professionals(location, query)
158
 
159
  return history, sentiment, emotion, suggestions_df, professionals
160
 
161
- # Custom CSS for beautification
162
- custom_css = """
163
- body {
164
- background: linear-gradient(135deg, #28a745, #218838);
165
- font-family: Arial, sans-serif;
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", lines=2, placeholder="How can I support you today?", elem_id="message_input")
197
- gr.Textbox(label="Location", placeholder="Enter your location (e.g., New York City)")
198
- gr.Textbox(label="Search Query", placeholder="Professionals nearby? (e.g., doctors, therapists)")
199
- submit_button = gr.Button("Submit")
200
 
201
  # Chatbot Section
202
- with gr.Row():
203
- chatbot_title = "### Chatbot Response"
204
- chatbot_output = gr.Chatbot(label=None)
205
 
206
- # Sentiment and Emotion Section
207
- with gr.Row():
208
- gr.Markdown("### Sentiment Analysis")
209
- sentiment_output = gr.Textbox(label=None)
210
- gr.Markdown("### Detected Emotion")
211
- emotion_output = gr.Textbox(label=None)
212
 
213
- # Suggestions Section
214
- with gr.Row():
215
- gr.Markdown("### Suggestions")
216
- suggestions_output = gr.DataFrame(headers=["Title", "Link"], interactive=False, max_height=300)
217
 
218
- # Location Search Results Section
219
- with gr.Row():
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=["message_input", "Location", "Search Query", chatbot_output],
226
- outputs=[chatbot_output, sentiment_output, emotion_output, suggestions_output, location_output],
 
 
 
 
 
 
227
  )
228
 
229
- # Launch the app
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()