DreamStream-1 commited on
Commit
6858546
Β·
verified Β·
1 Parent(s): 3fa01c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -116
app.py CHANGED
@@ -17,76 +17,65 @@ import torch
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
19
 
20
- # Suppress warnings related to missing CUDA libraries
21
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
22
 
23
- # Ensure necessary NLTK resources are downloaded
24
- try:
25
- nltk.download('punkt')
26
- except Exception as e:
27
- print(f"Error downloading NLTK data: {e}")
28
 
29
- # Initialize the stemmer
30
  stemmer = LancasterStemmer()
31
 
32
- # Load intents.json for Well-Being Chatbot
33
  with open("intents.json") as file:
34
- data = json.load(file)
35
 
36
  # Load preprocessed data for Well-Being Chatbot
37
  with open("data.pickle", "rb") as f:
38
  words, labels, training, output = pickle.load(f)
39
 
40
- # Build the model structure for Well-Being Chatbot
41
- net = tflearn.input_data(shape=[None, len(training[0])], dtype=tf.float32) # Fix for dtype
42
  net = tflearn.fully_connected(net, 8)
43
  net = tflearn.fully_connected(net, 8)
44
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
45
  net = tflearn.regression(net)
46
 
47
- # Load the trained model
48
- model = tflearn.DNN(net)
49
- model.load("MentalHealthChatBotmodel.tflearn")
50
 
51
- # Function to process user input into a bag-of-words format for Chatbot
52
  def bag_of_words(s, words):
53
  bag = [0 for _ in range(len(words))]
54
  s_words = word_tokenize(s)
55
- s_words = [stemmer.stem(word.lower()) for word in s_words if word.lower() in words]
56
  for se in s_words:
57
  for i, w in enumerate(words):
58
  if w == se:
59
  bag[i] = 1
60
  return np.array(bag)
61
 
62
- # Chat function for Well-Being Chatbot
63
  def chatbot(message, history):
64
  history = history or []
65
  message = message.lower()
66
  try:
67
- # Predict the tag
68
- results = model.predict([bag_of_words(message, words)])
69
- results_index = np.argmax(results)
70
- tag = labels[results_index]
71
-
72
- # Match tag with intent and choose a random response
73
- for tg in data["intents"]:
74
- if tg['tag'] == tag:
75
- responses = tg['responses']
76
- response = random.choice(responses)
77
  break
78
- else:
79
- response = "I'm sorry, I didn't understand that. Could you please rephrase?"
80
  except Exception as e:
81
- response = f"An error occurred: {str(e)}"
82
-
83
- # Convert the new message and response to the 'messages' format
84
  history.append({"role": "user", "content": message})
85
  history.append({"role": "assistant", "content": response})
86
-
87
- return history, history
88
 
89
- # Sentiment Analysis using Hugging Face model
90
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
91
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
92
 
@@ -94,103 +83,118 @@ def analyze_sentiment(user_input):
94
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
95
  with torch.no_grad():
96
  outputs = model_sentiment(**inputs)
97
- predicted_class = torch.argmax(outputs.logits, dim=1).item()
98
- sentiment = ["Negative", "Neutral", "Positive"][predicted_class] # Assuming 3 classes
99
- return f"Predicted Sentiment: {sentiment}"
100
 
101
- # Emotion Detection using Hugging Face model
102
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
103
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
104
 
105
  def detect_emotion(user_input):
106
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
107
  result = pipe(user_input)
108
- emotion = result[0]['label']
109
- return f"Emotion Detected: {emotion}"
 
 
 
 
 
 
 
 
110
 
111
- # Initialize Google Maps API client securely
112
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
113
 
114
- # Function to search for health professionals
115
- def search_health_professionals(query, location, radius=10000):
116
- places_result = gmaps.places_nearby(location, radius=radius, type='doctor', keyword=query)
117
- return places_result.get('results', [])
118
-
119
- # Function to get directions and display on Gradio UI
120
- def get_health_professionals_and_map(current_location, health_professional_query):
121
- location = gmaps.geocode(current_location)
122
- if location:
123
- lat = location[0]["geometry"]["location"]["lat"]
124
- lng = location[0]["geometry"]["location"]["lng"]
125
- location = (lat, lng)
126
-
127
- professionals = search_health_professionals(health_professional_query, location)
128
-
129
- # Generate map
130
- map_center = location
131
- m = folium.Map(location=map_center, zoom_start=13)
132
-
133
- # Add markers to the map
134
- for place in professionals:
135
- folium.Marker(
136
- location=[place['geometry']['location']['lat'], place['geometry']['location']['lng']],
137
- popup=place['name']
138
- ).add_to(m)
139
-
140
- # Convert map to HTML for Gradio display
141
- map_html = m._repr_html_()
142
-
143
- # Route information
144
- route_info = "\n".join([f"{place['name']} - {place['vicinity']}" for place in professionals])
145
-
146
- return route_info, map_html
147
- else:
148
- return "Unable to find location.", ""
149
-
150
- # Function to generate suggestions based on the detected emotion
151
  def generate_suggestions(emotion):
