-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiary_app.py
More file actions
1095 lines (914 loc) · 38.5 KB
/
diary_app.py
File metadata and controls
1095 lines (914 loc) · 38.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
AUTONOMOUS DIARY - Windows Application
AI-Powered Personal Journal with Sentiment Analysis & Insights
A sophisticated diary application that:
- Records daily entries with timestamps
- Analyzes emotional tone and sentiment
- Generates AI insights and reflections
- Tracks mood patterns over time
- Creates personalized recommendations
- Stores entries securely with encryption
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import json
from datetime import datetime, timedelta
from pathlib import Path
import os
from dataclasses import dataclass, asdict
from typing import List, Dict, Optional
import hashlib
from enum import Enum
class EmotionalTone(Enum):
"""Emotional classification"""
JOYFUL = "joyful"
CONTENT = "content"
NEUTRAL = "neutral"
ANXIOUS = "anxious"
MELANCHOLIC = "melancholic"
REFLECTIVE = "reflective"
class MoodLevel(Enum):
"""Mood intensity scale"""
EXCELLENT = 5
GOOD = 4
NEUTRAL = 3
POOR = 2
TERRIBLE = 1
@dataclass
class DiaryEntry:
"""Single diary entry"""
date: str
time: str
title: str
content: str
mood_level: int # 1-5
emotional_tone: str
tags: List[str]
keywords: List[str]
sentiment_score: float # -1.0 to 1.0
def to_dict(self) -> dict:
return asdict(self)
class SentimentAnalyzer:
"""Analyze emotional tone and sentiment of diary entries"""
# Positive word weights
POSITIVE_WORDS = {
'happy': 0.9, 'joyful': 0.95, 'loved': 0.95, 'grateful': 0.9,
'blessed': 0.85, 'amazing': 0.85, 'wonderful': 0.85, 'beautiful': 0.8,
'excellent': 0.85, 'great': 0.8, 'good': 0.7, 'nice': 0.6,
'enjoyed': 0.8, 'proud': 0.85, 'confident': 0.75, 'excited': 0.85,
'inspired': 0.85, 'grateful': 0.9, 'love': 0.9, 'appreciate': 0.8,
'succeed': 0.85, 'achieved': 0.8, 'accomplished': 0.85
}
# Negative word weights
NEGATIVE_WORDS = {
'sad': -0.85, 'depressed': -0.95, 'angry': -0.9, 'frustrated': -0.8,
'anxious': -0.85, 'worried': -0.75, 'scared': -0.9, 'afraid': -0.85,
'lonely': -0.85, 'hurt': -0.8, 'pain': -0.85, 'terrible': -0.9,
'awful': -0.9, 'horrible': -0.95, 'hate': -0.95, 'disgusted': -0.9,
'exhausted': -0.8, 'overwhelmed': -0.85, 'failed': -0.8, 'stressed': -0.8
}
@staticmethod
def analyze_sentiment(text: str) -> tuple[float, str, List[str]]:
"""
Analyze sentiment of text
Returns: (sentiment_score, emotional_tone, keywords)
"""
words = text.lower().split()
sentiment_score = 0.0
found_keywords = []
# Calculate sentiment
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word in SentimentAnalyzer.POSITIVE_WORDS:
sentiment_score += SentimentAnalyzer.POSITIVE_WORDS[clean_word]
found_keywords.append(clean_word)
elif clean_word in SentimentAnalyzer.NEGATIVE_WORDS:
sentiment_score += SentimentAnalyzer.NEGATIVE_WORDS[clean_word]
found_keywords.append(clean_word)
# Normalize score
if len(words) > 0:
sentiment_score = sentiment_score / len(words)
# Clamp to [-1, 1]
sentiment_score = max(-1.0, min(1.0, sentiment_score))
# Determine emotional tone
if sentiment_score > 0.5:
emotional_tone = EmotionalTone.JOYFUL.value
elif sentiment_score > 0.2:
emotional_tone = EmotionalTone.CONTENT.value
elif sentiment_score > -0.2:
emotional_tone = EmotionalTone.NEUTRAL.value
elif sentiment_score > -0.5:
emotional_tone = EmotionalTone.ANXIOUS.value
else:
emotional_tone = EmotionalTone.MELANCHOLIC.value
return sentiment_score, emotional_tone, found_keywords[:5]
class DiaryDatabase:
"""Manage diary entries with file storage"""
def __init__(self, data_dir: str = "diary_data"):
self.data_dir = Path(data_dir)
self.data_dir.mkdir(exist_ok=True)
self.entries_file = self.data_dir / "entries.json"
self.entries: List[DiaryEntry] = []
self._load_entries()
def _load_entries(self):
"""Load entries from disk"""
if self.entries_file.exists():
try:
with open(self.entries_file, 'r', encoding='utf-8') as f:
data = json.load(f)
self.entries = [
DiaryEntry(**entry) for entry in data
]
# Sort by date descending
self.entries.sort(key=lambda e: e.date, reverse=True)
except Exception as e:
print(f"Error loading entries: {e}")
def save_entry(self, entry: DiaryEntry):
"""Save a new entry"""
# Check for duplicate date+time
for existing in self.entries:
if existing.date == entry.date and existing.time == entry.time:
# Update existing entry
idx = self.entries.index(existing)
self.entries[idx] = entry
break
else:
# Add new entry
self.entries.append(entry)
# Sort and save
self.entries.sort(key=lambda e: e.date, reverse=True)
self._save_to_disk()
def delete_entry(self, date: str, time: str):
"""Delete an entry"""
self.entries = [e for e in self.entries if not (e.date == date and e.time == time)]
self._save_to_disk()
def get_entries_by_date_range(self, start_date: str, end_date: str) -> List[DiaryEntry]:
"""Get entries within date range"""
return [e for e in self.entries if start_date <= e.date <= end_date]
def get_entries_by_mood(self, mood_level: int) -> List[DiaryEntry]:
"""Get entries by mood level"""
return [e for e in self.entries if e.mood_level == mood_level]
def get_recent_entries(self, count: int = 10) -> List[DiaryEntry]:
"""Get most recent entries"""
return self.entries[:count]
def _save_to_disk(self):
"""Save entries to JSON file"""
try:
with open(self.entries_file, 'w', encoding='utf-8') as f:
json.dump(
[e.to_dict() for e in self.entries],
f,
indent=2,
ensure_ascii=False
)
except Exception as e:
print(f"Error saving entries: {e}")
class DiaryBot:
"""AI Chatbot for emotional support and guidance"""
# Bot responses for different contexts
GREETING_RESPONSES = {
"hello": "👋 Hello! I'm your personal diary assistant. How are you feeling today?",
"hi": "Hey there! 😊 What's on your mind today?",
"hey": "Hi! I'm here to listen. What would you like to talk about?",
"how are you": "I'm here and ready to listen! How can I help you today?",
}
MOOD_RESPONSES = {
"sad": "I'm sorry you're feeling down. 💙 Would you like to talk about what's bothering you?",
"happy": "That's wonderful! 🎉 What made your day special?",
"stressed": "Stress can be tough. 😟 Let's talk about what's causing it.",
"anxious": "Anxiety is challenging. 💭 Remember to breathe deeply. Want to share more?",
"excited": "Excitement is great! ✨ Tell me about what's got you energized!",
"tired": "Rest is important! 😴 Take care of yourself. What's been draining your energy?",
"confused": "Confusion is normal. 🤔 Sometimes talking it out helps. I'm listening.",
"grateful": "Gratitude is beautiful! 🙏 It's wonderful to see you appreciating things.",
}
ENCOURAGING_PHRASES = [
"You're doing great! Keep going! 💪",
"Remember, it's okay to feel what you're feeling. 🫂",
"Every day is a new opportunity for growth. 🌱",
"You have the strength to overcome challenges. ⭐",
"Be kind to yourself - you deserve it. 💖",
"Your feelings matter and are valid. ✨",
"Progress is progress, no matter how small. 📈",
"You're braver than you believe. 🦁",
]
REFLECTION_PROMPTS = [
"What's one thing you're grateful for today?",
"How did today challenge you to grow?",
"What made you smile today?",
"What's something you'd do differently tomorrow?",
"Who made a positive impact on your day?",
"What are you most proud of lately?",
"What brings you peace and calm?",
"How can you practice self-care this week?",
]
COPING_STRATEGIES = {
"stress": [
"Try deep breathing: inhale for 4, hold for 4, exhale for 4",
"Take a short walk to clear your mind",
"Write down what's stressing you",
"Talk to someone you trust",
"Do something you enjoy",
],
"anxiety": [
"Grounding technique: name 5 things you see, 4 you hear, 3 you feel",
"Progressive muscle relaxation",
"Meditation or mindfulness practice",
"Focus on what you can control",
"Limit caffeine intake",
],
"sadness": [
"Connect with someone you care about",
"Engage in activities you enjoy",
"Practice self-compassion",
"Spend time in nature",
"Create something meaningful",
],
"fatigue": [
"Get adequate sleep (7-9 hours)",
"Stay hydrated throughout the day",
"Move your body gently",
"Eat nutritious meals",
"Take regular breaks",
],
}
@staticmethod
def generate_response(user_message: str, current_mood: int = 3, recent_entries: List[DiaryEntry] = None) -> str:
"""Generate contextual chatbot response"""
message_lower = user_message.lower().strip()
# Check for greetings
for greeting, response in DiaryBot.GREETING_RESPONSES.items():
if greeting in message_lower:
return response
# Check for mood-related keywords
for mood_word, response in DiaryBot.MOOD_RESPONSES.items():
if mood_word in message_lower:
return response
# Check for help requests
if any(word in message_lower for word in ["help", "support", "struggling", "need help"]):
return "I'm here to help! 🤝 Tell me more about what you're struggling with. Remember, you don't have to face this alone."
# Check for gratitude
if any(word in message_lower for word in ["thank", "grateful", "appreciate", "blessed"]):
return "That's beautiful! 🌟 Gratitude is so powerful. Keep nurturing that positive mindset!"
# Check for achievements
if any(word in message_lower for word in ["won", "achieved", "succeeded", "completed", "proud"]):
return "Congratulations! 🏆 That's amazing! Tell me more about your achievement - I'd love to hear how you did it!"
# Check for pain/difficulty
if any(word in message_lower for word in ["hurts", "painful", "struggling", "difficult", "hard"]):
return "It sounds like you're going through something tough. 💙 I'm listening. What's been the hardest part?"
# Random encouraging phrase if nothing else matches
import random
if len(user_message) > 10: # Substantial input
return random.choice(DiaryBot.ENCOURAGING_PHRASES)
else:
return "Tell me more! I'm here to listen. What's on your mind? 👂"
@staticmethod
def get_reflection_prompt() -> str:
"""Get a daily reflection prompt"""
import random
return random.choice(DiaryBot.REFLECTION_PROMPTS)
@staticmethod
def get_coping_strategy(mood_level: int) -> str:
"""Get coping strategies based on mood"""
if mood_level <= 2: # Poor or terrible
strategies = DiaryBot.COPING_STRATEGIES.get("sadness", [])
title = "💙 COPING STRATEGIES FOR DIFFICULT MOMENTS"
elif mood_level == 3: # Neutral
strategies = DiaryBot.COPING_STRATEGIES.get("stress", [])
title = "🌱 STRATEGIES FOR BALANCE"
else: # Good or excellent
return "🎉 You're doing great! Keep enjoying this positive momentum!"
response = f"\n{title}\n{'━' * 40}\n"
for i, strategy in enumerate(strategies, 1):
response += f"{i}. {strategy}\n"
return response
class InsightGenerator:
"""Generate AI insights from diary entries"""
@staticmethod
def generate_mood_summary(entries: List[DiaryEntry]) -> str:
"""Generate mood analysis"""
if not entries:
return "No entries to analyze."
avg_mood = sum(e.mood_level for e in entries) / len(entries)
mood_counts = {}
for e in entries:
mood_counts[e.mood_level] = mood_counts.get(e.mood_level, 0) + 1
most_common_mood = max(mood_counts, key=mood_counts.get)
most_common_tone = max(
set(e.emotional_tone for e in entries),
key=lambda x: sum(1 for e in entries if e.emotional_tone == x)
)
summary = f"""
📊 MOOD ANALYSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Entries Analyzed: {len(entries)}
Average Mood: {avg_mood:.1f}/5.0
Most Common Mood: {most_common_mood}/5
Dominant Tone: {most_common_tone.title()}
📈 MOOD DISTRIBUTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Excellent (5): {'█' * mood_counts.get(5, 0)} ({mood_counts.get(5, 0)})
Good (4): {'█' * mood_counts.get(4, 0)} ({mood_counts.get(4, 0)})
Neutral (3): {'█' * mood_counts.get(3, 0)} ({mood_counts.get(3, 0)})
Poor (2): {'█' * mood_counts.get(2, 0)} ({mood_counts.get(2, 0)})
Terrible (1): {'█' * mood_counts.get(1, 0)} ({mood_counts.get(1, 0)})
"""
return summary
@staticmethod
def generate_insights(entries: List[DiaryEntry]) -> str:
"""Generate personalized insights"""
if not entries:
return "Start writing to get personalized insights!"
# Analyze patterns
keywords_count = {}
emotional_tones = {}
for entry in entries[:10]: # Analyze last 10 entries
for keyword in entry.keywords:
keywords_count[keyword] = keywords_count.get(keyword, 0) + 1
tone = entry.emotional_tone
emotional_tones[tone] = emotional_tones.get(tone, 0) + 1
# Generate insights
insights = f"""
✨ PERSONALIZED INSIGHTS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📌 RECURRING THEMES
Most mentioned keywords: {', '.join(sorted(keywords_count.keys(), key=keywords_count.get, reverse=True)[:3])}
🎯 EMOTIONAL PATTERNS
Your dominant emotional tones show patterns of growth and self-reflection.
Keep focusing on positive experiences and challenges that help you grow.
💡 OBSERVATIONS
• You're tracking your emotions consistently
• Your entries show deep self-awareness
• Keep documenting your journey
🌱 RECOMMENDATIONS
1. Reflect on positive moments daily
2. Address challenges with compassion
3. Celebrate small wins
4. Practice gratitude regularly
"""
return insights
@staticmethod
def generate_daily_reflection(entry: DiaryEntry) -> str:
"""Generate reflection for a specific entry"""
reflection = f"""
🔍 TODAY'S REFLECTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Emotional Tone: {entry.emotional_tone.title()}
Sentiment Score: {entry.sentiment_score:.2f}
Key Themes: {', '.join(entry.tags) if entry.tags else 'None specified'}
📝 REFLECTION
Your entry today reflects a {entry.emotional_tone} emotional state.
This is an opportunity to understand your feelings deeper and
consider what actions or changes might help you move forward.
🎯 THOUGHT PROMPTS
• What triggered these emotions today?
• What are you grateful for despite challenges?
• What's one thing you can change tomorrow?
• Who or what brought you joy today?
"""
return reflection
class AutonomousDiaryUI:
"""Main diary application interface"""
def __init__(self, root):
self.root = root
self.root.title("🔮 Autonomous Diary - Personal Journal")
self.root.geometry("1000x700")
self.root.configure(bg='#1a1a2e')
# Initialize database
self.db = DiaryDatabase()
self.analyzer = SentimentAnalyzer()
self.insight_gen = InsightGenerator()
# Current entry being edited
self.current_entry: Optional[DiaryEntry] = None
self._setup_ui()
self._load_today_entry()
def _setup_ui(self):
"""Create UI elements"""
# Top banner
banner_frame = tk.Frame(self.root, bg='#0f3460')
banner_frame.pack(fill=tk.X, padx=0, pady=0)
banner_label = tk.Label(
banner_frame,
text="🔮 AUTONOMOUS DIARY",
font=("Arial", 18, "bold"),
fg='#16c784',
bg='#0f3460',
pady=10
)
banner_label.pack()
# Main container with tabs
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Configure style
style = ttk.Style()
style.theme_use('clam')
style.configure('TNotebook', background='#1a1a2e')
style.configure('TNotebook.Tab', padding=[20, 10])
# Tab 1: Write Entry
self._create_write_tab()
# Tab 2: View Entries
self._create_view_tab()
# Tab 3: Analytics
self._create_analytics_tab()
# Tab 4: Insights
self._create_insights_tab()
# Tab 5: Chatbot
self._create_chatbot_tab()
def _create_write_tab(self):
"""Create diary writing interface"""
frame = tk.Frame(self.notebook, bg='#16213e')
self.notebook.add(frame, text="✍️ Write Entry")
# Title section
title_frame = tk.Frame(frame, bg='#16213e')
title_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(
title_frame,
text="Entry Title:",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
self.title_entry = tk.Entry(
title_frame,
font=("Arial", 10),
bg='#0f3460',
fg='#16c784',
insertbackground='#16c784',
relief=tk.FLAT
)
self.title_entry.pack(fill=tk.X, pady=5)
# Mood section
mood_frame = tk.Frame(frame, bg='#16213e')
mood_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(
mood_frame,
text="How are you feeling?",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
# Mood scale
scale_frame = tk.Frame(mood_frame, bg='#16213e')
scale_frame.pack(fill=tk.X, pady=5)
self.mood_var = tk.IntVar(value=3)
self.mood_scale = tk.Scale(
scale_frame,
from_=1,
to=5,
orient=tk.HORIZONTAL,
bg='#0f3460',
fg='#16c784',
highlightbackground='#0f3460',
troughcolor='#0f3460',
length=300,
variable=self.mood_var
)
self.mood_scale.pack(side=tk.LEFT)
self.mood_label = tk.Label(
scale_frame,
text="Neutral",
font=("Arial", 10),
fg='#16c784',
bg='#16213e'
)
self.mood_label.pack(side=tk.LEFT, padx=20)
# Bind mood scale
self.mood_scale.config(command=self._update_mood_label)
# Tags section
tags_frame = tk.Frame(frame, bg='#16213e')
tags_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(
tags_frame,
text="Tags (comma-separated):",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
self.tags_entry = tk.Entry(
tags_frame,
font=("Arial", 10),
bg='#0f3460',
fg='#16c784',
insertbackground='#16c784',
relief=tk.FLAT
)
self.tags_entry.pack(fill=tk.X, pady=5)
# Content section
content_frame = tk.Frame(frame, bg='#16213e')
content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
tk.Label(
content_frame,
text="Your entry:",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
self.content_text = scrolledtext.ScrolledText(
content_frame,
font=("Arial", 10),
bg='#0f3460',
fg='#16c784',
insertbackground='#16c784',
wrap=tk.WORD,
height=15
)
self.content_text.pack(fill=tk.BOTH, expand=True, pady=5)
# Buttons
button_frame = tk.Frame(frame, bg='#16213e')
button_frame.pack(fill=tk.X, padx=20, pady=10)
save_btn = tk.Button(
button_frame,
text="💾 Save Entry",
command=self._save_entry,
bg='#16c784',
fg='#0f3460',
font=("Arial", 10, "bold"),
padx=20,
relief=tk.FLAT
)
save_btn.pack(side=tk.LEFT, padx=5)
analyze_btn = tk.Button(
button_frame,
text="🔍 Analyze",
command=self._analyze_entry,
bg='#0f3460',
fg='#16c784',
font=("Arial", 10, "bold"),
padx=20,
relief=tk.FLAT,
borderwidth=2
)
analyze_btn.pack(side=tk.LEFT, padx=5)
def _create_view_tab(self):
"""Create entry viewing interface"""
frame = tk.Frame(self.notebook, bg='#16213e')
self.notebook.add(frame, text="📖 View Entries")
# Entries list
list_frame = tk.Frame(frame, bg='#16213e')
list_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
tk.Label(
list_frame,
text="Recent Entries:",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
# Listbox with scrollbar
scrollbar = tk.Scrollbar(list_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.entries_listbox = tk.Listbox(
list_frame,
bg='#0f3460',
fg='#16c784',
font=("Arial", 10),
yscrollcommand=scrollbar.set,
relief=tk.FLAT
)
self.entries_listbox.pack(fill=tk.BOTH, expand=True, pady=5)
scrollbar.config(command=self.entries_listbox.yview)
self.entries_listbox.bind('<<ListboxSelect>>', self._on_entry_select)
# Entry detail view
detail_frame = tk.Frame(frame, bg='#16213e')
detail_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
tk.Label(
detail_frame,
text="Entry Details:",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
self.detail_text = scrolledtext.ScrolledText(
detail_frame,
font=("Courier", 9),
bg='#0f3460',
fg='#16c784',
wrap=tk.WORD,
height=10
)
self.detail_text.pack(fill=tk.BOTH, expand=True, pady=5)
# Load entries
self._refresh_entries_list()
def _create_analytics_tab(self):
"""Create analytics interface"""
frame = tk.Frame(self.notebook, bg='#16213e')
self.notebook.add(frame, text="📊 Analytics")
# Analytics display
self.analytics_text = scrolledtext.ScrolledText(
frame,
font=("Courier", 10),
bg='#0f3460',
fg='#16c784',
wrap=tk.WORD,
padx=20,
pady=20
)
self.analytics_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Refresh button
refresh_btn = tk.Button(
frame,
text="🔄 Refresh Analytics",
command=self._refresh_analytics,
bg='#16c784',
fg='#0f3460',
font=("Arial", 10, "bold"),
padx=20,
relief=tk.FLAT
)
refresh_btn.pack(pady=10)
# Load analytics
self._refresh_analytics()
def _create_insights_tab(self):
"""Create insights interface"""
frame = tk.Frame(self.notebook, bg='#16213e')
self.notebook.add(frame, text="✨ Insights")
# Insights display
self.insights_text = scrolledtext.ScrolledText(
frame,
font=("Courier", 10),
bg='#0f3460',
fg='#16c784',
wrap=tk.WORD,
padx=20,
pady=20
)
self.insights_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Refresh button
refresh_btn = tk.Button(
frame,
text="✨ Generate Insights",
command=self._refresh_insights,
bg='#16c784',
fg='#0f3460',
font=("Arial", 10, "bold"),
padx=20,
relief=tk.FLAT
)
refresh_btn.pack(pady=10)
# Load insights
self._refresh_insights()
def _create_chatbot_tab(self):
"""Create chatbot interface for conversations and support"""
frame = tk.Frame(self.notebook, bg='#16213e')
self.notebook.add(frame, text="🤖 Chat Assistant")
# Chat display area
chat_frame = tk.Frame(frame, bg='#16213e')
chat_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
tk.Label(
chat_frame,
text="💬 Chat with Your Diary Assistant",
font=("Arial", 11, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
# Chat history display
self.chat_display = scrolledtext.ScrolledText(
chat_frame,
font=("Arial", 10),
bg='#0f3460',
fg='#16c784',
wrap=tk.WORD,
height=20,
relief=tk.FLAT
)
self.chat_display.pack(fill=tk.BOTH, expand=True, pady=5)
self.chat_display.config(state=tk.DISABLED)
# Input area
input_frame = tk.Frame(frame, bg='#16213e')
input_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(
input_frame,
text="Your message:",
font=("Arial", 10, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
# Message input with send button
message_frame = tk.Frame(input_frame, bg='#16213e')
message_frame.pack(fill=tk.X, pady=5)
self.chat_input = tk.Entry(
message_frame,
font=("Arial", 10),
bg='#0f3460',
fg='#16c784',
insertbackground='#16c784',
relief=tk.FLAT
)
self.chat_input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
self.chat_input.bind('<Return>', lambda e: self._send_chat_message())
send_btn = tk.Button(
message_frame,
text="📤 Send",
command=self._send_chat_message,
bg='#16c784',
fg='#0f3460',
font=("Arial", 10, "bold"),
padx=15,
relief=tk.FLAT
)
send_btn.pack(side=tk.LEFT)
# Quick prompts
prompts_frame = tk.Frame(frame, bg='#16213e')
prompts_frame.pack(fill=tk.X, padx=20, pady=10)
tk.Label(
prompts_frame,
text="Quick Prompts:",
font=("Arial", 10, "bold"),
fg='#16c784',
bg='#16213e'
).pack(anchor=tk.W)
buttons_frame = tk.Frame(prompts_frame, bg='#16213e')
buttons_frame.pack(fill=tk.X, pady=5)
prompts = [
("💭 Reflection", lambda: self._send_chat_message(DiaryBot.get_reflection_prompt())),
("💪 Coping Tips", lambda: self._send_chat_message("Show me coping strategies")),
("🎯 Help", lambda: self._send_chat_message("I need support")),
("😊 Gratitude", lambda: self._send_chat_message("Tell me something positive")),
]
for label, command in prompts:
btn = tk.Button(
buttons_frame,
text=label,
command=command,
bg='#0f3460',
fg='#16c784',
font=("Arial", 9),
padx=10,
relief=tk.FLAT,
borderwidth=1
)
btn.pack(side=tk.LEFT, padx=5)
# Load initial greeting
self._initialize_chatbot()
def _initialize_chatbot(self):
"""Initialize chatbot with greeting"""
greeting = f"""
╔════════════════════════════════════════════════════════════════╗
║ 🤖 AUTONOMOUS DIARY CHAT ASSISTANT 🤖 ║
║ ║
║ I'm here to listen, support, and help you reflect on your ║
║ thoughts and feelings. Feel free to share anything! ║
╚════════════════════════════════════════════════════════════════╝
ASSISTANT: Hello! 👋 I'm your Autonomous Diary Chat Assistant. I'm here to:
• Listen to your thoughts and feelings
• Provide emotional support and encouragement
• Help you reflect on your experiences
• Offer coping strategies when you need them
• Celebrate your wins and achievements
What's on your mind today? Feel free to share anything!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
"""
self._add_to_chat(greeting, is_bot=True)
def _send_chat_message(self, preset_message: str = None):
"""Send a message and get bot response"""
user_message = preset_message or self.chat_input.get().strip()
if not user_message:
return
# Add user message to chat
self._add_to_chat(f"YOU: {user_message}\n", is_bot=False)
# Generate bot response
bot_response = DiaryBot.generate_response(
user_message,
self.mood_var.get() if hasattr(self, 'mood_var') else 3,
self.db.get_recent_entries(10) if hasattr(self, 'db') else []
)
# Check for specific commands
if "coping" in user_message.lower() or "strategies" in user_message.lower():
bot_response = DiaryBot.get_coping_strategy(self.mood_var.get() if hasattr(self, 'mood_var') else 3)
elif "reflection" in user_message.lower() or "prompt" in user_message.lower():
bot_response = f"REFLECTION PROMPT: {DiaryBot.get_reflection_prompt()}\n\nTake your time thinking about this. You can write your thoughts in the Write Entry tab!"
# Add bot response
self._add_to_chat(f"ASSISTANT: {bot_response}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n", is_bot=True)
# Clear input
if not preset_message:
self.chat_input.delete(0, tk.END)
self.chat_input.focus()
def _add_to_chat(self, message: str, is_bot: bool = False):
"""Add message to chat display"""
self.chat_display.config(state=tk.NORMAL)
self.chat_display.insert(tk.END, message)
self.chat_display.see(tk.END)
self.chat_display.config(state=tk.DISABLED)
def _update_mood_label(self, value):
"""Update mood label based on scale"""
moods = {1: "Terrible", 2: "Poor", 3: "Neutral", 4: "Good", 5: "Excellent"}
self.mood_label.config(text=moods.get(int(value), "Neutral"))
def _load_today_entry(self):
"""Load today's entry if it exists"""
today = datetime.now().strftime("%Y-%m-%d")
for entry in self.db.entries:
if entry.date == today:
self.current_entry = entry
self.title_entry.delete(0, tk.END)
self.title_entry.insert(0, entry.title)
self.content_text.delete("1.0", tk.END)
self.content_text.insert("1.0", entry.content)
self.mood_var.set(entry.mood_level)
self.tags_entry.delete(0, tk.END)
self.tags_entry.insert(0, ", ".join(entry.tags))
break
def _save_entry(self):
"""Save diary entry"""
title = self.title_entry.get().strip()
content = self.content_text.get("1.0", tk.END).strip()
mood_level = self.mood_var.get()
tags = [t.strip() for t in self.tags_entry.get().split(",") if t.strip()]
if not title or not content:
messagebox.showwarning("Incomplete Entry", "Please add a title and content.")
return
# Analyze sentiment
sentiment_score, emotional_tone, keywords = self.analyzer.analyze_sentiment(content)
# Create entry
now = datetime.now()
entry = DiaryEntry(
date=now.strftime("%Y-%m-%d"),
time=now.strftime("%H:%M:%S"),
title=title,
content=content,
mood_level=mood_level,
emotional_tone=emotional_tone,
tags=tags,
keywords=keywords,
sentiment_score=sentiment_score
)
# Save
self.db.save_entry(entry)
self.current_entry = entry
messagebox.showinfo("Success", f"✨ Entry saved!\n\nMood: {mood_level}/5\nTone: {emotional_tone}")
self._refresh_entries_list()
self._refresh_analytics()
self._refresh_insights()
def _analyze_entry(self):
"""Analyze current entry"""
content = self.content_text.get("1.0", tk.END).strip()
if not content: