RozzaCreat commited on
Commit
9d30fad
·
verified ·
1 Parent(s): 5e04ef0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -572
app.py CHANGED
@@ -1,951 +1,545 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
 
 
 
 
 
 
 
 
 
2
  import json
3
+ import datetime
4
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, tool
 
 
 
 
 
5
  from typing import Dict, List, Any
6
+ import re
7
 
8
+ # Import your existing tools (assuming they're in the same file or properly imported)
9
+ # For this example, I'll include the key functions inline
 
10
 
11
  @tool
 
12
  def speech_emotion_analyzer(text: str, context: str = "therapy") -> str:
 
13
  """
 
14
  Analyzes patient's emotional state from speech text.
 
15
 
 
16
  Args:
 
17
  text: Patient's speech text
 
18
  context: Context (therapy, assessment, crisis)
 
19
 
 
20
  Returns:
 
21
  Analysis of emotional state and recommendations
 
22
  """
 
23
  if not text or len(text.strip()) < 10:
 
24
  return "Error: Text must be at least 10 characters long for analysis."
 
25
 
 
26
  # Emotion indicators for analysis
 
27
  emotion_indicators = {
 
28
  "depression": {
 
29
  "keywords": ["sad", "hopeless", "tired", "meaningless", "empty", "lonely",
 
30
  "depressed", "despair", "miserable", "worthless", "numb"],
 
31
  "patterns": [r"can't.*sleep", r"no.*energy", r"everything.*bad", r"don't.*want",
 
32
  r"life.*no.*meaning", r"better.*dead"]
 
33
  },
 
34
  "anxiety": {
 
35
  "keywords": ["anxious", "worried", "nervous", "scared", "panic", "tense",
 
36
  "anxiety", "worry", "fear", "stress", "phobia"],
 
37
  "patterns": [r"what.*if", r"afraid.*that", r"can't.*cope", r"heart.*racing",
 
38
  r"hands.*shaking", r"can't.*breathe", r"panic.*attack"]
 
39
  },
 
40
  "anger": {
 
41
  "keywords": ["angry", "furious", "irritated", "annoyed", "hate", "mad",
 
42
  "rage", "aggression", "hatred", "frustration"],
 
43
  "patterns": [r"fed up", r"sick of", r"can't.*stand", r"want.*hit",
 
44
  r"everything.*irritates", r"pissed off"]
 
45
  },
 
46
  "stress": {
 
47
  "keywords": ["stress", "pressure", "overwhelmed", "exhausted", "burned out",
 
48
  "burnout", "fatigue", "drained"],
 
49
  "patterns": [r"too.*much.*work", r"can't.*keep up", r"headache", r"no.*time",
 
50
  r"swamped", r"working.*nonstop"]
 
51
  },
 
52
  "trauma": {
 
53
  "keywords": ["trauma", "flashbacks", "nightmares", "memories", "avoiding",
 
54
  "ptsd", "triggered", "shock"],
 
55
  "patterns": [r"keep.*remembering", r"bad.*dreams", r"can't.*forget",
 
56
  r"avoid.*places", r"triggers"]
 
57
  }
 
58
  }
 
59
 
 
60
  # Analyze text
 
61
  text_lower = text.lower()
 
62
  detected_emotions = {}
 
63
 
 
64
  for emotion, indicators in emotion_indicators.items():
 
65
  score = 0
 
66
  matches = []
 
67
 
 
68
  # Check keywords
 
69
  for keyword in indicators["keywords"]:
 
70
  if keyword in text_lower:
 
71
  score += 1
 
72
  matches.append(keyword)
 
73
 
 
74
  # Check patterns
 
75
  for pattern in indicators["patterns"]:
 
76
  if re.search(pattern, text_lower):
 
77
  score += 2
 
78
  matches.append(f"pattern: {pattern}")
 
79
 
 
80
  if score > 0:
 
81
  detected_emotions[emotion] = {"score": score, "matches": matches}
 
82
 
 
83
  # Check for crisis indicators
 
84
  crisis_indicators = ["suicide", "kill myself", "end it all", "not worth living", "better off dead"]
 
85
  crisis_risk = any(indicator in text_lower for indicator in crisis_indicators)
 
86
 
 
87
  # Check positive indicators
 
88
  positive_indicators = ["happy", "joy", "good", "great", "wonderful", "excited", "grateful", "love"]
 
89
  positive_count = sum(1 for indicator in positive_indicators if indicator in text_lower)
 
90
 
 
91
  # Create report
 
92
  report = "## 🧠 Emotional State Analysis\n\n"
 
93
 
 
94
  if detected_emotions:
 
95
  report += "### 📊 Detected Emotional States:\n"
 
96
  for emotion, data in sorted(detected_emotions.items(), key=lambda x: x[1]["score"], reverse=True):
 
97
  emotion_names = {
 
98
  "depression": "😔 Depression signs",
 
99
  "anxiety": "😰 Anxiety",
 
100
  "anger": "😠 Anger/Irritation",
 
101
  "stress": "😵 Stress",
 
102
  "trauma": "💔 Trauma-related"
 
103
  }
 
104
  intensity = "High" if data['score'] >= 4 else "Medium" if data['score'] >= 2 else "Low"
 
105
  report += f"- {emotion_names[emotion]} (intensity: {intensity})\n"
 
106
  report += f" Found indicators: {', '.join(data['matches'][:3])}\n\n"
 
107
  else:
 
108
  report += "✅ No clear signs of emotional distress detected.\n\n"
 
109
 
 
110
  # Positive aspects
 
111
  if positive_count > 0:
 
112
  report += f"😊 Positive indicators: Found {positive_count} positive marker(s)\n\n"
 
113
 
 
114
  # Crisis assessment
 
115
  if crisis_risk:
 
116
  report += "🚨 CRITICAL: Suicide risk indicators detected!\n"
 
117
  report += "📞 Immediate consultation and safety assessment recommended.\n"
 
118
  report += "Emergency services: 911, Crisis hotline: 988\n\n"
 
119
 
 
120
  # Treatment recommendations
 
121
  report += "### 🎯 Treatment Recommendations:\n"
 
122
 
 
123
  if "depression" in detected_emotions:
 
124
  report += "- 🧘 CBT (Cognitive Behavioral Therapy) for negative thought patterns\n"
 
125
  report += "- 💊 Consider psychiatric consultation for medication support\n"
 
126
  report += "- 🏃 Behavioral activation (increase pleasant activities)\n"
 
127
 
 
128
  if "anxiety" in detected_emotions:
 
129
  report += "- 🫁 Relaxation techniques: breathing exercises, progressive muscle relaxation\n"
 
130
  report += "- 🎭 Exposure therapy for phobic avoidance\n"
 
131
  report += "- 🧠 Mindfulness therapy for anxious thoughts\n"
 
132
 
 
133
  if "anger" in detected_emotions:
 
134
  report += "- 🎯 Anger management training and self-regulation techniques\n"
 
135
  report += "- 🔍 Trigger identification and behavior patterns\n"
 
136
  report += "- 🤝 Communication skills training\n"
 
137
 
 
138
  if "stress" in detected_emotions:
 
139
  report += "- ⏰ Stress management and time management techniques\n"
 
140
  report += "- ⚖️ Work-life balance assessment and adjustment\n"
 
141
  report += "- 🛡️ Coping strategies for stressful situations\n"
 
142
 
 
143
  if "trauma" in detected_emotions:
 
144
  report += "- 👁️ EMDR therapy for traumatic memories\n"
 
145
  report += "- 🏠 Trauma-informed approach in therapy\n"
 
146
  report += "- 🧘 Somatic techniques for body-based trauma symptoms\n"
 
147
 
 
148
  if not detected_emotions or positive_count > 2:
 
149
  report += "- 💪 Supportive therapy to maintain resources\n"
 
150
  report += "- 🎯 Personal growth and life goals development\n"
 
151
 
 
152
  report += f"\n📅 Analysis date: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}"
 
153
  report += f"\n🌍 Context: {context}"
 
154
 
 
155
  return report
156
 
157
  @tool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  def create_therapy_worksheet(therapy_type: str, client_age: int, issue: str) -> str:
 
159
  """
 
160
  Creates a therapeutic worksheet/exercise for client.
 
161
 
 
162
  Args:
 
163
  therapy_type: Type of therapy (cbt, dbt, art, mindfulness)
 
164
  client_age: Client's age
 
165
  issue: Main problem
 
166
 
 
167
  Returns:
 
168
  Structured therapeutic worksheet
 
169
  """
 
170
  if client_age < 5 or client_age > 100:
 
171
  return "Error: Age must be between 5 and 100."
 
172
 
 
173
  therapy_type = therapy_type.lower()
 
174
  valid_types = ["cbt", "dbt", "art", "mindfulness"]
 
175
 
 
176
  if therapy_type not in valid_types:
 
177
  return f"Error: Therapy type must be one of: {', '.join(valid_types)}"
 
178
 
 
179
  # Determine level by age
 
180
  if client_age < 12:
 
181
  level = "child"
 
182
  elif client_age < 18:
 
183
  level = "teen"
 
184
  else:
 
185
  level = "adult"
 
186
 
 
187
  worksheets = {
 
188
  "cbt": {
 
189
  "child": {
 
190
  "title": "🌈 My Thoughts and Feelings",
 
191
  "exercises": [
 
192
  "🌤️ Mood Diary: Draw or mark your mood with an emoji each day",
 
193
  "🤔 Thought Catcher: Write down thoughts when sad or scared",
 
194
  "🎯 Helper Thoughts: Find 3 good thoughts for each bad thought",
 
195
  "⭐ My Successes: Write one good thing you did each day"
 
196
  ]
 
197
  },
 
198
  "teen": {
 
199
  "title": "🧠 Cognitive Restructuring",
 
200
  "exercises": [
 
201
  "📊 ABC Model: Situation (A) → Thought (B) → Feeling/Behavior (C)",
 
202
  "🔍 Thought Detective: Find evidence FOR and AGAINST your beliefs",
 
203
  "⚖️ Alternative Thoughts: Find 2-3 realistic alternatives for negative thoughts",
 
204
  "📝 Thought Diary: Daily record of automatic thoughts"
 
205
  ]
 
206
  },
 
207
  "adult": {
 
208
  "title": "🔄 Cognitive Behavioral Therapy",
 
209
  "exercises": [
 
210
  "🔄 Thought-Feeling-Behavior Cycle: Analyze connections in situations",
 
211
  "⚡ Cognitive Distortions: Identify and correct thinking errors",
 
212
  "🎯 Behavioral Experiments: Test catastrophic beliefs",
 
213
  "📈 Graded Tasks: Step-by-step overcoming avoidance"
 
214
  ]
 
215
  }
 
216
  },
 
217
  "dbt": {
 
218
  "teen": {
 
219
  "title": "🌊 Emotion Regulation Skills",
 
220
  "exercises": [
 
221
  "🌊 TIPP: Temperature, Intense exercise, Paced breathing, Paired muscle relaxation",
 
222
  "🚦 STOP: Stop → Take a breath → Observe → Proceed mindfully",
 
223
  "🎭 Emotion Diary: Track emotion intensity (1-10) with triggers",
 
224
  "🧘 Mindfulness: 5-10 minutes daily breathing meditation"
 
225
  ]
 
226
  },
 
227
  "adult": {
 
228
  "title": "⚖️ Dialectical Behavior Therapy",
 
229
  "exercises": [
 
230
  "⚖️ Wise Mind: Balance emotional and rational mind",
 
231
  "🛡️ Crisis Skills: TIPP, distraction, self-soothing",
 
232
  "🤝 DEAR MAN: Technique for healthy communication",
 
233
  "🎯 Radical Acceptance: Practice accepting unchangeable reality"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  ]
 
235
  }
 
236
  },
 
237
  "mindfulness": {
 
238
  "child": {
 
239
  "title": "🐸 Mindfulness for Kids",
 
240
  "exercises": [
 
241
  "🐸 Frog Pose: Sit still like a frog and listen to sounds",
 
242
  "🌬️ Belly Breathing: Watch a toy rise and fall on your belly",
 
243
  "👀 5-4-3-2-1: Find 5 things you see, 4 you hear, 3 you can touch...",
 
244
  "🍯 Slow Eating: Eat one raisin very slowly and mindfully"
 
245
  ]
 
246
  },
 
247
  "teen": {
 
248
  "title": "🧘 Teen Mindfulness",
 
249
  "exercises": [
 
250
  "📱 Digital Detox: 30-60 minutes without devices",
 
251
  "🚶 Mindful Walking: Walk slowly noticing each step",
 
252
  "💭 Thought Watching: Watch thoughts like clouds passing",
 
253
  "❤️ Body Scan: Relax and notice each body part"
 
254
  ]
 
255
  },
 
256
  "adult": {
 
257
  "title": "🧘‍♀️ Mindfulness Practice",
 
258
  "exercises": [
 
259
  "🧘 Formal Meditation: 20-30 minutes daily sitting practice",
 
260
  "🍽️ Mindful Eating: Full attention to taste, smell, texture",
 
261
  "💼 Work Mindfulness: Regular pauses to return to present",
 
262
  "😴 Sleep Meditation: Body scan and breathing for better sleep"
 
263
  ]
 
264
  }
 
265
  }
 
266
  }
 
267
 
 
268
  # Get appropriate exercises
 
269
  therapy_data = worksheets.get(therapy_type, {})
 
270
  level_data = therapy_data.get(level, therapy_data.get("adult", {}))
 
271
 
 
272
  if not level_data:
 
273
  return f"Exercises for {therapy_type} therapy and age {client_age} not yet available."
 
274
 
 
275
  # Create worksheet
 
276
  worksheet = f"# {level_data['title']}\n\n"
 
277
  worksheet += f"**👤 Client**: {client_age} years old\n"
 
278
  worksheet += f"**🎯 Main issue**: {issue}\n"
 
279
  worksheet += f"**🔬 Therapy type**: {therapy_type.upper()}\n"
 
280
  worksheet += f"**📅 Date created**: {datetime.datetime.now().strftime('%m/%d/%Y')}\n\n"
 
281
 
 
282
  worksheet += "## 📋 Exercises:\n\n"
 
283
 
 
284
  for i, exercise in enumerate(level_data['exercises'], 1):
 
285
  worksheet += f"### {i}. {exercise}\n\n"
 
286
 
 
287
  # Add space for notes
 
288
  worksheet += "**📝 Notes:**\n"
 
289
  worksheet += "```\n"
 
290
  worksheet += "Date completed: ___________\n"
 
291
  worksheet += "Observations: \n\n\n"
 
292
  worksheet += "Emotions during exercise: \n\n"
 
293
  worksheet += "Insights: \n\n"
 
294
  worksheet += "```\n\n"
 
295
 
 
296
  worksheet += "---\n\n"
 
297
  worksheet += "## 📖 Instructions:\n"
 
298
  worksheet += "✅ Complete exercises at your own pace\n"
 
299
  worksheet += "✅ Record all observations - this is important for progress\n"
 
300
  worksheet += "✅ Discuss results with your therapist\n"
 
301
  worksheet += "✅ Stop if you feel too uncomfortable and seek support\n\n"
 
302
 
 
303
  worksheet += "## 🆘 When to get help:\n"
 
304
  worksheet += "⚠️ If exercises cause severe anxiety or panic\n"
 
305
  worksheet += "⚠️ If you have thoughts of self-harm\n"
 
306
  worksheet += "⚠️ If symptoms worsen\n\n"
 
307
 
 
308
  worksheet += "📞 Emergency contacts:\n"
 
309
  worksheet += "- Crisis hotline: 988\n"
 
310
  worksheet += "- Emergency: 911\n"
 
311
  worksheet += "- Your therapist: ________________\n\n"
 
312
 
 
313
  return worksheet
314
 
315
+ def mood_tracker_analyzer(mood_data_str: str) -> str:
 
 
 
316
  """
 
317
  Analyzes mood tracking data to identify patterns.
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  """
 
319
  try:
320
+ # Try to parse as JSON
321
+ data = json.loads(mood_data_str)
 
322
  except:
323
+ # If not JSON, try to parse simple format like "5,7,3,8,6"
324
+ try:
325
+ moods = [float(x.strip()) for x in mood_data_str.split(',')]
326
+ data = [{"mood": mood, "date": f"Day {i+1}"} for i, mood in enumerate(moods)]
327
+ except:
328
+ return "Error: Please provide mood data as JSON or comma-separated numbers (e.g., '5,7,3,8,6')"
329
 
 
330
  if not isinstance(data, list) or len(data) == 0:
 
331
  return "Error: Mood data should be a non-empty list of entries."
 
332
 
 
333
  # Analyze mood patterns
 
334
  moods = []
 
335
  dates = []
 
336
 
 
337
  for entry in data:
338
+ if isinstance(entry, dict) and 'mood' in entry:
339
+ moods.append(float(entry['mood']))
340
+ dates.append(entry.get('date', f'Entry {len(dates)+1}'))
341
+ elif isinstance(entry, (int, float)):
342
+ moods.append(float(entry))
343
+ dates.append(f'Entry {len(dates)+1}')
 
344
 
 
345
  if not moods:
 
