DreamStream-1 commited on
Commit
494aa89
·
verified ·
1 Parent(s): 37c8a73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -64
app.py CHANGED
@@ -24,18 +24,12 @@ nltk.download('punkt')
24
  stemmer = LancasterStemmer()
25
 
26
  # Load intents.json for Well-Being Chatbot
27
- try:
28
- with open("intents.json") as file:
29
- data = json.load(file)
30
- except FileNotFoundError:
31
- print("Error: 'intents.json' file not found.")
32
 
33
  # Load preprocessed data for Well-Being Chatbot
34
- try:
35
- with open("data.pickle", "rb") as f:
36
- words, labels, training, output = pickle.load(f)
37
- except FileNotFoundError:
38
- print("Error: 'data.pickle' file not found.")
39
 
40
  # Build the model structure for Well-Being Chatbot
41
  net = tflearn.input_data(shape=[None, len(training[0])])
@@ -46,10 +40,7 @@ net = tflearn.regression(net)
46
 
47
  # Load the trained model
48
  model = tflearn.DNN(net)
49
- try:
50
- model.load("MentalHealthChatBotmodel.tflearn")
51
- except IOError:
52
- print("Error: Model file not found or corrupted.")
53
 
54
  # Function to process user input into a bag-of-words format for Chatbot
55
  def bag_of_words(s, words):
@@ -94,63 +85,61 @@ tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-senti
94
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
95
 
96
  def analyze_sentiment(user_input):
97
- try:
98
- inputs = tokenizer(user_input, return_tensors="pt")
99
- with torch.no_grad():
100
- outputs = model_sentiment(**inputs)
101
- predicted_class = torch.argmax(outputs.logits, dim=1).item()
102
- sentiment = ["Negative", "Neutral", "Positive"][predicted_class]
103
- return f"Predicted Sentiment: {sentiment}"
104
- except Exception as e:
105
- return f"Sentiment analysis error: {str(e)}"
106
 
107
  # Emotion Detection using Hugging Face model
108
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
109
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
110
 
111
  def detect_emotion(user_input):
112
- try:
113
- pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
114
- result = pipe(user_input)
115
- emotion = result[0]['label']
116
- return f"Emotion Detected: {emotion}"
117
- except Exception as e:
118
- return f"Emotion detection error: {str(e)}"
119
 
120
  # Initialize Google Maps API client securely
121
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
122
 
123
  # Function to search for health professionals
124
  def search_health_professionals(query, location, radius=10000):
125
- try:
126
- places_result = gmaps.places_nearby(location, radius=radius, type='doctor', keyword=query)
127
- if 'results' in places_result:
128
- return places_result['results']
129
- else:
130
- return []
131
- except Exception as e:
132
- print(f"Error fetching health professionals: {str(e)}")
133
- return []
134
 
135
  # Function to get directions and display on Gradio UI
136
  def get_health_professionals_and_map(current_location, health_professional_query):
137
- # Get health professionals using the search function
138
- health_professionals = search_health_professionals(health_professional_query, current_location)
139
-
140
- # Generate the map with the professionals' locations
141
- map_obj = folium.Map(location=current_location, zoom_start=13)
142
- for professional in health_professionals:
143
- location = professional['geometry']['location']
144
- folium.Marker([location['lat'], location['lng']], popup=professional['name']).add_to(map_obj)
145
-
146
- # Save the map to an HTML file
147
- map_html = "health_professionals_map.html"
148
- map_obj.save(map_html)
149
-
150
- # Generate route information (basic for now)
151
- route_info = [f"{hp['name']} - {hp['vicinity']}" for hp in health_professionals]
152
-
153
- return route_info, map_html
 
 
 
 
 
 
 
 
 
 
 
154
 
155
  # Function to generate suggestions based on the detected emotion
156
  def generate_suggestions(emotion):
@@ -184,14 +173,55 @@ def generate_suggestions(emotion):
184
  {"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
185
  ]
186
  }
187
-
188
  return suggestions.get(emotion.lower(), [])
189
 
190
- # Define the Gradio interface
191
- iface = gr.Interface(fn=chatbot,
192
- inputs=[gr.Textbox(label="Message"),
193
- gr.State()],
194
- outputs=[gr.Chatbot(), gr.State()],
195
- allow_flagging="never", theme="compact")
196
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  iface.launch()
 
24
  stemmer = LancasterStemmer()
25
 
26
  # Load intents.json for Well-Being Chatbot
27
+ with open("intents.json") as file:
28
+ data = json.load(file)
 
 
 
29
 
30
  # Load preprocessed data for Well-Being Chatbot
31
+ with open("data.pickle", "rb") as f:
32
+ words, labels, training, output = pickle.load(f)
 
 
 
33
 
34
  # Build the model structure for Well-Being Chatbot
35
  net = tflearn.input_data(shape=[None, len(training[0])])
 
40
 
41
  # Load the trained model
42
  model = tflearn.DNN(net)
43
+ model.load("MentalHealthChatBotmodel.tflearn")
 
 
 
44
 
45
  # Function to process user input into a bag-of-words format for Chatbot
46
  def bag_of_words(s, words):
 
