DreamStream-1 commited on
Commit
9e5813b
Β·
verified Β·
1 Parent(s): 6858546

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -83
app.py CHANGED
@@ -17,35 +17,40 @@ import torch
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
19
 
20
- # Suppress TensorFlow GPU warnings & logs
21
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
22
 
23
- # Download NLTK resources
24
  nltk.download("punkt")
25
 
26
- # Initialize Lancaster Stemmer
27
  stemmer = LancasterStemmer()
28
 
29
- # Load intents.json for the chatbot
30
  with open("intents.json") as file:
31
  intents_data = json.load(file)
32
 
33
- # Load preprocessed data for Well-Being Chatbot
34
  with open("data.pickle", "rb") as f:
35
  words, labels, training, output = pickle.load(f)
36
 
37
- # Build TFlearn Chatbot Model
38
  net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32)
39
  net = tflearn.fully_connected(net, 8)
40
  net = tflearn.fully_connected(net, 8)
41
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
42
  net = tflearn.regression(net)
43
-
44
- # Load and initialize the trained model
45
  chatbot_model = tflearn.DNN(net)
46
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
47
 
48
- # Function to process user input into a bag-of-words format
 
 
 
 
 
 
 
 
49
  def bag_of_words(s, words):
50
  bag = [0 for _ in range(len(words))]
51
  s_words = word_tokenize(s)
@@ -56,29 +61,26 @@ def bag_of_words(s, words):
56
  bag[i] = 1
57
  return np.array(bag)
58
 
59
- # Chatbot Response Function
60
  def chatbot(message, history):
61
  history = history or []
62
- message = message.lower()
63
  try:
64
  results = chatbot_model.predict([bag_of_words(message, words)])
65
  tag = labels[np.argmax(results)]
66
-
67
- response = "I'm not sure how to respond to that. πŸ€”"
68
  for intent in intents_data["intents"]:
69
  if intent["tag"] == tag:
70
  response = random.choice(intent["responses"])
71
  break
 
 
72
  except Exception as e:
73
  response = f"Error: {str(e)} πŸ’₯"
 
74
  history.append({"role": "user", "content": message})
75
  history.append({"role": "assistant", "content": response})
76
  return history, response
77
 
78
- # Sentiment Analysis Function
79
- tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
80
- model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
81
-
82
  def analyze_sentiment(user_input):
83
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
84
  with torch.no_grad():
@@ -87,10 +89,7 @@ def analyze_sentiment(user_input):
87
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
88
  return sentiment_map[sentiment_class]
89
 
90
- # Emotion Detection Function
91
- tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
92
- model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
93
-
94
  def detect_emotion(user_input):
95
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
96
  result = pipe(user_input)
@@ -105,63 +104,44 @@ def detect_emotion(user_input):
105
  }
106
  return emotion_map.get(emotion, "Unknown Emotion πŸ€”")
107
 
108
- # Health Professionals Search
109
- gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
110
-
111
- def get_health_professionals_and_map(location, query):
112
- """Search for health professionals and generate a map."""
113
- try:
114
- geo_location = gmaps.geocode(location)
115
- if geo_location:
116
- lat, lng = geo_location[0]["geometry"]["location"].values()
117
- places_result = gmaps.places_nearby(
118
- location=(lat, lng), radius=10000, type="doctor", keyword=query
119
- ).get("results", [])
120
-
121
- # Create map
122
- m = folium.Map(location=(lat, lng), zoom_start=13)
123
- for place in places_result:
124
- folium.Marker(
125
- location=[
126
- place["geometry"]["location"]["lat"],
127
- place["geometry"]["location"]["lng"],
128
- ],
129
- popup=place["name"],
130
- ).add_to(m)
131
- map_html = m._repr_html_()
132
- professionals_info = [
133
- f"{place['name']} - {place.get('vicinity', 'No address available')}"
134
- for place in places_result
135
- ]
136
- return "\n".join(professionals_info), map_html
137
- return "Unable to find location", ""
138
- except Exception as e:
139
- return f"Error: {e}", ""
140
-
141
- # Suggestions Based on Emotion
142
  def generate_suggestions(emotion):
