DreamStream-1 commited on
Commit
09396fc
Β·
verified Β·
1 Parent(s): 0c35f73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -68
app.py CHANGED
@@ -2,7 +2,9 @@ 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
@@ -35,14 +37,20 @@ with open("intents.json") as file:
35
  with open("data.pickle", "rb") as f:
36
  words, labels, training, output = pickle.load(f)
37
 
38
- # Build the chatbot model
39
- net = tflearn.input_data(shape=[None, len(training[0])])
40
- net = tflearn.fully_connected(net, 8)
41
- net = tflearn.fully_connected(net, 8)
42
- net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
43
- net = tflearn.regression(net)
44
- chatbot_model = tflearn.DNN(net)
45
- chatbot_model.load("MentalHealthChatBotmodel.tflearn")
 
 
 
 
 
 
46
 
47
  # Hugging Face sentiment and emotion models
48
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
@@ -57,37 +65,21 @@ emotion_pipeline = pipeline("text-classification", model=model_emotion, tokenize
57
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
58
 
59
  # Load the disease dataset
60
- df_train = pd.read_csv("Training.csv") # Change the file path as necessary
61
- df_test = pd.read_csv("Testing.csv") # Change the file path as necessary
62
-
63
- # Encode diseases dictionary (optional, currently unused directly)
64
- disease_dict = {
65
- 'Fungal infection': 0, 'Allergy': 1, 'GERD': 2, 'Chronic cholestasis': 3, 'Drug Reaction': 4,
66
- 'Peptic ulcer disease': 5, 'AIDS': 6, 'Diabetes ': 7, 'Gastroenteritis': 8, 'Bronchial Asthma': 9,
67
- 'Hypertension ': 10, 'Migraine': 11, 'Cervical spondylosis': 12, 'Paralysis (brain hemorrhage)': 13,
68
- 'Jaundice': 14, 'Malaria': 15, 'Chicken pox': 16, 'Dengue': 17, 'Typhoid': 18, 'hepatitis A': 19,
69
- 'Hepatitis B': 20, 'Hepatitis C': 21, 'Hepatitis D': 22, 'Hepatitis E': 23, 'Alcoholic hepatitis': 24,
70
- 'Tuberculosis': 25, 'Common Cold': 26, 'Pneumonia': 27, 'Dimorphic hemorrhoids(piles)': 28,
71
- 'Heart attack': 29, 'Varicose veins': 30, 'Hypothyroidism': 31, 'Hyperthyroidism': 32,
72
- 'Hypoglycemia': 33, 'Osteoarthritis': 34, 'Arthritis': 35,
73
- '(vertigo) Paroxysmal Positional Vertigo': 36, 'Acne': 37, 'Urinary tract infection': 38,
74
- 'Psoriasis': 39, 'Impetigo': 40
75
- }
76
 
77
  # Label encoder for consistent train/test encoding
78
  label_encoder = LabelEncoder()
79
 
80
  def prepare_data(df, is_train=True):
81
- """Prepares data for training/testing with consistent label encoding."""
82
- X = df.iloc[:, :-1] # Features
83
- y = df.iloc[:, -1] # Target
84
  if is_train:
85
  y_encoded = label_encoder.fit_transform(y)
86
  else:
87
  y_encoded = label_encoder.transform(y)
88
  return X, y_encoded
89
 
90
- # Preparing training and testing data with the same label encoder
91
  X_train, y_train = prepare_data(df_train, is_train=True)
92
  X_test, y_test = prepare_data(df_test, is_train=False)
93
 
@@ -109,7 +101,6 @@ for model_name, model_obj in models.items():
109
  # --- Helper Functions for Chatbot ---
110
 
111
  def bag_of_words(s, words):
112
- """Convert user input to bag-of-words vector."""
113
  bag = [0] * len(words)
114
  s_words = word_tokenize(s)
115
  s_words = [stemmer.stem(word.lower()) for word in s_words if word.isalnum()]
@@ -120,10 +111,9 @@ def bag_of_words(s, words):
120
  return np.array(bag)
121
 
122
  def generate_chatbot_response(message, history):
123
- """Generate chatbot response and maintain conversation history."""
124
  history = history or []
125
  try:
126
- result = chatbot_model.predict([bag_of_words(message, words)])
127
  tag = labels[np.argmax(result)]
128
  response = "I'm sorry, I didn't understand that. πŸ€”"
129
  for intent in intents_data["intents"]:
@@ -136,7 +126,6 @@ def generate_chatbot_response(message, history):
136
  return history, response
137
 
138
  def analyze_sentiment(user_input):
139
- """Analyze sentiment and map to emojis."""
140
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
141
  with torch.no_grad():
142
  outputs = model_sentiment(**inputs)
@@ -145,7 +134,6 @@ def analyze_sentiment(user_input):
145
  return f"Sentiment: {sentiment_map[sentiment_class]}"
146
 
147
  def detect_emotion(user_input):
148
- """Detect emotions based on input using cached pipeline."""
149
  result = emotion_pipeline(user_input)
150
  emotion = result[0]["label"].lower().strip()
151
  emotion_map = {
@@ -159,7 +147,6 @@ def detect_emotion(user_input):
159
  return emotion_map.get(emotion, "Unknown πŸ€”"), emotion
160
 
161
  def generate_suggestions(emotion):
162
- """Return relevant suggestions based on detected emotions."""
163
  emotion_key = emotion.lower()
164
  suggestions = {
165
  "joy": [
@@ -206,11 +193,9 @@ def generate_suggestions(emotion):
206
  return "\n".join(formatted_suggestions)
207
 
208
  def get_health_professionals_and_map(location, query):
209
- """Search nearby healthcare professionals using Google Maps API."""
210
  try:
211
  if not location or not query:
212
- return [], "" # Return empty list if inputs are missing
213
-
214
  geo_location = gmaps.geocode(location)
215
  if geo_location:
216
  lat, lng = geo_location[0]["geometry"]["location"].values()
@@ -229,7 +214,6 @@ def get_health_professionals_and_map(location, query):
229
  logging.error(f"Error fetching health professionals: {e}")
230
  return [], ""
231
 
232
- # Main Application Logic for Chatbot
233
  def app_function_chatbot(user_input, location, query, history):
234
  chatbot_history, _ = generate_chatbot_response(user_input, history)
235
  sentiment_result = analyze_sentiment(user_input)
@@ -238,25 +222,19 @@ def app_function_chatbot(user_input, location, query, history):
238
  professionals, map_html = get_health_professionals_and_map(location, query)
239
  return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
240
 
241
- # Disease Prediction Logic
242
  def predict_disease(symptoms):
243
- """Predict disease based on input symptoms."""
244
- valid_symptoms = [s for s in symptoms if s is not None] # Filter out None values
245
  if len(valid_symptoms) < 3:
246
  return "Please select at least 3 symptoms for a better prediction."
247
-
248
- input_test = np.zeros(len(X_train.columns)) # Create an array for feature input
249
  for symptom in valid_symptoms:
250
  if symptom in X_train.columns:
251
  input_test[X_train.columns.get_loc(symptom)] = 1
252
-
253
  predictions = {}
254
  for model_name, info in trained_models.items():
255
  prediction = info['model'].predict([input_test])[0]
256
  predicted_disease = label_encoder.inverse_transform([prediction])[0]
257
  predictions[model_name] = predicted_disease
258
-
259
- # Create a Markdown table for displaying predictions
260
  markdown_output = [
261
  "### Predicted Diseases",
262
  "| Model | Predicted Disease |",
@@ -264,10 +242,8 @@ def predict_disease(symptoms):
264
  ]
265
  for model_name, disease in predictions.items():
266
  markdown_output.append(f"| {model_name} | {disease} |")
267
-
268
  return "\n".join(markdown_output)
269
 
270
- # CSS for the animated welcome message and improved styles
271
  welcome_message = """
272
  <style>
273
  @keyframes fadeIn {
@@ -302,10 +278,8 @@ welcome_message = """
302
  <div id="welcome-message">Welcome to the Well-Being Companion!</div>
303
  """
304
 
305
- # Gradio Application Interface
306
  with gr.Blocks(theme="shivi/calm_seafoam") as app:
307
- gr.HTML(welcome_message) # Animated welcome message
308
-
309
  with gr.Tab("Well-Being Chatbot"):
310
  gr.HTML("""
311
  <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
@@ -323,8 +297,6 @@ with gr.Blocks(theme="shivi/calm_seafoam") as app:
323
  <li>πŸ‘‰ Receive emotional support suggestions based on your chat.</li>
324
  </ul>
325
  """)
326
-
327
- # Infographics with images
328
  gr.HTML("""
329
  <div class="info-graphic">
330
  <img src="https://i.imgur.com/3ixjqBf.png" alt="Wellness Image 1">
@@ -332,44 +304,35 @@ with gr.Blocks(theme="shivi/calm_seafoam") as app:
332
  <img src="https://i.imgur.com/hcYAUJ3.png" alt="Wellness Image 3">
333
  </div>
334
  """)
335
-
336
  with gr.Row():
337
  user_input = gr.Textbox(label="Please Enter Your Message Here", placeholder="Type your message here...", max_lines=3)
338
  location = gr.Textbox(label="Please Enter Your Current Location", placeholder="E.g., Honolulu", max_lines=1)
339
  query = gr.Textbox(label="Search Health Professionals Nearby", placeholder="E.g., Health Professionals", max_lines=1)
340
-
341
  with gr.Row():
342
  submit_chatbot = gr.Button(value="Submit Your Message", variant="primary")
343
  clear_chatbot = gr.Button(value="Clear", variant="secondary")
344
-
345
  chatbot = gr.Chatbot(label="Chat History", show_label=True)
346
  sentiment = gr.Textbox(label="Detected Sentiment", show_label=True)
347
  emotion = gr.Textbox(label="Detected Emotion", show_label=True)
348
-
349
  professionals = gr.DataFrame(
350
  label="Nearby Health Professionals",
351
  headers=["Name", "Address"],
352
  value=[]
353
  )
354
-
355
  suggestions_markdown = gr.Markdown(label="Suggestions")
356
  map_html = gr.HTML(label="Interactive Map")
357
-
358
  def clear_input():
359
  return "", []
360
-
361
  submit_chatbot.click(
362
  app_function_chatbot,
363
  inputs=[user_input, location, query, chatbot],
364
  outputs=[chatbot, sentiment, emotion, suggestions_markdown, professionals, map_html],
365
  )
366
-
367
  clear_chatbot.click(
368
  clear_input,
369
  inputs=None,
370
  outputs=[user_input, chatbot]
371
  )
372
-
373
  with gr.Tab("Disease Prediction"):
374
  gr.HTML("""
375
  <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
@@ -384,23 +347,18 @@ with gr.Blocks(theme="shivi/calm_seafoam") as app:
384
  <li>πŸ‘‰ Review the results displayed below!</li>
385
  </ul>
386
  """)
387
-
388
  symptom1 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 1", value=None)
389
  symptom2 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 2", value=None)
390
  symptom3 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 3", value=None)
391
  symptom4 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 4", value=None)
392
  symptom5 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 5", value=None)
393
-
394
  submit_disease = gr.Button(value="Predict Disease", variant="primary")
395
-
396
  disease_prediction_result = gr.Markdown(label="Predicted Diseases")
397
-
398
  submit_disease.click(
399
  lambda sym1, sym2, sym3, sym4, sym5: predict_disease([sym1, sym2, sym3, sym4, sym5]),
400
  inputs=[symptom1, symptom2, symptom3, symptom4, symptom5],
401
  outputs=disease_prediction_result
402
  )
403
 
404
- # Launch the Gradio application
405
  if __name__ == "__main__":
406
  app.launch(share=True)
 
2
  import gradio as gr
3
  import nltk
4
  import numpy as np
5
+ import tensorflow as tf
6
+ from tensorflow.keras.models import Sequential, load_model
7
+ from tensorflow.keras.layers import Dense
8
  import random
9
  import json
10
  import pickle
 
37
  with open("data.pickle", "rb") as f:
38
  words, labels, training, output = pickle.load(f)
39
 
40
+ # Build the chatbot model using TensorFlow 2.x Keras
41
+ chatbot_model = Sequential([
42
+ Dense(8, input_shape=(len(training[0]),), activation='relu'),
43
+ Dense(8, activation='relu'),
44
+ Dense(len(output[0]), activation='softmax')
45
+ ])
46
+ chatbot_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
47
+
48
+ # Load the saved model or train if not present
49
+ if os.path.exists("MentalHealthChatBotmodel.h5"):
50
+ chatbot_model = load_model("MentalHealthChatBotmodel.h5")
51
+ else:
52
+ chatbot_model.fit(training, output, epochs=1000, batch_size=8, verbose=1)
53
+ chatbot_model.save("MentalHealthChatBotmodel.h5")
54
 
55
  # Hugging Face sentiment and emotion models
56
  tokenizer_sentiment = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
 
65
  gmaps = googlemaps.Client(key=os.getenv("GOOGLE_API_KEY"))
66
 
67
  # Load the disease dataset
68
+ df_train = pd.read_csv("Training.csv")
69
+ df_test = pd.read_csv("Testing.csv")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  # Label encoder for consistent train/test encoding
72
  label_encoder = LabelEncoder()
73
 
74
  def prepare_data(df, is_train=True):
75
+ X = df.iloc[:, :-1]
76
+ y = df.iloc[:, -1]
 
77
  if is_train:
78
  y_encoded = label_encoder.fit_transform(y)
79
  else:
80
  y_encoded = label_encoder.transform(y)
81
  return X, y_encoded
82
 
 
83
  X_train, y_train = prepare_data(df_train, is_train=True)
84
  X_test, y_test = prepare_data(df_test, is_train=False)
85
 
 
101
  # --- Helper Functions for Chatbot ---
102
 
103
  def bag_of_words(s, words):
 
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()]
 
111
  return np.array(bag)
112
 
113
  def generate_chatbot_response(message, history):
 
114
  history = history or []
115
  try:
116
+ result = chatbot_model.predict(np.array([bag_of_words(message, words)]), verbose=0)
117
  tag = labels[np.argmax(result)]
118
  response = "I'm sorry, I didn't understand that. πŸ€”"
119
  for intent in intents_data["intents"]:
 
126
  return history, response
127
 
128
  def analyze_sentiment(user_input):
 
129
  inputs = tokenizer_sentiment(user_input, return_tensors="pt")
130
  with torch.no_grad():
131
  outputs = model_sentiment(**inputs)
 
134
  return f"Sentiment: {sentiment_map[sentiment_class]}"
135
 
136
  def detect_emotion(user_input):
 
137
  result = emotion_pipeline(user_input)
138
  emotion = result[0]["label"].lower().strip()
139
  emotion_map = {
 
147
  return emotion_map.get(emotion, "Unknown πŸ€”"), emotion
148
 
149
  def generate_suggestions(emotion):
 
150
  emotion_key = emotion.lower()
151
  suggestions = {
152
  "joy": [
 
193
  return "\n".join(formatted_suggestions)
194
 
195
  def get_health_professionals_and_map(location, query):
 
196
  try:
197
  if not location or not query:
198
+ return [], ""
 
199
  geo_location = gmaps.geocode(location)
200
  if geo_location:
201
  lat, lng = geo_location[0]["geometry"]["location"].values()
 
214
  logging.error(f"Error fetching health professionals: {e}")
215
  return [], ""
216
 
 
217
  def app_function_chatbot(user_input, location, query, history):
218
  chatbot_history, _ = generate_chatbot_response(user_input, history)
219
  sentiment_result = analyze_sentiment(user_input)
 
222
  professionals, map_html = get_health_professionals_and_map(location, query)
223
  return chatbot_history, sentiment_result, emotion_result, suggestions, professionals, map_html
224
 
 
225
  def predict_disease(symptoms):
226
+ valid_symptoms = [s for s in symptoms if s is not None]
 
227
  if len(valid_symptoms) < 3:
228
  return "Please select at least 3 symptoms for a better prediction."
229
+ input_test = np.zeros(len(X_train.columns))
 
230
  for symptom in valid_symptoms:
231
  if symptom in X_train.columns:
232
  input_test[X_train.columns.get_loc(symptom)] = 1
 
233
  predictions = {}
234
  for model_name, info in trained_models.items():
235
  prediction = info['model'].predict([input_test])[0]
236
  predicted_disease = label_encoder.inverse_transform([prediction])[0]
237
  predictions[model_name] = predicted_disease
 
 
238
  markdown_output = [
239
  "### Predicted Diseases",
240
  "| Model | Predicted Disease |",
 
242
  ]
243
  for model_name, disease in predictions.items():
244
  markdown_output.append(f"| {model_name} | {disease} |")
 
245
  return "\n".join(markdown_output)
246
 
 
247
  welcome_message = """
248
  <style>
249
  @keyframes fadeIn {
 
278
  <div id="welcome-message">Welcome to the Well-Being Companion!</div>
279
  """
280
 
 
281
  with gr.Blocks(theme="shivi/calm_seafoam") as app:
282
+ gr.HTML(welcome_message)
 
283
  with gr.Tab("Well-Being Chatbot"):
284
  gr.HTML("""
285
  <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
 
297
  <li>πŸ‘‰ Receive emotional support suggestions based on your chat.</li>
298
  </ul>
299
  """)
 
 
300
  gr.HTML("""
301
  <div class="info-graphic">
302
  <img src="https://i.imgur.com/3ixjqBf.png" alt="Wellness Image 1">
 
304
  <img src="https://i.imgur.com/hcYAUJ3.png" alt="Wellness Image 3">
305
  </div>
306
  """)
 
307
  with gr.Row():
308
  user_input = gr.Textbox(label="Please Enter Your Message Here", placeholder="Type your message here...", max_lines=3)
309
  location = gr.Textbox(label="Please Enter Your Current Location", placeholder="E.g., Honolulu", max_lines=1)
310
  query = gr.Textbox(label="Search Health Professionals Nearby", placeholder="E.g., Health Professionals", max_lines=1)
 
311
  with gr.Row():
312
  submit_chatbot = gr.Button(value="Submit Your Message", variant="primary")
313
  clear_chatbot = gr.Button(value="Clear", variant="secondary")
 
314
  chatbot = gr.Chatbot(label="Chat History", show_label=True)
315
  sentiment = gr.Textbox(label="Detected Sentiment", show_label=True)
316
  emotion = gr.Textbox(label="Detected Emotion", show_label=True)
 
317
  professionals = gr.DataFrame(
318
  label="Nearby Health Professionals",
319
  headers=["Name", "Address"],
320
  value=[]
321
  )
 
322
  suggestions_markdown = gr.Markdown(label="Suggestions")
323
  map_html = gr.HTML(label="Interactive Map")
 
324
  def clear_input():
325
  return "", []
 
326
  submit_chatbot.click(
327
  app_function_chatbot,
328
  inputs=[user_input, location, query, chatbot],
329
  outputs=[chatbot, sentiment, emotion, suggestions_markdown, professionals, map_html],
330
  )
 
331
  clear_chatbot.click(
332
  clear_input,
333
  inputs=None,
334
  outputs=[user_input, chatbot]
335
  )
 
336
  with gr.Tab("Disease Prediction"):
337
  gr.HTML("""
338
  <h1 style="color: #388e3c; font-family: 'Helvetica', sans-serif; text-align: center; font-size: 3.5em; margin-bottom: 0;">
 
347
  <li>πŸ‘‰ Review the results displayed below!</li>
348
  </ul>
349
  """)
 
350
  symptom1 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 1", value=None)
351
  symptom2 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 2", value=None)
352
  symptom3 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 3", value=None)
353
  symptom4 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 4", value=None)
354
  symptom5 = gr.Dropdown(choices=[None] + list(X_train.columns), label="Select Symptom 5", value=None)
 
355
  submit_disease = gr.Button(value="Predict Disease", variant="primary")
 
356
  disease_prediction_result = gr.Markdown(label="Predicted Diseases")
 
357
  submit_disease.click(
358
  lambda sym1, sym2, sym3, sym4, sym5: predict_disease([sym1, sym2, sym3, sym4, sym5]),
359
  inputs=[symptom1, symptom2, symptom3, symptom4, symptom5],
360
  outputs=disease_prediction_result
361
  )
362
 
 
363
  if __name__ == "__main__":
364
  app.launch(share=True)