Spaces:
Sleeping
Sleeping
import torch | |
import gradio as gr | |
from transformers import AutoModelForCausalLM, AutoTokenizer | |
import numpy as np | |
from datetime import datetime | |
import logging | |
import nltk | |
import emoji | |
import re | |
import json | |
import warnings | |
import random | |
warnings.filterwarnings('ignore') | |
class EnhancedMentalHealthBot: | |
def __init__(self): | |
# Initialize base model components | |
self.model_name = "microsoft/DialoGPT-medium" | |
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) | |
self.model = AutoModelForCausalLM.from_pretrained(self.model_name) | |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
self.model.to(self.device) | |
# Initialize session management | |
self.chat_history = [] | |
self.current_emotional_state = "neutral" | |
self.session_notes = [] | |
self.therapy_goals = {} | |
# Therapeutic approaches available | |
self.therapeutic_approaches = { | |
"cbt": { | |
"active": False, | |
"techniques": ["thought_challenging", "behavioral_activation", "cognitive_restructuring"], | |
"session_structure": ["review", "agenda", "homework", "feedback"] | |
}, | |
"dbt": { | |
"active": False, | |
"techniques": ["mindfulness", "distress_tolerance", "emotion_regulation"], | |
"skills": ["wise_mind", "radical_acceptance", "crisis_survival"] | |
}, | |
"solution_focused": { | |
"active": False, | |
"techniques": ["miracle_question", "scaling", "exception_finding"], | |
"focus": "future_oriented" | |
}, | |
"mindfulness": { | |
"active": False, | |
"exercises": ["breathing", "body_scan", "grounding"], | |
"duration": "5-10 minutes" | |
} | |
} | |
# Enhanced communication preferences | |
self.communication_modes = { | |
"text": True, | |
"simple": False, | |
"emoji": False, | |
"structured": False, | |
"metaphorical": False, | |
"visual_aids": False, | |
"guided_exercises": False | |
} | |
# Expanded support resources | |
self.support_resources = { | |
"crisis": { | |
"hotline": "988", | |
"text_line": "Text HOME to 741741", | |
"emergency": "911" | |
}, | |
"community": { | |
"support_groups": "https://www.nami.org/Support-Education/Support-Groups", | |
"peer_support": "https://www.mhanational.org/find-support-groups" | |
}, | |
"self_help": { | |
"meditation_apps": ["Headspace", "Calm", "Insight Timer"], | |
"workbooks": ["Mind Over Mood", "The Anxiety and Phobia Workbook"], | |
"online_resources": ["https://www.therapistaid.com/worksheets"] | |
}, | |
"professional": { | |
"find_therapist": "https://www.psychologytoday.com/us/therapists", | |
"teletherapy": ["BetterHelp", "Talkspace", "7 Cups"] | |
} | |
} | |
# Setup advanced logging and analytics | |
logging.basicConfig( | |
filename='therapy_sessions.log', | |
level=logging.INFO, | |
format='%(asctime)s - %(levelname)s - %(message)s' | |
) | |
# Initialize NLTK components | |
nltk.download('vader_lexicon') | |
nltk.download('punkt') | |
from nltk.sentiment.vader import SentimentIntensityAnalyzer | |
self.sia = SentimentIntensityAnalyzer() | |
# Initialize therapeutic progress tracking | |
self.progress_metrics = { | |
"mood_tracking": [], | |
"goal_progress": {}, | |
"skill_usage": {}, | |
"session_ratings": [] | |
} | |
def detect_therapeutic_needs(self, text): | |
"""Analyze text to determine appropriate therapeutic approach""" | |
# Keywords associated with different therapeutic approaches | |
approach_keywords = { | |
"cbt": ["thoughts", "beliefs", "thinking patterns", "behavior", "negative thoughts"], | |
"dbt": ["overwhelming emotions", "impulses", "relationships", "mindfulness"], | |
"solution_focused": ["goals", "future", "solutions", "changes", "better"], | |
"mindfulness": ["present moment", "awareness", "meditation", "breathing", "stress"] | |
} | |
text_lower = text.lower() | |
detected_approaches = [] | |
for approach, keywords in approach_keywords.items(): | |
if any(keyword in text_lower for keyword in keywords): | |
detected_approaches.append(approach) | |
return detected_approaches | |
def detect_emotion(self, text): | |
"""Detect emotion based on sentiment analysis""" | |
sentiment_scores = self.sia.polarity_scores(text) | |
compound_score = sentiment_scores['compound'] | |
if compound_score >= 0.05: | |
return "positive" | |
elif compound_score <= -0.05: | |
return "negative" | |
else: | |
return "neutral" | |
def generate_therapeutic_response(self, user_input, active_approaches=None): | |
"""Generate response using appropriate therapeutic approach""" | |
detected_needs = self.detect_therapeutic_needs(user_input) | |
emotion = self.detect_emotion(user_input) | |
# Base response generation | |
base_response = self._generate_base_response(user_input) | |
# Filter the base response | |
if base_response.lower().startswith(user_input.lower()): | |
base_response = "" # Remove the duplicate input | |
# Enhance response with therapeutic elements | |
enhanced_response = self._apply_therapeutic_techniques( | |
base_response, | |
detected_needs, | |
emotion | |
) | |
# Add coping strategies if needed | |
if emotion in ["distressed", "negative"]: | |
enhanced_response += self._suggest_coping_strategies(emotion) | |
# Add progress tracking | |
self._update_progress_metrics(user_input, emotion) | |
# If the response is still too generic, create a new base response | |
if not enhanced_response or enhanced_response.lower().startswith(user_input.lower()): | |
if "work anxiety" in user_input.lower(): | |
new_base_response = "It's understandable to feel anxious about work. What specific aspects of work are causing you anxiety?" | |
enhanced_response = self._apply_therapeutic_techniques( | |
new_base_response, | |
detected_needs, | |
emotion | |
) | |
elif "negative thoughts" in user_input.lower() or "can't control" in user_input.lower(): | |
new_base_response = "It's common to experience negative thoughts, and it's important to remember you're not alone. Can you tell me more about the thoughts you're having?" | |
enhanced_response = self._apply_therapeutic_techniques( | |
new_base_response, | |
detected_needs, | |
emotion | |
) | |
return enhanced_response | |
def _apply_therapeutic_techniques(self, response, approaches, emotion): | |
"""Apply specific therapeutic techniques to the response""" | |
enhanced_response = response | |
if "cbt" in approaches and self.therapeutic_approaches["cbt"]["active"]: | |
enhanced_response = self._add_cbt_elements(enhanced_response, emotion) | |
if "dbt" in approaches and self.therapeutic_approaches["dbt"]["active"]: | |
enhanced_response = self._add_dbt_elements(enhanced_response, emotion) | |
if "solution_focused" in approaches and self.therapeutic_approaches["solution_focused"]["active"]: | |
enhanced_response = self._add_solution_focused_elements(enhanced_response) | |
if "mindfulness" in approaches and self.therapeutic_approaches["mindfulness"]["active"]: | |
enhanced_response = self._add_mindfulness_elements(enhanced_response) | |
return enhanced_response | |
def _add_cbt_elements(self, response, emotion): | |
"""Add CBT-specific elements to response""" | |
cbt_prompts = [ | |
"What thoughts are coming up for you when you feel this way?", | |
"Let's examine the evidence for and against this thought. For example, what evidence supports the thought that you can't control them, and what evidence contradicts it?", | |
"Could there be another way to look at this situation? What might a more balanced or helpful thought be?" | |
] | |
return f"{response}\n\nFrom a CBT perspective: {random.choice(cbt_prompts)}" | |
def _add_dbt_elements(self, response, emotion): | |
"""Add DBT-specific elements to response""" | |
if emotion == "distressed": | |
dbt_skills = [ | |
"Try this distress tolerance skill: TIPP (Temperature, Intense exercise, Paced breathing, Progressive muscle relaxation)", | |
"Practice radical acceptance: 'This is where I am right now, and I can cope with this moment'", | |
"Use the PLEASE skill: treat PhysicaL illness, balanced Eating, avoid mood-Altering drugs, balanced Sleep, get Exercise" | |
] | |
return f"{response}\n\nDBT Skill Suggestion: {random.choice(dbt_skills)}" | |
return response | |
def _suggest_coping_strategies(self, emotion): | |
"""Suggest appropriate coping strategies based on emotional state""" | |
strategies = { | |
"distressed": [ | |
"Take slow, deep breaths for 2 minutes", | |
"Try the 5-4-3-2-1 grounding exercise", | |
"Step outside for fresh air", | |
"Engage in a relaxing activity you enjoy." | |
], | |
"negative": [ | |
"Write down three things you're grateful for", | |
"Do a brief mindfulness exercise like focusing on your breath or your senses.", | |
"Reach out to a supportive person" | |
] | |
} | |
if emotion in strategies: | |
selected_strategy = random.choice(strategies[emotion]) | |
return f"\n\nCoping Strategy Suggestion: {selected_strategy}" | |
return "" | |
def _update_progress_metrics(self, user_input, emotion): | |
"""Track therapeutic progress""" | |
self.progress_metrics["mood_tracking"].append({ | |
"timestamp": datetime.now().isoformat(), | |
"emotion": emotion, | |
"intensity": self.sia.polarity_scores(user_input)["compound"] | |
}) | |
def update_communication_preferences(self, preferences): | |
"""Update communication preferences""" | |
for key, value in preferences.items(): | |
if key in self.communication_modes: | |
self.communication_modes[key] = value | |
def _generate_base_response(self, user_input): | |
"""Generate a base response using the language model""" | |
# Tokenize and encode the input | |
input_ids = self.tokenizer.encode(user_input, return_tensors="pt") | |
input_ids = input_ids.to(self.device) | |
# Generate response | |
output = self.model.generate(input_ids, max_length=50, do_sample=True, top_k=50, top_p=0.95) | |
generated_text = self.tokenizer.decode(output[0], skip_special_tokens=True) | |
return generated_text | |
def _add_solution_focused_elements(self, response): | |
"""Add solution-focused elements to response""" | |
solution_focused_prompts = [ | |
"What would a successful outcome look like for you?", | |
"What are some small steps you can take towards achieving this goal?", | |
"When have you experienced similar challenges in the past, and what helped you cope?" | |
] | |
return f"{response}\n\nFrom a solution-focused perspective: {random.choice(solution_focused_prompts)}" | |
def _add_mindfulness_elements(self, response): | |
"""Add mindfulness elements to response""" | |
mindfulness_exercises = [ | |
"Take a few deep breaths and focus on your breath as it enters and leaves your body", | |
"Scan your body, noticing any sensations without judgment", | |
"Notice the sounds around you and try to identify them" | |
] | |
return f"{response}\n\nMindfulness Exercise Suggestion: {random.choice(mindfulness_exercises)}" | |
def create_enhanced_interface(): | |
bot = EnhancedMentalHealthBot() | |
def chat(message, history, | |
use_cbt, use_dbt, use_solution_focused, use_mindfulness, | |
simple_mode, emoji_mode, structured_mode, guided_mode): | |
# Update therapeutic approaches | |
bot.therapeutic_approaches["cbt"]["active"] = use_cbt | |
bot.therapeutic_approaches["dbt"]["active"] = use_dbt | |
bot.therapeutic_approaches["solution_focused"]["active"] = use_solution_focused | |
bot.therapeutic_approaches["mindfulness"]["active"] = use_mindfulness | |
# Update communication preferences | |
bot.update_communication_preferences({ | |
"simple": simple_mode, | |
"emoji": emoji_mode, | |
"structured": structured_mode, | |
"guided_exercises": guided_mode | |
}) | |
response = bot.generate_therapeutic_response(message, [ | |
"cbt" if use_cbt else None, | |
"dbt" if use_dbt else None, | |
"solution_focused" if use_solution_focused else None, | |
"mindfulness" if use_mindfulness else None | |
]) | |
return response | |
# Create enhanced Gradio interface | |
iface = gr.ChatInterface( | |
fn=chat, | |
additional_inputs=[ | |
gr.Checkbox(label="Use CBT Techniques", value=False), | |
gr.Checkbox(label="Use DBT Skills", value=False), | |
gr.Checkbox(label="Use Solution-Focused Approach", value=False), | |
gr.Checkbox(label="Include Mindfulness Exercises", value=False), | |
gr.Checkbox(label="Use Simple Language", value=False), | |
gr.Checkbox(label="Use Emoji Support", value=False), | |
gr.Checkbox(label="Use Structured Responses", value=False), | |
gr.Checkbox(label="Include Guided Exercises", value=False) | |
], | |
title="Professional Mental Health Support Platform", | |
description=""" | |
Welcome to your secure online mental health support session. This platform offers: | |
- Evidence-based therapeutic approaches (CBT, DBT, Solution-Focused, Mindfulness) | |
- Personalized communication styles | |
- Progress tracking | |
- Coping strategies and resources | |
Note: This is a supportive tool but not a replacement for professional mental health care. | |
For immediate crisis support, please call 988 (US) or your local emergency services. | |
Your privacy and confidentiality are important to us. | |
""", | |
examples=[ | |
["I've been feeling anxious about work lately"], | |
["I keep having negative thoughts that I can't control"], | |
["I want to improve my relationships but don't know where to start"], | |
["Everything feels overwhelming right now"] | |
] | |
) | |
return iface | |
# Launch the enhanced interface | |
if __name__ == "__main__": | |
iface = create_enhanced_interface() | |
iface.launch(share=True) |