RozzaCreat commited on
Commit
5e04ef0
·
verified ·
1 Parent(s): 14b3056

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +933 -397
app.py CHANGED
@@ -1,415 +1,951 @@
1
- import gradio as gr
 
2
  import datetime
 
 
 
 
 
 
 
3
  import json
 
4
  import re
 
 
 
5
  import os
 
6
  from typing import Dict, List, Any
7
- import openai
8
 
9
- class PsychologyToolsApp:
10
- def __init__(self):
11
- self.name = "Psychology Tools Suite"
12
- self.description = "AI-powered tools for mental health professionals"
13
-
14
- def speech_emotion_analyzer(self, text: str, context: str = "therapy") -> str:
15
- """Analyzes patient's emotional state from speech text."""
16
- if not text or len(text.strip()) < 10:
17
- return "Error: Text must be at least 10 characters long for analysis."
18
-
19
- # Emotion indicators for analysis
20
- emotion_indicators = {
21
- "depression": {
22
- "keywords": ["sad", "hopeless", "tired", "meaningless", "empty", "lonely",
23
- "depressed", "despair", "miserable", "worthless", "numb"],
24
- "patterns": [r"can't.*sleep", r"no.*energy", r"everything.*bad", r"don't.*want",
25
- r"life.*no.*meaning", r"better.*dead"]
26
- },
27
- "anxiety": {
28
- "keywords": ["anxious", "worried", "nervous", "scared", "panic", "tense",
29
- "anxiety", "worry", "fear", "stress", "phobia"],
30
- "patterns": [r"what.*if", r"afraid.*that", r"can't.*cope", r"heart.*racing",
31
- r"hands.*shaking", r"can't.*breathe", r"panic.*attack"]
32
- },
33
- "anger": {
34
- "keywords": ["angry", "furious", "irritated", "annoyed", "hate", "mad",
35
- "rage", "aggression", "hatred", "frustration"],
36
- "patterns": [r"fed up", r"sick of", r"can't.*stand", r"want.*hit",
37
- r"everything.*irritates", r"pissed off"]
38
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  }
40
-
41
- # Analyze text
42
- text_lower = text.lower()
43
- detected_emotions = {}
44
-
45
- for emotion, indicators in emotion_indicators.items():
46
- score = 0
47
- matches = []
48
-
49
- for keyword in indicators["keywords"]:
50
- if keyword in text_lower:
51
- score += 1
52
- matches.append(keyword)
53
-
54
- for pattern in indicators["patterns"]:
55
- if re.search(pattern, text_lower):
56
- score += 2
57
- matches.append(f"pattern: {pattern}")
58
-
59
- if score > 0:
60
- detected_emotions[emotion] = {"score": score, "matches": matches}
61
-
62
- # Check for crisis indicators
63
- crisis_indicators = ["suicide", "kill myself", "end it all", "not worth living"]
64
- crisis_risk = any(indicator in text_lower for indicator in crisis_indicators)
65
-
66
- # Create report
67
- report = "## 🧠 Emotional State Analysis\n\n"
68
-
69
- if detected_emotions:
70
- report += "### 📊 Detected Emotional States:\n"
71
- for emotion, data in sorted(detected_emotions.items(), key=lambda x: x[1]["score"], reverse=True):
72
- emotion_names = {
73
- "depression": "😔 Depression signs",
74
- "anxiety": "😰 Anxiety",
75
- "anger": "😠 Anger/Irritation"
76
- }
77
- intensity = "High" if data['score'] >= 4 else "Medium" if data['score'] >= 2 else "Low"
78
- report += f"- **{emotion_names.get(emotion, emotion)}** (intensity: {intensity})\n"
79
- else:
80
- report += "✅ No clear signs of emotional distress detected.\n\n"
81
-
82
- if crisis_risk:
83
- report += "\n🚨 **CRITICAL: Suicide risk indicators detected!**\n"
84
- report += "📞 Immediate consultation recommended. Crisis hotline: 988\n\n"
85
-
86
- report += f"\n📅 *Analysis date: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}*"
87
-
88
- return report
89
 
90
- def create_therapy_worksheet(self, therapy_type: str, client_age: int, issue: str) -> str:
91
- """Creates a therapeutic worksheet/exercise for client."""
92
- if client_age < 5 or client_age > 100:
93
- return "Error: Age must be between 5 and 100."
94
-
95
- therapy_type = therapy_type.lower()
96
- valid_types = ["cbt", "dbt", "mindfulness"]
 
 
 
 
 
 
 
 
97
 
98
- if therapy_type not in valid_types:
99
- return f"Error: Therapy type must be one of: {', '.join(valid_types)}"
 
 
 
 
 
 
 
 
 
100
 
101
- # Determine level by age
102
- if client_age < 12:
103
- level = "child"
104
- elif client_age < 18:
105
- level = "teen"
106
- else:
107
- level = "adult"
 
 
 
 
108
 
109
- worksheets = {
110
- "cbt": {
111
- "child": {
112
- "title": "🌈 My Thoughts and Feelings",
113
- "exercises": [
114
- "🌤️ **Mood Diary**: Draw or mark your mood with an emoji each day",
115
- "🤔 **Thought Catcher**: Write down thoughts when sad or scared",
116
- "🎯 **Helper Thoughts**: Find 3 good thoughts for each bad thought"
117
- ]
118
- },
119
- "teen": {
120
- "title": "🧠 Cognitive Restructuring",
121
- "exercises": [
122
- "📊 **ABC Model**: Situation → Thought → Feeling/Behavior",
123
- "🔍 **Thought Detective**: Find evidence FOR and AGAINST beliefs",
124
- "📝 **Thought Diary**: Daily record of automatic thoughts"
125
- ]
126
- },
127
- "adult": {
128
- "title": "🔄 Cognitive Behavioral Therapy",
129
- "exercises": [
130
- "🔄 **Thought-Feeling-Behavior Cycle**: Analyze connections",
131
- "⚡ **Cognitive Distortions**: Identify thinking errors",
132
- "🎯 **Behavioral Experiments**: Test catastrophic beliefs"
133
- ]
134
- }
135
- },
136
- "dbt": {
137
- "teen": {
138
- "title": "🌊 Emotion Regulation Skills",
139
- "exercises": [
140
- "🌊 **TIPP**: Temperature, Intense exercise, Paced breathing",
141
- "🚦 **STOP**: Stop → Take a breath → Observe → Proceed",
142
- "🎭 **Emotion Diary**: Track emotion intensity (1-10)"
143
- ]
144
- },
145
- "adult": {
146
- "title": "⚖️ Dialectical Behavior Therapy",
147
- "exercises": [
148
- "⚖️ **Wise Mind**: Balance emotional and rational mind",
149
- "🛡️ **Crisis Skills**: TIPP, distraction, self-soothing",
150
- "🤝 **DEAR MAN**: Healthy communication technique"
151
- ]
152
- }
153
- },
154
- "mindfulness": {
155
- "child": {
156
- "title": "🐸 Mindfulness for Kids",
157
- "exercises": [
158
- "🐸 **Frog Pose**: Sit still and listen to sounds",
159
- "🌬️ **Belly Breathing**: Watch toy rise and fall on belly",
160
- "👀 **5-4-3-2-1**: Find 5 things you see, 4 you hear..."
161
- ]
162
- },
163
- "teen": {
164
- "title": "🧘 Teen Mindfulness",
165
- "exercises": [
166
- "📱 **Digital Detox**: 30-60 minutes without devices",
167
- "🚶 **Mindful Walking**: Notice each step",
168
- "💭 **Thought Watching**: Observe thoughts like clouds"
169
- ]
170
- },
171
- "adult": {
172
- "title": "🧘‍♀️ Mindfulness Practice",
173
- "exercises": [
174
- "🧘 **Formal Meditation**: 20-30 minutes daily practice",
175
- "🍽️ **Mindful Eating**: Full attention to food",
176
- "💼 **Work Mindfulness**: Regular present-moment pauses"
177
- ]
178
- }
179
  }
180
- }
181
-
182
- # Get appropriate exercises
183
- therapy_data = worksheets.get(therapy_type, {})
184
- level_data = therapy_data.get(level, therapy_data.get("adult", {}))
185
-
186
- if not level_data:
187
- return f"Exercises for {therapy_type} therapy and age {client_age} not available."
188
-
189
- # Create worksheet
190
- worksheet = f"# {level_data['title']}\n\n"
191
- worksheet += f"**👤 Client**: {client_age} years old\n"
192
- worksheet += f"**🎯 Main issue**: {issue}\n"
193
- worksheet += f"**🔬 Therapy type**: {therapy_type.upper()}\n"
194
- worksheet += f"**📅 Date**: {datetime.datetime.now().strftime('%m/%d/%Y')}\n\n"
195
-
196
- worksheet += "## 📋 Exercises:\n\n"
197
-
198
- for i, exercise in enumerate(level_data['exercises'], 1):
199
- worksheet += f"### {i}. {exercise}\n\n"
200
- worksheet += "**Notes:**\n```\nDate: _____\nObservations:\n\n\n```\n\n"
201
-
202
- worksheet += "---\n"
203
- worksheet += "## 📞 Emergency contacts:\n"
204
- worksheet += "- Crisis hotline: 988\n"
205
- worksheet += "- Emergency: 911\n\n"
206
-
207
- return worksheet
208
 
209
- def mood_tracker_analyzer(self, mood_data: str) -> str:
210
- """Analyzes mood tracking data to identify patterns."""
211
- try:
212
- data = json.loads(mood_data)
213
- except:
214
- return "Error: Please provide mood data in JSON format.\nExample: [{\"date\": \"2024-01-01\", \"mood\": 7}]"
215
-
216
- if not isinstance(data, list) or len(data) == 0:
217
- return "Error: Mood data should be a list of entries with 'date' and 'mood' fields."
218
-
219
- # Analyze mood patterns
220
- moods = []
221
- dates = []
222
-
223
- for entry in data:
224
- if 'mood' in entry and 'date' in entry:
225
- moods.append(entry['mood'])
226
- dates.append(entry['date'])
227
-
228
- if not moods:
229
- return "Error: No valid mood entries found."
230
-
231
- # Calculate statistics
232
- avg_mood = sum(moods) / len(moods)
233
- mood_trend = "stable"
234
-
235
- if len(moods) > 3:
236
- recent_avg = sum(moods[-3:]) / 3
237
- older_avg = sum(moods[:-3]) / (len(moods) - 3)
238
-
239
- if recent_avg > older_avg + 0.5:
240
- mood_trend = "improving"
241
- elif recent_avg < older_avg - 0.5:
242
- mood_trend = "declining"
243
-
244
- # Create report
245
- report = "# 📊 Mood Tracking Analysis\n\n"
246
- report += f"**Period**: {dates[0]} to {dates[-1]}\n"
247
- report += f"**Entries analyzed**: {len(moods)}\n"
248
- report += f"**Average mood**: {avg_mood:.1f}/10\n"
249
- report += f"**Trend**: {mood_trend}\n\n"
250
-
251
- # Check for low mood periods
252
- low_mood_days = sum(1 for m in moods if m < 5)
253
- if low_mood_days > len(moods) * 0.3:
254
- report += "⚠️ **Concern**: Low mood in >30% of entries\n\n"
255
-
256
- report += "## 💡 Recommendations:\n"
257
-
258
- if mood_trend == "declining":
259
- report += "- 🚨 Schedule mental health appointment\n"
260
- report += "- 🧘 Increase self-care activities\n"
261
- elif mood_trend == "improving":
262
- report += "- ✅ Continue current strategies\n"
263
- report += "- 📝 Document what's working\n"
264
- else:
265
- report += "- 📊 Continue tracking\n"
266
- report += "- 🔍 Look for patterns\n"
267
-
268
- return report
 
 
 
 
 
269
 
270
- def transcribe_audio_with_whisper(self, audio_file, api_key: str = None) -> str:
271
- """Transcribes audio file using OpenAI Whisper API."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  try:
273
- # Set API key
274
- if api_key:
275
- openai.api_key = api_key
276
- elif os.getenv("OPENAI_API_KEY"):
277
- openai.api_key = os.getenv("OPENAI_API_KEY")
278
- else:
279
- return "Error: Please provide OpenAI API key."
280
-
281
- # Transcribe audio
282
- response = openai.Audio.transcribe(
283
- model="whisper-1",
284
- file=audio_file
285
- )
286
-
287
- text = response.get("text", "")
288
-
289
- # Create report
290
- report = f"## 🎤 Audio Transcription\n\n"
291
- report += f"**Timestamp**: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}\n\n"
292
- report += f"### 📝 Transcribed Text:\n\n{text}\n\n"
293
-
294
- # Analyze emotions
295
- emotion_analysis = self.speech_emotion_analyzer(text)
296
- report += "---\n\n" + emotion_analysis
297
-
298
- return report
299
-
300
  except Exception as e:
301
- return f"Error during transcription: {str(e)}"
302
 
303
- # Create Gradio interface
304
- def create_gradio_app():
305
- app = PsychologyToolsApp()
306
 
307
- with gr.Blocks(title="Psychology Tools Suite", theme=gr.themes.Soft()) as demo:
308
- gr.Markdown("# 🧠 Psychology Tools Suite")
309
- gr.Markdown("AI-powered tools for mental health professionals")
310
-
311
- with gr.Tabs():
312
- # Text Analysis Tab
313
- with gr.TabItem("📝 Text Analysis"):
314
- gr.Markdown("### Analyze emotional content from text")
315
- text_input = gr.Textbox(
316
- label="Enter patient's text",
317
- placeholder="Type or paste text here...",
318
- lines=5
319
- )
320
- context_input = gr.Dropdown(
321
- choices=["therapy", "assessment", "crisis"],
322
- value="therapy",
323
- label="Context"
324
- )
325
- analyze_btn = gr.Button("Analyze Emotions", variant="primary")
326
- analysis_output = gr.Markdown()
327
-
328
- analyze_btn.click(
329
- fn=app.speech_emotion_analyzer,
330
- inputs=[text_input, context_input],
331
- outputs=analysis_output
332
- )
333
-
334
- # Worksheet Creator Tab
335
- with gr.TabItem("📋 Worksheet Creator"):
336
- gr.Markdown("### Create therapy worksheets")
337
- therapy_type = gr.Dropdown(
338
- choices=["cbt", "dbt", "mindfulness"],
339
- value="cbt",
340
- label="Therapy Type"
341
- )
342
- age_input = gr.Number(
343
- label="Client Age",
344
- value=25,
345
- minimum=5,
346
- maximum=100
347
- )
348
- issue_input = gr.Textbox(
349
- label="Main Issue",
350
- placeholder="e.g., anxiety, depression, stress"
351
- )
352
- create_btn = gr.Button("Create Worksheet", variant="primary")
353
- worksheet_output = gr.Markdown()
354
-
355
- create_btn.click(
356
- fn=app.create_therapy_worksheet,
357
- inputs=[therapy_type, age_input, issue_input],
358
- outputs=worksheet_output
359
- )
360
-
361
- # Mood Analysis Tab
362
- with gr.TabItem("📊 Mood Tracker"):
363
- gr.Markdown("### Analyze mood tracking data")
364
- gr.Markdown("Enter data in JSON format: `[{\"date\": \"2024-01-01\", \"mood\": 7}, ...]`")
365
- mood_input = gr.Textbox(
366
- label="Mood Data (JSON)",
367
- placeholder='[{"date": "2024-01-01", "mood": 7}, {"date": "2024-01-02", "mood": 6}]',
368
- lines=5
369
- )
370
- analyze_mood_btn = gr.Button("Analyze Mood Patterns", variant="primary")
371
- mood_output = gr.Markdown()
372
-
373
- analyze_mood_btn.click(
374
- fn=app.mood_tracker_analyzer,
375
- inputs=mood_input,
376
- outputs=mood_output
377
- )
378
-
379
- # Audio Analysis Tab (with Whisper)
380
- with gr.TabItem("🎤 Audio Analysis"):
381
- gr.Markdown("### Transcribe and analyze audio sessions")
382
- api_key_input = gr.Textbox(
383
- label="OpenAI API Key",
384
- placeholder="sk-...",
385
- type="password"
386
- )
387
- audio_input = gr.Audio(
388
- label="Upload Audio File",
389
- type="file"
390
- )
391
- transcribe_btn = gr.Button("Transcribe & Analyze", variant="primary")
392
- audio_output = gr.Markdown()
393
-
394
- transcribe_btn.click(
395
- fn=app.transcribe_audio_with_whisper,
396
- inputs=[audio_input, api_key_input],
397
- outputs=audio_output
398
- )
399
-
400
- # Examples
401
- gr.Examples(
402
- examples=[
403
- ["I feel so sad and hopeless. Nothing seems to matter anymore.", "therapy"],
404
- ["I'm constantly worried about everything. My heart races and I can't sleep.", "therapy"],
405
- ["I'm doing much better. Feeling more positive and energetic.", "therapy"]
406
- ],
407
- inputs=[text_input, context_input]
408
- )
409
-
410
- return demo
411
-
412
- # Launch the app
413
- if __name__ == "__main__":
414
- demo = create_gradio_app()
415
- demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
+
3
  import datetime
4
+
5
+ import requests
6
+
7
+ import pytz
8
+
9
+ import yaml
10
+
11
  import json
12
+
13
  import re
14
+
15
+ import tempfile
16
+
17
  import os
18
+
19
  from typing import Dict, List, Any
 
20
 
21
+ from tools.final_answer import FinalAnswerTool
22
+
23
+ from Gradio_UI import GradioUI
24
+
25
+ @tool
26
+
27
+ def speech_emotion_analyzer(text: str, context: str = "therapy") -> str:
28
+
29
+ """
30
+
31
+ Analyzes patient's emotional state from speech text.
32
+
33
+
34
+
35
+ Args:
36
+
37
+ text: Patient's speech text
38
+
39
+ context: Context (therapy, assessment, crisis)
40
+
41
+
42
+
43
+ Returns:
44
+
45
+ Analysis of emotional state and recommendations
46
+
47
+ """
48
+
49
+ if not text or len(text.strip()) < 10:
50
+
51
+ return "Error: Text must be at least 10 characters long for analysis."
52
+
53
+
54
+
55
+ # Emotion indicators for analysis
56
+
57
+ emotion_indicators = {
58
+
59
+ "depression": {
60
+
61
+ "keywords": ["sad", "hopeless", "tired", "meaningless", "empty", "lonely",
62
+
63
+ "depressed", "despair", "miserable", "worthless", "numb"],
64
+
65
+ "patterns": [r"can't.*sleep", r"no.*energy", r"everything.*bad", r"don't.*want",
66
+
67
+ r"life.*no.*meaning", r"better.*dead"]
68
+
69
+ },
70
+
71
+ "anxiety": {
72
+
73
+ "keywords": ["anxious", "worried", "nervous", "scared", "panic", "tense",
74
+
75
+ "anxiety", "worry", "fear", "stress", "phobia"],
76
+
77
+ "patterns": [r"what.*if", r"afraid.*that", r"can't.*cope", r"heart.*racing",
78
+
79
+ r"hands.*shaking", r"can't.*breathe", r"panic.*attack"]
80
+
81
+ },
82
+
83
+ "anger": {
84
+
85
+ "keywords": ["angry", "furious", "irritated", "annoyed", "hate", "mad",
86
+
87
+ "rage", "aggression", "hatred", "frustration"],
88
+
89
+ "patterns": [r"fed up", r"sick of", r"can't.*stand", r"want.*hit",
90
+
91
+ r"everything.*irritates", r"pissed off"]
92
+
93
+ },
94
+
95
+ "stress": {
96
+
97
+ "keywords": ["stress", "pressure", "overwhelmed", "exhausted", "burned out",
98
+
99
+ "burnout", "fatigue", "drained"],
100
+
101
+ "patterns": [r"too.*much.*work", r"can't.*keep up", r"headache", r"no.*time",
102
+
103
+ r"swamped", r"working.*nonstop"]
104
+
105
+ },
106
+
107
+ "trauma": {
108
+
109
+ "keywords": ["trauma", "flashbacks", "nightmares", "memories", "avoiding",
110
+
111
+ "ptsd", "triggered", "shock"],
112
+
113
+ "patterns": [r"keep.*remembering", r"bad.*dreams", r"can't.*forget",
114
+
115
+ r"avoid.*places", r"triggers"]
116
+
117
  }
118
+
119
+ }
120
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
+
123
+ # Analyze text
124
+
125
+ text_lower = text.lower()
126
+
127
+ detected_emotions = {}
128
+
129
+
130
+
131
+ for emotion, indicators in emotion_indicators.items():
132
+
133
+ score = 0
134
+
135
+ matches = []
136
+
137
 
138
+
139
+ # Check keywords
140
+
141
+ for keyword in indicators["keywords"]:
142
+
143
+ if keyword in text_lower:
144
+
145
+ score += 1
146
+
147
+ matches.append(keyword)
148
+
149
 
150
+
151
+ # Check patterns
152
+
153
+ for pattern in indicators["patterns"]:
154
+
155
+ if re.search(pattern, text_lower):
156
+
157
+ score += 2
158
+
159
+ matches.append(f"pattern: {pattern}")
160
+
161
 
162
+
163
+ if score > 0:
164
+
165
+ detected_emotions[emotion] = {"score": score, "matches": matches}
166
+
167
+
168
+
169
+ # Check for crisis indicators
170
+
171
+ crisis_indicators = ["suicide", "kill myself", "end it all", "not worth living", "better off dead"]
172
+
173
+ crisis_risk = any(indicator in text_lower for indicator in crisis_indicators)
174
+
175
+
176
+
177
+ # Check positive indicators
178
+
179
+ positive_indicators = ["happy", "joy", "good", "great", "wonderful", "excited", "grateful", "love"]
180
+
181
+ positive_count = sum(1 for indicator in positive_indicators if indicator in text_lower)
182
+
183
+
184
+
185
+ # Create report
186
+
187
+ report = "## 🧠 Emotional State Analysis\n\n"
188
+
189
+
190
+
191
+ if detected_emotions:
192
+
193
+ report += "### 📊 Detected Emotional States:\n"
194
+
195
+ for emotion, data in sorted(detected_emotions.items(), key=lambda x: x[1]["score"], reverse=True):
196
+
197
+ emotion_names = {
198
+
199
+ "depression": "😔 Depression signs",
200
+
201
+ "anxiety": "😰 Anxiety",
202
+
203
+ "anger": "😠 Anger/Irritation",
204
+
205
+ "stress": "😵 Stress",
206
+
207
+ "trauma": "💔 Trauma-related"
208
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  }
210
+
211
+ intensity = "High" if data['score'] >= 4 else "Medium" if data['score'] >= 2 else "Low"
212
+
213
+ report += f"- {emotion_names[emotion]} (intensity: {intensity})\n"
214
+
215
+ report += f" Found indicators: {', '.join(data['matches'][:3])}\n\n"
216
+
217
+ else:
218
+
219
+ report += "✅ No clear signs of emotional distress detected.\n\n"
220
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+
223
+ # Positive aspects
224
+
225
+ if positive_count > 0:
226
+
227
+ report += f"😊 Positive indicators: Found {positive_count} positive marker(s)\n\n"
228
+
229
+
230
+
231
+ # Crisis assessment
232
+
233
+ if crisis_risk:
234
+
235
+ report += "🚨 CRITICAL: Suicide risk indicators detected!\n"
236
+
237
+ report += "📞 Immediate consultation and safety assessment recommended.\n"
238
+
239
+ report += "Emergency services: 911, Crisis hotline: 988\n\n"
240
+
241
+
242
+
243
+ # Treatment recommendations
244
+
245
+ report += "### 🎯 Treatment Recommendations:\n"
246
+
247
+
248
+
249
+ if "depression" in detected_emotions:
250
+
251
+ report += "- 🧘 CBT (Cognitive Behavioral Therapy) for negative thought patterns\n"
252
+
253
+ report += "- 💊 Consider psychiatric consultation for medication support\n"
254
+
255
+ report += "- 🏃 Behavioral activation (increase pleasant activities)\n"
256
+
257
+
258
+
259
+ if "anxiety" in detected_emotions:
260
+
261
+ report += "- 🫁 Relaxation techniques: breathing exercises, progressive muscle relaxation\n"
262
+
263
+ report += "- 🎭 Exposure therapy for phobic avoidance\n"
264
+
265
+ report += "- 🧠 Mindfulness therapy for anxious thoughts\n"
266
+
267
+
268
+
269
+ if "anger" in detected_emotions:
270
+
271
+ report += "- 🎯 Anger management training and self-regulation techniques\n"
272
+
273
+ report += "- 🔍 Trigger identification and behavior patterns\n"
274
+
275
+ report += "- 🤝 Communication skills training\n"
276
+
277
+
278
+
279
+ if "stress" in detected_emotions:
280
+
281
+ report += "- ⏰ Stress management and time management techniques\n"
282
+
283
+ report += "- ⚖️ Work-life balance assessment and adjustment\n"
284
+
285
+ report += "- 🛡️ Coping strategies for stressful situations\n"
286
+
287
 
288
+
289
+ if "trauma" in detected_emotions:
290
+
291
+ report += "- 👁️ EMDR therapy for traumatic memories\n"
292
+
293
+ report += "- 🏠 Trauma-informed approach in therapy\n"
294
+
295
+ report += "- 🧘 Somatic techniques for body-based trauma symptoms\n"
296
+
297
+
298
+
299
+ if not detected_emotions or positive_count > 2:
300
+
301
+ report += "- 💪 Supportive therapy to maintain resources\n"
302
+
303
+ report += "- 🎯 Personal growth and life goals development\n"
304
+
305
+
306
+
307
+ report += f"\n📅 Analysis date: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}"
308
+
309
+ report += f"\n🌍 Context: {context}"
310
+
311
+
312
+
313
+ return report
314
+
315
+ @tool
316
+
317
+ def research_therapy_techniques(disorder: str, age_group: str = "adult") -> str:
318
+
319
+ """
320
+
321
+ Searches for modern therapy methods for specific disorders via DuckDuckGo.
322
+
323
+
324
+
325
+ Args:
326
+
327
+ disorder: Mental disorder or problem
328
+
329
+ age_group: Age group (child, teen, adult, elderly)
330
+
331
+
332
+
333
+ Returns:
334
+
335
+ Information about modern therapy methods
336
+
337
+ """
338
+
339
+ search_tool = DuckDuckGoSearchTool()
340
+
341
+
342
+
343
+ # Create search queries
344
+
345
+ search_queries = [
346
+
347
+ f"evidence-based therapy {disorder} {age_group} 2024",
348
+
349
+ f"latest treatment {disorder} psychology",
350
+
351
+ f"CBT DBT therapy {disorder} research"
352
+
353
+ ]
354
+
355
+
356
+
357
+ results = []
358
+
359
+ for query in search_queries:
360
+
361
  try:
362
+
363
+ search_result = search_tool(query)
364
+
365
+ results.append(search_result)
366
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  except Exception as e:
 
368
 
369
+ results.append(f"Search error for '{query}': {str(e)}")
370
+
 
371
 
372
+
373
+ # Create report
374
+
375
+ report = f"# 🔬 Therapy Methods Research\n\n"
376
+
377
+ report += f"**Disorder/Problem**: {disorder}\n"
378
+
379
+ report += f"**Age group**: {age_group}\n"
380
+
381
+ report += f"**Search date**: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}\n\n"
382
+
383
+
384
+
385
+ report += "## 📚 Search Results:\n\n"
386
+
387
+
388
+
389
+ for i, result in enumerate(results, 1):
390
+
391
+ report += f"### Search {i}:\n"
392
+
393
+ report += f"{result}\n\n"
394
+
395
+ report += "---\n\n"
396
+
397
+
398
+
399
+ report += "## 💡 Recommendations:\n"
400
+
401
+ report += "- Verify the currency of found information\n"
402
+
403
+ report += "- Cross-reference with clinical guidelines\n"
404
+
405
+ report += "- Consider individual client characteristics\n"
406
+
407
+ report += "- Consult with colleagues when needed\n"
408
+
409
+
410
+
411
+ return report
412
+
413
+ @tool
414
+
415
+ def create_therapy_worksheet(therapy_type: str, client_age: int, issue: str) -> str:
416
+
417
+ """
418
+
419
+ Creates a therapeutic worksheet/exercise for client.
420
+
421
+
422
+
423
+ Args:
424
+
425
+ therapy_type: Type of therapy (cbt, dbt, art, mindfulness)
426
+
427
+ client_age: Client's age
428
+
429
+ issue: Main problem
430
+
431
+
432
+
433
+ Returns:
434
+
435
+ Structured therapeutic worksheet
436
+
437
+ """
438
+
439
+ if client_age < 5 or client_age > 100:
440
+
441
+ return "Error: Age must be between 5 and 100."
442
+
443
+
444
+
445
+ therapy_type = therapy_type.lower()
446
+
447
+ valid_types = ["cbt", "dbt", "art", "mindfulness"]
448
+
449
+
450
+
451
+ if therapy_type not in valid_types:
452
+
453
+ return f"Error: Therapy type must be one of: {', '.join(valid_types)}"
454
+
455
+
456
+
457
+ # Determine level by age
458
+
459
+ if client_age < 12:
460
+
461
+ level = "child"
462
+
463
+ elif client_age < 18:
464
+
465
+ level = "teen"
466
+
467
+ else:
468
+
469
+ level = "adult"
470
+
471
+
472
+
473
+ worksheets = {
474
+
475
+ "cbt": {
476
+
477
+ "child": {
478
+
479
+ "title": "🌈 My Thoughts and Feelings",
480
+
481
+ "exercises": [
482
+
483
+ "🌤️ Mood Diary: Draw or mark your mood with an emoji each day",
484
+
485
+ "🤔 Thought Catcher: Write down thoughts when sad or scared",
486
+
487
+ "🎯 Helper Thoughts: Find 3 good thoughts for each bad thought",
488
+
489
+ "⭐ My Successes: Write one good thing you did each day"
490
+
491
+ ]
492
+
493
+ },
494
+
495
+ "teen": {
496
+
497
+ "title": "🧠 Cognitive Restructuring",
498
+
499
+ "exercises": [
500
+
501
+ "📊 ABC Model: Situation (A) → Thought (B) → Feeling/Behavior (C)",
502
+
503
+ "🔍 Thought Detective: Find evidence FOR and AGAINST your beliefs",
504
+
505
+ "⚖️ Alternative Thoughts: Find 2-3 realistic alternatives for negative thoughts",
506
+
507
+ "📝 Thought Diary: Daily record of automatic thoughts"
508
+
509
+ ]
510
+
511
+ },
512
+
513
+ "adult": {
514
+
515
+ "title": "🔄 Cognitive Behavioral Therapy",
516
+
517
+ "exercises": [
518
+
519
+ "🔄 Thought-Feeling-Behavior Cycle: Analyze connections in situations",
520
+
521
+ "⚡ Cognitive Distortions: Identify and correct thinking errors",
522
+
523
+ "🎯 Behavioral Experiments: Test catastrophic beliefs",
524
+
525
+ "📈 Graded Tasks: Step-by-step overcoming avoidance"
526
+
527
+ ]
528
+
529
+ }
530
+
531
+ },
532
+
533
+ "dbt": {
534
+
535
+ "teen": {
536
+
537
+ "title": "🌊 Emotion Regulation Skills",
538
+
539
+ "exercises": [
540
+
541
+ "🌊 TIPP: Temperature, Intense exercise, Paced breathing, Paired muscle relaxation",
542
+
543
+ "🚦 STOP: Stop → Take a breath → Observe → Proceed mindfully",
544
+
545
+ "🎭 Emotion Diary: Track emotion intensity (1-10) with triggers",
546
+
547
+ "🧘 Mindfulness: 5-10 minutes daily breathing meditation"
548
+
549
+ ]
550
+
551
+ },
552
+
553
+ "adult": {
554
+
555
+ "title": "⚖️ Dialectical Behavior Therapy",
556
+
557
+ "exercises": [
558
+
559
+ "⚖️ Wise Mind: Balance emotional and rational mind",
560
+
561
+ "🛡️ Crisis Skills: TIPP, distraction, self-soothing",
562
+
563
+ "🤝 DEAR MAN: Technique for healthy communication",
564
+
565
+ "🎯 Radical Acceptance: Practice accepting unchangeable reality"
566
+
567
+ ]
568
+
569
+ }
570
+
571
+ },
572
+
573
+ "art": {
574
+
575
+ "child": {
576
+
577
+ "title": "🎨 Art Therapy Exercises",
578
+
579
+ "exercises": [
580
+
581
+ "🎨 Feeling Colors: Draw your feelings using different colors",
582
+
583
+ "🏠 House of Emotions: Draw a house with different feelings in each room",
584
+
585
+ "🦋 Feeling Mask: Make and color a mask showing outside and inside feelings",
586
+
587
+ "🌈 Color Your Day: Color different parts of your day by emotions"
588
+
589
+ ]
590
+
591
+ },
592
+
593
+ "teen": {
594
+
595
+ "title": "🎭 Creative Expression",
596
+
597
+ "exercises": [
598
+
599
+ "🖼️ Identity Collage: Create a visual collage about 'Who am I?'",
600
+
601
+ "🗺️ Emotion Map: Draw a map of your feelings",
602
+
603
+ "📖 Visual Journal: Keep a journal in drawings instead of words",
604
+
605
+ "🎭 Metaphor Images: Draw your problem as a symbol"
606
+
607
+ ]
608
+
609
+ },
610
+
611
+ "adult": {
612
+
613
+ "title": "🖌️ Art Therapy for Adults",
614
+
615
+ "exercises": [
616
+
617
+ "🌳 Life Tree: Roots = values, trunk = strength, crown = goals",
618
+
619
+ "🚪 Doors of Possibility: Draw life choices and paths",
620
+
621
+ "⚡ Energy Portrait: Express inner state through abstract art",
622
+
623
+ "🔄 Transformation: Before and After visualization of changes"
624
+
625
+ ]
626
+
627
+ }
628
+
629
+ },
630
+
631
+ "mindfulness": {
632
+
633
+ "child": {
634
+
635
+ "title": "🐸 Mindfulness for Kids",
636
+
637
+ "exercises": [
638
+
639
+ "🐸 Frog Pose: Sit still like a frog and listen to sounds",
640
+
641
+ "🌬️ Belly Breathing: Watch a toy rise and fall on your belly",
642
+
643
+ "👀 5-4-3-2-1: Find 5 things you see, 4 you hear, 3 you can touch...",
644
+
645
+ "🍯 Slow Eating: Eat one raisin very slowly and mindfully"
646
+
647
+ ]
648
+
649
+ },
650
+
651
+ "teen": {
652
+
653
+ "title": "🧘 Teen Mindfulness",
654
+
655
+ "exercises": [
656
+
657
+ "📱 Digital Detox: 30-60 minutes without devices",
658
+
659
+ "🚶 Mindful Walking: Walk slowly noticing each step",
660
+
661
+ "💭 Thought Watching: Watch thoughts like clouds passing",
662
+
663
+ "❤️ Body Scan: Relax and notice each body part"
664
+
665
+ ]
666
+
667
+ },
668
+
669
+ "adult": {
670
+
671
+ "title": "🧘‍♀️ Mindfulness Practice",
672
+
673
+ "exercises": [
674
+
675
+ "🧘 Formal Meditation: 20-30 minutes daily sitting practice",
676
+
677
+ "🍽️ Mindful Eating: Full attention to taste, smell, texture",
678
+
679
+ "💼 Work Mindfulness: Regular pauses to return to present",
680
+
681
+ "😴 Sleep Meditation: Body scan and breathing for better sleep"
682
+
683
+ ]
684
+
685
+ }
686
+
687
+ }
688
+
689
+ }
690
+
691
+
692
+
693
+ # Get appropriate exercises
694
+
695
+ therapy_data = worksheets.get(therapy_type, {})
696
+
697
+ level_data = therapy_data.get(level, therapy_data.get("adult", {}))
698
+
699
+
700
+
701
+ if not level_data:
702
+
703
+ return f"Exercises for {therapy_type} therapy and age {client_age} not yet available."
704
+
705
+
706
+
707
+ # Create worksheet
708
+
709
+ worksheet = f"# {level_data['title']}\n\n"
710
+
711
+ worksheet += f"**👤 Client**: {client_age} years old\n"
712
+
713
+ worksheet += f"**🎯 Main issue**: {issue}\n"
714
+
715
+ worksheet += f"**🔬 Therapy type**: {therapy_type.upper()}\n"
716
+
717
+ worksheet += f"**📅 Date created**: {datetime.datetime.now().strftime('%m/%d/%Y')}\n\n"
718
+
719
+
720
+
721
+ worksheet += "## 📋 Exercises:\n\n"
722
+
723
+
724
+
725
+ for i, exercise in enumerate(level_data['exercises'], 1):
726
+
727
+ worksheet += f"### {i}. {exercise}\n\n"
728
+
729
+
730
+
731
+ # Add space for notes
732
+
733
+ worksheet += "**📝 Notes:**\n"
734
+
735
+ worksheet += "```\n"
736
+
737
+ worksheet += "Date completed: ___________\n"
738
+
739
+ worksheet += "Observations: \n\n\n"
740
+
741
+ worksheet += "Emotions during exercise: \n\n"
742
+
743
+ worksheet += "Insights: \n\n"
744
+
745
+ worksheet += "```\n\n"
746
+
747
+
748
+
749
+ worksheet += "---\n\n"
750
+
751
+ worksheet += "## 📖 Instructions:\n"
752
+
753
+ worksheet += "✅ Complete exercises at your own pace\n"
754
+
755
+ worksheet += "✅ Record all observations - this is important for progress\n"
756
+
757
+ worksheet += "✅ Discuss results with your therapist\n"
758
+
759
+ worksheet += "✅ Stop if you feel too uncomfortable and seek support\n\n"
760
+
761
+
762
+
763
+ worksheet += "## 🆘 When to get help:\n"
764
+
765
+ worksheet += "⚠️ If exercises cause severe anxiety or panic\n"
766
+
767
+ worksheet += "⚠️ If you have thoughts of self-harm\n"
768
+
769
+ worksheet += "⚠️ If symptoms worsen\n\n"
770
+
771
+
772
+
773
+ worksheet += "📞 Emergency contacts:\n"
774
+
775
+ worksheet += "- Crisis hotline: 988\n"
776
+
777
+ worksheet += "- Emergency: 911\n"
778
+
779
+ worksheet += "- Your therapist: ________________\n\n"
780
+
781
+
782
+
783
+ return worksheet
784
+
785
+ @tool
786
+
787
+ def mood_tracker_analyzer(mood_data: str) -> str:
788
+
789
+ """
790
+
791
+ Analyzes mood tracking data to identify patterns.
792
+
793
+
794
+
795
+ Args:
796
+
797
+ mood_data: JSON string with mood entries
798
+
799
+
800
+
801
+ Returns:
802
+
803
+ Analysis report with patterns and recommendations
804
+
805
+ """
806
+
807
+ try:
808
+
809
+ data = json.loads(mood_data)
810
+
811
+ except:
812
+
813
+ return "Error: Please provide mood data in JSON format."
814
+
815
+
816
+
817
+ if not isinstance(data, list) or len(data) == 0:
818
+
819
+ return "Error: Mood data should be a non-empty list of entries."
820
+
821
+
822
+
823
+ # Analyze mood patterns
824
+
825
+ moods = []
826
+
827
+ dates = []
828
+
829
+
830
+
831
+ for entry in data:
832
+
833
+ if 'mood' in entry and 'date' in entry:
834
+
835
+ moods.append(entry['mood'])
836
+
837
+ dates.append(entry['date'])
838
+
839
+
840
+
841
+ if not moods:
842
+
843
+ return "Error: No valid mood entries found."
844
+
845
+
846
+
847
+ # Calculate statistics
848
+
849
+ avg_mood = sum(moods) / len(moods)
850
+
851
+ mood_trend = "stable"
852
+
853
+
854
+
855
+ if len(moods) > 3:
856
+
857
+ recent_avg = sum(moods[-3:]) / 3
858
+
859
+ older_avg = sum(moods[:-3]) / (len(moods) - 3)
860
+
861
+
862
+
863
+ if recent_avg > older_avg + 0.5:
864
+
865
+ mood_trend = "improving"
866
+
867
+ elif recent_avg < older_avg - 0.5:
868
+
869
+ mood_trend = "declining"
870
+
871
+
872
+
873
+ # Create report
874
+
875
+ report = "# 📊 Mood Tracking Analysis\n\n"
876
+
877
+ report += f"**Period**: {dates[0]} to {dates[-1]}\n"
878
+
879
+ report += f"**Entries analyzed**: {len(moods)}\n"
880
+
881
+ report += f"**Average mood**: {avg_mood:.1f}/10\n"
882
+
883
+ report += f"**Trend**: {mood_trend}\n\n"
884
+
885
+
886
+
887
+ report += "## 📈 Pattern Analysis:\n"
888
+
889
+
890
+
891
+ # Check for low mood periods
892
+
893
+ low_mood_days = sum(1 for m in moods if m < 5)
894
+
895
+ if low_mood_days > len(moods) * 0.3:
896
+
897
+ report += "⚠️ Concern: Low mood detected in >30% of entries\n"
898
+
899
+ report += " → Consider professional evaluation for depression\n\n"
900
+
901
+
902
+
903
+ # Check volatility
904
+
905
+ if len(moods) > 2:
906
+
907
+ volatility = sum(abs(moods[i] - moods[i-1]) for i in range(1, len(moods))) / (len(moods) - 1)
908
+
909
+ if volatility > 2:
910
+
911
+ report += "🎢 High mood volatility detected\n"
912
+
913
+ report += " → May benefit from emotion regulation skills\n\n"
914
+
915
+
916
+
917
+ report += "## 💡 Recommendations:\n"
918
+
919
+
920
+
921
+ if mood_trend == "declining":
922
+
923
+ report += "- 🚨 Schedule appointment with mental health professional\n"
924
+
925
+ report += "- 🧘 Increase self-care activities\n"
926
+
927
+ report += "- 👥 Reach out to support network\n"
928
+
929
+ elif mood_trend == "improving":
930
+
931
+ report += "- ✅ Continue current strategies\n"
932
+
933
+ report += "- 📝 Document what's working well\n"
934
+
935
+ report += "- 🎯 Set new wellness goals\n"
936
+
937
+ else:
938
+
939
+ report += "- 📊 Continue tracking for more data\n"
940
+
941
+ report += "- 🔍 Look for mood triggers\n"
942
+
943
+ report += "- 💪 Maintain healthy routines\n"
944
+
945
+
946
+
947
+ report += f"\n*Analysis completed: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}*"
948
+
949
+
950
+
951
+ return report