152
  suggestions = {
153
- 'joy': [
154
- {"Title": "Relaxation Techniques 🌿", "Subject": "Relaxation", "Link": '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Mindful Breathing Meditation</a>'},
155
- {"Title": "Dealing with Stress πŸ’†", "Subject": "Stress Management", "Link": '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Tips for Dealing with Anxiety</a>'},
156
- {"Title": "Emotional Wellness Toolkit πŸ’ͺ", "Subject": "Wellness", "Link": '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Emotional Wellness Toolkit</a>'},
157
- {"Title": "Relaxation Video πŸŽ₯", "Subject": "Video", "Link": '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch Video</a>'}
158
  ],
159
- 'anger': [
160
- {"Title": "Emotional Wellness Toolkit πŸ’‘", "Subject": "Wellness", "Link": '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Emotional Wellness Toolkit</a>'},
161
- {"Title": "Managing Anger 🌿", "Subject": "Anger Management", "Link": '<a href="https://www.helpguide.org/mental-health/anger-management.htm" target="_blank">HelpGuide on Anger Management</a>'},
162
- {"Title": "Relaxation Techniques πŸ’†", "Subject": "Relaxation", "Link": '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Mindful Breathing Meditation</a>'},
163
- {"Title": "Dealing with Stress πŸ’‘", "Subject": "Stress Management", "Link": '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Tips for Dealing with Anxiety</a>'}
164
  ],
165
- 'sadness': [
166
- {"Title": "Overcoming Sadness 🌈", "Subject": "Well-being", "Link": '<a href="https://www.helpguide.org/mental-health/depression.htm" target="_blank">Overcoming Sadness</a>'},
167
- {"Title": "Building Self-Esteem πŸ’ͺ", "Subject": "Confidence", "Link": '<a href="https://www.helpguide.org/mental-health/self-confidence.htm" target="_blank">Self-Confidence Guide</a>'},
168
- {"Title": "Breathing Exercises πŸ§˜β€β™€οΈ", "Subject": "Breathing", "Link": '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Mindful Breathing Meditation</a>'},
169
- {"Title": "Relaxation Tips 🌿", "Subject": "Relaxation", "Link": '<a href="https://www.helpguide.org/mental-health/stress-relief.htm" target="_blank">Stress Relief Tips</a>'}
170
- ]
171
  }
172
-
173
- # Return suggestions based on emotion
174
- return suggestions.get(emotion.lower(), [])
 
 
 
 
 
 
 
175
 
176
  # Gradio Interface
177
  with gr.Blocks() as demo:
 
 
 
178
  with gr.Row():
179
- with gr.Column():
180
- message_input = gr.Textbox(label="Your Message", placeholder="Type a message here...", lines=4)
181
- location_input = gr.Textbox(label="Your Location", placeholder="Enter your location (e.g., Pune, India)...", lines=2)
182
- health_query_input = gr.Textbox(label="Health Professional Search", placeholder="Type a health professional type (e.g., therapist, doctor)...", lines=1)
183
- history_output = gr.Chatbot(label="Chat History", scale=3)
184
- sentiment_output = gr.Textbox(label="Sentiment Analysis")
185
- emotion_output = gr.Textbox(label="Emotion Detection")
186
- suggestions_output = gr.Dataframe(label="Suggestions", headers=["Title", "Subject", "Link"], interactive=True)
187
- map_output = gr.HTML(label="Map")
188
- route_info_output = gr.Textbox(label="Nearby Health Professionals Info")
189
-
190
- message_input.submit(chatbot, [message_input, history_output], [history_output, history_output])
191
- message_input.submit(analyze_sentiment, message_input, sentiment_output)
192
- message_input.submit(detect_emotion, message_input, emotion_output)
193
- message_input.submit(generate_suggestions, emotion_output, suggestions_output)
194
- location_input.submit(get_health_professionals_and_map, [location_input, health_query_input], [route_info_output, map_output])
195
-
196
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
52
+ s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
53
  for se in s_words:
54
  for i, w in enumerate(words):
55
  if w == se:
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
 
 
83
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
84
  with torch.no_grad():
85
  outputs = model_sentiment(**inputs)
86
+ sentiment_class = torch.argmax(outputs.logits, dim=1).item()
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)
97
+ emotion = result[0]["label"]
98
+ emotion_map = {
99
+ "joy": "😊 Joy",
100
+ "anger": "😠 Anger",
101
+ "sadness": "😒 Sadness",
102
+ "fear": "😨 Fear",
103
+ "surprise": "😲 Surprise",
104
+ "neutral": "😐 Neutral",
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 πŸ’š")
168
+
169
  with gr.Row():
170
+ user_input = gr.Textbox(label="Your Message", placeholder="Type your message...", lines=2)
171
+ location_input = gr.Textbox(label="Your Location", placeholder="Enter location...", lines=2)
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()