143
  suggestions = {
144
  "😊 Joy": [
145
- {"Title": "Meditation 🧘", "Subject": "Relaxation", "Link": "https://example.com/meditation"},
146
- {"Title": "Learn a skill πŸš€", "Subject": "Growth", "Link": "https://example.com/skills"},
 
 
 
 
 
 
 
 
147
  ],
148
  "😒 Sadness": [
149
- {"Title": "Therapist Help πŸ’¬", "Subject": "Support", "Link": "https://example.com/therapist"},
150
- {"Title": "Stress Management 🌿", "Subject": "Wellness", "Link": "https://example.com/stress"},
 
 
 
 
 
 
 
151
  ],
152
  }
153
- return suggestions.get(emotion.split(" ")[1].lower(), [])
154
 
155
- # Main Gradio App Function
156
  def app_function(message, location, query, history):
157
  chatbot_history, _ = chatbot(message, history)
158
  sentiment = analyze_sentiment(message)
159
  emotion = detect_emotion(message)
160
  suggestions = generate_suggestions(emotion)
161
- places_info, map_html = get_health_professionals_and_map(location, query)
162
- return chatbot_history, sentiment, emotion, suggestions, map_html, places_info
163
 
164
- # Gradio Interface
165
  with gr.Blocks() as demo:
166
  gr.Markdown("# 🌟 Well-being Companion")
167
  gr.Markdown("Empowering your mental health journey πŸ’š")
@@ -172,29 +152,15 @@ with gr.Blocks() as demo:
172
  query_input = gr.Textbox(label="Search Query", placeholder="Enter query (e.g., therapist)...", lines=1)
173
  submit_btn = gr.Button("Submit")
174
 
175
- with gr.Row():
176
- chatbot_output = gr.Chatbot(label="Chat History", type="messages")
177
- with gr.Row():
178
- sentiment_output = gr.Textbox(label="Sentiment Analysis")
179
- emotion_output = gr.Textbox(label="Emotion Detected")
180
- with gr.Row():
181
- suggestions_output = gr.DataFrame(label="Suggestions", headers=["Title", "Subject", "Link"])
182
- with gr.Row():
183
- map_display = gr.HTML(label="Map of Nearby Professionals")
184
- health_info_output = gr.Textbox(label="Health Professionals Info", lines=5)
185
 
186
- # Button interaction
187
  submit_btn.click(
188
  app_function,
189
  inputs=[user_input, location_input, query_input, chatbot_output],
190
- outputs=[
191
- chatbot_output,
192
- sentiment_output,
193
- emotion_output,
194
- suggestions_output,
195
- map_display,
196
- health_info_output,
197
- ],
198
  )
199
 
200
  demo.launch()
 
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
19
 
20
+ # Suppress TensorFlow warnings
21
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
22
 
23
+ # Download necessary NLTK resources
24
  nltk.download("punkt")
25
 
26
+ # Initialize a stemmer for NLP
27
  stemmer = LancasterStemmer()
28
 
29
+ # Load chatbot intents and training data
30
  with open("intents.json") as file:
31
  intents_data = json.load(file)
32
 
 
33
  with open("data.pickle", "rb") as f:
34
  words, labels, training, output = pickle.load(f)
35
 
36
+ # Build the chatbot's neural network model
37
  net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32)
38
  net = tflearn.fully_connected(net, 8)
39
  net = tflearn.fully_connected(net, 8)
40
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
41
  net = tflearn.regression(net)
 
 
42
  chatbot_model = tflearn.DNN(net)
43
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
44
 
45
+ # Tokenizer and model for sentiment analysis (Hugging Face)
46
+ tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
47
+ model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
48
+
49
+ # Tokenizer and model for emotion detection (Hugging Face)
50
+ tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
51
+ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
52
+
53
+ # Function to process input for TensorFlow model
54
  def bag_of_words(s, words):
