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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -41
app.py CHANGED
@@ -16,25 +16,23 @@ import torch
16
 
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")
@@ -42,17 +40,20 @@ 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)
57
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
58
  for se in s_words:
@@ -61,26 +62,24 @@ def bag_of_words(s, words):
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,7 +88,7 @@ def analyze_sentiment(user_input):
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,63 +103,83 @@ def detect_emotion(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 πŸ’š")
148
-
149
  with gr.Row():
150
- user_input = gr.Textbox(label="Your Message", placeholder="Type your message...", lines=2)
151
- location_input = gr.Textbox(label="Your Location", placeholder="Enter location...", lines=2)
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()
 
16
 
17
  # Disable GPU usage for TensorFlow
18
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
 
 
19
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
20
 
21
+ # Ensure necessary NLTK resources are downloaded
22
  nltk.download("punkt")
23
 
24
+ # Initialize stemmer
25
  stemmer = LancasterStemmer()
26
 
27
+ # Load intents.json and training data for chatbot
28
  with open("intents.json") as file:
29
  intents_data = json.load(file)
30
 
31
  with open("data.pickle", "rb") as f:
32
  words, labels, training, output = pickle.load(f)
33
 
34
+ # Build Chatbot Model
35
+ net = tflearn.input_data(shape=[None, len(training[0])])
36
  net = tflearn.fully_connected(net, 8)
37
  net = tflearn.fully_connected(net, 8)
38
  net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
 
40
  chatbot_model = tflearn.DNN(net)
41
  chatbot_model.load("MentalHealthChatBotmodel.tflearn")
42
 
43
+ # Sentiment Analysis Model (Hugging Face)
44
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
45
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
46
 
47
+ # Emotion Detection Model
48
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
49
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
50
 
51
+ # Google Maps API Client
52
+ gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
53
+
54
+ # Process Text Input for Chatbot
55
  def bag_of_words(s, words):
56
+ bag = [0] * len(words)
57
  s_words = word_tokenize(s)
58
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
59
  for se in s_words:
 
62
  bag[i] = 1
63
  return np.array(bag)
64
 
65
+ # Chatbot Functionality
66
  def chatbot(message, history):
67
  history = history or []
68
  try:
69
  results = chatbot_model.predict([bag_of_words(message, words)])
70
  tag = labels[np.argmax(results)]
71
+ response = "I'm not sure how to respond to that. πŸ€”"
72
  for intent in intents_data["intents"]:
73
  if intent["tag"] == tag:
74
  response = random.choice(intent["responses"])
75
  break
 
 
76
  except Exception as e:
77
  response = f"Error: {str(e)} πŸ’₯"
 
78
  history.append({"role": "user", "content": message})
79
  history.append({"role": "assistant", "content": response})
80
  return history, response
81
 
82
+ # Detect Sentiment
83
  def analyze_sentiment(user_input):
84
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
85
  with torch.no_grad():
 
88
  sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
89
  return sentiment_map[sentiment_class]
90
 
91
+ # Detect Emotion
92
  def detect_emotion(user_input):
93
  pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
94
  result = pipe(user_input)
 
103
  }
104
  return emotion_map.get(emotion, "Unknown Emotion πŸ€”")
105
 
106
+ # Generate Suggestions for Detected Emotion
107
  def generate_suggestions(emotion):
108
+ resources = {
109
  "😊 Joy": [
110
  ["Relaxation Techniques", "Relaxation", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
111
  ["Dealing with Stress", "Stress Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
112
  ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
113
  ["Relaxation Videos", "Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>']
114
  ],
 
 
 
 
 
 
115
  "😒 Sadness": [
116
  ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
117
+ ["Dealing with Anxiety", "Anxiety Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
118
  ["Relaxation Videos", "Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>']
119
  ],
120
  "😨 Fear": [
121
  ["Mindfulness Practices", "Mindfulness", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
122
+ ["Coping with Anxiety", "Anxiety Management", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
123
  ["Emotional Wellness Toolkit", "Wellness", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
124
  ["Relaxation Videos", "Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>']
125
+ ]
126
  }
127
+ return resources.get(emotion.split(" ")[1], [["No specific suggestions available", "", ""]])
128
 
129
+ # Search Professionals and Generate Map
130
+ def get_health_professionals_and_map(location, query):
131
+ try:
132
+ geo_location = gmaps.geocode(location)
133
+ if geo_location:
134
+ lat, lng = geo_location[0]["geometry"]["location"].values()
135
+ places_result = gmaps.places_nearby(
136
+ location=(lat, lng), radius=10000, type="doctor", keyword=query
137
+ )["results"]
138
+ map_ = folium.Map(location=(lat, lng), zoom_start=13)
139
+ professionals = []
140
+ for place in places_result:
141
+ professionals.append(f"{place['name']} - {place.get('vicinity', '')}")
142
+ lat, lng = place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]
143
+ folium.Marker([lat, lng], popup=place["name"]).add_to(map_)
144
+ return professionals, map_._repr_html_()
145
+ return ["No professionals found"], ""
146
+ except Exception as e:
147
+ return [f"Error: {e}"], ""
148
+
149
+ # Gradio App Function
150
  def app_function(message, location, query, history):
151
  chatbot_history, _ = chatbot(message, history)
152
  sentiment = analyze_sentiment(message)
153
  emotion = detect_emotion(message)
154
  suggestions = generate_suggestions(emotion)
155
+ professionals_info, map_html = get_health_professionals_and_map(location, query)
156
+ return chatbot_history, sentiment, emotion, suggestions, professionals_info, map_html
157
 
158
+ # Gradio Interface
159
  with gr.Blocks() as demo:
160
+ gr.Markdown("# 🌟 Well-Being Companion")
161
  gr.Markdown("Empowering your mental health journey πŸ’š")
162
+
163
  with gr.Row():
164
+ user_input = gr.Textbox(label="Your Message")
165
+ location_input = gr.Textbox(label="Your Location")
166
+ query_input = gr.Textbox(label="Search Query")
167
+ submit_button = gr.Button("Submit")
168
 
169
  chatbot_output = gr.Chatbot(label="Chat History", type="messages")
170
+ sentiment_output = gr.Textbox(label="Sentiment Detected")
171
  emotion_output = gr.Textbox(label="Emotion Detected")
172
  suggestions_output = gr.DataFrame(label="Suggestions", headers=["Title", "Subject", "Link"])
173
+ professionals_output = gr.Textbox(label="Nearby Professionals", lines=5)
174
+ map_output = gr.HTML(label="Map of Nearby Professionals")
175
 
176
+ submit_button.click(
177
  app_function,
178
  inputs=[user_input, location_input, query_input, chatbot_output],
179
+ outputs=[
180
+ chatbot_output, sentiment_output, emotion_output,
181
+ suggestions_output, professionals_output, map_output
182
+ ],
183
  )
184
 
185
  demo.launch()