85
  model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
86
 
87
  def analyze_sentiment(user_input):
88
+ inputs = tokenizer(user_input, return_tensors="pt")
89
+ with torch.no_grad():
90
+ outputs = model_sentiment(**inputs)
91
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
92
+ sentiment = ["Negative", "Neutral", "Positive"][predicted_class] # Assuming 3 classes
93
+ return f"Predicted Sentiment: {sentiment}"
 
 
 
94
 
95
  # Emotion Detection using Hugging Face model
96
  tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
97
  model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
98
 
99
  def detect_emotion(user_input):
100
+ pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
101
+ result = pipe(user_input)
102
+ emotion = result[0]['label']
103
+ return f"Emotion Detected: {emotion}"
 
 
 
104
 
105
  # Initialize Google Maps API client securely
106
  gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
107
 
108
  # Function to search for health professionals
109
  def search_health_professionals(query, location, radius=10000):
110
+ places_result = gmaps.places_nearby(location, radius=radius, type='doctor', keyword=query)
111
+ return places_result.get('results', [])
 
 
 
 
 
 
 
112
 
113
  # Function to get directions and display on Gradio UI
114
  def get_health_professionals_and_map(current_location, health_professional_query):
115
+ location = gmaps.geocode(current_location)
116
+ if location:
117
+ lat = location[0]["geometry"]["location"]["lat"]
118
+ lng = location[0]["geometry"]["location"]["lng"]
119
+ location = (lat, lng)
120
+
121
+ professionals = search_health_professionals(health_professional_query, location)
122
+
123
+ # Generate map
124
+ map_center = location
125
+ m = folium.Map(location=map_center, zoom_start=13)
126
+
127
+ # Add markers to the map
128
+ for place in professionals:
129
+ folium.Marker(
130
+ location=[place['geometry']['location']['lat'], place['geometry']['location']['lng']],
131
+ popup=place['name']
132
+ ).add_to(m)
133
+
134
+ # Convert map to HTML for Gradio display
135
+ map_html = m._repr_html_()
136
+
137
+ # Route information
138
+ route_info = "\n".join([f"{place['name']} - {place['vicinity']}" for place in professionals])
139
+
140
+ return route_info, map_html
141
+ else:
142
+ return "Unable to find location.", ""
143
 
144
  # Function to generate suggestions based on the detected emotion
145
  def generate_suggestions(emotion):
 
173
  {"Title": "Relaxation Video", "Subject": "Video", "Link": "https://youtu.be/m1vaUGtyo-A"}
174
  ]
175
  }
 
176
  return suggestions.get(emotion.lower(), [])
177
 
178
+ # Gradio interface
179
+ def gradio_app(message, location, health_query, submit_button, history, state):
180
+ # Chatbot interaction
181
+ history, _ = chatbot(message, history)
182
+
183
+ # Sentiment analysis
184
+ sentiment_response = analyze_sentiment(message)
185
+
186
+ # Emotion detection
187
+ emotion_response = detect_emotion(message)
188
+
189
+ # Health professional search and map display
190
+ route_info, map_html = get_health_professionals_and_map(location, health_query)
191
+
192
+ # Generate suggestions based on the detected emotion
193
+ suggestions = generate_suggestions(emotion_response.split(': ')[1])
194
+
195
+ # Create a DataFrame for displaying suggestions
196
+ suggestions_df = pd.DataFrame(suggestions)
197
+
198
+ return history, sentiment_response, emotion_response, route_info, map_html, gr.DataFrame(suggestions_df, headers=["Title", "Subject", "Link"]), state
199
+
200
+ # Gradio UI components
201
+ message_input = gr.Textbox(lines=1, label="Message")
202
+ location_input = gr.Textbox(value="Honolulu, HI", label="Current Location")
203
+ health_query_input = gr.Textbox(value="doctor", label="Health Professional Query (e.g., doctor, psychiatrist, psychologist)")
204
+ submit_button = gr.Button("Submit") # Submit button
205
+
206
+ # Updated chat history component with 'messages' type
207
+ chat_history = gr.Chatbot(label="Well-Being Chat History", type='messages')
208
+
209
+ # Outputs
210
+ sentiment_output = gr.Textbox(label="Sentiment Analysis Result")
211
+ emotion_output = gr.Textbox(label="Emotion Detection Result")
212
+ route_info_output = gr.Textbox(label="Health Professionals Information")
213
+ map_output = gr.HTML(label="Map with Health Professionals")
214
+ suggestions_output = gr.DataFrame(label="Well-Being Suggestions", headers=["Title", "Subject", "Link"])
215
+
216
+ # Create Gradio interface
217
+ iface = gr.Interface(
218
+ fn=gradio_app,
219
+ inputs=[message_input, location_input, health_query_input, submit_button, gr.State()],
220
+ outputs=[chat_history, sentiment_output, emotion_output, route_info_output, map_output, suggestions_output, gr.State()],
221
+ allow_flagging="never",
222
+ live=True,
223
+ title="Well-Being App: Support, Sentiment, Emotion Detection & Health Professional Search"
224
+ )
225
+
226
+ # Launch the Gradio interface
227
  iface.launch()