346
  return "Error: No valid mood entries found."
 
347
 
 
348
  # Calculate statistics
 
349
  avg_mood = sum(moods) / len(moods)
 
350
  mood_trend = "stable"
 
351
 
 
352
  if len(moods) > 3:
 
353
  recent_avg = sum(moods[-3:]) / 3
 
354
  older_avg = sum(moods[:-3]) / (len(moods) - 3)
 
355
 
 
356
  if recent_avg > older_avg + 0.5:
 
357
  mood_trend = "improving"
 
358
  elif recent_avg < older_avg - 0.5:
 
359
  mood_trend = "declining"
 
360
 
 
361
  # Create report
 
362
  report = "# 📊 Mood Tracking Analysis\n\n"
 
363
  report += f"**Period**: {dates[0]} to {dates[-1]}\n"
 
364
  report += f"**Entries analyzed**: {len(moods)}\n"
 
365
  report += f"**Average mood**: {avg_mood:.1f}/10\n"
 
366
  report += f"**Trend**: {mood_trend}\n\n"
 
367
 
 
368
  report += "## 📈 Pattern Analysis:\n"
 
369
 
 
370
  # Check for low mood periods
 
371
  low_mood_days = sum(1 for m in moods if m < 5)
 
372
  if low_mood_days > len(moods) * 0.3:
 
373
  report += "⚠️ Concern: Low mood detected in >30% of entries\n"
 
374
  report += " → Consider professional evaluation for depression\n\n"
 
375
 
 
376
  # Check volatility
 
377
  if len(moods) > 2:
 
378
  volatility = sum(abs(moods[i] - moods[i-1]) for i in range(1, len(moods))) / (len(moods) - 1)
 
379
  if volatility > 2:
 
380
  report += "🎢 High mood volatility detected\n"
 
381
  report += " → May benefit from emotion regulation skills\n\n"
 
382
 
 
383
  report += "## 💡 Recommendations:\n"
 
384
 
 
385
  if mood_trend == "declining":
 
386
  report += "- 🚨 Schedule appointment with mental health professional\n"
 
387
  report += "- 🧘 Increase self-care activities\n"
 
388
  report += "- 👥 Reach out to support network\n"
 
389
  elif mood_trend == "improving":
 
390
  report += "- ✅ Continue current strategies\n"
 
391
  report += "- 📝 Document what's working well\n"
 
392
  report += "- 🎯 Set new wellness goals\n"
 
393
  else:
 
394
  report += "- 📊 Continue tracking for more data\n"
 
395
  report += "- 🔍 Look for mood triggers\n"
 
396
  report += "- 💪 Maintain healthy routines\n"
 
397
 
 
398
  report += f"\n*Analysis completed: {datetime.datetime.now().strftime('%m/%d/%Y %H:%M')}*"
 
399
 
400
+ return report
401
 
402
+ # Create the Gradio interface
403
+ def create_interface():
404
+ """Create and return the Gradio interface"""
405
+
406
+ with gr.Blocks(title="🧠 Mental Health Therapy Assistant", theme=gr.themes.Soft()) as app:
407
+ gr.Markdown("""
408
+ # 🧠 Mental Health Therapy Assistant
409
+
410
+ **⚠️ Important Disclaimer**: This tool is for educational and supportive purposes only.
411
+ It is not a substitute for professional mental health care. If you're in crisis,
412
+ please contact emergency services (911) or the crisis hotline (988).
413
+ """)
414
+
415
+ with gr.Tabs():
416
+ # Emotion Analysis Tab
417
+ with gr.TabItem("🎭 Emotion Analysis"):
418
+ gr.Markdown("### Analyze emotional content from speech or text")
419
+
420
+ with gr.Row():
421
+ with gr.Column():
422
+ emotion_text = gr.Textbox(
423
+ label="Patient Speech/Text",
424
+ placeholder="Enter the text you want to analyze for emotional content...",
425
+ lines=5
426
+ )
427
+ emotion_context = gr.Dropdown(
428
+ choices=["therapy", "assessment", "crisis"],
429
+ value="therapy",
430
+ label="Context"
431
+ )
432
+ emotion_btn = gr.Button("🔍 Analyze Emotions", variant="primary")
433
+
434
+ with gr.Column():
435
+ emotion_output = gr.Markdown(label="Analysis Results")
436
+
437
+ emotion_btn.click(
438
+ fn=speech_emotion_analyzer,
439
+ inputs=[emotion_text, emotion_context],
440
+ outputs=emotion_output
441
+ )
442
+
443
+ # Worksheet Generator Tab
444
+ with gr.TabItem("📝 Therapy Worksheets"):
445
+ gr.Markdown("### Generate age-appropriate therapeutic exercises")
446
+
447
+ with gr.Row():
448
+ with gr.Column():
449
+ worksheet_therapy = gr.Dropdown(
450
+ choices=["CBT", "DBT", "Art", "Mindfulness"],
451
+ value="CBT",
452
+ label="Therapy Type"
453
+ )
454
+ worksheet_age = gr.Slider(
455
+ minimum=5,
456
+ maximum=100,
457
+ value=25,
458
+ step=1,
459
+ label="Client Age"
460
+ )
461
+ worksheet_issue = gr.Textbox(
462
+ label="Main Issue/Concern",
463
+ placeholder="e.g., anxiety, depression, anger management..."
464
+ )
465
+ worksheet_btn = gr.Button("📋 Generate Worksheet", variant="primary")
466
+
467
+ with gr.Column():
468
+ worksheet_output = gr.Markdown(label="Generated Worksheet")
469
+
470
+ worksheet_btn.click(
471
+ fn=create_therapy_worksheet,
472
+ inputs=[worksheet_therapy, worksheet_age, worksheet_issue],
473
+ outputs=worksheet_output
474
+ )
475
+
476
+ # Mood Tracker Tab
477
+ with gr.TabItem("📊 Mood Analysis"):
478
+ gr.Markdown("### Analyze mood tracking patterns")
479
+
480
+ with gr.Row():
481
+ with gr.Column():
482
+ mood_data = gr.Textbox(
483
+ label="Mood Data",
484
+ placeholder="Enter mood scores (1-10) separated by commas: 5,7,3,8,6\nOr JSON format: [{\"mood\": 5, \"date\": \"2024-01-01\"}, ...]",
485
+ lines=5
486
+ )
487
+ mood_btn = gr.Button("📈 Analyze Mood Patterns", variant="primary")
488
+
489
+ gr.Markdown("""
490
+ **Example formats:**
491
+ - Simple: `5,7,3,8,6,4,9`
492
+ - JSON: `[{"mood": 5, "date": "2024-01-01"}, {"mood": 7, "date": "2024-01-02"}]`
493
+ """)
494
+
495
+ with gr.Column():
496
+ mood_output = gr.Markdown(label="Mood Analysis Results")
497
+
498
+ mood_btn.click(
499
+ fn=mood_tracker_analyzer,
500
+ inputs=mood_data,
501
+ outputs=mood_output
502
+ )
503
+
504
+ # Resources Tab
505
+ with gr.TabItem("📚 Resources"):
506
+ gr.Markdown("""
507
+ ### 🆘 Crisis Resources
508
+
509
+ **Immediate Help:**
510
+ - 🚨 Emergency: **911**
511
+ - 📞 Crisis Hotline: **988** (Suicide & Crisis Lifeline)
512
+ - 💬 Crisis Text Line: Text HOME to **741741**
513
+
514
+ **Online Resources:**
515
+ - [National Alliance on Mental Illness (NAMI)](https://nami.org)
516
+ - [Mental Health America](https://www.mhanational.org)
517
+ - [Psychology Today Therapist Finder](https://www.psychologytoday.com)
518
+
519
+ ### 🧘 Self-Care Tips
520
+
521
+ **Daily Practices:**
522
+ - 🌅 Maintain regular sleep schedule
523
+ - 🏃 Regular physical activity
524
+ - 🥗 Balanced nutrition
525
+ - 🧘 Mindfulness/meditation practice
526
+ - 👥 Social connections
527
+ - 📚 Limit news/social media if overwhelming
528
+
529
+ **Remember:** This tool provides educational support but cannot replace professional mental health care.
530
+ """)
531
+
532
+ return app
533
+
534
+ # Main execution
535
+ if __name__ == "__main__":
536
+ # Create and launch the interface
537
+ app = create_interface()
538
+
539
+ # Launch with appropriate settings for deployment
540
+ app.launch(
541
+ server_name="0.0.0.0", # Allow external access
542
+ server_port=7860, # Standard port for Hugging Face Spaces
543
+ share=False, # Don't create a public link
544
+ debug=False # Disable debug mode for production
545
+ )