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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
+
import numpy as np
|
5 |
+
from datetime import datetime
|
6 |
+
import logging
|
7 |
+
import nltk
|
8 |
+
import emoji
|
9 |
+
import re
|
10 |
+
import json
|
11 |
+
import warnings
|
12 |
+
import random
|
13 |
+
|
14 |
+
warnings.filterwarnings('ignore')
|
15 |
+
|
16 |
+
class EnhancedMentalHealthBot:
|
17 |
+
def __init__(self):
|
18 |
+
# Initialize base model components
|
19 |
+
self.model_name = "microsoft/DialoGPT-medium"
|
20 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
21 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.model_name)
|
22 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
23 |
+
self.model.to(self.device)
|
24 |
+
|
25 |
+
# Initialize session management
|
26 |
+
self.chat_history = []
|
27 |
+
self.current_emotional_state = "neutral"
|
28 |
+
self.session_notes = []
|
29 |
+
self.therapy_goals = {}
|
30 |
+
|
31 |
+
# Therapeutic approaches available
|
32 |
+
self.therapeutic_approaches = {
|
33 |
+
"cbt": {
|
34 |
+
"active": False,
|
35 |
+
"techniques": ["thought_challenging", "behavioral_activation", "cognitive_restructuring"],
|
36 |
+
"session_structure": ["review", "agenda", "homework", "feedback"]
|
37 |
+
},
|
38 |
+
"dbt": {
|
39 |
+
"active": False,
|
40 |
+
"techniques": ["mindfulness", "distress_tolerance", "emotion_regulation"],
|
41 |
+
"skills": ["wise_mind", "radical_acceptance", "crisis_survival"]
|
42 |
+
},
|
43 |
+
"solution_focused": {
|
44 |
+
"active": False,
|
45 |
+
"techniques": ["miracle_question", "scaling", "exception_finding"],
|
46 |
+
"focus": "future_oriented"
|
47 |
+
},
|
48 |
+
"mindfulness": {
|
49 |
+
"active": False,
|
50 |
+
"exercises": ["breathing", "body_scan", "grounding"],
|
51 |
+
"duration": "5-10 minutes"
|
52 |
+
}
|
53 |
+
}
|
54 |
+
|
55 |
+
# Enhanced communication preferences
|
56 |
+
self.communication_modes = {
|
57 |
+
"text": True,
|
58 |
+
"simple": False,
|
59 |
+
"emoji": False,
|
60 |
+
"structured": False,
|
61 |
+
"metaphorical": False,
|
62 |
+
"visual_aids": False,
|
63 |
+
"guided_exercises": False
|
64 |
+
}
|
65 |
+
|
66 |
+
# Expanded support resources
|
67 |
+
self.support_resources = {
|
68 |
+
"crisis": {
|
69 |
+
"hotline": "988",
|
70 |
+
"text_line": "Text HOME to 741741",
|
71 |
+
"emergency": "911"
|
72 |
+
},
|
73 |
+
"community": {
|
74 |
+
"support_groups": "https://www.nami.org/Support-Education/Support-Groups",
|
75 |
+
"peer_support": "https://www.mhanational.org/find-support-groups"
|
76 |
+
},
|
77 |
+
"self_help": {
|
78 |
+
"meditation_apps": ["Headspace", "Calm", "Insight Timer"],
|
79 |
+
"workbooks": ["Mind Over Mood", "The Anxiety and Phobia Workbook"],
|
80 |
+
"online_resources": ["https://www.therapistaid.com/worksheets"]
|
81 |
+
},
|
82 |
+
"professional": {
|
83 |
+
"find_therapist": "https://www.psychologytoday.com/us/therapists",
|
84 |
+
"teletherapy": ["BetterHelp", "Talkspace", "7 Cups"]
|
85 |
+
}
|
86 |
+
}
|
87 |
+
|
88 |
+
# Setup advanced logging and analytics
|
89 |
+
logging.basicConfig(
|
90 |
+
filename='therapy_sessions.log',
|
91 |
+
level=logging.INFO,
|
92 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
93 |
+
)
|
94 |
+
|
95 |
+
# Initialize NLTK components
|
96 |
+
nltk.download('vader_lexicon')
|
97 |
+
nltk.download('punkt')
|
98 |
+
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
99 |
+
self.sia = SentimentIntensityAnalyzer()
|
100 |
+
|
101 |
+
# Initialize therapeutic progress tracking
|
102 |
+
self.progress_metrics = {
|
103 |
+
"mood_tracking": [],
|
104 |
+
"goal_progress": {},
|
105 |
+
"skill_usage": {},
|
106 |
+
"session_ratings": []
|
107 |
+
}
|
108 |
+
|
109 |
+
def detect_therapeutic_needs(self, text):
|
110 |
+
"""Analyze text to determine appropriate therapeutic approach"""
|
111 |
+
# Keywords associated with different therapeutic approaches
|
112 |
+
approach_keywords = {
|
113 |
+
"cbt": ["thoughts", "beliefs", "thinking patterns", "behavior", "negative thoughts"],
|
114 |
+
"dbt": ["overwhelming emotions", "impulses", "relationships", "mindfulness"],
|
115 |
+
"solution_focused": ["goals", "future", "solutions", "changes", "better"],
|
116 |
+
"mindfulness": ["present moment", "awareness", "meditation", "breathing", "stress"]
|
117 |
+
}
|
118 |
+
|
119 |
+
text_lower = text.lower()
|
120 |
+
detected_approaches = []
|
121 |
+
|
122 |
+
for approach, keywords in approach_keywords.items():
|
123 |
+
if any(keyword in text_lower for keyword in keywords):
|
124 |
+
detected_approaches.append(approach)
|
125 |
+
|
126 |
+
return detected_approaches
|
127 |
+
|
128 |
+
def detect_emotion(self, text):
|
129 |
+
"""Detect emotion based on sentiment analysis"""
|
130 |
+
sentiment_scores = self.sia.polarity_scores(text)
|
131 |
+
compound_score = sentiment_scores['compound']
|
132 |
+
|
133 |
+
if compound_score >= 0.05:
|
134 |
+
return "positive"
|
135 |
+
elif compound_score <= -0.05:
|
136 |
+
return "negative"
|
137 |
+
else:
|
138 |
+
return "neutral"
|
139 |
+
|
140 |
+
def generate_therapeutic_response(self, user_input, active_approaches=None):
|
141 |
+
"""Generate response using appropriate therapeutic approach"""
|
142 |
+
detected_needs = self.detect_therapeutic_needs(user_input)
|
143 |
+
emotion = self.detect_emotion(user_input)
|
144 |
+
|
145 |
+
# Base response generation
|
146 |
+
base_response = self._generate_base_response(user_input)
|
147 |
+
|
148 |
+
# Filter the base response
|
149 |
+
if base_response.lower().startswith(user_input.lower()):
|
150 |
+
base_response = "" # Remove the duplicate input
|
151 |
+
|
152 |
+
# Enhance response with therapeutic elements
|
153 |
+
enhanced_response = self._apply_therapeutic_techniques(
|
154 |
+
base_response,
|
155 |
+
detected_needs,
|
156 |
+
emotion
|
157 |
+
)
|
158 |
+
|
159 |
+
# Add coping strategies if needed
|
160 |
+
if emotion in ["distressed", "negative"]:
|
161 |
+
enhanced_response += self._suggest_coping_strategies(emotion)
|
162 |
+
|
163 |
+
# Add progress tracking
|
164 |
+
self._update_progress_metrics(user_input, emotion)
|
165 |
+
|
166 |
+
# If the response is still too generic, create a new base response
|
167 |
+
if not enhanced_response or enhanced_response.lower().startswith(user_input.lower()):
|
168 |
+
if "work anxiety" in user_input.lower():
|
169 |
+
new_base_response = "It's understandable to feel anxious about work. What specific aspects of work are causing you anxiety?"
|
170 |
+
enhanced_response = self._apply_therapeutic_techniques(
|
171 |
+
new_base_response,
|
172 |
+
detected_needs,
|
173 |
+
emotion
|
174 |
+
)
|
175 |
+
elif "negative thoughts" in user_input.lower() or "can't control" in user_input.lower():
|
176 |
+
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?"
|
177 |
+
enhanced_response = self._apply_therapeutic_techniques(
|
178 |
+
new_base_response,
|
179 |
+
detected_needs,
|
180 |
+
emotion
|
181 |
+
)
|
182 |
+
|
183 |
+
return enhanced_response
|
184 |
+
|
185 |
+
def _apply_therapeutic_techniques(self, response, approaches, emotion):
|
186 |
+
"""Apply specific therapeutic techniques to the response"""
|
187 |
+
enhanced_response = response
|
188 |
+
|
189 |
+
if "cbt" in approaches and self.therapeutic_approaches["cbt"]["active"]:
|
190 |
+
enhanced_response = self._add_cbt_elements(enhanced_response, emotion)
|
191 |
+
|
192 |
+
if "dbt" in approaches and self.therapeutic_approaches["dbt"]["active"]:
|
193 |
+
enhanced_response = self._add_dbt_elements(enhanced_response, emotion)
|
194 |
+
|
195 |
+
if "solution_focused" in approaches and self.therapeutic_approaches["solution_focused"]["active"]:
|
196 |
+
enhanced_response = self._add_solution_focused_elements(enhanced_response)
|
197 |
+
|
198 |
+
if "mindfulness" in approaches and self.therapeutic_approaches["mindfulness"]["active"]:
|
199 |
+
enhanced_response = self._add_mindfulness_elements(enhanced_response)
|
200 |
+
|
201 |
+
return enhanced_response
|
202 |
+
|
203 |
+
def _add_cbt_elements(self, response, emotion):
|
204 |
+
"""Add CBT-specific elements to response"""
|
205 |
+
cbt_prompts = [
|
206 |
+
"What thoughts are coming up for you when you feel this way?",
|
207 |
+
"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?",
|
208 |
+
"Could there be another way to look at this situation? What might a more balanced or helpful thought be?"
|
209 |
+
]
|
210 |
+
|
211 |
+
return f"{response}\n\nFrom a CBT perspective: {random.choice(cbt_prompts)}"
|
212 |
+
|
213 |
+
def _add_dbt_elements(self, response, emotion):
|
214 |
+
"""Add DBT-specific elements to response"""
|
215 |
+
if emotion == "distressed":
|
216 |
+
dbt_skills = [
|
217 |
+
"Try this distress tolerance skill: TIPP (Temperature, Intense exercise, Paced breathing, Progressive muscle relaxation)",
|
218 |
+
"Practice radical acceptance: 'This is where I am right now, and I can cope with this moment'",
|
219 |
+
"Use the PLEASE skill: treat PhysicaL illness, balanced Eating, avoid mood-Altering drugs, balanced Sleep, get Exercise"
|
220 |
+
]
|
221 |
+
return f"{response}\n\nDBT Skill Suggestion: {random.choice(dbt_skills)}"
|
222 |
+
return response
|
223 |
+
|
224 |
+
def _suggest_coping_strategies(self, emotion):
|
225 |
+
"""Suggest appropriate coping strategies based on emotional state"""
|
226 |
+
strategies = {
|
227 |
+
"distressed": [
|
228 |
+
"Take slow, deep breaths for 2 minutes",
|
229 |
+
"Try the 5-4-3-2-1 grounding exercise",
|
230 |
+
"Step outside for fresh air",
|
231 |
+
"Engage in a relaxing activity you enjoy."
|
232 |
+
],
|
233 |
+
"negative": [
|
234 |
+
"Write down three things you're grateful for",
|
235 |
+
"Do a brief mindfulness exercise like focusing on your breath or your senses.",
|
236 |
+
"Reach out to a supportive person"
|
237 |
+
]
|
238 |
+
}
|
239 |
+
|
240 |
+
if emotion in strategies:
|
241 |
+
selected_strategy = random.choice(strategies[emotion])
|
242 |
+
return f"\n\nCoping Strategy Suggestion: {selected_strategy}"
|
243 |
+
return ""
|
244 |
+
|
245 |
+
def _update_progress_metrics(self, user_input, emotion):
|
246 |
+
"""Track therapeutic progress"""
|
247 |
+
self.progress_metrics["mood_tracking"].append({
|
248 |
+
"timestamp": datetime.now().isoformat(),
|
249 |
+
"emotion": emotion,
|
250 |
+
"intensity": self.sia.polarity_scores(user_input)["compound"]
|
251 |
+
})
|
252 |
+
|
253 |
+
def update_communication_preferences(self, preferences):
|
254 |
+
"""Update communication preferences"""
|
255 |
+
for key, value in preferences.items():
|
256 |
+
if key in self.communication_modes:
|
257 |
+
self.communication_modes[key] = value
|
258 |
+
|
259 |
+
def _generate_base_response(self, user_input):
|
260 |
+
"""Generate a base response using the language model"""
|
261 |
+
# Tokenize and encode the input
|
262 |
+
input_ids = self.tokenizer.encode(user_input, return_tensors="pt")
|
263 |
+
input_ids = input_ids.to(self.device)
|
264 |
+
|
265 |
+
# Generate response
|
266 |
+
output = self.model.generate(input_ids, max_length=50, do_sample=True, top_k=50, top_p=0.95)
|
267 |
+
generated_text = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
268 |
+
|
269 |
+
return generated_text
|
270 |
+
|
271 |
+
def _add_solution_focused_elements(self, response):
|
272 |
+
"""Add solution-focused elements to response"""
|
273 |
+
solution_focused_prompts = [
|
274 |
+
"What would a successful outcome look like for you?",
|
275 |
+
"What are some small steps you can take towards achieving this goal?",
|
276 |
+
"When have you experienced similar challenges in the past, and what helped you cope?"
|
277 |
+
]
|
278 |
+
|
279 |
+
return f"{response}\n\nFrom a solution-focused perspective: {random.choice(solution_focused_prompts)}"
|
280 |
+
|
281 |
+
def _add_mindfulness_elements(self, response):
|
282 |
+
"""Add mindfulness elements to response"""
|
283 |
+
mindfulness_exercises = [
|
284 |
+
"Take a few deep breaths and focus on your breath as it enters and leaves your body",
|
285 |
+
"Scan your body, noticing any sensations without judgment",
|
286 |
+
"Notice the sounds around you and try to identify them"
|
287 |
+
]
|
288 |
+
|
289 |
+
return f"{response}\n\nMindfulness Exercise Suggestion: {random.choice(mindfulness_exercises)}"
|
290 |
+
|
291 |
+
def create_enhanced_interface():
|
292 |
+
bot = EnhancedMentalHealthBot()
|
293 |
+
|
294 |
+
def chat(message, history,
|
295 |
+
use_cbt, use_dbt, use_solution_focused, use_mindfulness,
|
296 |
+
simple_mode, emoji_mode, structured_mode, guided_mode):
|
297 |
+
|
298 |
+
# Update therapeutic approaches
|
299 |
+
bot.therapeutic_approaches["cbt"]["active"] = use_cbt
|
300 |
+
bot.therapeutic_approaches["dbt"]["active"] = use_dbt
|
301 |
+
bot.therapeutic_approaches["solution_focused"]["active"] = use_solution_focused
|
302 |
+
bot.therapeutic_approaches["mindfulness"]["active"] = use_mindfulness
|
303 |
+
|
304 |
+
# Update communication preferences
|
305 |
+
bot.update_communication_preferences({
|
306 |
+
"simple": simple_mode,
|
307 |
+
"emoji": emoji_mode,
|
308 |
+
"structured": structured_mode,
|
309 |
+
"guided_exercises": guided_mode
|
310 |
+
})
|
311 |
+
|
312 |
+
response = bot.generate_therapeutic_response(message, [
|
313 |
+
"cbt" if use_cbt else None,
|
314 |
+
"dbt" if use_dbt else None,
|
315 |
+
"solution_focused" if use_solution_focused else None,
|
316 |
+
"mindfulness" if use_mindfulness else None
|
317 |
+
])
|
318 |
+
return response
|
319 |
+
|
320 |
+
# Create enhanced Gradio interface
|
321 |
+
iface = gr.ChatInterface(
|
322 |
+
fn=chat,
|
323 |
+
additional_inputs=[
|
324 |
+
gr.Checkbox(label="Use CBT Techniques", value=False),
|
325 |
+
gr.Checkbox(label="Use DBT Skills", value=False),
|
326 |
+
gr.Checkbox(label="Use Solution-Focused Approach", value=False),
|
327 |
+
gr.Checkbox(label="Include Mindfulness Exercises", value=False),
|
328 |
+
gr.Checkbox(label="Use Simple Language", value=False),
|
329 |
+
gr.Checkbox(label="Use Emoji Support", value=False),
|
330 |
+
gr.Checkbox(label="Use Structured Responses", value=False),
|
331 |
+
gr.Checkbox(label="Include Guided Exercises", value=False)
|
332 |
+
],
|
333 |
+
title="Professional Mental Health Support Platform",
|
334 |
+
description="""
|
335 |
+
Welcome to your secure online mental health support session. This platform offers:
|
336 |
+
|
337 |
+
- Evidence-based therapeutic approaches (CBT, DBT, Solution-Focused, Mindfulness)
|
338 |
+
- Personalized communication styles
|
339 |
+
- Progress tracking
|
340 |
+
- Coping strategies and resources
|
341 |
+
|
342 |
+
Note: This is a supportive tool but not a replacement for professional mental health care.
|
343 |
+
For immediate crisis support, please call 988 (US) or your local emergency services.
|
344 |
+
|
345 |
+
Your privacy and confidentiality are important to us.
|
346 |
+
""",
|
347 |
+
examples=[
|
348 |
+
["I've been feeling anxious about work lately"],
|
349 |
+
["I keep having negative thoughts that I can't control"],
|
350 |
+
["I want to improve my relationships but don't know where to start"],
|
351 |
+
["Everything feels overwhelming right now"]
|
352 |
+
]
|
353 |
+
)
|
354 |
+
|
355 |
+
return iface
|
356 |
+
|
357 |
+
# Launch the enhanced interface
|
358 |
+
if __name__ == "__main__":
|
359 |
+
iface = create_enhanced_interface()
|
360 |
+
iface.launch(share=True)
|