|
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): |
|
|
|
self.sentiment_pipeline = pipeline("text-classification", model=sentiment_model_path) |
|
self.classify_pipeline = pipeline("text-classification", model=disorder_model_path) |
|
|
|
|
|
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 = { |
|
|
|
} |
|
|
|
|
|
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() |
|
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("------------------------------------------------------------") |
|
|
|
|