File size: 11,898 Bytes
b067019 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
from transformers import pipeline
import numpy as np
import matplotlib.pyplot as plt
from lime.lime_text import LimeTextExplainer
class MentalHealthChatbot:
def __init__(self, sentiment_model_path, disorder_model_path):
# Load sentiment and classification models
self.sentiment_pipeline = pipeline("text-classification", model=sentiment_model_path)
self.classify_pipeline = pipeline("text-classification", model=disorder_model_path)
# Label mappings
self.label_mapping = {
"LABEL_0": "ADHD",
"LABEL_1": "BPD",
"LABEL_2": "OCD",
"LABEL_3": "PTSD",
"LABEL_4": "Anxiety",
"LABEL_5": "Autism",
"LABEL_6": "Bipolar",
"LABEL_7": "Depression",
"LABEL_8": "Eating Disorders",
"LABEL_9": "Health",
"LABEL_10": "Mental Illness",
"LABEL_11": "Schizophrenia",
"LABEL_12": "Suicide Watch"
}
self.sentiment_mapping = {
"POS": "Positive",
"NEG": "Negative",
"NEU": "Neutral"
}
self.exercise_recommendations = {
# Exercise recommendations data as defined in the original code
}
# Initialize the LIME explainer
self.explainer = LimeTextExplainer(class_names=list(self.sentiment_mapping.values()) + list(self.label_mapping.values()))
def get_sentiment(self, text):
results = self.sentiment_pipeline(text)
if results and isinstance(results, list):
best_result = results[0]
label = self.sentiment_mapping.get(best_result["label"], "Unknown")
confidence = best_result["score"] * 100
return label, confidence
return "Unknown", 0
def get_disorder(self, text, threshold=50):
results = self.classify_pipeline(text)
if results and isinstance(results, list):
best_result = results[0]
disorder_confidence = best_result["score"] * 100
if disorder_confidence > threshold:
disorder_label = self.label_mapping.get(best_result["label"], "Unknown")
if disorder_confidence < 50:
risk_level = "Low Risk"
elif 50 <= disorder_confidence <= 75:
risk_level = "Moderate Risk"
else:
risk_level = "High Risk"
if risk_level == "High Risk":
print("β π¨ Alert Notification Triggered: High risk detected!\n")
return disorder_label, disorder_confidence, risk_level
return "No significant disorder detected", 0.0, "No Risk"
def predict_fn(self, texts):
sentiment_output = self.sentiment_pipeline(texts)
sentiment_probs = np.array([[item['score']] for item in sentiment_output])
disorder_output = self.classify_pipeline(texts)
disorder_probs = np.vstack([np.array([item['score']]) for item in disorder_output])
result = np.hstack([sentiment_probs, disorder_probs])
return result
def explain_text(self, text):
explanation = self.explainer.explain_instance(text, self.predict_fn, num_features=5, num_samples=25)
explanation.as_pyplot_figure() # Display the plot
plt.show()
explanation_str = "The model's prediction is influenced by the following factors: "
explanation_str += "; ".join([f'"{feature}" contributes with a weight of {weight:.4f}'
for feature, weight in explanation.as_list()]) + "."
return explanation_str
def get_recommendations(self,condition, risk_level):
exercise_recommendations = {
"Depression": {
"High Risk": ["Try 10 minutes of deep breathing.", "Go for a 15-minute walk in nature.", "Practice guided meditation."],
"Moderate Risk": ["Write down 3 things youβre grateful for.", "Do light stretching or yoga for 10 minutes.", "Listen to calming music."],
"Low Risk": ["Engage in a hobby you enjoy.", "Call a friend and have a short chat.", "Do a short 5-minute mindfulness exercise."]
},
"Anxiety": {
"High Risk": ["Try progressive muscle relaxation.", "Use the 4-7-8 breathing technique.", "Write down your thoughts to clear your mind."],
"Moderate Risk": ["Listen to nature sounds or white noise.", "Take a 15-minute break from screens.", "Try a short visualization exercise."],
"Low Risk": ["Practice slow, deep breathing for 5 minutes.", "Drink herbal tea and relax.", "Read a book for 10 minutes."]
},
"Bipolar": {
"High Risk": ["Engage in grounding techniques like 5-4-3-2-1.", "Try slow-paced walking in a quiet area.", "Listen to calm instrumental music."],
"Moderate Risk": ["Do a 10-minute gentle yoga session.", "Keep a mood journal for self-awareness.", "Practice self-affirmations."],
"Low Risk": ["Engage in light exercise like jogging.", "Practice mindful eating for a meal.", "Do deep breathing exercises."]
},
"OCD": {
"High Risk": ["Use exposure-response prevention techniques.", "Try 5 minutes of guided meditation.", "Write down intrusive thoughts and challenge them."],
"Moderate Risk": ["Take a short break from triggers.", "Practice progressive relaxation.", "Engage in a calming activity like drawing."],
"Low Risk": ["Practice deep breathing with slow exhales.", "Listen to soft music and relax.", "Try focusing on one simple task at a time."]
},
"PTSD": {
"High Risk": ["Try grounding techniques (hold an object, describe it).", "Do 4-7-8 breathing for relaxation.", "Write in a trauma journal."],
"Moderate Risk": ["Practice mindfulness for 5 minutes.", "Engage in slow, rhythmic movement (walking, stretching).", "Listen to soothing music."],
"Low Risk": ["Try positive visualization techniques.", "Engage in light exercise or stretching.", "Spend time in a quiet, safe space."]
},
"Suicide Watch": {
"High Risk": ["Immediately reach out to a mental health professional.", "Call a trusted friend or family member.", "Try a grounding exercise like cold water on hands."],
"Moderate Risk": ["Write a letter to your future self.", "Listen to uplifting music.", "Practice self-care (take a bath, make tea, etc.)."],
"Low Risk": ["Watch a motivational video.", "Write down your emotions in a journal.", "Spend time with loved ones."]
},
"ADHD": {
"High Risk": ["Try structured routines for the day.", "Use a timer for focus sessions.", "Engage in short bursts of physical activity."],
"Moderate Risk": ["Do a quick exercise routine (jumping jacks, stretches).", "Use fidget toys to channel energy.", "Try meditation with background music."],
"Low Risk": ["Practice deep breathing.", "Listen to classical or instrumental music.", "Organize your workspace."]
},
"BPD": {
"High Risk": ["Try dialectical behavior therapy (DBT) techniques.", "Practice mindfulness.", "Use a weighted blanket for comfort."],
"Moderate Risk": ["Write down emotions and analyze them.", "Engage in creative activities like painting.", "Listen to calming podcasts."],
"Low Risk": ["Watch a lighthearted movie.", "Do breathing exercises.", "Call a friend for a short chat."]
},
"Autism": {
"High Risk": ["Engage in deep-pressure therapy (weighted blanket).", "Use noise-canceling headphones.", "Try sensory-friendly relaxation techniques."],
"Moderate Risk": ["Do repetitive physical activities like rocking.", "Practice structured breathing exercises.", "Engage in puzzles or memory games."],
"Low Risk": ["Spend time in a quiet space.", "Listen to soft instrumental music.", "Follow a structured schedule."]
},
"Schizophrenia": {
"High Risk": ["Seek immediate support from a trusted person.", "Try simple grounding exercises.", "Use distraction techniques like puzzles."],
"Moderate Risk": ["Engage in light physical activity.", "Listen to calming sounds or music.", "Write thoughts in a journal."],
"Low Risk": ["Read a familiar book.", "Do a 5-minute breathing exercise.", "Try progressive muscle relaxation."]
},
"Eating Disorders": {
"High Risk": ["Seek professional help immediately.", "Try self-affirmations.", "Practice intuitive eating (listen to body cues)."],
"Moderate Risk": ["Engage in mindful eating.", "Write down your emotions before meals.", "Do light stretching after meals."],
"Low Risk": ["Try a gentle walk after eating.", "Listen to calming music.", "Write a gratitude journal about your body."]
},
"Mental Health": {
"High Risk": ["Reach out to a mental health professional.", "Engage in deep relaxation techniques.", "Talk to a support group."],
"Moderate Risk": ["Write in a daily journal.", "Practice guided meditation.", "Do light physical activities like walking."],
"Low Risk": ["Try deep breathing exercises.", "Watch an uplifting video.", "Call a friend for a chat."]
}
}
if condition in exercise_recommendations:
if risk_level in exercise_recommendations[condition]:
return exercise_recommendations[condition][risk_level]
return ["No specific recommendations available."]
def run_chat(self, text):
sentiment, sentiment_confidence = self.get_sentiment(text)
disorder_label, disorder_confidence, risk_level = self.get_disorder(text)
print("\nπ§ Mental Health Chatbot Assessment")
print("--------------------------------------------------")
print(f"π¨ You said: \"{text}\"\n")
print("Thank you for sharing. Let's take a closer look at what you're feeling.\n")
print("π Analysis Summary:")
print(f" π¬ Sentiment: {sentiment} | Confidence: {sentiment_confidence:.2f}%")
print(f" π©Ί Identified Condition: {disorder_label} | Confidence: {disorder_confidence:.2f}%")
print(f" π¦ Risk Level: {risk_level}")
print("\nπ Explanation (LIME Interpretation):")
print("--------------------------------------------------")
print("Hereβs how the system interpreted your message using explainable AI techniques:")
explanation_str = self.explain_text(text)
print(explanation_str + "\n")
print("\nπ§ Personalized Recommendations:")
print("--------------------------------------------------")
print("These are tailored suggestions to help guide you toward the next steps:")
recommendations = self.get_recommendations(disorder_label, risk_level)
for idx, action in enumerate(recommendations, 1):
print(f" {idx}. {action}")
print("We encourage you to try the steps that resonate with your situation.")
print("\nπ‘β¨ Just a Note from Your AI Companion:")
print("π€ I'm here to provide thoughtful insights and emotional support based on your input.")
print("π₯ If you're seeking connection or advice, feel free to visit our π Community Support Page.")
print("π§ββοΈ If things feel overwhelming, consider reaching out to a professional β either directly or with guidance from the community.")
print("You're not alone on this journey. We're here with you. π")
print("------------------------------------------------------------")
|