hasanmustafa0503 commited on
Commit
05a1b2e
·
verified ·
1 Parent(s): 9a5142e

Upload mentalchatbot.py

Browse files
Files changed (1) hide show
  1. mentalchatbot.py +190 -0
mentalchatbot.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from lime.lime_text import LimeTextExplainer
5
+
6
+ class MentalHealthChatbot:
7
+ def __init__(self, sentiment_model_path, disorder_model_path):
8
+ # Load sentiment and classification models
9
+ self.sentiment_pipeline = pipeline("text-classification", model=sentiment_model_path)
10
+ self.classify_pipeline = pipeline("text-classification", model=disorder_model_path)
11
+
12
+ # Label mappings
13
+ self.label_mapping = {
14
+ "LABEL_0": "ADHD",
15
+ "LABEL_1": "BPD",
16
+ "LABEL_2": "OCD",
17
+ "LABEL_3": "PTSD",
18
+ "LABEL_4": "Anxiety",
19
+ "LABEL_5": "Autism",
20
+ "LABEL_6": "Bipolar",
21
+ "LABEL_7": "Depression",
22
+ "LABEL_8": "Eating Disorders",
23
+ "LABEL_9": "Health",
24
+ "LABEL_10": "Mental Illness",
25
+ "LABEL_11": "Schizophrenia",
26
+ "LABEL_12": "Suicide Watch"
27
+ }
28
+
29
+ self.sentiment_mapping = {
30
+ "POS": "Positive",
31
+ "NEG": "Negative",
32
+ "NEU": "Neutral"
33
+ }
34
+
35
+ self.exercise_recommendations = {
36
+ # Exercise recommendations data as defined in the original code
37
+ }
38
+
39
+ # Initialize the LIME explainer
40
+ self.explainer = LimeTextExplainer(class_names=list(self.sentiment_mapping.values()) + list(self.label_mapping.values()))
41
+
42
+ def get_sentiment(self, text):
43
+ results = self.sentiment_pipeline(text)
44
+ if results and isinstance(results, list):
45
+ best_result = results[0]
46
+ label = self.sentiment_mapping.get(best_result["label"], "Unknown")
47
+ confidence = best_result["score"] * 100
48
+ return label, confidence
49
+ return "Unknown", 0
50
+
51
+ def get_disorder(self, text, threshold=50):
52
+ results = self.classify_pipeline(text)
53
+ if results and isinstance(results, list):
54
+ best_result = results[0]
55
+ disorder_confidence = best_result["score"] * 100
56
+ if disorder_confidence > threshold:
57
+ disorder_label = self.label_mapping.get(best_result["label"], "Unknown")
58
+
59
+ if disorder_confidence < 50:
60
+ risk_level = "Low Risk"
61
+ elif 50 <= disorder_confidence <= 75:
62
+ risk_level = "Moderate Risk"
63
+ else:
64
+ risk_level = "High Risk"
65
+
66
+ if risk_level == "High Risk":
67
+ print("✔ 🚨 Alert Notification Triggered: High risk detected!\n")
68
+
69
+ return disorder_label, disorder_confidence, risk_level
70
+
71
+ return "No significant disorder detected", 0.0, "No Risk"
72
+
73
+ def predict_fn(self, texts):
74
+ sentiment_output = self.sentiment_pipeline(texts)
75
+ sentiment_probs = np.array([[item['score']] for item in sentiment_output])
76
+
77
+ disorder_output = self.classify_pipeline(texts)
78
+ disorder_probs = np.vstack([np.array([item['score']]) for item in disorder_output])
79
+
80
+ result = np.hstack([sentiment_probs, disorder_probs])
81
+ return result
82
+
83
+ def explain_text(self, text):
84
+ explanation = self.explainer.explain_instance(text, self.predict_fn, num_features=5, num_samples=25)
85
+ explanation.as_pyplot_figure() # Display the plot
86
+ plt.show()
87
+
88
+ explanation_str = "The model's prediction is influenced by the following factors: "
89
+ explanation_str += "; ".join([f'"{feature}" contributes with a weight of {weight:.4f}'
90
+ for feature, weight in explanation.as_list()]) + "."
91
+ return explanation_str
92
+
93
+ def get_recommendations(self,condition, risk_level):
94
+ exercise_recommendations = {
95
+ "Depression": {
96
+ "High Risk": ["Try 10 minutes of deep breathing.", "Go for a 15-minute walk in nature.", "Practice guided meditation."],
97
+ "Moderate Risk": ["Write down 3 things you’re grateful for.", "Do light stretching or yoga for 10 minutes.", "Listen to calming music."],
98
+ "Low Risk": ["Engage in a hobby you enjoy.", "Call a friend and have a short chat.", "Do a short 5-minute mindfulness exercise."]
99
+ },
100
+ "Anxiety": {
101
+ "High Risk": ["Try progressive muscle relaxation.", "Use the 4-7-8 breathing technique.", "Write down your thoughts to clear your mind."],
102
+ "Moderate Risk": ["Listen to nature sounds or white noise.", "Take a 15-minute break from screens.", "Try a short visualization exercise."],
103
+ "Low Risk": ["Practice slow, deep breathing for 5 minutes.", "Drink herbal tea and relax.", "Read a book for 10 minutes."]
104
+ },
105
+ "Bipolar": {
106
+ "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."],
107
+ "Moderate Risk": ["Do a 10-minute gentle yoga session.", "Keep a mood journal for self-awareness.", "Practice self-affirmations."],
108
+ "Low Risk": ["Engage in light exercise like jogging.", "Practice mindful eating for a meal.", "Do deep breathing exercises."]
109
+ },
110
+ "OCD": {
111
+ "High Risk": ["Use exposure-response prevention techniques.", "Try 5 minutes of guided meditation.", "Write down intrusive thoughts and challenge them."],
112
+ "Moderate Risk": ["Take a short break from triggers.", "Practice progressive relaxation.", "Engage in a calming activity like drawing."],
113
+ "Low Risk": ["Practice deep breathing with slow exhales.", "Listen to soft music and relax.", "Try focusing on one simple task at a time."]
114
+ },
115
+ "PTSD": {
116
+ "High Risk": ["Try grounding techniques (hold an object, describe it).", "Do 4-7-8 breathing for relaxation.", "Write in a trauma journal."],
117
+ "Moderate Risk": ["Practice mindfulness for 5 minutes.", "Engage in slow, rhythmic movement (walking, stretching).", "Listen to soothing music."],
118
+ "Low Risk": ["Try positive visualization techniques.", "Engage in light exercise or stretching.", "Spend time in a quiet, safe space."]
119
+ },
120
+ "Suicide Watch": {
121
+ "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."],
122
+ "Moderate Risk": ["Write a letter to your future self.", "Listen to uplifting music.", "Practice self-care (take a bath, make tea, etc.)."],
123
+ "Low Risk": ["Watch a motivational video.", "Write down your emotions in a journal.", "Spend time with loved ones."]
124
+ },
125
+ "ADHD": {
126
+ "High Risk": ["Try structured routines for the day.", "Use a timer for focus sessions.", "Engage in short bursts of physical activity."],
127
+ "Moderate Risk": ["Do a quick exercise routine (jumping jacks, stretches).", "Use fidget toys to channel energy.", "Try meditation with background music."],
128
+ "Low Risk": ["Practice deep breathing.", "Listen to classical or instrumental music.", "Organize your workspace."]
129
+ },
130
+ "BPD": {
131
+ "High Risk": ["Try dialectical behavior therapy (DBT) techniques.", "Practice mindfulness.", "Use a weighted blanket for comfort."],
132
+ "Moderate Risk": ["Write down emotions and analyze them.", "Engage in creative activities like painting.", "Listen to calming podcasts."],
133
+ "Low Risk": ["Watch a lighthearted movie.", "Do breathing exercises.", "Call a friend for a short chat."]
134
+ },
135
+ "Autism": {
136
+ "High Risk": ["Engage in deep-pressure therapy (weighted blanket).", "Use noise-canceling headphones.", "Try sensory-friendly relaxation techniques."],
137
+ "Moderate Risk": ["Do repetitive physical activities like rocking.", "Practice structured breathing exercises.", "Engage in puzzles or memory games."],
138
+ "Low Risk": ["Spend time in a quiet space.", "Listen to soft instrumental music.", "Follow a structured schedule."]
139
+ },
140
+ "Schizophrenia": {
141
+ "High Risk": ["Seek immediate support from a trusted person.", "Try simple grounding exercises.", "Use distraction techniques like puzzles."],
142
+ "Moderate Risk": ["Engage in light physical activity.", "Listen to calming sounds or music.", "Write thoughts in a journal."],
143
+ "Low Risk": ["Read a familiar book.", "Do a 5-minute breathing exercise.", "Try progressive muscle relaxation."]
144
+ },
145
+ "Eating Disorders": {
146
+ "High Risk": ["Seek professional help immediately.", "Try self-affirmations.", "Practice intuitive eating (listen to body cues)."],
147
+ "Moderate Risk": ["Engage in mindful eating.", "Write down your emotions before meals.", "Do light stretching after meals."],
148
+ "Low Risk": ["Try a gentle walk after eating.", "Listen to calming music.", "Write a gratitude journal about your body."]
149
+ },
150
+ "Mental Health": {
151
+ "High Risk": ["Reach out to a mental health professional.", "Engage in deep relaxation techniques.", "Talk to a support group."],
152
+ "Moderate Risk": ["Write in a daily journal.", "Practice guided meditation.", "Do light physical activities like walking."],
153
+ "Low Risk": ["Try deep breathing exercises.", "Watch an uplifting video.", "Call a friend for a chat."]
154
+ }
155
+
156
+ }
157
+ if condition in exercise_recommendations:
158
+ if risk_level in exercise_recommendations[condition]:
159
+ return exercise_recommendations[condition][risk_level]
160
+ return ["No specific recommendations available."]
161
+
162
+ def run_chat(self, text):
163
+ sentiment, sentiment_confidence = self.get_sentiment(text)
164
+ disorder_label, disorder_confidence, risk_level = self.get_disorder(text)
165
+
166
+ print(f"\nText: {text}")
167
+ print(f"Sentiment: {sentiment} ({sentiment_confidence:.2f}%)")
168
+ print(f"Disorder: {disorder_label} ({disorder_confidence:.2f}%)")
169
+ print(f"Risk Level: {risk_level}")
170
+ print("\nLIME Explanation:")
171
+ explanation_str = self.explain_text(text)
172
+ print(f"\nExplanation:\n{explanation_str}")
173
+
174
+ # Provide recommendations
175
+ recommendations = self.get_recommendations(disorder_label, risk_level)
176
+ print("\nRecommended Actions:")
177
+ for action in recommendations:
178
+ print(f" - {action}")
179
+ print("-" * 50)
180
+
181
+ # Example of how to run the chatbot
182
+ if __name__ == "__main__":
183
+ # Replace the paths with actual paths to your models
184
+ chatbot = MentalHealthChatbot(sentiment_model_path="../ai_models/sentiment_model",
185
+ disorder_model_path="../ai_models/mental_health_model")
186
+
187
+ text = input("Enter your text: ")
188
+ chatbot.run_chat(text)
189
+ print("Thanks")
190
+