55
  bag = [0 for _ in range(len(words))]
56
  s_words = word_tokenize(s)
 
61
  bag[i] = 1
62
  return np.array(bag)
63
 
64
+ # Chatbot response function
65
  def chatbot(message, history):
66
  history = history or []
 
67
  try:
68
  results = chatbot_model.predict([bag_of_words(message, words)])
69
  tag = labels[np.argmax(results)]
 
 
70
  for intent in intents_data["intents"]:
71
  if intent["tag"] == tag:
72
  response = random.choice(intent["responses"])
73
  break
74
+ else:
75
+ response = "I'm not sure how to respond to that. πŸ€”"
76
  except Exception as e:
77
  response = f"Error: {str(e)} πŸ’₯"
78
+
79
  history.append({"role": "user", "content": message})
80
  history.append({"role": "assistant", "content": response})
81
  return history, response
82
 
83
+ # Sentiment analysis
 
 
 
84
  def analyze_sentiment(user_input):
85
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
86
  with torch.no_grad():
 
89
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
90
  return sentiment_map[sentiment_class]
91
 
92
+ # Emotion detection
 
 
 
93
  def detect_emotion(user_input):
94
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
95
  result = pipe(user_input)
 
104
  }
105
  return emotion_map.get(emotion, "Unknown Emotion πŸ€”")
106
 
107
+ # Generate emotion-based suggestions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  def generate_suggestions(emotion):
109
  suggestions = {
110
  "😊 Joy": [
111
+ ["Relaxation Techniques", "Relaxation", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
112
+ ["Dealing with Stress", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
113
+ ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
114
+ ["Relaxation Videos", "Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
115
+ ],
116
+ "😠 Anger": [
117
+ ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
118
+ ["Stress Management Tips", "Stress Management", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
119
+ ["Dealing with Anger", "Anger Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
120
+ ["Relaxation Videos", "Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>']
121
  ],
122
  "😒 Sadness": [
123
+ ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
124
+ ["Dealing with Anxiety", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
125
+ ["Relaxation Videos", "Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
126
+ ],
127
+ "😨 Fear": [
128
+ ["Mindfulness Practices", "Mindfulness", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
129
+ ["Coping with Anxiety", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
130
+ ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
131
+ ["Relaxation Videos", "Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
132
  ],
133
  }
134
+ return suggestions.get(emotion.split(" ")[1], [["No specific suggestions available", "", ""]])
135
 
136
+ # Main app function
137
  def app_function(message, location, query, history):
138
  chatbot_history, _ = chatbot(message, history)
139
  sentiment = analyze_sentiment(message)
140
  emotion = detect_emotion(message)
141
  suggestions = generate_suggestions(emotion)
142
+ return chatbot_history, sentiment, emotion, suggestions
 
143
 
144
+ # Gradio UI
145
  with gr.Blocks() as demo:
146
  gr.Markdown("# 🌟 Well-being Companion")
147
  gr.Markdown("Empowering your mental health journey πŸ’š")
 
152
  query_input = gr.Textbox(label="Search Query", placeholder="Enter query (e.g., therapist)...", lines=1)
153
  submit_btn = gr.Button("Submit")
154
 
155
+ chatbot_output = gr.Chatbot(label="Chat History", type="messages")
156
+ sentiment_output = gr.Textbox(label="Sentiment Analysis")
157
+ emotion_output = gr.Textbox(label="Emotion Detected")
158
+ suggestions_output = gr.DataFrame(label="Suggestions", headers=["Title", "Subject", "Link"])
 
 
 
 
 
 
159
 
 
160
  submit_btn.click(
161
  app_function,
162
  inputs=[user_input, location_input, query_input, chatbot_output],
163
+ outputs=[chatbot_output, sentiment_output, emotion_output, suggestions_output],
 
 
 
 
 
 
 
164
  )
165
 
166
  demo.launch()