DreamStream-1 commited on
Commit
da0d067
Β·
verified Β·
1 Parent(s): 5ad7094

Create app.py

Browse files

Final App Updated

Files changed (1) hide show
  1. app.py +395 -0
app.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import nltk
4
+ import numpy as np
5
+ import tflearn
6
+ import random
7
+ import json
8
+ import pickle
9
+ from nltk.tokenize import word_tokenize
10
+ from nltk.stem.lancaster import LancasterStemmer
11
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
12
+ import googlemaps
13
+ import folium
14
+ import torch
15
+ import pandas as pd
16
+ from sklearn.preprocessing import LabelEncoder
17
+ from sklearn.tree import DecisionTreeClassifier
18
+ from sklearn.ensemble import RandomForestClassifier
19
+ from sklearn.naive_bayes import GaussianNB
20
+ from sklearn.metrics import accuracy_score
21
+
22
+ # Suppress TensorFlow warnings
23
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
24
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
25
+
26
+ # Download necessary NLTK resources
27
+ nltk.download("punkt")
28
+ stemmer = LancasterStemmer()
29
+
30
+ # Load intents and chatbot training data
31
+ with open("intents.json") as file:
32
+ intents_data = json.load(file)
33
+
34
+ with open("data.pickle", "rb") as f:
35
+ words, labels, training, output = pickle.load(f)
36
+
37
+ # Build the chatbot model
38
+ net = tflearn.input_data(shape=[None, len(training[0])])
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
+ chatbot_model = tflearn.DNN(net)
44
+ chatbot_model.load("MentalHealthChatBotmodel.tflearn")
45
+
46
+ # Hugging Face sentiment and emotion models
47
+ tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
48
+ model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
49
+ tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
50
+ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
51
+
52
+ # Google Maps API Client
53
+ gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
54
+
55
+ # Load the disease dataset
56
+ df_train = pd.read_csv("Training.csv") # Change the file path as necessary
57
+ df_test = pd.read_csv("Testing.csv") # Change the file path as necessary
58
+
59
+ # Encode diseases
60
+ disease_dict = {
61
+ 'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
62
+ 'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
63
+ 'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
64
+ 'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, 'hepatitis A': 19,
65
+ 'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
66
+ 'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic hemorrhoids(piles)': 28,
67
+ 'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
68
+ 'Hypoglycemia': 33, 'Osteoarthritis': 34, 'Arthritis': 35,
69
+ '(vertigo) Paroxysmal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
70
+ 'Psoriasis': 39, 'Impetigo': 40
71
+ }
72
+
73
+ # Function to prepare data
74
+ def prepare_data(df):
75
+ """Prepares data for training/testing."""
76
+ X = df.iloc[:, :-1] # Features
77
+ y = df.iloc[:, -1] # Target
78
+ label_encoder = LabelEncoder()
79
+ y_encoded = label_encoder.fit_transform(y)
80
+ return X, y_encoded, label_encoder
81
+
82
+ # Preparing training and testing data
83
+ X_train, y_train, label_encoder_train = prepare_data(df_train)
84
+ X_test, y_test, label_encoder_test = prepare_data(df_test)
85
+
86
+ # Define the models
87
+ models = {
88
+ "Decision Tree": DecisionTreeClassifier(),
89
+ "Random Forest": RandomForestClassifier(),
90
+ "Naive Bayes": GaussianNB()
91
+ }
92
+
93
+ # Train and evaluate models
94
+ trained_models = {}
95
+ for model_name, model_obj in models.items():
96
+ model_obj.fit(X_train, y_train) # Fit the model
97
+ y_pred = model_obj.predict(X_test) # Make predictions
98
+ acc = accuracy_score(y_test, y_pred) # Calculate accuracy
99
+ trained_models[model_name] = {'model': model_obj, 'accuracy': acc}
100
+
101
+ # Helper Functions for Chatbot
102
+ def bag_of_words(s, words):
103
+ """Convert user input to bag-of-words vector."""
104
+ bag = [0] * len(words)
105
+ s_words = word_tokenize(s)
106
+ s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
107
+ for se in s_words:
108
+ for i, w in enumerate(words):
109
+ if w == se:
110
+ bag[i] = 1
111
+ return np.array(bag)
112
+
113
+ def generate_chatbot_response(message, history):
114
+ """Generate chatbot response and maintain conversation history."""
115
+ history = history or []
116
+ try:
117
+ result = chatbot_model.predict([bag_of_words(message, words)])
118
+ tag = labels[np.argmax(result)]
119
+ response = "I'm sorry, I didn't understand that. πŸ€”"
120
+ for intent in intents_data["intents"]:
121
+ if intent["tag"] == tag:
122
+ response = random.choice(intent["responses"])
123
+ break
124
+ except Exception as e:
125
+ response = f"Error: {e}"
126
+ history.append((message, response))
127
+ return history, response
128
+
129
+ def analyze_sentiment(user_input):
130
+ """Analyze sentiment and map to emojis."""
131
+ inputs = tokenizer_sentiment(user_input, return_tensors="pt")
132
+ with torch.no_grad():
133
+ outputs = model_sentiment(**inputs)
134
+ sentiment_class = torch.argmax(outputs.logits, dim=1).item()
135
+ sentiment_map = ["Negative πŸ˜”", "Neutral 😐", "Positive 😊"]
136
+ return f"Sentiment: {sentiment_map[sentiment_class]}"
137
+
138
+ def detect_emotion(user_input):
139
+ """Detect emotions based on input."""
140
+ pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
141
+ result = pipe(user_input)
142
+ emotion = result[0]["label"].lower().strip()
143
+ emotion_map = {
144
+ "joy": "Joy 😊",
145
+ "anger": "Anger 😠",
146
+ "sadness": "Sadness 😒",
147
+ "fear": "Fear 😨",
148
+ "surprise": "Surprise 😲",
149
+ "neutral": "Neutral 😐",
150
+ }
151
+ return emotion_map.get(emotion, "Unknown πŸ€”"), emotion
152
+
153
+ def generate_suggestions(emotion):
154
+ """Return relevant suggestions based on detected emotions."""
155
+ emotion_key = emotion.lower()
156
+ suggestions = {
157
+ "joy": [
158
+ ("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
159
+ ("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
160
+ ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
161
+ ("Relaxation Video", "https://youtu.be/yGKKz185M5o"),
162
+ ],
163
+ "anger": [
164
+ ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
165
+ ("Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"),
166
+ ("Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
167
+ ("Relaxation Video", "https://youtu.be/MIc299Flibs"),
168
+ ],
169
+ "fear": [
170
+ ("Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"),
171
+ ("Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
172
+ ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
173
+ ("Relaxation Video", "https://youtu.be/yGKKz185M5o"),
174
+ ],
175
+ "sadness": [
176
+ ("Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"),
177
+ ("Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
178
+ ("Relaxation Video", "https://youtu.be/-e-4Kx5px_I"),
179
+ ],
180
+ "surprise": [
181
+ ("Managing Stress", "https://www.health.harvard.edu/health-a-to-z"),
182
+ ("Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"),
183
+ ("Relaxation Video", "https://youtu.be/m1vaUGtyo-A"),
184
+ ],
185
+ }
186
+
187
+ # Create a markdown string for clickable suggestions in a table format
188
+ formatted_suggestions = ["### Suggestions"]
189
+ formatted_suggestions.append(f"Since you’re feeling {emotion}, you might find these links particularly helpful. Don’t hesitate to explore:")
190
+ formatted_suggestions.append("| Title | Link |")
191
+ formatted_suggestions.append("|-------|------|") # Table headers
192
+ formatted_suggestions += [
193
+ f"| {title} | [{link}]({link}) |" for title, link in suggestions.get(emotion_key, [("No specific suggestions available.", "#")])
194
+ ]
195
+
196
+ return "\n".join(formatted_suggestions)
197
+
198
+ def get_health_professionals_and_map(location, query):
199
+ """Search nearby healthcare professionals using Google Maps API."""
200
+ try:
201
+ if not location or not query:
202
+ return [], "" # Return empty list if inputs are missing
203
+
204
+ geo_location = gmaps.geocode(location)
205
+ if geo_location:
206
+ lat, lng = geo_location[0]["geometry"]["location"].values()
207
+ places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
208
+ professionals = []
209
+ map_ = folium.Map(location=(lat, lng), zoom_start=13)
210
+ for place in places_result:
211
+ professionals.append([place['name'], place.get('vicinity', 'No address provided')])
212
+ folium.Marker(
213
+ location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
214
+ popup=f"{place['name']}"
215
+ ).add_to(map_)
216
+ return professionals, map_._repr_html_()
217
+ return [], "" # Return empty list if no professionals found
218
+ except Exception as e:
219
+ return [], "" # Return empty list on exception
220
+
221
+ # Main Application Logic for Chatbot
222
+ def app_function_chatbot(user_input, location, query, history):
223
+ chatbot_history, _ = generate_chatbot_response(user_input, history)
224
+ sentiment_result = analyze_sentiment(user_input)
225
+ emotion_result, cleaned_emotion = detect_emotion(user_input)
226
+ suggestions = generate_suggestions(cleaned_emotion)
227
+ professionals, map_html = get_health_professionals_and_map(location, query)
228
+ return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
229
+
230
+ # Disease Prediction Logic
231
+ def predict_disease(symptoms):
232
+ """Predict disease based on input symptoms."""
233
+ valid_symptoms = [s for s in symptoms if s is not None] # Filter out None values
234
+ if len(valid_symptoms) < 3:
235
+ return "Please select at least 3 symptoms for a better prediction."
236
+
237
+ input_test = np.zeros(len(X_train.columns)) # Create an array for feature input
238
+ for symptom in valid_symptoms:
239
+ if symptom in X_train.columns:
240
+ input_test[X_train.columns.get_loc(symptom)] = 1
241
+
242
+ predictions = {}
243
+ for model_name, info in trained_models.items():
244
+ prediction = info['model'].predict([input_test])[0]
245
+ predicted_disease = label_encoder_train.inverse_transform([prediction])[0]
246
+ predictions[model_name] = predicted_disease
247
+
248
+ # Create a Markdown table for displaying predictions
249
+ markdown_output = ["### Predicted Diseases"]
250
+ markdown_output.append("| Model | Predicted Disease |")
251
+ markdown_output.append("|-------|------------------|") # Table headers
252
+ for model_name, disease in predictions.items():
253
+ markdown_output.append(f"| {model_name} | {disease} |")
254
+
255
+ return "\n".join(markdown_output)
256
+
257
+ # CSS for the animated welcome message and improved styles
258
+ welcome_message = """
259
+ <style>
260
+ @keyframes fadeIn {
261
+ 0% { opacity: 0; }
262
+ 100% { opacity: 1; }
263
+ }
264
+ #welcome-message {
265
+ font-size: 2em;
266
+ font-weight: bold;
267
+ text-align: center;
268
+ animation: fadeIn 3s ease-in-out;
269
+ margin-bottom: 20px;
270
+ }
271
+ .info-graphic {
272
+ display: flex;
273
+ justify-content: center;
274
+ align-items: center;
275
+ margin: 20px 0;
276
+ }
277
+ .info-graphic img {
278
+ width: 150px; /* Adjust size as needed */
279
+ height: auto; /* Keep aspect ratio */
280
+ margin: 0 10px; /* Space between images */
281
+ }
282
+ h1 {
283
+ text-align: center; /* Center-align the main title */
284
+ font-size: 3em; /* Increase title size */
285
+ color: #004d40; /* Use your theme's color */
286
+ margin-bottom: 20px; /* Space below the title */
287
+ }
288
+ </style>
289
+ <div id="welcome-message">Welcome to the Well-Being Companion!</div>
290
+ """
291
+
292
+ # Gradio Application Interface
293
+ with gr.Blocks(theme="shivi/calm_seafoam") as app:
294
+ gr.HTML(welcome_message) # Animated welcome message
295
+
296
+ with gr.Tab("Well-Being Chatbot"):
297
+ gr.HTML("""
298
+ <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
299
+ 🌼 Well-Being Companion 🌼
300
+ </h1>
301
+ <p style="color: #4caf50; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 1.5em; margin-top: 0;">
302
+ Your Trustworthy Guide to Emotional Wellness and Health
303
+ </p>
304
+ <h2 style="color: #2e7d32; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 1.2em;">
305
+ 🌈 Emotional Support | πŸ§˜πŸ»β€β™€οΈ Mindfulness | πŸ₯— Nutrition | πŸ‹οΈ Physical Health | πŸ’€ Sleep Hygiene
306
+ </h2>
307
+ <ul style="text-align: center; color: #2e7d32;">
308
+ <li>πŸ‘‰ Enter your messages in the input box to chat with our well-being companion.</li>
309
+ <li>πŸ‘‰ Share your current location to find nearby health professionals.</li>
310
+ <li>πŸ‘‰ Receive emotional support suggestions based on your chat.</li>
311
+ </ul>
312
+ """)
313
+
314
+ # Infographics with images
315
+ gr.HTML("""
316
+ <div class="info-graphic">
317
+ <img src="https://i.imgur.com/3ixjqBf.png" alt="Wellness Image 1">
318
+ <img src="https://i.imgur.com/Nvljr1A.png" alt="Wellness Image 2">
319
+ <img src="https://i.imgur.com/hcYAUJ3.png" alt="Wellness Image 3">
320
+ </div>
321
+ """)
322
+
323
+ with gr.Row():
324
+ user_input = gr.Textbox(label="Please Enter Your Message Here", placeholder="Type your message here...", max_lines=3)
325
+ location = gr.Textbox(label="Please Enter Your Current Location", placeholder="E.g., Honolulu", max_lines=1)
326
+ query = gr.Textbox(label="Search Health Professionals Nearby", placeholder="E.g., Health Professionals", max_lines=1)
327
+
328
+ with gr.Row(): # Align Submit and Clear buttons side by side
329
+ submit_chatbot = gr.Button(value="Submit Your Message", variant="primary")
330
+ clear_chatbot = gr.Button(value="Clear", variant="secondary") # Clear button
331
+
332
+ chatbot = gr.Chatbot(label="Chat History", show_label=True)
333
+ sentiment = gr.Textbox(label="Detected Sentiment", show_label=True)
334
+ emotion = gr.Textbox(label="Detected Emotion", show_label=True)
335
+
336
+ # Apply styles and create the DataFrame
337
+ professionals = gr.DataFrame(
338
+ label="Nearby Health Professionals", # Use label parameter to set the title
339
+ headers=["Name", "Address"],
340
+ value=[] # Initialize with empty data
341
+ )
342
+
343
+ suggestions_markdown = gr.Markdown(label="Suggestions")
344
+ map_html = gr.HTML(label="Interactive Map")
345
+
346
+ # Functionality to clear the chat input
347
+ def clear_input():
348
+ return "", [] # Clear both the user input and chat history
349
+
350
+ submit_chatbot.click(
351
+ app_function_chatbot,
352
+ inputs=[user_input, location, query, chatbot],
353
+ outputs=[chatbot, sentiment, emotion, suggestions_markdown, professionals, map_html],
354
+ )
355
+
356
+ clear_chatbot.click(
357
+ clear_input,
358
+ inputs=None,
359
+ outputs=[user_input, chatbot] # Reset user input and chat history
360
+ )
361
+
362
+ with gr.Tab("Disease Prediction"):
363
+ gr.HTML("""
364
+ <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
365
+ Disease Prediction
366
+ </h1>
367
+ <p style="color: #4caf50; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 1.5em; margin-top: 0;">
368
+ Help us understand your symptoms!
369
+ </p>
370
+ <ul style="text-align: center; color: #2e7d32;">
371
+ <li>πŸ‘‰ Select at least 3 symptoms from the dropdown lists.</li>
372
+ <li>πŸ‘‰ Click on "Predict Disease" to see potential conditions.</li>
373
+ <li>πŸ‘‰ Review the results displayed below!</li>
374
+ </ul>
375
+ """)
376
+
377
+ symptom1 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 1", value=None)
378
+ symptom2 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 2", value=None)
379
+ symptom3 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 3", value=None)
380
+ symptom4 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 4", value=None)
381
+ symptom5 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 5", value=None)
382
+
383
+ submit_disease = gr.Button(value="Predict Disease", variant="primary")
384
+
385
+ disease_prediction_result = gr.Markdown(label="Predicted Diseases")
386
+
387
+ submit_disease.click(
388
+ lambda symptom1, symptom2, symptom3, symptom4, symptom5: predict_disease(
389
+ [symptom1, symptom2, symptom3, symptom4, symptom5]),
390
+ inputs=[symptom1, symptom2, symptom3, symptom4, symptom5],
391
+ outputs=disease_prediction_result
392
+ )
393
+
394
+ # Launch the Gradio application
395
+ app.launch()