RozzaCreat commited on
Commit
4a69ef1
·
verified ·
1 Parent(s): 8c5c24b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +464 -53
app.py CHANGED
@@ -1,69 +1,480 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
 
 
 
 
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
 
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
 
 
 
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
 
26
  """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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