hasanmustafa0503 commited on
Commit
5c884db
·
verified ·
1 Parent(s): 26a4d5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +283 -284
app.py CHANGED
@@ -1,285 +1,284 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
- import numpy as np
4
- from gradio_client import Client
5
- import matplotlib.pyplot as plt
6
- from lime.lime_text import LimeTextExplainer
7
- from datetime import datetime
8
- import sqlite3
9
- import logging
10
-
11
-
12
- DB_NAME = "mental_health.db"
13
-
14
- # --- Database Setup ---
15
- def create_database():
16
- conn = sqlite3.connect(DB_NAME)
17
- cursor = conn.cursor()
18
- cursor.execute("""
19
- CREATE TABLE IF NOT EXISTS mental_health_analysis (
20
- id INTEGER PRIMARY KEY AUTOINCREMENT,
21
- user_id TEXT NOT NULL
22
- text TEXT NOT NULL,
23
- sentiment TEXT,
24
- sentiment_confidence REAL,
25
- disorder TEXT,
26
- disorder_confidence REAL,
27
- risk_level TEXT,
28
- recommendations TEXT,
29
- date TEXT
30
- )
31
- """)
32
- conn.commit()
33
- conn.close()
34
-
35
- # --- Insert Results into Database ---
36
- def insert_into_database(user_id, text, sentiment, sentiment_confidence, disorder, disorder_confidence, risk_level, recommendations, date):
37
- conn = sqlite3.connect(DB_NAME)
38
- cursor = conn.cursor()
39
-
40
- # Convert list to string for recommendations
41
- recommendations_str = "; ".join(recommendations)
42
-
43
- cursor.execute("""
44
- INSERT INTO mental_health (
45
- user_id, text, sentiment, sentiment_confidence, disorder, disorder_confidence, risk_level, recommendations, date
46
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
47
- """, (
48
- text, sentiment, sentiment_confidence, disorder,
49
- disorder_confidence, risk_level, recommendations_str, date
50
- ))
51
-
52
- conn.commit()
53
- conn.close()
54
-
55
- create_database()
56
-
57
- class MentalHealthChatbot:
58
- def __init__(self):
59
- self.sentiment_client = Client("hasanmustafa0503/sentiment-api")
60
- self.disorder_client = Client("hasanmustafa0503/disoreder-api")
61
-
62
- # Label mappings
63
- self.label_mapping = {
64
- "LABEL_0": "ADHD",
65
- "LABEL_1": "BPD",
66
- "LABEL_2": "OCD",
67
- "LABEL_3": "PTSD",
68
- "LABEL_4": "Anxiety",
69
- "LABEL_5": "Autism",
70
- "LABEL_6": "Bipolar",
71
- "LABEL_7": "Depression",
72
- "LABEL_8": "Eating Disorders",
73
- "LABEL_9": "Health",
74
- "LABEL_10": "Mental Illness",
75
- "LABEL_11": "Schizophrenia",
76
- "LABEL_12": "Suicide Watch"
77
- }
78
-
79
- self.sentiment_mapping = {
80
- "POS": "Positive",
81
- "NEG": "Negative",
82
- "NEU": "Neutral"
83
- }
84
-
85
- self.exercise_recommendations = {
86
- # Exercise recommendations data as defined in the original code
87
- }
88
-
89
- # Initialize the LIME explainer
90
- self.explainer = LimeTextExplainer(class_names=list(self.sentiment_mapping.values()) + list(self.label_mapping.values()))
91
-
92
- def get_sentiment(self, text):
93
- results = self.sentiment_client.predict(text=text, api_name="/predict")
94
-
95
- if results and isinstance(results, list):
96
- label = results[0]['label']
97
- confidence_score = results[0]['score']*100
98
- sentiment = self.sentiment_mapping.get(label, "Unknown")
99
- return sentiment, confidence_score
100
- return "Unknown", 0
101
-
102
-
103
- def get_disorder(self, text, threshold=35):
104
- results = self.disorder_client.predict(text=text, api_name="/predict")
105
- if results and isinstance(results, list):
106
- best_result = results[0]
107
- disorder_confidence = best_result["score"] * 100
108
-
109
- if disorder_confidence > threshold:
110
- disorder_label = self.label_mapping.get(best_result["label"], "Unknown Disorder")
111
-
112
- if disorder_confidence < 50:
113
- risk_level = "Low Risk"
114
- elif 50 <= disorder_confidence <= 75:
115
- risk_level = "Moderate Risk"
116
- else:
117
- risk_level = "High Risk"
118
-
119
- return disorder_label, disorder_confidence, risk_level
120
-
121
- return "No significant disorder detected", 0.0, "No Risk"
122
-
123
-
124
- def predict_fn(self, texts):
125
- sentiment_probs = []
126
- disorder_probs = []
127
- sentiment_labels = []
128
- disorder_labels = []
129
-
130
- for text in texts:
131
- sentiment, sentiment_confidence = self.get_sentiment(text)
132
- sentiment_probs.append([sentiment_confidence / 100])
133
- sentiment_labels.append(sentiment)
134
-
135
- disorder_label, disorder_confidence, risk_level = self.get_disorder(text)
136
- disorder_probs.append([disorder_confidence / 100])
137
- disorder_labels.append(disorder_label)
138
-
139
- sentiment_probs = np.array(sentiment_probs)
140
- disorder_probs = np.array(disorder_probs)
141
-
142
- result = np.hstack([sentiment_probs, disorder_probs])
143
-
144
- return result, sentiment_labels, disorder_labels
145
-
146
- def lime_predict_fn(self, texts):
147
- result, _, _ = self.predict_fn(texts)
148
- return result
149
-
150
-
151
- def explain_text(self, text):
152
- explanation = self.explainer.explain_instance(text, self.lime_predict_fn, num_features=5, num_samples=25)
153
- explanation.as_pyplot_figure() # Display the plot
154
- plt.show()
155
-
156
- explanation_str = "The model's prediction is influenced by the following factors: "
157
- explanation_str += "; ".join([f'"{feature}" contributes with a weight of {weight:.4f}'
158
- for feature, weight in explanation.as_list()]) + "."
159
- return explanation_str
160
-
161
- def get_recommendations(self, condition, risk_level):
162
- exercise_recommendations = {
163
- "Depression": {
164
- "High Risk": ["Try 10 minutes of deep breathing.", "Go for a 15-minute walk in nature.", "Practice guided meditation."],
165
- "Moderate Risk": ["Write down 3 things you’re grateful for.", "Do light stretching or yoga for 10 minutes.", "Listen to calming music."],
166
- "Low Risk": ["Engage in a hobby you enjoy.", "Call a friend and have a short chat.", "Do a short 5-minute mindfulness exercise."]
167
- },
168
- "Anxiety": {
169
- "High Risk": ["Try progressive muscle relaxation.", "Use the 4-7-8 breathing technique.", "Write down your thoughts to clear your mind."],
170
- "Moderate Risk": ["Listen to nature sounds or white noise.", "Take a 15-minute break from screens.", "Try a short visualization exercise."],
171
- "Low Risk": ["Practice slow, deep breathing for 5 minutes.", "Drink herbal tea and relax.", "Read a book for 10 minutes."]
172
- },
173
- "Bipolar": {
174
- "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."],
175
- "Moderate Risk": ["Do a 10-minute gentle yoga session.", "Keep a mood journal for self-awareness.", "Practice self-affirmations."],
176
- "Low Risk": ["Engage in light exercise like jogging.", "Practice mindful eating for a meal.", "Do deep breathing exercises."]
177
- },
178
- "OCD": {
179
- "High Risk": ["Use exposure-response prevention techniques.", "Try 5 minutes of guided meditation.", "Write down intrusive thoughts and challenge them."],
180
- "Moderate Risk": ["Take a short break from triggers.", "Practice progressive relaxation.", "Engage in a calming activity like drawing."],
181
- "Low Risk": ["Practice deep breathing with slow exhales.", "Listen to soft music and relax.", "Try focusing on one simple task at a time."]
182
- },
183
- "PTSD": {
184
- "High Risk": ["Try grounding techniques (hold an object, describe it).", "Do 4-7-8 breathing for relaxation.", "Write in a trauma journal."],
185
- "Moderate Risk": ["Practice mindfulness for 5 minutes.", "Engage in slow, rhythmic movement (walking, stretching).", "Listen to soothing music."],
186
- "Low Risk": ["Try positive visualization techniques.", "Engage in light exercise or stretching.", "Spend time in a quiet, safe space."]
187
- },
188
- "Suicide Watch": {
189
- "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."],
190
- "Moderate Risk": ["Write a letter to your future self.", "Listen to uplifting music.", "Practice self-care (take a bath, make tea, etc.)."],
191
- "Low Risk": ["Watch a motivational video.", "Write down your emotions in a journal.", "Spend time with loved ones."]
192
- },
193
- "ADHD": {
194
- "High Risk": ["Try structured routines for the day.", "Use a timer for focus sessions.", "Engage in short bursts of physical activity."],
195
- "Moderate Risk": ["Do a quick exercise routine (jumping jacks, stretches).", "Use fidget toys to channel energy.", "Try meditation with background music."],
196
- "Low Risk": ["Practice deep breathing.", "Listen to classical or instrumental music.", "Organize your workspace."]
197
- },
198
- "BPD": {
199
- "High Risk": ["Try dialectical behavior therapy (DBT) techniques.", "Practice mindfulness.", "Use a weighted blanket for comfort."],
200
- "Moderate Risk": ["Write down emotions and analyze them.", "Engage in creative activities like painting.", "Listen to calming podcasts."],
201
- "Low Risk": ["Watch a lighthearted movie.", "Do breathing exercises.", "Call a friend for a short chat."]
202
- },
203
- "Autism": {
204
- "High Risk": ["Engage in deep-pressure therapy (weighted blanket).", "Use noise-canceling headphones.", "Try sensory-friendly relaxation techniques."],
205
- "Moderate Risk": ["Do repetitive physical activities like rocking.", "Practice structured breathing exercises.", "Engage in puzzles or memory games."],
206
- "Low Risk": ["Spend time in a quiet space.", "Listen to soft instrumental music.", "Follow a structured schedule."]
207
- },
208
- "Schizophrenia": {
209
- "High Risk": ["Seek immediate support from a trusted person.", "Try simple grounding exercises.", "Use distraction techniques like puzzles."],
210
- "Moderate Risk": ["Engage in light physical activity.", "Listen to calming sounds or music.", "Write thoughts in a journal."],
211
- "Low Risk": ["Read a familiar book.", "Do a 5-minute breathing exercise.", "Try progressive muscle relaxation."]
212
- },
213
- "Eating Disorders": {
214
- "High Risk": ["Seek professional help immediately.", "Try self-affirmations.", "Practice intuitive eating (listen to body cues)."],
215
- "Moderate Risk": ["Engage in mindful eating.", "Write down your emotions before meals.", "Do light stretching after meals."],
216
- "Low Risk": ["Try a gentle walk after eating.", "Listen to calming music.", "Write a gratitude journal about your body."]
217
- },
218
- "Mental Health": {
219
- "High Risk": ["Reach out to a mental health professional.", "Engage in deep relaxation techniques.", "Talk to a support group."],
220
- "Moderate Risk": ["Write in a daily journal.", "Practice guided meditation.", "Do light physical activities like walking."],
221
- "Low Risk": ["Try deep breathing exercises.", "Watch an uplifting video.", "Call a friend for a chat."]
222
- }
223
-
224
- }
225
- if condition in exercise_recommendations:
226
- if risk_level in exercise_recommendations[condition]:
227
- return exercise_recommendations[condition][risk_level]
228
- return ["No specific recommendations available."]
229
-
230
-
231
- bot = MentalHealthChatbot()
232
-
233
- def analyze_text(text):
234
- if not text.strip():
235
- return "No input provided.", "", "", "", "", ""
236
-
237
- sentiment, sentiment_conf = bot.get_sentiment(text)
238
- disorder, disorder_conf, risk = bot.get_disorder(text)
239
-
240
- if risk == "High Risk":
241
- logging.info("🚨 High risk detected! Alert triggered.")
242
- alert_msg = "✔ 🚨 Alert Notification Triggered: High risk detected!"
243
- else:
244
- alert_msg = "✔ Risk is not high. No alert triggered."
245
-
246
- recs = bot.get_recommendations(disorder, risk)
247
- lime_explanation = bot.explain_text(text)
248
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
249
-
250
- # Insert data into DB
251
- insert_into_database(
252
- text,
253
- sentiment,
254
- sentiment_conf,
255
- disorder,
256
- disorder_conf,
257
- risk,
258
- recs,
259
- timestamp
260
- )
261
-
262
- return (
263
- f"{sentiment} ({sentiment_conf:.2f}%)",
264
- f"{disorder} ({disorder_conf:.2f}%)",
265
- risk,
266
- "; ".join(recs),
267
- lime_explanation,
268
- alert_msg
269
- )
270
-
271
- # Gradio interface
272
- gr.Interface(
273
- fn=analyze_text,
274
- inputs=gr.Textbox(lines=6, label="Describe how you're feeling..."),
275
- outputs=[
276
- gr.Text(label="Sentiment"),
277
- gr.Text(label="Disorder"),
278
- gr.Text(label="Risk Level"),
279
- gr.Text(label="Recommendations"),
280
- gr.Text(label="LIME Explanation"),
281
- gr.Text(label="Alert Message")
282
- ],
283
- title="🧠 Mental Health Analysis Assistant",
284
- description="This tool uses AI to detect mental health conditions based on your input and suggest possible actions."
285
  ).launch()
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import numpy as np
4
+ from gradio_client import Client
5
+ import matplotlib.pyplot as plt
6
+ from lime.lime_text import LimeTextExplainer
7
+ from datetime import datetime
8
+ import sqlite3
9
+ import logging
10
+
11
+
12
+ DB_NAME = "mental_health_analysis.db"
13
+
14
+ # --- Database Setup ---
15
+ def create_database():
16
+ conn = sqlite3.connect(DB_NAME)
17
+ cursor = conn.cursor()
18
+ cursor.execute("""
19
+ CREATE TABLE IF NOT EXISTS mental_health_analysis (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ text TEXT NOT NULL,
22
+ sentiment TEXT,
23
+ sentiment_confidence REAL,
24
+ disorder TEXT,
25
+ disorder_confidence REAL,
26
+ risk_level TEXT,
27
+ recommendations TEXT,
28
+ date TEXT
29
+ )
30
+ """)
31
+ conn.commit()
32
+ conn.close()
33
+
34
+ # --- Insert Results into Database ---
35
+ def insert_into_database(text, sentiment, sentiment_confidence, disorder, disorder_confidence, risk_level, recommendations, date):
36
+ conn = sqlite3.connect(DB_NAME)
37
+ cursor = conn.cursor()
38
+
39
+ # Convert list to string for recommendations
40
+ recommendations_str = "; ".join(recommendations)
41
+
42
+ cursor.execute("""
43
+ INSERT INTO mental_health_analysis (
44
+ text, sentiment, sentiment_confidence, disorder, disorder_confidence, risk_level, recommendations, date
45
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
46
+ """, (
47
+ text, sentiment, sentiment_confidence, disorder,
48
+ disorder_confidence, risk_level, recommendations_str, date
49
+ ))
50
+
51
+ conn.commit()
52
+ conn.close()
53
+
54
+ create_database()
55
+
56
+ class MentalHealthChatbot:
57
+ def __init__(self):
58
+ self.sentiment_client = Client("hasanmustafa0503/sentiment-api")
59
+ self.disorder_client = Client("hasanmustafa0503/disoreder-api")
60
+
61
+ # Label mappings
62
+ self.label_mapping = {
63
+ "LABEL_0": "ADHD",
64
+ "LABEL_1": "BPD",
65
+ "LABEL_2": "OCD",
66
+ "LABEL_3": "PTSD",
67
+ "LABEL_4": "Anxiety",
68
+ "LABEL_5": "Autism",
69
+ "LABEL_6": "Bipolar",
70
+ "LABEL_7": "Depression",
71
+ "LABEL_8": "Eating Disorders",
72
+ "LABEL_9": "Health",
73
+ "LABEL_10": "Mental Illness",
74
+ "LABEL_11": "Schizophrenia",
75
+ "LABEL_12": "Suicide Watch"
76
+ }
77
+
78
+ self.sentiment_mapping = {
79
+ "POS": "Positive",
80
+ "NEG": "Negative",
81
+ "NEU": "Neutral"
82
+ }
83
+
84
+ self.exercise_recommendations = {
85
+ # Exercise recommendations data as defined in the original code
86
+ }
87
+
88
+ # Initialize the LIME explainer
89
+ self.explainer = LimeTextExplainer(class_names=list(self.sentiment_mapping.values()) + list(self.label_mapping.values()))
90
+
91
+ def get_sentiment(self, text):
92
+ results = self.sentiment_client.predict(text=text, api_name="/predict")
93
+
94
+ if results and isinstance(results, list):
95
+ label = results[0]['label']
96
+ confidence_score = results[0]['score']*100
97
+ sentiment = self.sentiment_mapping.get(label, "Unknown")
98
+ return sentiment, confidence_score
99
+ return "Unknown", 0
100
+
101
+
102
+ def get_disorder(self, text, threshold=35):
103
+ results = self.disorder_client.predict(text=text, api_name="/predict")
104
+ if results and isinstance(results, list):
105
+ best_result = results[0]
106
+ disorder_confidence = best_result["score"] * 100
107
+
108
+ if disorder_confidence > threshold:
109
+ disorder_label = self.label_mapping.get(best_result["label"], "Unknown Disorder")
110
+
111
+ if disorder_confidence < 50:
112
+ risk_level = "Low Risk"
113
+ elif 50 <= disorder_confidence <= 75:
114
+ risk_level = "Moderate Risk"
115
+ else:
116
+ risk_level = "High Risk"
117
+
118
+ return disorder_label, disorder_confidence, risk_level
119
+
120
+ return "No significant disorder detected", 0.0, "No Risk"
121
+
122
+
123
+ def predict_fn(self, texts):
124
+ sentiment_probs = []
125
+ disorder_probs = []
126
+ sentiment_labels = []
127
+ disorder_labels = []
128
+
129
+ for text in texts:
130
+ sentiment, sentiment_confidence = self.get_sentiment(text)
131
+ sentiment_probs.append([sentiment_confidence / 100])
132
+ sentiment_labels.append(sentiment)
133
+
134
+ disorder_label, disorder_confidence, risk_level = self.get_disorder(text)
135
+ disorder_probs.append([disorder_confidence / 100])
136
+ disorder_labels.append(disorder_label)
137
+
138
+ sentiment_probs = np.array(sentiment_probs)
139
+ disorder_probs = np.array(disorder_probs)
140
+
141
+ result = np.hstack([sentiment_probs, disorder_probs])
142
+
143
+ return result, sentiment_labels, disorder_labels
144
+
145
+ def lime_predict_fn(self, texts):
146
+ result, _, _ = self.predict_fn(texts)
147
+ return result
148
+
149
+
150
+ def explain_text(self, text):
151
+ explanation = self.explainer.explain_instance(text, self.lime_predict_fn, num_features=5, num_samples=25)
152
+ explanation.as_pyplot_figure() # Display the plot
153
+ plt.show()
154
+
155
+ explanation_str = "The model's prediction is influenced by the following factors: "
156
+ explanation_str += "; ".join([f'"{feature}" contributes with a weight of {weight:.4f}'
157
+ for feature, weight in explanation.as_list()]) + "."
158
+ return explanation_str
159
+
160
+ def get_recommendations(self, condition, risk_level):
161
+ exercise_recommendations = {
162
+ "Depression": {
163
+ "High Risk": ["Try 10 minutes of deep breathing.", "Go for a 15-minute walk in nature.", "Practice guided meditation."],
164
+ "Moderate Risk": ["Write down 3 things you’re grateful for.", "Do light stretching or yoga for 10 minutes.", "Listen to calming music."],
165
+ "Low Risk": ["Engage in a hobby you enjoy.", "Call a friend and have a short chat.", "Do a short 5-minute mindfulness exercise."]
166
+ },
167
+ "Anxiety": {
168
+ "High Risk": ["Try progressive muscle relaxation.", "Use the 4-7-8 breathing technique.", "Write down your thoughts to clear your mind."],
169
+ "Moderate Risk": ["Listen to nature sounds or white noise.", "Take a 15-minute break from screens.", "Try a short visualization exercise."],
170
+ "Low Risk": ["Practice slow, deep breathing for 5 minutes.", "Drink herbal tea and relax.", "Read a book for 10 minutes."]
171
+ },
172
+ "Bipolar": {
173
+ "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."],
174
+ "Moderate Risk": ["Do a 10-minute gentle yoga session.", "Keep a mood journal for self-awareness.", "Practice self-affirmations."],
175
+ "Low Risk": ["Engage in light exercise like jogging.", "Practice mindful eating for a meal.", "Do deep breathing exercises."]
176
+ },
177
+ "OCD": {
178
+ "High Risk": ["Use exposure-response prevention techniques.", "Try 5 minutes of guided meditation.", "Write down intrusive thoughts and challenge them."],
179
+ "Moderate Risk": ["Take a short break from triggers.", "Practice progressive relaxation.", "Engage in a calming activity like drawing."],
180
+ "Low Risk": ["Practice deep breathing with slow exhales.", "Listen to soft music and relax.", "Try focusing on one simple task at a time."]
181
+ },
182
+ "PTSD": {
183
+ "High Risk": ["Try grounding techniques (hold an object, describe it).", "Do 4-7-8 breathing for relaxation.", "Write in a trauma journal."],
184
+ "Moderate Risk": ["Practice mindfulness for 5 minutes.", "Engage in slow, rhythmic movement (walking, stretching).", "Listen to soothing music."],
185
+ "Low Risk": ["Try positive visualization techniques.", "Engage in light exercise or stretching.", "Spend time in a quiet, safe space."]
186
+ },
187
+ "Suicide Watch": {
188
+ "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."],
189
+ "Moderate Risk": ["Write a letter to your future self.", "Listen to uplifting music.", "Practice self-care (take a bath, make tea, etc.)."],
190
+ "Low Risk": ["Watch a motivational video.", "Write down your emotions in a journal.", "Spend time with loved ones."]
191
+ },
192
+ "ADHD": {
193
+ "High Risk": ["Try structured routines for the day.", "Use a timer for focus sessions.", "Engage in short bursts of physical activity."],
194
+ "Moderate Risk": ["Do a quick exercise routine (jumping jacks, stretches).", "Use fidget toys to channel energy.", "Try meditation with background music."],
195
+ "Low Risk": ["Practice deep breathing.", "Listen to classical or instrumental music.", "Organize your workspace."]
196
+ },
197
+ "BPD": {
198
+ "High Risk": ["Try dialectical behavior therapy (DBT) techniques.", "Practice mindfulness.", "Use a weighted blanket for comfort."],
199
+ "Moderate Risk": ["Write down emotions and analyze them.", "Engage in creative activities like painting.", "Listen to calming podcasts."],
200
+ "Low Risk": ["Watch a lighthearted movie.", "Do breathing exercises.", "Call a friend for a short chat."]
201
+ },
202
+ "Autism": {
203
+ "High Risk": ["Engage in deep-pressure therapy (weighted blanket).", "Use noise-canceling headphones.", "Try sensory-friendly relaxation techniques."],
204
+ "Moderate Risk": ["Do repetitive physical activities like rocking.", "Practice structured breathing exercises.", "Engage in puzzles or memory games."],
205
+ "Low Risk": ["Spend time in a quiet space.", "Listen to soft instrumental music.", "Follow a structured schedule."]
206
+ },
207
+ "Schizophrenia": {
208
+ "High Risk": ["Seek immediate support from a trusted person.", "Try simple grounding exercises.", "Use distraction techniques like puzzles."],
209
+ "Moderate Risk": ["Engage in light physical activity.", "Listen to calming sounds or music.", "Write thoughts in a journal."],
210
+ "Low Risk": ["Read a familiar book.", "Do a 5-minute breathing exercise.", "Try progressive muscle relaxation."]
211
+ },
212
+ "Eating Disorders": {
213
+ "High Risk": ["Seek professional help immediately.", "Try self-affirmations.", "Practice intuitive eating (listen to body cues)."],
214
+ "Moderate Risk": ["Engage in mindful eating.", "Write down your emotions before meals.", "Do light stretching after meals."],
215
+ "Low Risk": ["Try a gentle walk after eating.", "Listen to calming music.", "Write a gratitude journal about your body."]
216
+ },
217
+ "Mental Health": {
218
+ "High Risk": ["Reach out to a mental health professional.", "Engage in deep relaxation techniques.", "Talk to a support group."],
219
+ "Moderate Risk": ["Write in a daily journal.", "Practice guided meditation.", "Do light physical activities like walking."],
220
+ "Low Risk": ["Try deep breathing exercises.", "Watch an uplifting video.", "Call a friend for a chat."]
221
+ }
222
+
223
+ }
224
+ if condition in exercise_recommendations:
225
+ if risk_level in exercise_recommendations[condition]:
226
+ return exercise_recommendations[condition][risk_level]
227
+ return ["No specific recommendations available."]
228
+
229
+
230
+ bot = MentalHealthChatbot()
231
+
232
+ def analyze_text(text):
233
+ if not text.strip():
234
+ return "No input provided.", "", "", "", "", ""
235
+
236
+ sentiment, sentiment_conf = bot.get_sentiment(text)
237
+ disorder, disorder_conf, risk = bot.get_disorder(text)
238
+
239
+ if risk == "High Risk":
240
+ logging.info("🚨 High risk detected! Alert triggered.")
241
+ alert_msg = "🚨 Alert Notification Triggered: High risk detected!"
242
+ else:
243
+ alert_msg = "✔ Risk is not high. No alert triggered."
244
+
245
+ recs = bot.get_recommendations(disorder, risk)
246
+ lime_explanation = bot.explain_text(text)
247
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
248
+
249
+ # Insert data into DB
250
+ insert_into_database(
251
+ text,
252
+ sentiment,
253
+ sentiment_conf,
254
+ disorder,
255
+ disorder_conf,
256
+ risk,
257
+ recs,
258
+ timestamp
259
+ )
260
+
261
+ return (
262
+ f"{sentiment} ({sentiment_conf:.2f}%)",
263
+ f"{disorder} ({disorder_conf:.2f}%)",
264
+ risk,
265
+ "; ".join(recs),
266
+ lime_explanation,
267
+ alert_msg
268
+ )
269
+
270
+ # Gradio interface
271
+ gr.Interface(
272
+ fn=analyze_text,
273
+ inputs=gr.Textbox(lines=6, label="Describe how you're feeling..."),
274
+ outputs=[
275
+ gr.Text(label="Sentiment"),
276
+ gr.Text(label="Disorder"),
277
+ gr.Text(label="Risk Level"),
278
+ gr.Text(label="Recommendations"),
279
+ gr.Text(label="LIME Explanation"),
280
+ gr.Text(label="Alert Message")
281
+ ],
282
+ title="🧠 Mental Health Analysis Assistant",
283
+ description="This tool uses AI to detect mental health conditions based on your input and suggest possible actions."
 
284
  ).launch()