RozzaCreat commited on
Commit
14b3056
·
verified ·
1 Parent(s): 4a69ef1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +398 -463
app.py CHANGED
@@ -1,480 +1,415 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
  import json
7
  import re
8
- import tempfile
9
  import os
10
  from typing import Dict, List, Any
11
- from tools.final_answer import FinalAnswerTool
12
- from Gradio_UI import GradioUI
13
 
14
- @tool
15
- def speech_emotion_analyzer(text: str, context: str = "therapy") -> str:
16
- """
17
- Analyzes patient's emotional state from speech text.
18
-
19
- Args:
20
- text: Patient's speech text
21
- context: Context (therapy, assessment, crisis)
22
-
23
- Returns:
24
- Analysis of emotional state and recommendations
25
- """
26
- if not text or len(text.strip()) < 10:
27
- return "Error: Text must be at least 10 characters long for analysis."
28
-
29
- # Emotion indicators for analysis
30
- emotion_indicators = {
31
- "depression": {
32
- "keywords": ["sad", "hopeless", "tired", "meaningless", "empty", "lonely",
33
- "depressed", "despair", "miserable", "worthless", "numb"],
34
- "patterns": [r"can't.*sleep", r"no.*energy", r"everything.*bad", r"don't.*want",
35
- r"life.*no.*meaning", r"better.*dead"]
36
- },
37
- "anxiety": {
38
- "keywords": ["anxious", "worried", "nervous", "scared", "panic", "tense",
39
- "anxiety", "worry", "fear", "stress", "phobia"],
40
- "patterns": [r"what.*if", r"afraid.*that", r"can't.*cope", r"heart.*racing",
41
- r"hands.*shaking", r"can't.*breathe", r"panic.*attack"]
42
- },
43
- "anger": {
44
- "keywords": ["angry", "furious", "irritated", "annoyed", "hate", "mad",
45
- "rage", "aggression", "hatred", "frustration"],
46
- "patterns": [r"fed up", r"sick of", r"can't.*stand", r"want.*hit",
47
- r"everything.*irritates", r"pissed off"]
48
- },
49
- "stress": {
50
- "keywords": ["stress", "pressure", "overwhelmed", "exhausted", "burned out",
51
- "burnout", "fatigue", "drained"],
52
- "patterns": [r"too.*much.*work", r"can't.*keep up", r"headache", r"no.*time",
53
- r"swamped", r"working.*nonstop"]
54
- },
55
- "trauma": {
56
- "keywords": ["trauma", "flashbacks", "nightmares", "memories", "avoiding",
57
- "ptsd", "triggered", "shock"],
58
- "patterns": [r"keep.*remembering", r"bad.*dreams", r"can't.*forget",
59
- r"avoid.*places", r"triggers"]
60
- }
61
- }
62
-
63
- # Analyze text
64
- text_lower = text.lower()
65
- detected_emotions = {}
66
-
67
- for emotion, indicators in emotion_indicators.items():
68
- score = 0
69
- matches = []
70
-
71
- # Check keywords
72
- for keyword in indicators["keywords"]:
73
- if keyword in text_lower:
74
- score += 1
75
- matches.append(keyword)
76
-
77
- # Check patterns
78
- for pattern in indicators["patterns"]:
79
- if re.search(pattern, text_lower):
80
- score += 2
81
- matches.append(f"pattern: {pattern}")
82
-
83
- if score > 0:
84
- detected_emotions[emotion] = {"score": score, "matches": matches}
85
-
86
- # Check for crisis indicators
87
- crisis_indicators = ["suicide", "kill myself", "end it all", "not worth living", "better off dead"]
88
- crisis_risk = any(indicator in text_lower for indicator in crisis_indicators)
89
-
90
- # Check positive indicators
91
- positive_indicators = ["happy", "joy", "good", "great", "wonderful", "excited", "grateful", "love"]
92
- positive_count = sum(1 for indicator in positive_indicators if indicator in text_lower)
93
-
94
- # Create report
95
- report = "## 🧠 Emotional State Analysis\n\n"
96
-
97
- if detected_emotions:
98
- report += "### 📊 Detected Emotional States:\n"
99
- for emotion, data in sorted(detected_emotions.items(), key=lambda x: x[1]["score"], reverse=True):
100
- emotion_names = {
101
- "depression": "😔 Depression signs",
102
- "anxiety": "😰 Anxiety",
103
- "anger": "😠 Anger/Irritation",
104
- "stress": "😵 Stress",
105
- "trauma": "💔 Trauma-related"
106
- }
107
- intensity = "High" if data['score'] >= 4 else "Medium" if data['score'] >= 2 else "Low"
108
- report += f"- **{emotion_names[emotion]}** (intensity: {intensity})\n"
109
- report += f" Found indicators: {', '.join(data['matches'][:3])}\n\n"
110
- else:
111
- report += "✅ No clear signs of emotional distress detected.\n\n"
112
-
113
- # Positive aspects
114
- if positive_count > 0:
115
- report += f"😊 **Positive indicators**: Found {positive_count} positive marker(s)\n\n"
116
-
117
- # Crisis assessment
118
- if crisis_risk:
119
- report += "🚨 **CRITICAL: Suicide risk indicators detected!**\n"
120
- report += "📞 Immediate consultation and safety assessment recommended.\n"
121
- report += "Emergency services: 911, Crisis hotline: 988\n\n"
122
-
123
- # Treatment recommendations
124
- report += "### 🎯 Treatment Recommendations:\n"
125
-
126
- if "depression" in detected_emotions:
127
- report += "- 🧘 **CBT (Cognitive Behavioral Therapy)** for negative thought patterns\n"
128
- report += "- 💊 Consider psychiatric consultation for medication support\n"
129
- report += "- 🏃 Behavioral activation (increase pleasant activities)\n"
130
-
131
- if "anxiety" in detected_emotions:
132
- report += "- 🫁 **Relaxation techniques**: breathing exercises, progressive muscle relaxation\n"
133
- report += "- 🎭 **Exposure therapy** for phobic avoidance\n"
134
- report += "- 🧠 **Mindfulness therapy** for anxious thoughts\n"
135
-
136
- if "anger" in detected_emotions:
137
- report += "- 🎯 **Anger management training** and self-regulation techniques\n"
138
- report += "- 🔍 **Trigger identification** and behavior patterns\n"
139
- report += "- 🤝 **Communication skills training**\n"
140
-
141
- if "stress" in detected_emotions:
142
- report += "- ⏰ **Stress management** and time management techniques\n"
143
- report += "- ⚖️ **Work-life balance** assessment and adjustment\n"
144
- report += "- 🛡️ **Coping strategies** for stressful situations\n"
145
-
146
- if "trauma" in detected_emotions:
147
- report += "- 👁️ **EMDR therapy** for traumatic memories\n"
148
- report += "- 🏠 **Trauma-informed approach** in therapy\n"
149
- report += "- 🧘 **Somatic techniques** for body-based trauma symptoms\n"
150
-
151
- if not detected_emotions or positive_count > 2:
152
- report += "- 💪 **Supportive therapy** to maintain resources\n"
153
- report += "- 🎯 **Personal growth** and life goals development\n"
154
-
155
- report += f"\n📅 *Analysis date: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}*"
156
- report += f"\n🌍 *Context: {context}*"
157
-
158
- return report
159
-
160
- @tool
161
- def research_therapy_techniques(disorder: str, age_group: str = "adult") -> str:
162
- """
163
- Searches for modern therapy methods for specific disorders via DuckDuckGo.
164
-
165
- Args:
166
- disorder: Mental disorder or problem
167
- age_group: Age group (child, teen, adult, elderly)
168
-
169
- Returns:
170
- Information about modern therapy methods
171
- """
172
- search_tool = DuckDuckGoSearchTool()
173
-
174
- # Create search queries
175
- search_queries = [
176
- f"evidence-based therapy {disorder} {age_group} 2024",
177
- f"latest treatment {disorder} psychology",
178
- f"CBT DBT therapy {disorder} research"
179
- ]
180
-
181
- results = []
182
- for query in search_queries:
183
- try:
184
- search_result = search_tool(query)
185
- results.append(search_result)
186
- except Exception as e:
187
- results.append(f"Search error for '{query}': {str(e)}")
188
-
189
- # Create report
190
- report = f"# 🔬 Therapy Methods Research\n\n"
191
- report += f"**Disorder/Problem**: {disorder}\n"
192
- report += f"**Age group**: {age_group}\n"
193
- report += f"**Search date**: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}\n\n"
194
-
195
- report += "## 📚 Search Results:\n\n"
196
-
197
- for i, result in enumerate(results, 1):
198
- report += f"### Search {i}:\n"
199
- report += f"{result}\n\n"
200
- report += "---\n\n"
201
-
202
- report += "## 💡 Recommendations:\n"
203
- report += "- Verify the currency of found information\n"
204
- report += "- Cross-reference with clinical guidelines\n"
205
- report += "- Consider individual client characteristics\n"
206
- report += "- Consult with colleagues when needed\n"
207
-
208
- return report
209
-
210
- @tool
211
- def create_therapy_worksheet(therapy_type: str, client_age: int, issue: str) -> str:
212
- """
213
- Creates a therapeutic worksheet/exercise for client.
214
-
215
- Args:
216
- therapy_type: Type of therapy (cbt, dbt, art, mindfulness)
217
- client_age: Client's age
218
- issue: Main problem
219
-
220
- Returns:
221
- Structured therapeutic worksheet
222
- """
223
- if client_age < 5 or client_age > 100:
224
- return "Error: Age must be between 5 and 100."
225
-
226
- therapy_type = therapy_type.lower()
227
- valid_types = ["cbt", "dbt", "art", "mindfulness"]
228
-
229
- if therapy_type not in valid_types:
230
- return f"Error: Therapy type must be one of: {', '.join(valid_types)}"
231
-
232
- # Determine level by age
233
- if client_age < 12:
234
- level = "child"
235
- elif client_age < 18:
236
- level = "teen"
237
- else:
238
- level = "adult"
239
-
240
- worksheets = {
241
- "cbt": {
242
- "child": {
243
- "title": "🌈 My Thoughts and Feelings",
244
- "exercises": [
245
- "🌤️ **Mood Diary**: Draw or mark your mood with an emoji each day",
246
- "🤔 **Thought Catcher**: Write down thoughts when sad or scared",
247
- "🎯 **Helper Thoughts**: Find 3 good thoughts for each bad thought",
248
- "⭐ **My Successes**: Write one good thing you did each day"
249
- ]
250
- },
251
- "teen": {
252
- "title": "🧠 Cognitive Restructuring",
253
- "exercises": [
254
- "📊 **ABC Model**: Situation (A) → Thought (B) → Feeling/Behavior (C)",
255
- "🔍 **Thought Detective**: Find evidence FOR and AGAINST your beliefs",
256
- "⚖️ **Alternative Thoughts**: Find 2-3 realistic alternatives for negative thoughts",
257
- "📝 **Thought Diary**: Daily record of automatic thoughts"
258
- ]
259
- },
260
- "adult": {
261
- "title": "🔄 Cognitive Behavioral Therapy",
262
- "exercises": [
263
- "🔄 **Thought-Feeling-Behavior Cycle**: Analyze connections in situations",
264
- "⚡ **Cognitive Distortions**: Identify and correct thinking errors",
265
- "🎯 **Behavioral Experiments**: Test catastrophic beliefs",
266
- "📈 **Graded Tasks**: Step-by-step overcoming avoidance"
267
- ]
268
- }
269
- },
270
- "dbt": {
271
- "teen": {
272
- "title": "🌊 Emotion Regulation Skills",
273
- "exercises": [
274
- "🌊 **TIPP**: Temperature, Intense exercise, Paced breathing, Paired muscle relaxation",
275
- "🚦 **STOP**: Stop → Take a breath → Observe → Proceed mindfully",
276
- "🎭 **Emotion Diary**: Track emotion intensity (1-10) with triggers",
277
- "🧘 **Mindfulness**: 5-10 minutes daily breathing meditation"
278
- ]
279
- },
280
- "adult": {
281
- "title": "⚖️ Dialectical Behavior Therapy",
282
- "exercises": [
283
- "⚖️ **Wise Mind**: Balance emotional and rational mind",
284
- "🛡️ **Crisis Skills**: TIPP, distraction, self-soothing",
285
- "🤝 **DEAR MAN**: Technique for healthy communication",
286
- "🎯 **Radical Acceptance**: Practice accepting unchangeable reality"
287
- ]
288
- }
289
- },
290
- "art": {
291
- "child": {
292
- "title": "🎨 Art Therapy Exercises",
293
- "exercises": [
294
- "🎨 **Feeling Colors**: Draw your feelings using different colors",
295
- "🏠 **House of Emotions**: Draw a house with different feelings in each room",
296
- "🦋 **Feeling Mask**: Make and color a mask showing outside and inside feelings",
297
- "🌈 **Color Your Day**: Color different parts of your day by emotions"
298
- ]
299
  },
300
- "teen": {
301
- "title": "🎭 Creative Expression",
302
- "exercises": [
303
- "🖼️ **Identity Collage**: Create a visual collage about 'Who am I?'",
304
- "🗺️ **Emotion Map**: Draw a map of your feelings",
305
- "📖 **Visual Journal**: Keep a journal in drawings instead of words",
306
- "🎭 **Metaphor Images**: Draw your problem as a symbol"
307
- ]
308
  },
309
- "adult": {
310
- "title": "🖌️ Art Therapy for Adults",
311
- "exercises": [
312
- "🌳 **Life Tree**: Roots = values, trunk = strength, crown = goals",
313
- "🚪 **Doors of Possibility**: Draw life choices and paths",
314
- "⚡ **Energy Portrait**: Express inner state through abstract art",
315
- "🔄 **Transformation**: Before and After visualization of changes"
316
- ]
317
  }
318
- },
319
- "mindfulness": {
320
- "child": {
321
- "title": "🐸 Mindfulness for Kids",
322
- "exercises": [
323
- "🐸 **Frog Pose**: Sit still like a frog and listen to sounds",
324
- "🌬️ **Belly Breathing**: Watch a toy rise and fall on your belly",
325
- "👀 **5-4-3-2-1**: Find 5 things you see, 4 you hear, 3 you can touch...",
326
- "🍯 **Slow Eating**: Eat one raisin very slowly and mindfully"
327
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  },
329
- "teen": {
330
- "title": "🧘 Teen Mindfulness",
331
- "exercises": [
332
- "📱 **Digital Detox**: 30-60 minutes without devices",
333
- "🚶 **Mindful Walking**: Walk slowly noticing each step",
334
- "💭 **Thought Watching**: Watch thoughts like clouds passing",
335
- "❤️ **Body Scan**: Relax and notice each body part"
336
- ]
 
 
 
 
 
 
 
 
 
337
  },
338
- "adult": {
339
- "title": "🧘‍♀️ Mindfulness Practice",
340
- "exercises": [
341
- "🧘 **Formal Meditation**: 20-30 minutes daily sitting practice",
342
- "🍽️ **Mindful Eating**: Full attention to taste, smell, texture",
343
- "💼 **Work Mindfulness**: Regular pauses to return to present",
344
- "😴 **Sleep Meditation**: Body scan and breathing for better sleep"
345
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  }
347
  }
348
- }
349
-
350
- # Get appropriate exercises
351
- therapy_data = worksheets.get(therapy_type, {})
352
- level_data = therapy_data.get(level, therapy_data.get("adult", {}))
353
-
354
- if not level_data:
355
- return f"Exercises for {therapy_type} therapy and age {client_age} not yet available."
356
-
357
- # Create worksheet
358
- worksheet = f"# {level_data['title']}\n\n"
359
- worksheet += f"**👤 Client**: {client_age} years old\n"
360
- worksheet += f"**🎯 Main issue**: {issue}\n"
361
- worksheet += f"**🔬 Therapy type**: {therapy_type.upper()}\n"
362
- worksheet += f"**📅 Date created**: {datetime.datetime.now().strftime('%m/%d/%Y')}\n\n"
363
-
364
- worksheet += "## 📋 Exercises:\n\n"
365
-
366
- for i, exercise in enumerate(level_data['exercises'], 1):
367
- worksheet += f"### {i}. {exercise}\n\n"
368
-
369
- # Add space for notes
370
- worksheet += "**📝 Notes:**\n"
371
- worksheet += "```\n"
372
- worksheet += "Date completed: ___________\n"
373
- worksheet += "Observations: \n\n\n"
374
- worksheet += "Emotions during exercise: \n\n"
375
- worksheet += "Insights: \n\n"
376
- worksheet += "```\n\n"
377
-
378
- worksheet += "---\n\n"
379
- worksheet += "## 📖 Instructions:\n"
380
- worksheet += "✅ Complete exercises at your own pace\n"
381
- worksheet += "✅ Record all observations - this is important for progress\n"
382
- worksheet += "✅ Discuss results with your therapist\n"
383
- worksheet += "✅ Stop if you feel too uncomfortable and seek support\n\n"
384
-
385
- worksheet += "## 🆘 When to get help:\n"
386
- worksheet += "⚠️ If exercises cause severe anxiety or panic\n"
387
- worksheet += "⚠️ If you have thoughts of self-harm\n"
388
- worksheet += "⚠️ If symptoms worsen\n\n"
389
 
390
- worksheet += "📞 **Emergency contacts:**\n"
391
- worksheet += "- Crisis hotline: 988\n"
392
- worksheet += "- Emergency: 911\n"
393
- worksheet += "- Your therapist: ________________\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
 
395
- return worksheet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
 
397
- @tool
398
- def mood_tracker_analyzer(mood_data: str) -> str:
399
- """
400
- Analyzes mood tracking data to identify patterns.
401
-
402
- Args:
403
- mood_data: JSON string with mood entries
404
-
405
- Returns:
406
- Analysis report with patterns and recommendations
407
- """
408
- try:
409
- data = json.loads(mood_data)
410
- except:
411
- return "Error: Please provide mood data in JSON format."
412
-
413
- if not isinstance(data, list) or len(data) == 0:
414
- return "Error: Mood data should be a non-empty list of entries."
415
-
416
- # Analyze mood patterns
417
- moods = []
418
- dates = []
419
-
420
- for entry in data:
421
- if 'mood' in entry and 'date' in entry:
422
- moods.append(entry['mood'])
423
- dates.append(entry['date'])
424
 
425
- if not moods:
426
- return "Error: No valid mood entries found."
427
-
428
- # Calculate statistics
429
- avg_mood = sum(moods) / len(moods)
430
- mood_trend = "stable"
431
-
432
- if len(moods) > 3:
433
- recent_avg = sum(moods[-3:]) / 3
434
- older_avg = sum(moods[:-3]) / (len(moods) - 3)
435
-
436
- if recent_avg > older_avg + 0.5:
437
- mood_trend = "improving"
438
- elif recent_avg < older_avg - 0.5:
439
- mood_trend = "declining"
440
-
441
- # Create report
442
- report = "# 📊 Mood Tracking Analysis\n\n"
443
- report += f"**Period**: {dates[0]} to {dates[-1]}\n"
444
- report += f"**Entries analyzed**: {len(moods)}\n"
445
- report += f"**Average mood**: {avg_mood:.1f}/10\n"
446
- report += f"**Trend**: {mood_trend}\n\n"
447
-
448
- report += "## 📈 Pattern Analysis:\n"
449
-
450
- # Check for low mood periods
451
- low_mood_days = sum(1 for m in moods if m < 5)
452
- if low_mood_days > len(moods) * 0.3:
453
- report += "⚠️ **Concern**: Low mood detected in >30% of entries\n"
454
- report += " → Consider professional evaluation for depression\n\n"
455
-
456
- # Check volatility
457
- if len(moods) > 2:
458
- volatility = sum(abs(moods[i] - moods[i-1]) for i in range(1, len(moods))) / (len(moods) - 1)
459
- if volatility > 2:
460
- report += "🎢 **High mood volatility detected**\n"
461
- report += " → May benefit from emotion regulation skills\n\n"
462
-
463
- report += "## 💡 Recommendations:\n"
464
-
465
- if mood_trend == "declining":
466
- report += "- 🚨 Schedule appointment with mental health professional\n"
467
- report += "- 🧘 Increase self-care activities\n"
468
- report += "- 👥 Reach out to support network\n"
469
- elif mood_trend == "improving":
470
- report += "- ✅ Continue current strategies\n"
471
- report += "- 📝 Document what's working well\n"
472
- report += "- 🎯 Set new wellness goals\n"
473
- else:
474
- report += "- 📊 Continue tracking for more data\n"
475
- report += "- 🔍 Look for mood triggers\n"
476
- report += "- 💪 Maintain healthy routines\n"
477
-
478
- report += f"\n*Analysis completed: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}*"
479
-
480
- return report
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)