Spaces:
Sleeping
Sleeping
File size: 15,226 Bytes
d5e7677 |
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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
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) |