Mishal23 commited on
Commit
749407b
·
verified ·
1 Parent(s): 1b5fc3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +305 -257
app.py CHANGED
@@ -1,257 +1,305 @@
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
-
16
- # Suppress TensorFlow warnings
17
- os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
18
- os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
19
-
20
- # Download necessary NLTK resources
21
- nltk.download("punkt")
22
- stemmer = LancasterStemmer()
23
-
24
- # Load intents and chatbot training data
25
- with open("intents.json") as file:
26
- intents_data = json.load(file)
27
-
28
- with open("data.pickle", "rb") as f:
29
- words, labels, training, output = pickle.load(f)
30
-
31
- # Build the chatbot model
32
- net = tflearn.input_data(shape=[None, len(training[0])])
33
- net = tflearn.fully_connected(net, 8)
34
- net = tflearn.fully_connected(net, 8)
35
- net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
36
- net = tflearn.regression(net)
37
- chatbot_model = tflearn.DNN(net)
38
- chatbot_model.load("MentalHealthChatBotmodel.tflearn")
39
-
40
- # Hugging Face sentiment and emotion models
41
- tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
42
- model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
43
- tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
44
- model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
45
-
46
- # Google Maps API Client
47
- gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
48
-
49
- # Helper Functions
50
- def bag_of_words(s, words):
51
- """Convert user input to bag-of-words vector."""
52
- bag = [0] * len(words)
53
- s_words = word_tokenize(s)
54
- s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
55
- for se in s_words:
56
- for i, w in enumerate(words):
57
- if w == se:
58
- bag[i] = 1
59
- return np.array(bag)
60
-
61
- def generate_chatbot_response(message, history):
62
- """Generate chatbot response and maintain conversation history."""
63
- history = history or []
64
- try:
65
- result = chatbot_model.predict([bag_of_words(message, words)])
66
- tag = labels[np.argmax(result)]
67
- response = "I'm sorry, I didn't understand 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: {e}"
74
- history.append((message, response))
75
- return history, response
76
-
77
- def analyze_sentiment(user_input):
78
- """Analyze sentiment and map to emojis."""
79
- inputs = tokenizer_sentiment(user_input, return_tensors="pt")
80
- with torch.no_grad():
81
- outputs = model_sentiment(**inputs)
82
- sentiment_class = torch.argmax(outputs.logits, dim=1).item()
83
- sentiment_map = ["Negative 😔", "Neutral 😐", "Positive 😊"]
84
- return f"Sentiment: {sentiment_map[sentiment_class]}"
85
-
86
- def detect_emotion(user_input):
87
- """Detect emotions based on input."""
88
- pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
89
- result = pipe(user_input)
90
- emotion = result[0]["label"].lower().strip()
91
- emotion_map = {
92
- "joy": "Joy 😊",
93
- "anger": "Anger 😠",
94
- "sadness": "Sadness 😢",
95
- "fear": "Fear 😨",
96
- "surprise": "Surprise 😲",
97
- "neutral": "Neutral 😐",
98
- }
99
- return emotion_map.get(emotion, "Unknown 🤔"), emotion
100
-
101
- def generate_suggestions(emotion):
102
- """Return relevant suggestions based on detected emotions."""
103
- emotion_key = emotion.lower()
104
- suggestions = {
105
- "joy": [
106
- ["Relaxation Techniques", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
107
- ["Dealing with Stress", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
108
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
109
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
110
- ],
111
- "anger": [
112
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
113
- ["Stress Management Tips", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
114
- ["Dealing with Anger", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
115
- ["Relaxation Video", '<a href="https://youtu.be/MIc299Flibs" target="_blank">Watch</a>'],
116
- ],
117
- "fear": [
118
- ["Mindfulness Practices", '<a href="https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation" target="_blank">Visit</a>'],
119
- ["Coping with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
120
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
121
- ["Relaxation Video", '<a href="https://youtu.be/yGKKz185M5o" target="_blank">Watch</a>'],
122
- ],
123
- "sadness": [
124
- ["Emotional Wellness Toolkit", '<a href="https://www.nih.gov/health-information/emotional-wellness-toolkit" target="_blank">Visit</a>'],
125
- ["Dealing with Anxiety", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
126
- ["Relaxation Video", '<a href="https://youtu.be/-e-4Kx5px_I" target="_blank">Watch</a>'],
127
- ],
128
- "surprise": [
129
- ["Managing Stress", '<a href="https://www.health.harvard.edu/health-a-to-z" target="_blank">Visit</a>'],
130
- ["Coping Strategies", '<a href="https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety" target="_blank">Visit</a>'],
131
- ["Relaxation Video", '<a href="https://youtu.be/m1vaUGtyo-A" target="_blank">Watch</a>'],
132
- ],
133
- }
134
- return suggestions.get(emotion_key, [["No specific suggestions available.", ""]])
135
-
136
- def get_health_professionals_and_map(location, query):
137
- """Search nearby healthcare professionals using Google Maps API."""
138
- try:
139
- if not location or not query:
140
- return ["Please provide both location and query."], ""
141
-
142
- geo_location = gmaps.geocode(location)
143
- if geo_location:
144
- lat, lng = geo_location[0]["geometry"]["location"].values()
145
- places_result = gmaps.places_nearby(location=(lat, lng), radius=10000, keyword=query)["results"]
146
- professionals = []
147
- map_ = folium.Map(location=(lat, lng), zoom_start=13)
148
- for place in places_result:
149
- professionals.append(f"{place['name']} - {place.get('vicinity', 'No address provided')}")
150
- folium.Marker(
151
- location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
152
- popup=f"{place['name']}"
153
- ).add_to(map_)
154
- return professionals, map_._repr_html_()
155
-
156
- return ["No professionals found for the given location."], ""
157
- except Exception as e:
158
- return [f"An error occurred: {e}"], ""
159
-
160
- # Main Application Logic
161
- def app_function(user_input, location, query, history):
162
- chatbot_history, _ = generate_chatbot_response(user_input, history)
163
- sentiment_result = analyze_sentiment(user_input)
164
- emotion_result, cleaned_emotion = detect_emotion(user_input)
165
- suggestions = generate_suggestions(cleaned_emotion)
166
- professionals, map_html = get_health_professionals_and_map(location, query)
167
- return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
168
-
169
- # CSS Styling
170
- custom_css = """
171
- body {
172
- font-family: 'Roboto', sans-serif;
173
- background: linear-gradient(135deg, #0d0d0d, #ff5722);
174
- color: white;
175
- }
176
-
177
- h1 {
178
- background: #ffffff;
179
- color: #000000;
180
- border-radius: 8px;
181
- padding: 10px;
182
- font-weight: bold;
183
- text-align: center;
184
- font-size: 2.5rem;
185
- }
186
-
187
- textarea, input {
188
- background: transparent;
189
- color: black;
190
- border: 2px solid orange;
191
- padding: 8px;
192
- font-size: 1rem;
193
- caret-color: black;
194
- outline: none;
195
- border-radius: 8px;
196
- }
197
-
198
- textarea:focus, input:focus {
199
- background: transparent;
200
- color: black;
201
- border: 2px solid orange;
202
- outline: none;
203
- }
204
-
205
- textarea:hover, input:hover {
206
- background: transparent;
207
- color: black;
208
- border: 2px solid orange;
209
- }
210
-
211
- .df-container {
212
- background: white;
213
- color: black;
214
- border: 2px solid orange;
215
- border-radius: 10px;
216
- padding: 10px;
217
- font-size: 14px;
218
- max-height: 400px;
219
- height: auto;
220
- overflow-y: auto;
221
- }
222
-
223
- #suggestions-title {
224
- text-align: center;
225
- font-weight: bold;
226
- color: white;
227
- font-size: 2.2rem;
228
- margin-bottom: 20px;
229
- }
230
- """
231
-
232
- # Gradio Application
233
- with gr.Blocks(css=custom_css) as app:
234
- gr.HTML("<h1>🌟 Well-Being Companion</h1>")
235
- with gr.Row():
236
- user_input = gr.Textbox(label="Your Message")
237
- location = gr.Textbox(label="Your Location")
238
- query = gr.Textbox(label="Search Query")
239
- chatbot = gr.Chatbot(label="Chat History")
240
- sentiment = gr.Textbox(label="Detected Sentiment")
241
- emotion = gr.Textbox(label="Detected Emotion")
242
-
243
- # Adding Suggestions Title with Styled Markdown (Centered and Bold)
244
- gr.Markdown("Suggestions", elem_id="suggestions-title")
245
-
246
- suggestions = gr.DataFrame(headers=["Title", "Link"]) # Table for suggestions
247
- professionals = gr.Textbox(label="Nearby Professionals", lines=6)
248
- map_html = gr.HTML(label="Interactive Map")
249
- submit = gr.Button(value="Submit", variant="primary")
250
-
251
- submit.click(
252
- app_function,
253
- inputs=[user_input, location, query, chatbot],
254
- outputs=[chatbot, sentiment, emotion, suggestions, professionals, map_html],
255
- )
256
-
257
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import nltk
4
+ import numpy as np
5
+ import json
6
+ import pickle
7
+ from nltk.tokenize import word_tokenize
8
+ from nltk.stem.lancaster import LancasterStemmer
9
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
10
+ import torch
11
+ import pandas as pd
12
+ from sklearn.tree import DecisionTreeClassifier
13
+ from sklearn.ensemble import RandomForestClassifier
14
+ from sklearn.naive_bayes import GaussianNB
15
+ from sklearn.metrics import accuracy_score
16
+
17
+ # Suppress TensorFlow warnings
18
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
19
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
20
+
21
+ # NLTK Setup
22
+ nltk.download("punkt")
23
+ stemmer = LancasterStemmer()
24
+
25
+ # Load data
26
+ with open("intents.json") as file:
27
+ intents_data = json.load(file)
28
+
29
+ with open("data.pickle", "rb") as f:
30
+ words, labels, training, output = pickle.load(f)
31
+
32
+ # Hugging Face models for Well-Being Companion
33
+ tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
34
+ model_sentiment = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
35
+ tokenizer_emotion = AutoTokenizer.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
36
+ model_emotion = AutoModelForSequenceClassification.from_pretrained("j-hartmann/emotion-english-distilroberta-base")
37
+
38
+ # Helper Functions
39
+ def bag_of_words(s, words):
40
+ bag = [0] * len(words)
41
+ s_words = word_tokenize(s)
42
+ s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
43
+ for se in s_words:
44
+ for i, w in enumerate(words):
45
+ if w == se:
46
+ bag[i] = 1
47
+ return np.array(bag)
48
+ def analyze_sentiment(user_input):
49
+ """Analyze sentiment and map to emojis."""
50
+ inputs = tokenizer_sentiment(user_input, return_tensors="pt")
51
+ with torch.no_grad():
52
+ outputs = model_sentiment(**inputs)
53
+ sentiment_class = torch.argmax(outputs.logits, dim=1).item()
54
+ sentiment_map = ["Negative 😔", "Neutral 😐", "Positive 😊"]
55
+ return f"Sentiment: {sentiment_map[sentiment_class]}"
56
+
57
+ def detect_emotion(user_input):
58
+ """Detect emotions based on input."""
59
+ pipe = pipeline("text-classification", model=model_emotion, tokenizer=tokenizer_emotion)
60
+ result = pipe(user_input)
61
+ emotion = result[0]["label"].lower().strip()
62
+ emotion_map = {
63
+ "joy": "Joy 😊",
64
+ "anger": "Anger 😠",
65
+ "sadness": "Sadness 😢",
66
+ "fear": "Fear 😨",
67
+ "surprise": "Surprise 😲",
68
+ "neutral": "Neutral 😐",
69
+ }
70
+ # Return only the formatted emotion string
71
+ return emotion_map.get(emotion, "Unknown 🤔")
72
+
73
+ def generate_suggestions(emotion):
74
+ """Return relevant suggestions based on detected emotions."""
75
+ emotion_key = emotion.lower()
76
+ suggestions = {
77
+ "joy": [
78
+ ["Relaxation Techniques", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
79
+ ["Dealing with Stress", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
80
+ ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
81
+ ["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
82
+ ],
83
+ "anger": [
84
+ ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
85
+ ["Stress Management Tips", "https://www.health.harvard.edu/health-a-to-z"],
86
+ ["Dealing with Anger", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
87
+ ["Relaxation Video", "https://youtu.be/MIc299Flibs"],
88
+ ],
89
+ "fear": [
90
+ ["Mindfulness Practices", "https://www.helpguide.org/mental-health/meditation/mindful-breathing-meditation"],
91
+ ["Coping with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
92
+ ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
93
+ ["Relaxation Video", "https://youtu.be/yGKKz185M5o"],
94
+ ],
95
+ "sadness": [
96
+ ["Emotional Wellness Toolkit", "https://www.nih.gov/health-information/emotional-wellness-toolkit"],
97
+ ["Dealing with Anxiety", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
98
+ ["Relaxation Video", "https://youtu.be/-e-4Kx5px_I"],
99
+ ],
100
+ "surprise": [
101
+ ["Managing Stress", "https://www.health.harvard.edu/health-a-to-z"],
102
+ ["Coping Strategies", "https://www.helpguide.org/mental-health/anxiety/tips-for-dealing-with-anxiety"],
103
+ ["Relaxation Video", "https://youtu.be/m1vaUGtyo-A"],
104
+ ],
105
+ }
106
+ return suggestions.get(emotion_key, [["No specific suggestions available.", "#"]])
107
+
108
+ def get_health_professionals_and_map(location, query):
109
+ """Search nearby healthcare professionals using Google Maps API."""
110
+ try:
111
+ if not location or not query:
112
+ return [], "" # Return empty list if inputs are missing
113
+
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(location=(lat, lng), radius=10000, keyword=query)["results"]
118
+ professionals = []
119
+ map_ = folium.Map(location=(lat, lng), zoom_start=13)
120
+ for place in places_result:
121
+ # Use a list of values to append each professional
122
+ professionals.append([place['name'], place.get('vicinity', 'No address provided')])
123
+ folium.Marker(
124
+ location=[place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"]],
125
+ popup=f"{place['name']}"
126
+ ).add_to(map_)
127
+ return professionals, map_._repr_html_()
128
+
129
+ return [], "" # Return empty list if no professionals found
130
+ except Exception as e:
131
+ return [], "" # Return empty list on exception
132
+
133
+
134
+ # Chronic Disease Prediction Functions
135
+ def load_data():
136
+ df = pd.read_csv("Training.csv")
137
+ tr = pd.read_csv("Testing.csv")
138
+ disease_dict = { 'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
139
+ 'Peptic ulcer diseae': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
140
+ 'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
141
+ 'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, 'hepatitis A': 19,
142
+ 'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
143
+ 'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic hemmorhoids(piles)': 28,
144
+ 'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
145
+ 'Hypoglycemia': 33, 'Osteoarthristis': 34, 'Arthritis': 35,
146
+ '(vertigo) Paroymsal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
147
+ 'Psoriasis': 39, 'Impetigo': 40
148
+ } # Same logic.
149
+ df.replace({'prognosis': disease_dict}, inplace=True)
150
+ return df, tr, disease_dict
151
+
152
+ df, tr, disease_dict = load_data()
153
+ l1 = list(df.columns[:-1])
154
+ X = df[l1]
155
+ y = df['prognosis']
156
+ X_test = tr[l1]
157
+ y_test = tr['prognosis']
158
+
159
+ def train_models():
160
+ models = {
161
+ "Decision Tree": DecisionTreeClassifier(),
162
+ "Random Forest": RandomForestClassifier(),
163
+ "Naive Bayes": GaussianNB()
164
+ }
165
+ trained_models = {}
166
+ for model_name, model_obj in models.items():
167
+ model_obj.fit(X, y)
168
+ acc = accuracy_score(y_test, model_obj.predict(X_test))
169
+ trained_models[model_name] = (model_obj, acc)
170
+ return trained_models
171
+
172
+ trained_models = train_models()
173
+
174
+ disease_to_professional = {
175
+ 'Fungal infection': ["Dermatologist", "Family Doctor"],
176
+ 'Allergy': ["Allergist", "Family Doctor"],
177
+ 'GERD': ["Gastroenterologist", "Family Doctor"],
178
+ 'Chronic cholestasis': ["Gastroenterologist", "Family Doctor"],
179
+ 'Drug Reaction': ["Dermatologist", "Family Doctor"],
180
+ 'Peptic ulcer disease': ["Gastroenterologist", "Family Doctor"],
181
+ 'AIDS': ["Infectious Disease Specialist", "Family Doctor"],
182
+ 'Diabetes ': ["Endocrinologist", "Family Doctor"],
183
+ 'Gastroenteritis': ["Gastroenterologist", "Family Doctor"],
184
+ 'Bronchial Asthma': ["Pulmonologist", "Family Doctor"],
185
+ 'Hypertension ': ["Cardiologist", "Family Doctor"],
186
+ 'Migraine': ["Neurologist", "Family Doctor"],
187
+ 'Cervical spondylosis': ["Orthopedist", "Family Doctor"],
188
+ 'Paralysis (brain hemorrhage)': ["Neurologist", "Family Doctor"],
189
+ 'Jaundice': ["Hepatologist", "Family Doctor"],
190
+ 'Malaria': ["Infectious Disease Specialist", "Family Doctor"],
191
+ 'Chicken pox': ["Pediatrician", "Family Doctor"],
192
+ 'Dengue': ["Infectious Disease Specialist", "Family Doctor"],
193
+ 'Typhoid': ["Infectious Disease Specialist", "Family Doctor"],
194
+ 'hepatitis A': ["Hepatologist", "Family Doctor"],
195
+ 'Hepatitis B': ["Hepatologist", "Family Doctor"],
196
+ 'Hepatitis C': ["Hepatologist", "Family Doctor"],
197
+ 'Hepatitis D': ["Hepatologist", "Family Doctor"],
198
+ 'Hepatitis E': ["Hepatologist", "Family Doctor"],
199
+ 'Alcoholic hepatitis': ["Hepatologist", "Family Doctor"],
200
+ 'Tuberculosis': ["Pulmonologist", "Family Doctor"],
201
+ 'Common Cold': ["General Practitioner"],
202
+ 'Pneumonia': ["Pulmonologist", "Family Doctor"],
203
+ 'Dimorphic hemorrhoids(piles)': ["Gastroenterologist", "Family Doctor"],
204
+ 'Heart attack': ["Cardiologist"],
205
+ 'Varicose veins': ["Vascular Surgeon", "Family Doctor"],
206
+ 'Hypothyroidism': ["Endocrinologist", "Family Doctor"],
207
+ 'Hyperthyroidism': ["Endocrinologist", "Family Doctor"],
208
+ 'Hypoglycemia': ["Endocrinologist", "Family Doctor"],
209
+ 'Osteoarthritis': ["Orthopedist", "Family Doctor"],
210
+ 'Arthritis': ["Rheumatologist", "Family Doctor"],
211
+ '(vertigo) Paroxysmal Positional Vertigo': ["Neurologist", "Family Doctor"],
212
+ 'Acne': ["Cosmetic Dermatologist", "Family Doctor"],
213
+ 'Urinary tract infection': ["Urologist", "Family Doctor"],
214
+ 'Psoriasis': ["Dermatologist", "Family Doctor"],
215
+ 'Impetigo': ["Dermatologist", "Family Doctor"]
216
+ }
217
+ def disease_predictor(symptoms):
218
+ results = []
219
+
220
+ for model_name, (model, acc) in trained_models.items():
221
+ disease = predict_disease(model, symptoms)
222
+ pro = disease_to_professional.get(disease, ["No Recommendations Available"])
223
+
224
+ # Convert the list of recommended professionals into a string without commas
225
+ pro_str = " and ".join(pro) if isinstance(pro, list) else pro
226
+
227
+ results.append(f"Model: {model_name}\nPredicted Disease: {disease}\nRecommended Professionals: {pro_str}\n")
228
+
229
+ return "\n".join(results)
230
+
231
+
232
+
233
+ def predict_disease_button(symptom1, symptom2, symptom3, symptom4, symptom5):
234
+ # Filter out "None" values and pass selected symptoms
235
+ selected_symptoms = [s for s in [symptom1, symptom2, symptom3, symptom4, symptom5] if s != "None"]
236
+
237
+ # Check if at least 3 symptoms are selected
238
+ if len(selected_symptoms) < 3:
239
+ return "Please select at least three symptoms."
240
+ else:
241
+ return disease_predictor(selected_symptoms)
242
+
243
+ # Gradio App
244
+ with gr.Blocks() as app:
245
+
246
+ with gr.Tab("Well-Being Companion"):
247
+ gr.Markdown("<h1>🌟 Well-Being Companion</h1><p>Track your health, mood, and more!</p>")
248
+
249
+ with gr.Row():
250
+ user_input = gr.Textbox(label="Describe Your Current Feeling or Concern:", placeholder="How are you feeling today?")
251
+ location = gr.Textbox(label="Location", placeholder="e.g., New York")
252
+ query = gr.Textbox(label="Search for Professionals or Services", placeholder="e.g., therapist, dietitian.")
253
+
254
+ with gr.Row():
255
+ sentiment_btn = gr.Button("Analyze Sentiment")
256
+ sentiment_result = gr.Textbox(label="Sentiment Analysis")
257
+ emotion_btn = gr.Button("Detect Emotion")
258
+ emotion_result = gr.Textbox(label="Emotion Detection")
259
+
260
+ # Set up click functionality
261
+ sentiment_btn.click(analyze_sentiment, inputs=user_input, outputs=sentiment_result)
262
+ emotion_btn.click(detect_emotion, inputs=user_input, outputs=emotion_result)
263
+
264
+ gr.Markdown("### Suggestions", elem_id="suggestions-title")
265
+
266
+ # Table to display suggestions
267
+ suggestions_table = gr.DataFrame(headers=["Title", "Link"])
268
+
269
+ # New 'Get Suggestion' button
270
+ with gr.Row():
271
+ suggestion_btn = gr.Button("Get Suggestion")
272
+ suggestion_btn.click(generate_suggestions, inputs=emotion_result, outputs=suggestions_table)
273
+
274
+ with gr.Row():
275
+ nearby_btn = gr.Button("Find Nearby Professionals")
276
+ professionals_output = gr.Textbox(label="Professionals")
277
+
278
+ nearby_btn.click(get_health_professionals_and_map, inputs=[location, query], outputs=professionals_output)
279
+
280
+ with gr.Tab("Chat History"):
281
+ gr.Markdown("<h3>Chat History:</h3>")
282
+ chat_history = gr.Textbox(label="Chat Logs", placeholder="Conversation history will appear here.")
283
+
284
+ with gr.Tab("Chronic Disease Prediction"):
285
+ gr.Markdown("<h1>🩺 Chronic Disease Prediction</h1><p>Enter your symptoms to get a prediction.</p>")
286
+
287
+ symptom1 = gr.Dropdown(["None"] + l1, label="Symptom 1")
288
+ symptom2 = gr.Dropdown(["None"] + l1, label="Symptom 2")
289
+ symptom3 = gr.Dropdown(["None"] + l1, label="Symptom 3")
290
+ symptom4 = gr.Dropdown(["None"] + l1, label="Symptom 4")
291
+ symptom5 = gr.Dropdown(["None"] + l1, label="Symptom 5")
292
+
293
+ predict_button = gr.Button("Predict Disease")
294
+ prediction_result = gr.Textbox(label="Prediction Result")
295
+
296
+ predict_button.click(
297
+ fn=predict_disease_button,
298
+ inputs=[symptom1, symptom2, symptom3, symptom4, symptom5],
299
+ outputs=prediction_result
300
+ )
301
+
302
+ # Launch the app
303
+ app.launch()
304
+
305
+